diff --git a/resources/assets/enderio/lang/en_US.lang b/resources/assets/enderio/lang/en_US.lang index e5c37419..24f6e8f9 100644 --- a/resources/assets/enderio/lang/en_US.lang +++ b/resources/assets/enderio/lang/en_US.lang @@ -75,9 +75,11 @@ item.itemExtractSpeedUpgrade.tooltip.detailed.line1=Increases speed by 4 item.itemExtractSpeedUpgrade.tooltip.detailed.line2=items per extraction item.itemExtractSpeedUpgrade.tooltip.detailed.line3=Max upgrades is 15 +enderio.itemGasConduit.name=Gas Conduit - -enderio.itemMeConduit.name=ME Conduit +enderio.itemGasConduit.tooltip.maxExtract=Max Extract: +enderio.itemGasConduit.tooltip.maxIo=Max IO: +enderio.itemGasConduit.tooltip.detailed.line1=Transfers Mekanism-compatible gases //Materials enderio.itemMaterial.name=Materials @@ -105,6 +107,7 @@ enderio.fluid.millibucket.abr=mB enderio.fuel.tooltip.heading=Fuel Details enderio.fuel.tooltip.burnTime=burn time enderio.fluid.millibucketsTick=mB/t +enderio.gas.gasTick=Gas/t //Materials @@ -598,6 +601,8 @@ enderio.gui.conduit.redstone.color=Color enderio.gui.conduit.fluid.autoExtract=Auto Extract enderio.gui.conduit.fluid.filter=Filter +enderio.gui.conduit.gas.autoExtract=Auto Extract + //Configuration enderio.config.title=Ender IO Configuration diff --git a/resources/assets/enderio/textures/blocks/gasConduit.png b/resources/assets/enderio/textures/blocks/gasConduit.png new file mode 100644 index 00000000..a19312c7 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/gasConduit.png differ diff --git a/resources/assets/enderio/textures/blocks/gasConduitCore.png b/resources/assets/enderio/textures/blocks/gasConduitCore.png new file mode 100644 index 00000000..cb770b71 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/gasConduitCore.png differ diff --git a/resources/assets/enderio/textures/blocks/gasConduitEdge.png b/resources/assets/enderio/textures/blocks/gasConduitEdge.png new file mode 100644 index 00000000..d46d17ea Binary files /dev/null and b/resources/assets/enderio/textures/blocks/gasConduitEdge.png differ diff --git a/resources/assets/enderio/textures/blocks/gasConduitInput.png b/resources/assets/enderio/textures/blocks/gasConduitInput.png new file mode 100644 index 00000000..3202f5ec Binary files /dev/null and b/resources/assets/enderio/textures/blocks/gasConduitInput.png differ diff --git a/resources/assets/enderio/textures/blocks/gasConduitOutput.png b/resources/assets/enderio/textures/blocks/gasConduitOutput.png new file mode 100644 index 00000000..a718dfa1 Binary files /dev/null and b/resources/assets/enderio/textures/blocks/gasConduitOutput.png differ diff --git a/resources/assets/enderio/textures/gui/widgets.png b/resources/assets/enderio/textures/gui/widgets.png index 6580271d..f1bb7a1a 100644 Binary files a/resources/assets/enderio/textures/gui/widgets.png and b/resources/assets/enderio/textures/gui/widgets.png differ diff --git a/resources/assets/enderio/textures/items/itemGasConduit.png b/resources/assets/enderio/textures/items/itemGasConduit.png new file mode 100644 index 00000000..cb770b71 Binary files /dev/null and b/resources/assets/enderio/textures/items/itemGasConduit.png differ diff --git a/src/api/java/mekanism/api/AdvancedInput.java b/src/api/java/mekanism/api/AdvancedInput.java new file mode 100644 index 00000000..46ede3fe --- /dev/null +++ b/src/api/java/mekanism/api/AdvancedInput.java @@ -0,0 +1,28 @@ +package mekanism.api; + +import mekanism.api.gas.Gas; + +import net.minecraft.item.ItemStack; + +public class AdvancedInput +{ + public ItemStack itemStack; + + public Gas gasType; + + public AdvancedInput(ItemStack item, Gas gas) + { + itemStack = item; + gasType = gas; + } + + public boolean isValid() + { + return itemStack != null && gasType != null; + } + + public boolean matches(AdvancedInput input) + { + return StackUtils.equalsWildcard(itemStack, input.itemStack) && input.itemStack.stackSize >= itemStack.stackSize; + } +} diff --git a/src/api/java/mekanism/api/BlockInfo.java b/src/api/java/mekanism/api/BlockInfo.java new file mode 100644 index 00000000..50c990f2 --- /dev/null +++ b/src/api/java/mekanism/api/BlockInfo.java @@ -0,0 +1,38 @@ +package mekanism.api; + +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; + +public class BlockInfo +{ + public Block block; + public int meta; + + public BlockInfo(Block b, int j) + { + block = b; + meta = j; + } + + public static BlockInfo get(ItemStack stack) + { + return new BlockInfo(Block.getBlockFromItem(stack.getItem()), stack.getItemDamage()); + } + + @Override + public boolean equals(Object obj) + { + return obj instanceof BlockInfo && + ((BlockInfo)obj).block == block && + ((BlockInfo)obj).meta == meta; + } + + @Override + public int hashCode() + { + int code = 1; + code = 31 * code + block.getUnlocalizedName().hashCode(); + code = 31 * code + meta; + return code; + } +} \ No newline at end of file diff --git a/src/api/java/mekanism/api/ChanceOutput.java b/src/api/java/mekanism/api/ChanceOutput.java new file mode 100644 index 00000000..5b3e512d --- /dev/null +++ b/src/api/java/mekanism/api/ChanceOutput.java @@ -0,0 +1,48 @@ +package mekanism.api; + +import java.util.Random; + +import net.minecraft.item.ItemStack; + +public class ChanceOutput +{ + private static Random rand = new Random(); + + public ItemStack primaryOutput; + + public ItemStack secondaryOutput; + + public double secondaryChance; + + public ChanceOutput(ItemStack primary, ItemStack secondary, double chance) + { + primaryOutput = primary; + secondaryOutput = secondary; + secondaryChance = chance; + } + + public ChanceOutput(ItemStack primary) + { + primaryOutput = primary; + } + + public boolean checkSecondary() + { + return rand.nextDouble() <= secondaryChance; + } + + public boolean hasPrimary() + { + return primaryOutput != null; + } + + public boolean hasSecondary() + { + return secondaryOutput != null; + } + + public ChanceOutput copy() + { + return new ChanceOutput(StackUtils.copy(primaryOutput), StackUtils.copy(secondaryOutput), secondaryChance); + } +} diff --git a/src/api/java/mekanism/api/ChemicalPair.java b/src/api/java/mekanism/api/ChemicalPair.java new file mode 100644 index 00000000..7c28ea0d --- /dev/null +++ b/src/api/java/mekanism/api/ChemicalPair.java @@ -0,0 +1,116 @@ +package mekanism.api; + +import mekanism.api.gas.GasStack; +import mekanism.api.gas.GasTank; + +/** + * An input of gasses for recipe use. + * @author aidancbrady + * + */ +public class ChemicalPair +{ + /** The left gas of this chemical input */ + public GasStack leftGas; + + /** The right gas of this chemical input */ + public GasStack rightGas; + + /** + * Creates a chemical input with two defined gasses. + * @param left - left gas + * @param right - right gas + */ + public ChemicalPair(GasStack left, GasStack right) + { + leftGas = left; + rightGas = right; + } + + /** + * If this is a valid ChemicalPair + * @return + */ + public boolean isValid() + { + return leftGas != null && rightGas != null; + } + + /** + * Whether or not the defined input contains the same gasses and at least the required amount of the defined gasses as this input. + * @param input - input to check + * @return if the input meets this input's requirements + */ + public boolean meetsInput(ChemicalPair input) + { + return meets(input) || meets(input.swap()); + } + + /** + * Swaps the right gas and left gas of this input. + * @return a swapped ChemicalInput + */ + public ChemicalPair swap() + { + return new ChemicalPair(rightGas, leftGas); + } + + /** + * Draws the needed amount of gas from each tank. + * @param leftTank - left tank to draw from + * @param rightTank - right tank to draw from + */ + public void draw(GasTank leftTank, GasTank rightTank) + { + if(meets(new ChemicalPair(leftTank.getGas(), rightTank.getGas()))) + { + leftTank.draw(leftGas.amount, true); + rightTank.draw(rightGas.amount, true); + } + else if(meets(new ChemicalPair(rightTank.getGas(), leftTank.getGas()))) + { + leftTank.draw(rightGas.amount, true); + rightTank.draw(leftGas.amount, true); + } + } + + /** + * Whether or not one of this ChemicalInput's GasStack entry's gas type is equal to the gas type of the given gas. + * @param stack - stack to check + * @return if the stack's gas type is contained in this ChemicalInput + */ + public boolean containsType(GasStack stack) + { + if(stack == null || stack.amount == 0) + { + return false; + } + + return stack.isGasEqual(leftGas) || stack.isGasEqual(rightGas); + } + + /** + * Actual implementation of meetsInput(), performs the checks. + * @param input - input to check + * @return if the input meets this input's requirements + */ + private boolean meets(ChemicalPair input) + { + if(input == null || !input.isValid()) + { + return false; + } + + if(input.leftGas.getGas() != leftGas.getGas() || input.rightGas.getGas() != rightGas.getGas()) + { + return false; + } + + return input.leftGas.amount >= leftGas.amount && input.rightGas.amount >= rightGas.amount; + } + + public ChemicalPair copy() + { + return new ChemicalPair(leftGas.copy(), rightGas.copy()); + } +} diff --git a/src/api/java/mekanism/api/Chunk3D.java b/src/api/java/mekanism/api/Chunk3D.java new file mode 100644 index 00000000..854be715 --- /dev/null +++ b/src/api/java/mekanism/api/Chunk3D.java @@ -0,0 +1,108 @@ +package mekanism.api; + +import net.minecraft.entity.Entity; +import net.minecraft.world.World; +import net.minecraft.world.chunk.Chunk; + +/** + * Chunk3D - an integer-based way to keep track of and perform operations on chunks in a Minecraft-based environment. This also takes + * in account the dimension the chunk is in. + * @author aidancbrady + * + */ +public class Chunk3D +{ + public int dimensionId; + + public int xCoord; + public int zCoord; + + /** + * Creates a Chunk3D object from the given x and z coordinates, as well as a dimension. + * @param x - chunk x location + * @param z - chunk z location + * @param dimension - the dimension this Chunk3D is in + */ + public Chunk3D(int x, int z, int dimension) + { + xCoord = x; + zCoord = z; + + dimensionId = dimension; + } + + /** + * Creates a Chunk3D from an entity based on it's location and dimension. + * @param entity - the entity to get the Chunk3D object from + */ + public Chunk3D(Entity entity) + { + xCoord = ((int)entity.posX) >> 4; + zCoord = ((int)entity.posZ) >> 4; + + dimensionId = entity.dimension; + } + + /** + * Creates a Chunk3D from a Coord4D based on it's coordinates and dimension. + * @param coord - the Coord4D object to get this Chunk3D from + */ + public Chunk3D(Coord4D coord) + { + xCoord = coord.xCoord >> 4; + zCoord = coord.zCoord >> 4; + + dimensionId = coord.dimensionId; + } + + /** + * Whether or not this chunk exists in the given world. + * @param world - the world to check in + * @return if the chunk exists + */ + public boolean exists(World world) + { + return world.getChunkProvider().chunkExists(xCoord, zCoord); + } + + /** + * Gets a Chunk object corresponding to this Chunk3D's coordinates. + * @param world - the world to get the Chunk object from + * @return the corresponding Chunk object + */ + public Chunk getChunk(World world) + { + return world.getChunkFromChunkCoords(xCoord, zCoord); + } + + @Override + public Coord4D clone() + { + return new Coord4D(xCoord, zCoord, dimensionId); + } + + @Override + public String toString() + { + return "[Chunk3D: " + xCoord + ", " + zCoord + ", dim=" + dimensionId + "]"; + } + + @Override + public boolean equals(Object obj) + { + return obj instanceof Chunk3D && + ((Chunk3D)obj).xCoord == xCoord && + ((Chunk3D)obj).zCoord == zCoord && + ((Chunk3D)obj).dimensionId == dimensionId; + } + + @Override + public int hashCode() + { + int code = 1; + code = 31 * code + xCoord; + code = 31 * code + zCoord; + code = 31 * code + dimensionId; + return code; + } +} diff --git a/src/api/java/mekanism/api/Coord4D.java b/src/api/java/mekanism/api/Coord4D.java new file mode 100644 index 00000000..22db2ccd --- /dev/null +++ b/src/api/java/mekanism/api/Coord4D.java @@ -0,0 +1,358 @@ +package mekanism.api; + +import io.netty.buffer.ByteBuf; + +import java.util.ArrayList; + +import net.minecraft.block.Block; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.MathHelper; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraft.world.chunk.Chunk; +import net.minecraftforge.common.util.ForgeDirection; +import cpw.mods.fml.common.network.NetworkRegistry.TargetPoint; + +/** + * Coord4D - an integer-based way to keep track of and perform operations on blocks in a Minecraft-based environment. This also takes + * in account the dimension the coordinate is in. + * @author aidancbrady + * + */ +public class Coord4D +{ + public int xCoord; + public int yCoord; + public int zCoord; + + public int dimensionId; + + /** + * Creates a Coord4D WITHOUT a dimensionId. Don't use unless absolutely necessary. + * @param x - x coordinate + * @param y - y coordinate + * @param z - z coordinate + */ + public Coord4D(int x, int y, int z) + { + xCoord = x; + yCoord = y; + zCoord = z; + + dimensionId = 0; + } + + /** + * Creates a Coord4D from the defined x, y, z, and dimension values. + * @param x - x coordinate + * @param y - y coordinate + * @param z - z coordinate + * @param dimension - dimension ID + */ + public Coord4D(int x, int y, int z, int dimension) + { + xCoord = x; + yCoord = y; + zCoord = z; + + dimensionId = dimension; + } + + /** + * Gets the metadata of the block representing this Coord4D. + * @param world - world this Coord4D is in + * @return the metadata of this Coord4D's block + */ + public int getMetadata(IBlockAccess world) + { + return world.getBlockMetadata(xCoord, yCoord, zCoord); + } + + /** + * Gets the TileEntity of the block representing this Coord4D. + * @param world - world this Coord4D is in + * @return the TileEntity of this Coord4D's block + */ + public TileEntity getTileEntity(IBlockAccess world) + { + if(world instanceof World && !exists((World)world)) + { + return null; + } + + return world.getTileEntity(xCoord, yCoord, zCoord); + } + + /** + * Gets the Block value of the block representing this Coord4D. + * @param world - world this Coord4D is in + * @return the Block value of this Coord4D's block + */ + public Block getBlock(IBlockAccess world) + { + if(world instanceof World && !exists((World)world)) + { + return null; + } + + return world.getBlock(xCoord, yCoord, zCoord); + } + + /** + * Writes this Coord4D's data to an NBTTagCompound. + * @param nbtTags - tag compound to write to + * @return the tag compound with this Coord4D's data + */ + public NBTTagCompound write(NBTTagCompound nbtTags) + { + nbtTags.setInteger("x", xCoord); + nbtTags.setInteger("y", yCoord); + nbtTags.setInteger("z", zCoord); + nbtTags.setInteger("dimensionId", dimensionId); + + return nbtTags; + } + + /** + * Writes this Coord4D's data to an ArrayList for packet transfer. + * @param data - the ArrayList to add the data to + */ + public void write(ArrayList data) + { + data.add(xCoord); + data.add(yCoord); + data.add(zCoord); + data.add(dimensionId); + } + + /** + * Writes this Coord4D's data to a ByteBuf for packet transfer. + * @param dataStream - the ByteBuf to add the data to + */ + public void write(ByteBuf dataStream) + { + dataStream.writeInt(xCoord); + dataStream.writeInt(yCoord); + dataStream.writeInt(zCoord); + dataStream.writeInt(dimensionId); + } + + /** + * Translates this Coord4D by the defined x, y, and z values. + * @param x - x value to translate + * @param y - y value to translate + * @param z - z value to translate + * @return translated Coord4D + */ + public Coord4D translate(int x, int y, int z) + { + xCoord += x; + yCoord += y; + zCoord += z; + + return this; + } + + /** + * Creates and returns a new Coord4D translated to the defined offsets of the side. + * @param side - side to translate this Coord4D to + * @return translated Coord4D + */ + public Coord4D getFromSide(ForgeDirection side) + { + return getFromSide(side, 1); + } + + public Coord4D getFromSide(ForgeDirection side, int amount) + { + return new Coord4D(xCoord+(side.offsetX*amount), yCoord+(side.offsetY*amount), zCoord+(side.offsetZ*amount), dimensionId); + } + + /** + * Returns a new Coord4D from a defined TileEntity's xCoord, yCoord and zCoord values. + * @param tileEntity - TileEntity at the location that will represent this Coord4D + * @return the Coord4D object from the TileEntity + */ + public static Coord4D get(TileEntity tileEntity) + { + return new Coord4D(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord, tileEntity.getWorldObj().provider.dimensionId); + } + + /** + * Returns a new Coord4D from a tag compound. + * @param data - tag compound to read from + * @return the Coord4D from the tag compound + */ + public static Coord4D read(NBTTagCompound tag) + { + return new Coord4D(tag.getInteger("x"), tag.getInteger("y"), tag.getInteger("z"), tag.getInteger("id")); + } + + /** + * Returns a new Coord4D from a ByteBuf. + * @param dataStream - data input to read from + * @return the Coord4D from the data input + */ + public static Coord4D read(ByteBuf dataStream) + { + return new Coord4D(dataStream.readInt(), dataStream.readInt(), dataStream.readInt(), dataStream.readInt()); + } + + /** + * Creates and returns a new Coord4D with values representing the difference between the defined Coord4D + * @param other - the Coord4D to subtract from this + * @return a Coord4D representing the distance between the defined Coord4D + */ + public Coord4D difference(Coord4D other) + { + return new Coord4D(xCoord-other.xCoord, yCoord-other.yCoord, zCoord-other.zCoord, dimensionId); + } + + /** + * A method used to find the ForgeDirection represented by the distance of the defined Coord4D. Most likely won't have many + * applicable uses. + * @param other - Coord4D to find the side difference of + * @return ForgeDirection representing the side the defined relative Coord4D is on to this + */ + public ForgeDirection sideDifference(Coord4D other) + { + Coord4D diff = difference(other); + + for(ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) + { + if(side.offsetX == diff.xCoord && side.offsetY == diff.yCoord && side.offsetZ == diff.zCoord) + { + return side; + } + } + + return ForgeDirection.UNKNOWN; + } + + /** + * Gets the distance to a defined Coord4D. + * @param obj - the Coord4D to find the distance to + * @return the distance to the defined Coord4D + */ + public int distanceTo(Coord4D obj) + { + int subX = xCoord - obj.xCoord; + int subY = yCoord - obj.yCoord; + int subZ = zCoord - obj.zCoord; + return (int)MathHelper.sqrt_double(subX * subX + subY * subY + subZ * subZ); + } + + /** + * Whether or not the defined side of this Coord4D is visible. + * @param side - side to check + * @param world - world this Coord4D is in + * @return + */ + public boolean sideVisible(ForgeDirection side, IBlockAccess world) + { + return world.isAirBlock(xCoord+side.offsetX, yCoord+side.offsetY, zCoord+side.offsetZ); + } + + /** + * Gets a TargetPoint with the defined range from this Coord4D with the appropriate coordinates and dimension ID. + * @param range - the range the packet can be sent in of this Coord4D + * @return TargetPoint relative to this Coord4D + */ + public TargetPoint getTargetPoint(double range) + { + return new TargetPoint(dimensionId, xCoord, yCoord, zCoord, range); + } + + /** + * Steps this Coord4D in the defined side's offset without creating a new value. + * @param side - side to step towards + * @return this Coord4D + */ + public Coord4D step(ForgeDirection side) + { + return translate(side.offsetX, side.offsetY, side.offsetZ); + } + + /** + * Whether or not the chunk this Coord4D is in exists and is loaded. + * @param world - world this Coord4D is in + * @return the chunk of this Coord4D + */ + public boolean exists(World world) + { + return world.getChunkProvider().chunkExists(xCoord >> 4, zCoord >> 4); + } + + /** + * Gets the chunk this Coord4D is in. + * @param world - world this Coord4D is in + * @return the chunk of this Coord4D + */ + public Chunk getChunk(World world) + { + return world.getChunkFromBlockCoords(xCoord, zCoord); + } + + /** + * Gets the Chunk3D object with chunk coordinates correlating to this Coord4D's location + * @return Chunk3D with correlating chunk coordinates. + */ + public Chunk3D getChunk3D() + { + return new Chunk3D(this); + } + + /** + * Whether or not the block this Coord4D represents is an air block. + * @param world - world this Coord4D is in + * @return if this Coord4D is an air block + */ + public boolean isAirBlock(IBlockAccess world) + { + return world.isAirBlock(xCoord, yCoord, zCoord); + } + + /** + * Gets a bounding box that contains the area this Coord4D would take up in a world. + * @return this Coord4D's bounding box + */ + public AxisAlignedBB getBoundingBox() + { + return AxisAlignedBB.getBoundingBox(xCoord, yCoord, zCoord, xCoord+1, yCoord+1, zCoord+1); + } + + @Override + public Coord4D clone() + { + return new Coord4D(xCoord, yCoord, zCoord, dimensionId); + } + + @Override + public String toString() + { + return "[Coord4D: " + xCoord + ", " + yCoord + ", " + zCoord + ", dim=" + dimensionId + "]"; + } + + @Override + public boolean equals(Object obj) + { + return obj instanceof Coord4D && + ((Coord4D)obj).xCoord == xCoord && + ((Coord4D)obj).yCoord == yCoord && + ((Coord4D)obj).zCoord == zCoord && + ((Coord4D)obj).dimensionId == dimensionId; + } + + @Override + public int hashCode() + { + int code = 1; + code = 31 * code + xCoord; + code = 31 * code + yCoord; + code = 31 * code + zCoord; + code = 31 * code + dimensionId; + return code; + } +} \ No newline at end of file diff --git a/src/api/java/mekanism/api/EnumColor.java b/src/api/java/mekanism/api/EnumColor.java new file mode 100644 index 00000000..5c1351e9 --- /dev/null +++ b/src/api/java/mekanism/api/EnumColor.java @@ -0,0 +1,112 @@ +package mekanism.api; + +import net.minecraft.util.StatCollector; + +/** + * Simple color enum for adding colors to in-game GUI strings of text. + * @author AidanBrady + * + */ +public enum EnumColor +{ + BLACK("\u00a70", "black", "Black", new int[] {0, 0, 0}, 0), + DARK_BLUE("\u00a71", "darkBlue", "Blue", new int[] {0, 0, 170}, 4), + DARK_GREEN("\u00a72", "darkGreen", "Green", new int[] {0, 170, 0}, 2), + DARK_AQUA("\u00a73", "darkAqua", "Cyan", new int[] {0, 170, 170}, 6), + DARK_RED("\u00a74", "darkRed", null, new int[] {170, 0, 0}, -1), + PURPLE("\u00a75", "purple", "Purple", new int[] {170, 0, 170}, 5), + ORANGE("\u00a76", "orange", "Orange", new int[] {255, 170, 0}, 14), + GREY("\u00a77", "grey", "LightGray", new int[] {170, 170, 170}, 7), + DARK_GREY("\u00a78", "darkGrey", "Gray", new int[] {85, 85, 85}, 8), + INDIGO("\u00a79", "indigo", "LightBlue", new int[] {85, 85, 255}, 12), + BRIGHT_GREEN("\u00a7a", "brightGreen", "Lime", new int[] {85, 255, 85}, 10), + AQUA("\u00a7b", "aqua", null, new int[] {85, 255, 255}, -1), + RED("\u00a7c", "red", "Red", new int[] {255, 0, 0}, 1), + PINK("\u00a7d", "pink", "Magenta", new int[] {255, 85, 255}, 13), + YELLOW("\u00a7e", "yellow", "Yellow", new int[] {255, 255, 85}, 11), + WHITE("\u00a7f", "white", "White", new int[] {255, 255, 255}, 15), + //Extras for dye-completeness + BROWN("\u00a76", "brown", "Brown", new int[] {150, 75, 0}, 3), + BRIGHT_PINK("\u00a7d", "brightPink", "Pink", new int[] {255, 192, 203}, 9); + + public static EnumColor[] DYES = new EnumColor[] {BLACK, RED, DARK_GREEN, BROWN, DARK_BLUE, PURPLE, DARK_AQUA, GREY, DARK_GREY, BRIGHT_PINK, BRIGHT_GREEN, YELLOW, INDIGO, PINK, ORANGE, WHITE}; + + /** The color code that will be displayed */ + public final String code; + + public final int[] rgbCode; + + public final int mcMeta; + + /** A friendly name of the color. */ + public String unlocalizedName; + + public String dyeName; + + private EnumColor(String s, String n, String dye, int[] rgb, int meta) + { + code = s; + unlocalizedName = n; + dyeName = dye; + rgbCode = rgb; + mcMeta = meta; + } + + /** + * Gets the localized name of this color by translating the unlocalized name. + * @return localized name + */ + public String getLocalizedName() + { + return StatCollector.translateToLocal("color." + unlocalizedName); + } + + public String getDyeName() + { + return StatCollector.translateToLocal("dye." + unlocalizedName); + } + + public String getOreDictName() + { + return dyeName; + } + + /** + * Gets the name of this color with it's color prefix code. + * @return the color's name and color prefix + */ + public String getName() + { + return code + getLocalizedName(); + } + + public String getDyedName() + { + return code + getDyeName(); + } + + /** + * Gets the 0-1 of this color's RGB value by dividing by 255 (used for OpenGL coloring). + * @param index - R:0, G:1, B:2 + * @return the color value + */ + public float getColor(int index) + { + return (float)rgbCode[index]/255F; + } + + /** + * Gets the value of this color mapped to MC in-game item colors present in dyes and wool. + * @return mc meta value + */ + public int getMetaValue() + { + return mcMeta; + } + + @Override + public String toString() + { + return code; + } +} diff --git a/src/api/java/mekanism/api/IClientTicker.java b/src/api/java/mekanism/api/IClientTicker.java new file mode 100644 index 00000000..22889737 --- /dev/null +++ b/src/api/java/mekanism/api/IClientTicker.java @@ -0,0 +1,8 @@ +package mekanism.api; + +public interface IClientTicker +{ + public void clientTick(); + + public boolean needsTicks(); +} diff --git a/src/api/java/mekanism/api/IConfigurable.java b/src/api/java/mekanism/api/IConfigurable.java new file mode 100644 index 00000000..512fabf4 --- /dev/null +++ b/src/api/java/mekanism/api/IConfigurable.java @@ -0,0 +1,27 @@ +package mekanism.api; + +import net.minecraft.entity.player.EntityPlayer; + +/** + * Implement this in your TileEntity class if your block can be modified by a Configurator. + * @author aidancbrady + * + */ +public interface IConfigurable +{ + /** + * Called when a player shift-right clicks this block with a Configurator. + * @param player - the player who clicked the block + * @param side - the side the block was clicked on + * @return whether or not an action was performed + */ + public boolean onSneakRightClick(EntityPlayer player, int side); + + /** + * Called when a player right clicks this block with a Configurator. + * @param player - the player who clicked the block + * @param side - the side the block was clicked on + * @return whether or not an action was performed + */ + public boolean onRightClick(EntityPlayer player, int side); +} diff --git a/src/api/java/mekanism/api/IFilterAccess.java b/src/api/java/mekanism/api/IFilterAccess.java new file mode 100644 index 00000000..abdcf29a --- /dev/null +++ b/src/api/java/mekanism/api/IFilterAccess.java @@ -0,0 +1,31 @@ +package mekanism.api; + +import net.minecraft.nbt.NBTTagCompound; + +/** + * Implement this in your TileEntity class if you wish for Mekanism filters to be able to store any of their + * information. + * @author aidancbrady + * + */ +public interface IFilterAccess +{ + /** + * Collects the TileEntity's filter card data into the parameterized NBTTagCompound. + * @param nbtTags - the NBTTagCompound of the filter card ItemStack + * @return the NBTTagCompound that now contains the TileEntity's filter card data + */ + public NBTTagCompound getFilterData(NBTTagCompound nbtTags); + + /** + * Retrieves the TileEntity's data contained in the filter card based on the given NBTTagCompopund. + * @param nbtTags - the NBTTagCompound of the filter card ItemStack + */ + public void setFilterData(NBTTagCompound nbtTags); + + /** + * A String name of this TileEntity that will be displayed as the type of data on the filter card. + * @return the String name of this TileEntity + */ + public String getDataType(); +} diff --git a/src/api/java/mekanism/api/ISalinationSolar.java b/src/api/java/mekanism/api/ISalinationSolar.java new file mode 100644 index 00000000..20e3e1ec --- /dev/null +++ b/src/api/java/mekanism/api/ISalinationSolar.java @@ -0,0 +1,11 @@ +package mekanism.api; + +/** + * Implement this class in a TileEntity if you wish for it to be able to heat up a Salination Plant. + * @author aidancbrady + * + */ +public interface ISalinationSolar +{ + public boolean seesSun(); +} diff --git a/src/api/java/mekanism/api/ItemInfo.java b/src/api/java/mekanism/api/ItemInfo.java new file mode 100644 index 00000000..2c45f0cf --- /dev/null +++ b/src/api/java/mekanism/api/ItemInfo.java @@ -0,0 +1,38 @@ +package mekanism.api; + +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; + +public class ItemInfo +{ + public Item item; + public int meta; + + public ItemInfo(Item i, int j) + { + item = i; + meta = j; + } + + public static ItemInfo get(ItemStack stack) + { + return new ItemInfo(stack.getItem(), stack.getItemDamage()); + } + + @Override + public boolean equals(Object obj) + { + return obj instanceof BlockInfo && + ((ItemInfo)obj).item == item && + ((ItemInfo)obj).meta == meta; + } + + @Override + public int hashCode() + { + int code = 1; + code = 31 * code + item.getUnlocalizedName().hashCode(); + code = 31 * code + meta; + return code; + } +} diff --git a/src/api/java/mekanism/api/ItemRetriever.java b/src/api/java/mekanism/api/ItemRetriever.java new file mode 100644 index 00000000..a66b8b5b --- /dev/null +++ b/src/api/java/mekanism/api/ItemRetriever.java @@ -0,0 +1,71 @@ +package mekanism.api; + +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; + +/** + * Use this class's 'getItem()' method to retrieve ItemStacks from the 'Mekanism' + * class. + * @author AidanBrady + * + */ +public final class ItemRetriever +{ + /** The 'Mekanism' class that items and blocks are retrieved from. */ + private static Class Mekanism; + + /** + * Attempts to retrieve an ItemStack of an item or block with the declared identifier. + * + * Mekanism identifiers follow an easy-to-remember pattern. All identifiers + * are identical to the String returned by 'getItemName().' None include spaces, + * and all start with a capital letter. The name that shows up in-game can be + * stripped down to identifier form by removing spaces and all non-alphabetic + * characters (,./'=-_). Below is an example: + * + * ItemStack enrichedAlloy = ItemRetriever.getItem("EnrichedAlloy"); + * + * The same also works for blocks. + * + * ItemStack refinedObsidian = ItemRetriever.getItem("RefinedObsidian"); + * + * Note that for items or blocks that have specific metadata you will need to create + * a new ItemStack with that specified value, as this will only return an ItemStack + * with the meta value '0.' + * + * Make sure you run this in or after FMLPostInitializationEvent runs, because most + * items are registered when FMLInitializationEvent runs. However, some items ARE + * registered later in order to hook into other mods. In a rare circumstance you may + * have to add "after:Mekanism" in the @Mod 'dependencies' annotation. + * + * @param identifier - a String to be searched in the 'Mekanism' class + * @return an ItemStack of the declared identifier, otherwise null. + */ + public static ItemStack getItem(String identifier) + { + try { + if(Mekanism == null) + { + Mekanism = Class.forName("mekanism.common.Mekanism"); + } + + Object ret = Mekanism.getField(identifier).get(null); + + if(ret instanceof Item) + { + return new ItemStack((Item)ret, 1); + } + else if(ret instanceof Block) + { + return new ItemStack((Block)ret, 1); + } + else { + return null; + } + } catch(Exception e) { + System.err.println("Error retrieving item with identifier '" + identifier + "': " + e.getMessage()); + return null; + } + } +} diff --git a/src/api/java/mekanism/api/ListUtils.java b/src/api/java/mekanism/api/ListUtils.java new file mode 100644 index 00000000..fb319cee --- /dev/null +++ b/src/api/java/mekanism/api/ListUtils.java @@ -0,0 +1,282 @@ +package mekanism.api; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; + +public class ListUtils +{ + public static List inverse(List list) + { + List toReturn = new ArrayList(); + + for(int i = list.size() - 1; i >= 0; i--) + { + toReturn.add(list.get(i)); + } + + return toReturn; + } + + public static List cap(List list, int cap) + { + List toReturn = new ArrayList(); + + if(list.size() <= cap) + { + toReturn = copy(list); + } + else { + int count = 0; + + for(V obj : list) + { + count++; + + toReturn.add(obj); + + if(count == cap) + { + break; + } + } + } + + return toReturn; + } + + public static List copy(List list) + { + List toReturn = new ArrayList(); + + for(V obj : list) + { + toReturn.add(obj); + } + + return toReturn; + } + + public static List merge(List listOne, List listTwo) + { + List newList = new ArrayList(); + + for(V obj : listOne) + { + newList.add(obj); + } + + for(V obj : listTwo) + { + newList.add(obj); + } + + return newList; + } + + public static List capRemains(List list, int cap) + { + List toReturn = new ArrayList(); + + if(list.size() <= cap) + { + return toReturn; + } + else { + List inverse = inverse(list); + + int iterNeeded = list.size() - cap; + int count = 0; + + for(V obj : list) + { + count++; + + toReturn.add(obj); + + if(count == iterNeeded) + { + break; + } + } + + return toReturn; + } + } + + public static ArrayList> split(List list, int divide) + { + int remain = list.size() % divide; + int size = (list.size() - remain) / divide; + + ArrayList> toReturn = new ArrayList>(); + + for(int i = 0; i < divide; i++) + { + toReturn.add(i, new ArrayList()); + } + + for(List iterSet : toReturn) + { + List removed = new ArrayList(); + + int toAdd = size; + + if(remain > 0) + { + remain--; + toAdd++; + } + + for(V obj : list) + { + if(toAdd == 0) + { + break; + } + + iterSet.add(obj); + removed.add(obj); + toAdd--; + } + + for(V obj : removed) + { + list.remove(obj); + } + } + + return toReturn; + } + + public static V getTop(List list) + { + for(V obj : list) + { + return obj; + } + + return null; + } + + public static List asList(Set set) + { + return (List)Arrays.asList(set.toArray()); + } + + public static List asList(V... values) + { + return (List)Arrays.asList(values); + } + + public static double[] splitDouble(int size, double num) + { + double[] split = new double[size]; + + for(int i = 0; i < size; i++) + { + double remain = num%size; + double ret = (num-remain)/size; + ret += remain; + + split[i] = ret; + num -= remain; + } + + return split; + } + + public static double[] percent(double[] values) + { + double[] ret = new double[values.length]; + double total = 0; + + for(double d : values) total += d; + + for(int i = 0; i < values.length; i++) + { + ret[i] = values[i]/total; + } + + return ret; + } + + public static int[] calcPercentInt(double[] percent, int val) + { + int[] ret = new int[percent.length]; + + for(int i = 0; i < percent.length; i++) + { + ret[i] = (int)Math.round(val*percent[i]); + } + + int newTotal = 0; + for(int i : ret) newTotal += i; + + int diff = val-newTotal; + + if(diff != val) + { + for(int i = 0; i < ret.length; i++) + { + int num = ret[i]; + + if(diff < 0 && num == 0) + { + continue; + } + + if(diff > 0) + { + ret[i]++; + diff--; + } + else if(diff < 0) + { + ret[i]--; + diff++; + } + + if(diff == 0) + { + return ret; + } + } + } + + return ret; + } + + public static int[] splitInt(int size, int num) + { + int[] split = new int[size]; + + for(int i = 0; i < size; i++) + { + int remain = num%size; + int ret = (num-remain)/size; + ret += remain; + + split[i] = ret; + num -= remain; + } + + return split; + } + + public static double[] percent(int[] values) + { + double[] ret = new double[values.length]; + double total = 0; + + for(double d : values) total += d; + + for(int i = 0; i < values.length; i++) + { + ret[i] = values[i]/total; + } + + return ret; + } +} diff --git a/src/api/java/mekanism/api/MekanismAPI.java b/src/api/java/mekanism/api/MekanismAPI.java new file mode 100644 index 00000000..4f4cef4a --- /dev/null +++ b/src/api/java/mekanism/api/MekanismAPI.java @@ -0,0 +1,45 @@ +package mekanism.api; + +import java.util.HashSet; +import java.util.Set; + +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import cpw.mods.fml.common.eventhandler.Event; +import net.minecraftforge.oredict.OreDictionary; + +public class MekanismAPI +{ + //Add a BlockInfo value here if you don't want a certain block to be picked up by cardboard boxes + private static Set cardboardBoxIgnore = new HashSet(); + + public static boolean isBlockCompatible(Item item, int meta) + { + for(BlockInfo i : cardboardBoxIgnore) + { + if(i.block == Block.getBlockFromItem(item) && (i.meta == OreDictionary.WILDCARD_VALUE || i.meta == meta)) + { + return false; + } + } + + return true; + } + + public static void addBoxBlacklist(Block block, int meta) + { + cardboardBoxIgnore.add(new BlockInfo(block, meta)); + } + + public static void removeBoxBlacklist(Block block, int meta) + { + cardboardBoxIgnore.remove(new BlockInfo(block, meta)); + } + + public static Set getBoxIgnore() + { + return cardboardBoxIgnore; + } + + public static class BoxBlacklistEvent extends Event {} +} diff --git a/src/api/java/mekanism/api/Pos3D.java b/src/api/java/mekanism/api/Pos3D.java new file mode 100644 index 00000000..aa4ae089 --- /dev/null +++ b/src/api/java/mekanism/api/Pos3D.java @@ -0,0 +1,191 @@ +package mekanism.api; + +import net.minecraft.entity.Entity; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.MathHelper; + +/** + * Pos3D - a way of performing operations on objects in a three dimensional environment. + * @author aidancbrady + * + */ +public class Pos3D +{ + public double xPos; + public double yPos; + public double zPos; + + public Pos3D() + { + this(0, 0, 0); + } + + public Pos3D(double x, double y, double z) + { + xPos = x; + yPos = y; + zPos = z; + } + + public Pos3D(Coord4D coord) + { + xPos = coord.xCoord; + yPos = coord.yCoord; + zPos = coord.zCoord; + } + + /** + * Creates a Pos3D with an entity's posX, posY, and posZ values. + * @param entity - entity to create the Pos3D from + */ + public Pos3D(Entity entity) + { + this(entity.posX, entity.posY, entity.posZ); + } + + /** + * Creates a Pos3D with a TileEntity's xCoord, yCoord and zCoord values. + * @param tileEntity - TileEntity to create the Pos3D from + */ + public Pos3D(TileEntity tileEntity) + { + this(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord); + } + + /** + * Creates and returns a Pos3D with values representing the difference between this and the Pos3D in the parameters. + * @param pos - Pos3D to subtract + * @return difference of the two Pos3Ds + */ + public Pos3D diff(Pos3D pos) + { + return new Pos3D(xPos-pos.xPos, yPos-pos.yPos, zPos-pos.zPos); + } + + /** + * Creates a new Pos3D from the motion of an entity. + * @param entity + * @return + */ + public static Pos3D fromMotion(Entity entity) + { + return new Pos3D(entity.motionX, entity.motionY, entity.motionZ); + } + + /** + * Translates this Pos3D by the defined values. + * @param x - amount to translate on the x axis + * @param y - amount to translate on the y axis + * @param z - amount to translate on the z axis + * @return the translated Pos3D + */ + public Pos3D translate(double x, double y, double z) + { + xPos += x; + yPos += y; + zPos += z; + + return this; + } + + /** + * Performs the same operation as translate(x, y, z), but with a Pos3D value instead. + * @param pos - Pos3D value to translate by + * @return translated Pos3D + */ + public Pos3D translate(Pos3D pos) + { + return translate(pos.xPos, pos.yPos, pos.zPos); + } + + /** + * Returns the distance between this and the defined Pos3D. + * @param pos - the Pos3D to find the distance to + * @return the distance between this and the defined Pos3D + */ + public double distance(Pos3D pos) + { + double subX = xPos - pos.xPos; + double subY = yPos - pos.yPos; + double subZ = zPos - pos.zPos; + return MathHelper.sqrt_double(subX * subX + subY * subY + subZ * subZ); + } + + /** + * Rotates this Pos3D by the defined yaw value. + * @param yaw - yaw to rotate by + * @return rotated Pos3D + */ + public Pos3D rotateYaw(double yaw) + { + double yawRadians = Math.toRadians(yaw); + + double x = xPos; + double z = zPos; + + if(yaw != 0) + { + xPos = x * Math.cos(yawRadians) - z * Math.sin(yawRadians); + zPos = x * Math.sin(yawRadians) + z * Math.cos(yawRadians); + } + + return this; + } + + /** + * Scales this Pos3D by the defined x, y, an z values. + * @param x - x value to scale by + * @param y - y value to scale by + * @param z - z value to scale by + * @return scaled Pos3D + */ + public Pos3D scale(double x, double y, double z) + { + xPos *= x; + yPos *= y; + zPos *= z; + + return this; + } + + /** + * Performs the same operation as scale(x, y, z), but with a value representing all three dimensions. + * @param scale - value to scale by + * @return scaled Pos3D + */ + public Pos3D scale(double scale) + { + return scale(scale, scale, scale); + } + + @Override + public Pos3D clone() + { + return new Pos3D(xPos, yPos, zPos); + } + + @Override + public String toString() + { + return "[Pos3D: " + xPos + ", " + yPos + ", " + zPos + "]"; + } + + @Override + public boolean equals(Object obj) + { + return obj instanceof Pos3D && + ((Pos3D)obj).xPos == xPos && + ((Pos3D)obj).yPos == yPos && + ((Pos3D)obj).zPos == zPos; + } + + @Override + public int hashCode() + { + int code = 1; + code = 31 * code + new Double(xPos).hashCode(); + code = 31 * code + new Double(yPos).hashCode(); + code = 31 * code + new Double(zPos).hashCode(); + return code; + } +} diff --git a/src/api/java/mekanism/api/PressurizedProducts.java b/src/api/java/mekanism/api/PressurizedProducts.java new file mode 100644 index 00000000..830fc55a --- /dev/null +++ b/src/api/java/mekanism/api/PressurizedProducts.java @@ -0,0 +1,50 @@ +package mekanism.api; + +import mekanism.api.gas.GasStack; +import mekanism.api.gas.GasTank; + +import net.minecraft.item.ItemStack; + +public class PressurizedProducts +{ + private ItemStack itemOutput; + private GasStack gasOutput; + + public PressurizedProducts(ItemStack item, GasStack gas) + { + itemOutput = item; + gasOutput = gas; + } + + public void fillTank(GasTank tank) + { + tank.receive(gasOutput, true); + } + + public void addProducts(ItemStack[] inventory, int index) + { + if(inventory[index] == null) + { + inventory[index] = itemOutput.copy(); + } + else if(inventory[index].isItemEqual(itemOutput)) + { + inventory[index].stackSize += itemOutput.stackSize; + } + } + + public ItemStack getItemOutput() + { + return itemOutput; + } + + public GasStack getGasOutput() + { + return gasOutput; + } + + public PressurizedProducts copy() + { + return new PressurizedProducts(itemOutput.copy(), gasOutput.copy()); + } +} diff --git a/src/api/java/mekanism/api/PressurizedReactants.java b/src/api/java/mekanism/api/PressurizedReactants.java new file mode 100644 index 00000000..d0c3ac8d --- /dev/null +++ b/src/api/java/mekanism/api/PressurizedReactants.java @@ -0,0 +1,139 @@ +package mekanism.api; + +import mekanism.api.gas.GasStack; +import mekanism.api.gas.GasTank; + +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTank; + +/** + * An input of a gas, a fluid and an item for the pressurized reaction chamber + */ +public class PressurizedReactants +{ + private ItemStack theSolid; + private FluidStack theFluid; + private GasStack theGas; + + public PressurizedReactants(ItemStack solid, FluidStack fluid, GasStack gas) + { + theSolid = solid; + theFluid = fluid; + theGas = gas; + } + + /** + * If this is a valid PressurizedReactants + */ + public boolean isValid() + { + return theSolid != null && theFluid != null && theGas != null; + } + + /** + * Draws the needed amount of gas from each tank. + * @param item - ItemStack to draw from + * @param fluidTank - fluid tank to draw from + * @param gasTank - gas tank to draw from + */ + public void use(ItemStack item, FluidTank fluidTank, GasTank gasTank) + { + if(meets(new PressurizedReactants(item, fluidTank.getFluid(), gasTank.getGas()))) + { + item.stackSize -= theSolid.stackSize; + fluidTank.drain(theFluid.amount, true); + gasTank.draw(theGas.amount, true); + } + } + + /** + * Whether or not this PressurizedReactants's ItemStack entry's item type is equal to the item type of the given item. + * @param stack - stack to check + * @return if the stack's item type is contained in this PressurizedReactants + */ + public boolean containsType(ItemStack stack) + { + if(stack == null || stack.stackSize == 0) + { + return false; + } + + return StackUtils.equalsWildcard(stack, theSolid); + } + + /** + * Whether or not this PressurizedReactants's FluidStack entry's fluid type is equal to the fluid type of the given fluid. + * @param stack - stack to check + * @return if the stack's fluid type is contained in this PressurizedReactants + */ + public boolean containsType(FluidStack stack) + { + if(stack == null || stack.amount == 0) + { + return false; + } + + return stack.isFluidEqual(theFluid); + } + + /** + * Whether or not this PressurizedReactants's GasStack entry's gas type is equal to the gas type of the given gas. + * @param stack - stack to check + * @return if the stack's gas type is contained in this PressurizedReactants + */ + public boolean containsType(GasStack stack) + { + if(stack == null || stack.amount == 0) + { + return false; + } + + return stack.isGasEqual(theGas); + } + + public boolean meetsInput(ItemStack itemStack, FluidStack fluidStack, GasStack gasStack) + { + return meets(new PressurizedReactants(itemStack, fluidStack, gasStack)); + } + + /** + * Actual implementation of meetsInput(), performs the checks. + * @param input - input to check + * @return if the input meets this input's requirements + */ + private boolean meets(PressurizedReactants input) + { + if(input == null || !input.isValid()) + { + return false; + } + + if(!(StackUtils.equalsWildcard(input.theSolid, theSolid) && input.theFluid.isFluidEqual(theFluid) && input.theGas.isGasEqual(theGas))) + { + return false; + } + + return input.theSolid.stackSize >= theSolid.stackSize && input.theFluid.amount >= theFluid.amount && input.theGas.amount >= theGas.amount; + } + + public PressurizedReactants copy() + { + return new PressurizedReactants(theSolid.copy(), theFluid.copy(), theGas.copy()); + } + + public ItemStack getSolid() + { + return theSolid; + } + + public FluidStack getFluid() + { + return theFluid; + } + + public GasStack getGas() + { + return theGas; + } +} diff --git a/src/api/java/mekanism/api/PressurizedRecipe.java b/src/api/java/mekanism/api/PressurizedRecipe.java new file mode 100644 index 00000000..d0572bda --- /dev/null +++ b/src/api/java/mekanism/api/PressurizedRecipe.java @@ -0,0 +1,25 @@ +package mekanism.api; + +public class PressurizedRecipe +{ + public PressurizedReactants reactants; + + public double extraEnergy; + + public PressurizedProducts products; + + public int ticks; + + public PressurizedRecipe(PressurizedReactants pressurizedReactants, double energy, PressurizedProducts pressurizedProducts, int duration) + { + reactants = pressurizedReactants; + extraEnergy = energy; + products = pressurizedProducts; + ticks = duration; + } + + public PressurizedRecipe copy() + { + return new PressurizedRecipe(reactants.copy(), extraEnergy, products.copy(), ticks); + } +} diff --git a/src/api/java/mekanism/api/Range4D.java b/src/api/java/mekanism/api/Range4D.java new file mode 100644 index 00000000..a8071ddf --- /dev/null +++ b/src/api/java/mekanism/api/Range4D.java @@ -0,0 +1,110 @@ +package mekanism.api; + +import net.minecraft.entity.player.EntityPlayer; +import cpw.mods.fml.common.FMLCommonHandler; + +public class Range4D +{ + public int dimensionId; + + public int xMin; + public int yMin; + public int zMin; + public int xMax; + public int yMax; + public int zMax; + + public Range4D(int minX, int minY, int minZ, int maxX, int maxY, int maxZ, int dimension) + { + xMin = minX; + yMin = minY; + zMin = minZ; + xMax = maxX; + yMax = maxY; + zMax = maxZ; + + dimensionId = dimension; + } + + public Range4D(Chunk3D chunk) + { + xMin = chunk.xCoord*16; + yMin = 0; + zMin = chunk.zCoord*16; + xMax = xMin+16; + yMax = 255; + zMax = zMin+16; + } + + public Range4D(Coord4D coord) + { + xMin = coord.xCoord; + yMin = coord.yCoord; + zMin = coord.zCoord; + + xMax = coord.xCoord+1; + yMax = coord.yCoord+1; + zMax = coord.zCoord+1; + } + + public static Range4D getChunkRange(EntityPlayer player) + { + int radius = FMLCommonHandler.instance().getMinecraftServerInstance().getConfigurationManager().getViewDistance(); + + return new Range4D(new Chunk3D(player)).expandChunks(radius); + } + + public Range4D expandChunks(int chunks) + { + xMin -= chunks*16; + xMax += chunks*16; + zMin -= chunks*16; + zMax += chunks*16; + + return this; + } + + public boolean intersects(Range4D range) + { + return (xMax+1 - 1.E-05D > range.xMin) && (range.xMax+1 - 1.E-05D > xMin) && (yMax+1 - 1.E-05D > range.yMin) && (range.yMax+1 - 1.E-05D > yMin) && (zMax+1 - 1.E-05D > range.zMin) && (range.zMax+1 - 1.E-05D > zMin); + } + + @Override + public Range4D clone() + { + return new Range4D(xMin, yMin, zMin, xMax, yMax, zMax, dimensionId); + } + + @Override + public String toString() + { + return "[Range4D: " + xMin + ", " + yMin + ", " + zMin + ", " + xMax + ", " + yMax + ", " + zMax + ", dim=" + dimensionId + "]"; + } + + @Override + public boolean equals(Object obj) + { + return obj instanceof Range4D && + ((Range4D)obj).xMin == xMin && + ((Range4D)obj).yMin == yMin && + ((Range4D)obj).zMin == zMin && + ((Range4D)obj).xMax == xMax && + ((Range4D)obj).yMax == yMax && + ((Range4D)obj).zMax == zMax && + ((Range4D)obj).dimensionId == dimensionId; + } + + @Override + public int hashCode() + { + int code = 1; + code = 31 * code + xMin; + code = 31 * code + yMin; + code = 31 * code + zMin; + code = 31 * code + xMax; + code = 31 * code + yMax; + code = 31 * code + zMax; + code = 31 * code + dimensionId; + return code; + } +} diff --git a/src/api/java/mekanism/api/RecipeHelper.java b/src/api/java/mekanism/api/RecipeHelper.java new file mode 100644 index 00000000..6e27c0cd --- /dev/null +++ b/src/api/java/mekanism/api/RecipeHelper.java @@ -0,0 +1,258 @@ +package mekanism.api; + +import java.lang.reflect.Method; + +import mekanism.api.gas.GasStack; +import mekanism.api.infuse.InfusionInput; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidStack; + +/** + * Use this handy class to add recipes to Mekanism machinery. + * @author AidanBrady + * + */ +public final class RecipeHelper +{ + /** + * Add an Enrichment Chamber recipe. + * @param input - input ItemStack + * @param output - output ItemStack + */ + public static void addEnrichmentChamberRecipe(ItemStack input, ItemStack output) + { + try { + Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); + Method m = recipeClass.getMethod("addEnrichmentChamberRecipe", ItemStack.class, ItemStack.class); + m.invoke(null, input, output); + } catch(Exception e) { + System.err.println("Error while adding recipe: " + e.getMessage()); + } + } + + /** + * Add an Osmium Compressor recipe. + * @param input - input ItemStack + * @param output - output ItemStack + */ + public static void addOsmiumCompressorRecipe(ItemStack input, ItemStack output) + { + try { + Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); + Method m = recipeClass.getMethod("addOsmiumCompressorRecipe", ItemStack.class, ItemStack.class); + m.invoke(null, input, output); + } catch(Exception e) { + System.err.println("Error while adding recipe: " + e.getMessage()); + } + } + + /** + * Add a Combiner recipe. + * @param input - input ItemStack + * @param output - output ItemStack + */ + public static void addCombinerRecipe(ItemStack input, ItemStack output) + { + try { + Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); + Method m = recipeClass.getMethod("addCombinerRecipe", ItemStack.class, ItemStack.class); + m.invoke(null, input, output); + } catch(Exception e) { + System.err.println("Error while adding recipe: " + e.getMessage()); + } + } + + /** + * Add a Crusher recipe. + * @param input - input ItemStack + * @param output - output ItemStack + */ + public static void addCrusherRecipe(ItemStack input, ItemStack output) + { + try { + Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); + Method m = recipeClass.getMethod("addCrusherRecipe", ItemStack.class, ItemStack.class); + m.invoke(null, input, output); + } catch(Exception e) { + System.err.println("Error while adding recipe: " + e.getMessage()); + } + } + + /** + * Add a Purification Chamber recipe. + * @param input - input ItemStack + * @param output - output ItemStack + */ + public static void addPurificationChamberRecipe(ItemStack input, ItemStack output) + { + try { + Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); + Method m = recipeClass.getMethod("addPurificationChamberRecipe", ItemStack.class, ItemStack.class); + m.invoke(null, input, output); + } catch(Exception e) { + System.err.println("Error while adding recipe: " + e.getMessage()); + } + } + + /** + * Add a Chemical Oxidizer recipe. + * @param input - input ItemStack + * @param output - output GasStack + */ + public static void addChemicalOxidizerRecipe(ItemStack input, GasStack output) + { + try { + Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); + Method m = recipeClass.getMethod("addChemicalOxidizerRecipe", ItemStack.class, GasStack.class); + m.invoke(null, input, output); + } catch(Exception e) { + System.err.println("Error while adding recipe: " + e.getMessage()); + } + } + + /** + * Add a Chemical Infuser recipe. + * @param input - input ChemicalInput + * @param output - output GasStack + */ + public static void addChemicalInfuserRecipe(ChemicalPair input, GasStack output) + { + try { + Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); + Method m = recipeClass.getMethod("addChemicalInfuserRecipe", ChemicalPair.class, GasStack.class); + m.invoke(null, input, output); + } catch(Exception e) { + System.err.println("Error while adding recipe: " + e.getMessage()); + } + } + + /** + * Add a Precision Sawmill recipe. + * @param input - input ItemStack + * @param output - output ChanceOutput + */ + public static void addPrecisionSawmillRecipe(ItemStack input, ChanceOutput output) + { + try { + Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); + Method m = recipeClass.getMethod("addPrecisionSawmillRecipe", ItemStack.class, ChanceOutput.class); + m.invoke(null, input, output); + } catch(Exception e) { + System.err.println("Error while adding recipe: " + e.getMessage()); + } + } + + /** + * Add a Chemical Injection Chamber recipe. + * @param input - input AdvancedInput + * @param output - output ItemStack + */ + public static void addChemicalInjectionChamberRecipe(AdvancedInput input, ItemStack output) + { + try { + Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); + Method m = recipeClass.getMethod("addChemicalInjectionChamberRecipe", AdvancedInput.class, ItemStack.class); + m.invoke(null, input, output); + } catch(Exception e) { + System.err.println("Error while adding recipe: " + e.getMessage()); + } + } + + /** + * Add an Electrolytic Separator recipe. + * @param input - input FluidStack + * @param output - output ChemicalPair + */ + public static void addElectrolyticSeparatorRecipe(FluidStack input, ChemicalPair output) + { + try { + Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); + Method m = recipeClass.getMethod("addElectrolyticSeparatorRecipe", FluidStack.class, ChemicalPair.class); + m.invoke(null, input, output); + } catch(Exception e) { + System.err.println("Error while adding recipe: " + e.getMessage()); + } + } + + /** + * Add a Chemical Dissolution Chamber recipe. + * @param input - input ItemStack + * @param output - output GasStack + */ + public static void addChemicalDissolutionChamberRecipe(ItemStack input, GasStack output) + { + try { + Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); + Method m = recipeClass.getMethod("addChemicalDissolutionChamberRecipe", ItemStack.class, GasStack.class); + m.invoke(null, input, output); + } catch(Exception e) { + System.err.println("Error while adding recipe: " + e.getMessage()); + } + } + + /** + * Add a Chemical Washer recipe. + * @param input - input GasStack + * @param output - output GasStack + */ + public static void addChemicalWasherRecipe(GasStack input, GasStack output) + { + try { + Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); + Method m = recipeClass.getMethod("addChemicalWasherRecipe", GasStack.class, GasStack.class); + m.invoke(null, input, output); + } catch(Exception e) { + System.err.println("Error while adding recipe: " + e.getMessage()); + } + } + + /** + * Add a Chemical Crystallizer recipe. + * @param input - input GasStack + * @param output - output ItemStack + */ + public static void addChemicalCrystallizerRecipe(GasStack input, ItemStack output) + { + try { + Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); + Method m = recipeClass.getMethod("addChemicalCrystallizerRecipe", GasStack.class, ItemStack.class); + m.invoke(null, input, output); + } catch(Exception e) { + System.err.println("Error while adding recipe: " + e.getMessage()); + } + } + + /** + * Add a Metallurgic Infuser recipe. + * @param input - input Infusion + * @param output - output ItemStack + */ + public static void addMetallurgicInfuserRecipe(InfusionInput input, ItemStack output) + { + try { + Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); + Method m = recipeClass.getMethod("addMetallurgicInfuserRecipe", InfusionInput.class, ItemStack.class); + m.invoke(null, input, output); + } catch(Exception e) { + System.err.println("Error while adding recipe: " + e.getMessage()); + } + } + + /** + * Add a Pressurized Reaction Chamber recipe. + * @param input - input PressurizedReactants + * @param output - output PressurizedProducts + * @param extraEnergy - extra energy needed by the recipe + * @param ticks - amount of ticks it takes for this recipe to complete + */ + public static void addPRCRecipe(PressurizedReactants input, PressurizedProducts output, double extraEnergy, int ticks) + { + try { + Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); + Method m = recipeClass.getMethod("addPRCRecipe", PressurizedReactants.class, PressurizedProducts.class, Double.TYPE, Integer.TYPE); + m.invoke(null, input, output); + } catch(Exception e) { + System.err.println("Error while adding recipe: " + e.getMessage()); + } + } +} diff --git a/src/api/java/mekanism/api/StackUtils.java b/src/api/java/mekanism/api/StackUtils.java new file mode 100644 index 00000000..f175879b --- /dev/null +++ b/src/api/java/mekanism/api/StackUtils.java @@ -0,0 +1,149 @@ +package mekanism.api; + +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraftforge.oredict.OreDictionary; + +public final class StackUtils +{ + public static List split(ItemStack stack) + { + if(stack == null || stack.stackSize == 0) + { + return null; + } + + List ret = new ArrayList(); + + if(stack.stackSize == 1) + { + ret.add(stack); + return ret; + } + + int remain = stack.stackSize % 2; + int split = (int)((float)(stack.stackSize)/2F); + + ret.add(size(stack, split+remain)); + ret.add(size(stack, split)); + + return ret; + } + + public static Item getItem(ItemStack stack) + { + if(stack == null) + { + return null; + } + + return stack.getItem(); + } + + public static boolean diffIgnoreNull(ItemStack stack1, ItemStack stack2) + { + if(stack1 == null || stack2 == null) + { + return false; + } + + return stack1.getItem() != stack2.getItem() || stack1.getItemDamage() != stack2.getItemDamage(); + } + + public static boolean equalsWildcard(ItemStack wild, ItemStack check) + { + return wild.getItem() == check.getItem() && (wild.getItemDamage() == OreDictionary.WILDCARD_VALUE || wild.getItemDamage() == check.getItemDamage()); + } + + public static List even(ItemStack stack1, ItemStack stack2) + { + ArrayList ret = new ArrayList(); + + if(getSize(stack1) == getSize(stack2) || Math.abs(getSize(stack1)-getSize(stack2)) == 1) + { + ret.add(stack1); + ret.add(stack2); + + return ret; + } + + if(getSize(stack1) > getSize(stack2)) + { + int diff = getSize(stack1)-getSize(stack2); + + List split = split(size(stack1, diff)); + + ret.add(subtract(stack1, split.get(0))); + ret.add(add(stack2, split.get(0))); + } + else if(getSize(stack2) > getSize(stack1)) + { + int diff = getSize(stack2)-getSize(stack1); + + List split = split(size(stack2, diff)); + + ret.add(subtract(stack2, split.get(0))); + ret.add(add(stack1, split.get(0))); + } + + return ret; + } + + public static ItemStack add(ItemStack stack1, ItemStack stack2) + { + if(stack1 == null) + { + return stack2; + } + else if(stack2 == null) + { + return stack1; + } + + return size(stack1, getSize(stack1)+getSize(stack2)); + } + + public static ItemStack subtract(ItemStack stack1, ItemStack stack2) + { + if(stack1 == null) + { + return null; + } + else if(stack2 == null) + { + return stack1; + } + + return size(stack1, getSize(stack1)-getSize(stack2)); + } + + public static ItemStack size(ItemStack stack, int size) + { + if(size <= 0 || stack == null) + { + return null; + } + + ItemStack ret = stack.copy(); + ret.stackSize = size; + return ret; + } + + public static ItemStack copy(ItemStack stack) + { + if(stack == null) + { + return null; + } + + return stack.copy(); + } + + public static int getSize(ItemStack stack) + { + return stack != null ? stack.stackSize : 0; + } +} diff --git a/src/api/java/mekanism/api/TabProxy.java b/src/api/java/mekanism/api/TabProxy.java new file mode 100644 index 00000000..c562c024 --- /dev/null +++ b/src/api/java/mekanism/api/TabProxy.java @@ -0,0 +1,42 @@ +package mekanism.api; + +import net.minecraft.creativetab.CreativeTabs; + +/** + * Class used to indirectly reference the Mekanism creative tab. + * @author AidanBrady + * + */ +public final class TabProxy +{ + /** The 'Mekanism' class where the tab instance is stored. */ + public static Class Mekanism; + + /** + * Attempts to get the Mekanism creative tab instance from the 'Mekanism' class. Will return + * the tab if the mod is loaded, but otherwise will return the defined 'preferred' creative tab. This way + * you don't need to worry about NPEs! + * @return Mekanism creative tab if can, otherwise preferred tab + */ + public static CreativeTabs tabMekanism(CreativeTabs preferred) + { + try { + if(Mekanism == null) + { + Mekanism = Class.forName("mekanism.common.Mekanism"); + } + + Object ret = Mekanism.getField("tabMekanism").get(null); + + if(ret instanceof CreativeTabs) + { + return (CreativeTabs)ret; + } + + return preferred; + } catch(Exception e) { + System.err.println("Error retrieving Mekanism creative tab."); + return preferred; + } + } +} diff --git a/src/api/java/mekanism/api/energy/EnergizedItemManager.java b/src/api/java/mekanism/api/energy/EnergizedItemManager.java new file mode 100644 index 00000000..165bdf60 --- /dev/null +++ b/src/api/java/mekanism/api/energy/EnergizedItemManager.java @@ -0,0 +1,60 @@ +package mekanism.api.energy; + +import net.minecraft.item.ItemStack; + +public class EnergizedItemManager +{ + /** + * Discharges an IEnergizedItem with the defined amount of energy. + * @param itemStack - ItemStack to discharge + * @param amount - amount of energy to discharge from the item, usually the total amount of energy needed in a TileEntity + * @return amount of energy discharged + */ + public static double discharge(ItemStack itemStack, double amount) + { + if(itemStack != null) + { + if(itemStack.getItem() instanceof IEnergizedItem) + { + IEnergizedItem energizedItem = (IEnergizedItem)itemStack.getItem(); + + if(energizedItem.canSend(itemStack)) + { + double energyToUse = Math.min(energizedItem.getMaxTransfer(itemStack), Math.min(energizedItem.getEnergy(itemStack), amount)); + energizedItem.setEnergy(itemStack, energizedItem.getEnergy(itemStack) - energyToUse); + + return energyToUse; + } + } + } + + return 0; + } + + /** + * Charges an IEnergizedItem with the defined amount of energy. + * @param itemStack - ItemStack to charge + * @param amount - amount of energy to charge the item with, usually the total amount of energy stored in a TileEntity + * @return amount of energy charged + */ + public static double charge(ItemStack itemStack, double amount) + { + if(itemStack != null) + { + if(itemStack.getItem() instanceof IEnergizedItem) + { + IEnergizedItem energizedItem = (IEnergizedItem)itemStack.getItem(); + + if(energizedItem.canReceive(itemStack)) + { + double energyToSend = Math.min(energizedItem.getMaxTransfer(itemStack), Math.min(energizedItem.getMaxEnergy(itemStack) - energizedItem.getEnergy(itemStack), amount)); + energizedItem.setEnergy(itemStack, energizedItem.getEnergy(itemStack) + energyToSend); + + return energyToSend; + } + } + } + + return 0; + } +} diff --git a/src/api/java/mekanism/api/energy/ICableOutputter.java b/src/api/java/mekanism/api/energy/ICableOutputter.java new file mode 100644 index 00000000..015379c0 --- /dev/null +++ b/src/api/java/mekanism/api/energy/ICableOutputter.java @@ -0,0 +1,18 @@ +package mekanism.api.energy; + +import net.minecraftforge.common.util.ForgeDirection; + +/** + * Implement this if your TileEntity is capable of outputting energy to cables, overriding Mekanism's default implementation. + * @author AidanBrady + * + */ +public interface ICableOutputter +{ + /** + * Whether or not this block can output to a cable on a specific side. + * @param side - side to check + * @return if the block can output + */ + public boolean canOutputTo(ForgeDirection side); +} diff --git a/src/api/java/mekanism/api/energy/IEnergizedItem.java b/src/api/java/mekanism/api/energy/IEnergizedItem.java new file mode 100644 index 00000000..b6725459 --- /dev/null +++ b/src/api/java/mekanism/api/energy/IEnergizedItem.java @@ -0,0 +1,59 @@ +package mekanism.api.energy; + +import net.minecraft.item.ItemStack; + +/** + * Implement this in an item's class if it should be able to store electricity. + * @author aidancbrady + * + */ +public interface IEnergizedItem +{ + /** + * Gets and returns the amount of energy stored in this item. + * @param itemStack - the ItemStack to check + * @return energy stored + */ + public double getEnergy(ItemStack itemStack); + + /** + * Sets this item's stored energy value to a new amount. + * @param itemStack - the ItemStack who's energy value is to be change + * @param amount - new amount of energy + */ + public void setEnergy(ItemStack itemStack, double amount); + + /** + * Gets and returns this item's maximum amount of energy that can be stored. + * @param itemStack - the ItemStack to check + * @return maximum energy + */ + public double getMaxEnergy(ItemStack itemStack); + + /** + * Gets and returns how much energy this item can transfer to and from charging slots. + * @param itemStack - the ItemStack to check + * @return transfer amount + */ + public double getMaxTransfer(ItemStack itemStack); + + /** + * Gets and returns whether or not this item can receive energy from a charging slot. + * @param itemStack - the ItemStack to check + * @return if the item can receive energy + */ + public boolean canReceive(ItemStack itemStack); + + /** + * Gets and returns whether or not this item can send energy to a charging slot. + * @param itemStack - the ItemStack to check + * @return if the item can send energy + */ + public boolean canSend(ItemStack itemStack); + + /** + * Returns whether or not this item contains metadata-specific subtypes instead of using metadata for damage display. + * @return if the item contains metadata-specific subtypes + */ + public boolean isMetadataSpecific(ItemStack itemStack); +} diff --git a/src/api/java/mekanism/api/energy/IStrictEnergyAcceptor.java b/src/api/java/mekanism/api/energy/IStrictEnergyAcceptor.java new file mode 100644 index 00000000..53edc68e --- /dev/null +++ b/src/api/java/mekanism/api/energy/IStrictEnergyAcceptor.java @@ -0,0 +1,25 @@ +package mekanism.api.energy; + +import net.minecraftforge.common.util.ForgeDirection; + +/** + * Implement this if your TileEntity can accept energy at a floating-point double value from Universal Cables. + * @author AidanBrady + * + */ +public interface IStrictEnergyAcceptor extends IStrictEnergyStorage +{ + /** + * Transfer a certain amount of energy to this acceptor. + * @param amount - amount to transfer + * @return energy used + */ + public double transferEnergyToAcceptor(ForgeDirection side, double amount); + + /** + * Whether or not this tile entity accepts energy from a certain side. + * @param side - side to check + * @return if tile entity accepts energy + */ + public boolean canReceiveEnergy(ForgeDirection side); +} diff --git a/src/api/java/mekanism/api/energy/IStrictEnergyStorage.java b/src/api/java/mekanism/api/energy/IStrictEnergyStorage.java new file mode 100644 index 00000000..fd560fa1 --- /dev/null +++ b/src/api/java/mekanism/api/energy/IStrictEnergyStorage.java @@ -0,0 +1,27 @@ +package mekanism.api.energy; + +/** + * Mekanism-specific energy storage for TileEntities, already implemented in IStrictEnergyAcceptor. + * @author aidancbrady + * + */ +public interface IStrictEnergyStorage +{ + /** + * Gets the amount of energy this TileEntity is currently storing. + * @return stored energy + */ + public double getEnergy(); + + /** + * Sets the amount of stored energy of this TileEntity to a new amount. + * @param energy - new energy value + */ + public void setEnergy(double energy); + + /** + * Gets the maximum amount of energy this TileEntity can store. + * @return maximum energy + */ + public double getMaxEnergy(); +} diff --git a/src/api/java/mekanism/api/gas/Gas.java b/src/api/java/mekanism/api/gas/Gas.java new file mode 100644 index 00000000..f05be52c --- /dev/null +++ b/src/api/java/mekanism/api/gas/Gas.java @@ -0,0 +1,221 @@ +package mekanism.api.gas; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.IIcon; +import net.minecraft.util.StatCollector; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidRegistry; + +/** + * Gas - a class used to set specific properties of gasses when used or seen in-game. + * @author aidancbrady + * + */ +public class Gas +{ + private String name; + + private String unlocalizedName; + + private Fluid fluid; + + private IIcon icon; + + private boolean visible = true; + + private boolean from_fluid = false; + + /** + * Creates a new Gas object with a defined name or key value. + * @param s - name or key to associate this Gas with + */ + public Gas(String s) + { + unlocalizedName = name = s; + } + + /** + * Creates a new Gas object that corresponds to the given Fluid + */ + public Gas(Fluid f) + { + unlocalizedName = name = f.getName(); + icon = f.getStillIcon(); + fluid = f; + from_fluid = true; + } + + /** + * Gets the name (key) of this Gas. This is NOT a translated or localized display name. + * @return this Gas's name or key + */ + public String getName() + { + return name; + } + + /** + * Whether or not this is a visible gas. + * @return if this gas is visible + */ + public boolean isVisible() + { + return visible; + } + + /** + * Sets this gas's "visible" state to a new value. Setting it to 'false' will treat this gas as an internal gas, and it will not be displayed or accessed by other mods. + * @param v - new visible state + * @return this Gas object + */ + public Gas setVisible(boolean v) + { + visible = v; + + return this; + } + + /** + * Gets the unlocalized name of this Gas. + * @return this Gas's unlocalized name + */ + public String getUnlocalizedName() + { + return "gas." + unlocalizedName; + } + + /** + * Translates this Gas's unlocalized name and returns it as localized. + * @return this Gas's localized name + */ + public String getLocalizedName() + { + return StatCollector.translateToLocal(getUnlocalizedName()); + } + + /** + * Sets the unlocalized name of this Gas. + * @param s - unlocalized name to set + * @return this Gas object + */ + public Gas setUnlocalizedName(String s) + { + unlocalizedName = s; + + return this; + } + + /** + * Gets the IIcon associated with this Gas. + * @return associated IIcon + */ + public IIcon getIcon() + { + if(from_fluid) + { + return this.getFluid().getIcon(); + } + + return icon; + } + + /** + * Sets this gas's icon. + * @param i - IIcon to associate with this Gas + * @return this Gas object + */ + public Gas setIcon(IIcon i) + { + icon = i; + + if(hasFluid()) + { + fluid.setIcons(getIcon()); + } + + from_fluid = false; + + return this; + } + + /** + * Gets the ID associated with this gas. + * @return the associated gas ID + */ + public int getID() + { + return GasRegistry.getGasID(this); + } + + /** + * Writes this Gas to a defined tag compound. + * @param nbtTags - tag compound to write this Gas to + * @return the tag compound this gas was written to + */ + public NBTTagCompound write(NBTTagCompound nbtTags) + { + nbtTags.setString("gasName", getName()); + + return nbtTags; + } + + /** + * Returns the Gas stored in the defined tag compound. + * @param nbtTags - tag compound to get the Gas from + * @return Gas stored in the tag compound + */ + public static Gas readFromNBT(NBTTagCompound nbtTags) + { + if(nbtTags == null || nbtTags.hasNoTags()) + { + return null; + } + + return GasRegistry.getGas(nbtTags.getString("gasName")); + } + + /** + * Whether or not this Gas has an associated fluid. + * @return if this gas has a fluid + */ + public boolean hasFluid() + { + return fluid != null; + } + + /** + * Gets the fluid associated with this Gas. + * @return fluid associated with this gas + */ + public Fluid getFluid() + { + return fluid; + } + + /** + * Registers a new fluid out of this Gas or gets one from the FluidRegistry. + * @return this Gas object + */ + public Gas registerFluid() + { + if(fluid == null) + { + if(FluidRegistry.getFluid(getName()) == null) + { + fluid = new Fluid(getName()).setGaseous(true); + FluidRegistry.registerFluid(fluid); + } + else { + fluid = FluidRegistry.getFluid(getName()); + } + } + + return this; + } + + @Override + public String toString() + { + return name; + } +} diff --git a/src/api/java/mekanism/api/gas/GasNetwork.java b/src/api/java/mekanism/api/gas/GasNetwork.java new file mode 100644 index 00000000..c65f04b9 --- /dev/null +++ b/src/api/java/mekanism/api/gas/GasNetwork.java @@ -0,0 +1,474 @@ +package mekanism.api.gas; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import mekanism.api.Coord4D; +import mekanism.api.ListUtils; +import mekanism.api.transmitters.DynamicNetwork; +import mekanism.api.transmitters.IGridTransmitter; +import mekanism.api.transmitters.ITransmitterNetwork; +import mekanism.api.transmitters.TransmissionType; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.common.util.ForgeDirection; +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.eventhandler.Event; + +/** + * A DynamicNetwork extension created specifically for the transfer of Gasses. By default this is server-only, but if ticked on + * the client side and if it's posted events are handled properly, it has the capability to visually display gasses network-wide. + * @author aidancbrady + * + */ +public class GasNetwork extends DynamicNetwork +{ + public int transferDelay = 0; + + public boolean didTransfer; + public boolean prevTransfer; + + public float gasScale; + + public Gas refGas; + + public GasStack gasStored; + public int prevStored; + + public int prevTransferAmount = 0; + + public GasNetwork(IGridTransmitter... varPipes) + { + transmitters.addAll(Arrays.asList(varPipes)); + register(); + } + + public GasNetwork(Collection> collection) + { + transmitters.addAll(collection); + register(); + } + + public GasNetwork(Set networks) + { + for(GasNetwork net : networks) + { + if(net != null) + { + if(FMLCommonHandler.instance().getEffectiveSide().isClient()) + { + if(net.refGas != null && net.gasScale > gasScale) + { + gasScale = net.gasScale; + refGas = net.refGas; + gasStored = net.gasStored; + + net.gasScale = 0; + net.refGas = null; + net.gasStored = null; + } + } + else { + if(net.gasStored != null) + { + if(gasStored == null) + { + gasStored = net.gasStored; + } + else { + gasStored.amount += net.gasStored.amount; + } + + net.gasStored = null; + } + } + + addAllTransmitters(net.transmitters); + net.deregister(); + } + } + + gasScale = getScale(); + + register(); + } + + @Override + public void onNetworksCreated(List networks) + { + if(gasStored != null && FMLCommonHandler.instance().getEffectiveSide().isServer()) + { + int[] caps = new int[networks.size()]; + int cap = 0; + + for(GasNetwork network : networks) + { + caps[networks.indexOf(network)] = network.getCapacity(); + cap += network.getCapacity(); + } + + gasStored.amount = Math.min(cap, gasStored.amount); + + int[] values = ListUtils.calcPercentInt(ListUtils.percent(caps), gasStored.amount); + + for(GasNetwork network : networks) + { + int index = networks.indexOf(network); + + if(values[index] > 0) + { + network.gasStored = new GasStack(gasStored.getGas(), values[index]); + network.refGas = gasStored.getGas(); + } + } + } + + gasScale = 0; + refGas = null; + gasStored = null; + } + + public synchronized int getGasNeeded() + { + return getCapacity()-(gasStored != null ? gasStored.amount : 0); + } + + public synchronized int tickEmit(GasStack stack) + { + List availableAcceptors = Arrays.asList(getAcceptors(stack.getGas()).toArray()); + + Collections.shuffle(availableAcceptors); + + int toSend = stack.amount; + int prevSending = toSend; + + if(!availableAcceptors.isEmpty()) + { + int divider = availableAcceptors.size(); + int remaining = toSend % divider; + int sending = (toSend-remaining)/divider; + + for(Object obj : availableAcceptors) + { + if(obj instanceof IGasHandler) + { + IGasHandler acceptor = (IGasHandler)obj; + + int currentSending = sending; + + if(remaining > 0) + { + currentSending++; + remaining--; + } + + toSend -= acceptor.receiveGas(acceptorDirections.get(acceptor).getOpposite(), new GasStack(stack.getGas(), currentSending)); + } + } + } + + int sent = prevSending-toSend; + + if(sent > 0 && FMLCommonHandler.instance().getEffectiveSide().isServer()) + { + didTransfer = true; + transferDelay = 2; + } + + return sent; + } + + public synchronized int emit(GasStack stack) + { + if(gasStored != null && gasStored.getGas() != stack.getGas()) + { + return 0; + } + + int toUse = Math.min(getGasNeeded(), stack.amount); + + if(gasStored == null) + { + gasStored = stack.copy(); + gasStored.amount = toUse; + } + else { + gasStored.amount += toUse; + } + + return toUse; + } + + @Override + public void onUpdate() + { + super.onUpdate(); + + if(FMLCommonHandler.instance().getEffectiveSide().isServer()) + { + prevTransferAmount = 0; + + if(transferDelay == 0) + { + didTransfer = false; + } + else { + transferDelay--; + } + + int stored = gasStored != null ? gasStored.amount : 0; + + if(stored != prevStored) + { + needsUpdate = true; + } + + prevStored = stored; + + if(didTransfer != prevTransfer || needsUpdate) + { + MinecraftForge.EVENT_BUS.post(new GasTransferEvent(this, gasStored, didTransfer)); + needsUpdate = false; + } + + prevTransfer = didTransfer; + + if(gasStored != null) + { + prevTransferAmount = tickEmit(gasStored); + gasStored.amount -= prevTransferAmount; + + if(gasStored.amount <= 0) + { + gasStored = null; + } + } + } + } + + @Override + public void clientTick() + { + super.clientTick(); + + gasScale = Math.max(gasScale, getScale()); + + if(didTransfer && gasScale < 1) + { + gasScale = Math.max(getScale(), Math.min(1, gasScale+0.02F)); + } + else if(!didTransfer && gasScale > 0) + { + gasScale = Math.max(getScale(), Math.max(0, gasScale-0.02F)); + + if(gasScale == 0) + { + gasStored = null; + } + } + } + + @Override + public synchronized Set getAcceptors(Object... data) + { + Gas type = (Gas)data[0]; + Set toReturn = new HashSet(); + + for(IGasHandler acceptor : ((Map)possibleAcceptors.clone()).values()) + { + if(acceptorDirections.get(acceptor) == null) + { + continue; + } + + if(acceptor.canReceiveGas(acceptorDirections.get(acceptor).getOpposite(), type)) + { + toReturn.add(acceptor); + } + } + + return toReturn; + } + + @Override + public synchronized void refresh() + { + Set> iterTubes = (Set>)transmitters.clone(); + Iterator> it = iterTubes.iterator(); + boolean networkChanged = false; + + while(it.hasNext()) + { + IGridTransmitter conductor = (IGridTransmitter)it.next(); + + if(conductor == null || conductor.getTile().isInvalid()) + { + it.remove(); + networkChanged = true; + transmitters.remove(conductor); + } + else { + conductor.setTransmitterNetwork(this); + } + } + + if(networkChanged) + { + updateCapacity(); + } + } + + @Override + public synchronized void refresh(IGridTransmitter transmitter) + { + IGasHandler[] acceptors = GasTransmission.getConnectedAcceptors(transmitter.getTile()); + + clearAround(transmitter); + + for(IGasHandler acceptor : acceptors) + { + ForgeDirection side = ForgeDirection.getOrientation(Arrays.asList(acceptors).indexOf(acceptor)); + + if(side != null && acceptor != null && !(acceptor instanceof IGridTransmitter) && transmitter.canConnectToAcceptor(side, true)) + { + possibleAcceptors.put(Coord4D.get((TileEntity)acceptor), acceptor); + acceptorDirections.put(acceptor, ForgeDirection.getOrientation(Arrays.asList(acceptors).indexOf(acceptor))); + } + } + } + + public static class GasTransferEvent extends Event + { + public final GasNetwork gasNetwork; + + public final GasStack transferType; + public final boolean didTransfer; + + public GasTransferEvent(GasNetwork network, GasStack type, boolean did) + { + gasNetwork = network; + transferType = type; + didTransfer = did; + } + } + + public float getScale() + { + return Math.min(1, (gasStored == null || getCapacity() == 0 ? 0 : (float)gasStored.amount/getCapacity())); + } + + @Override + public String toString() + { + return "[GasNetwork] " + transmitters.size() + " transmitters, " + possibleAcceptors.size() + " acceptors."; + } + + @Override + public boolean canMerge(List> networks) + { + Gas found = null; + + for(ITransmitterNetwork network : networks) + { + if(network instanceof GasNetwork) + { + GasNetwork net = (GasNetwork)network; + + if(net.gasStored != null) + { + if(found != null && found != net.gasStored.getGas()) + { + return false; + } + + found = net.gasStored.getGas(); + } + } + } + + return true; + } + + @Override + protected GasNetwork create(IGridTransmitter... varTransmitters) + { + GasNetwork network = new GasNetwork(varTransmitters); + network.refGas = refGas; + + if(gasStored != null) + { + if(network.gasStored == null) + { + network.gasStored = gasStored; + } + else { + network.gasStored.amount += gasStored.amount; + } + } + + network.gasScale = network.getScale(); + gasScale = 0; + refGas = null; + gasStored = null; + + return network; + } + + @Override + protected GasNetwork create(Collection> collection) + { + GasNetwork network = new GasNetwork(collection); + network.refGas = refGas; + + if(gasStored != null) + { + if(network.gasStored == null) + { + network.gasStored = gasStored; + } + else { + network.gasStored.amount += gasStored.amount; + } + } + + network.gasScale = network.getScale(); + network.updateCapacity(); + return network; + } + + @Override + protected GasNetwork create(Set networks) + { + return new GasNetwork(networks); + } + + @Override + public TransmissionType getTransmissionType() + { + return TransmissionType.GAS; + } + + @Override + public String getNeededInfo() + { + return Integer.toString(getGasNeeded()); + } + + @Override + public String getStoredInfo() + { + return gasStored != null ? gasStored.getGas().getLocalizedName() + " (" + gasStored.amount + ")" : "None"; + } + + @Override + public String getFlowInfo() + { + return Integer.toString(prevTransferAmount) + "/t"; + } +} diff --git a/src/api/java/mekanism/api/gas/GasRegistry.java b/src/api/java/mekanism/api/gas/GasRegistry.java new file mode 100644 index 00000000..25db9667 --- /dev/null +++ b/src/api/java/mekanism/api/gas/GasRegistry.java @@ -0,0 +1,113 @@ +package mekanism.api.gas; + +import java.util.ArrayList; +import java.util.List; + +import net.minecraftforge.fluids.Fluid; + +public class GasRegistry +{ + private static ArrayList registeredGasses = new ArrayList(); + + /** + * Register a new gas into GasRegistry. + * @param gas - Gas to register + * @return the gas that has been registered, pulled right out of GasRegistry + */ + public static Gas register(Gas gas) + { + if(gas == null) + { + return null; + } + + registeredGasses.add(gas); + + return getGas(gas.getName()); + } + + /** + * Gets the gas associated with the defined ID. + * @param id - ID to check + * @return gas associated with defined ID + */ + public static Gas getGas(int id) + { + if(id == -1) + { + return null; + } + + return registeredGasses.get(id); + } + + /** + * Gets the gas associated with the defined fluid. + * @param f - fluid to check + * @return the gas associated with the fluid + */ + public static Gas getGas(Fluid f) + { + for(Gas gas : getRegisteredGasses()) + { + if(gas.hasFluid() && gas.getFluid() == f) + { + return gas; + } + } + + return null; + } + + /** + * Whether or not GasRegistry contains a gas with the specified name + * @param name - name to check + * @return if GasRegistry contains a gas with the defined name + */ + public static boolean containsGas(String name) + { + return getGas(name) != null; + } + + /** + * Gets the list of all gasses registered in GasRegistry. + * @return a cloned list of all registered gasses + */ + public static List getRegisteredGasses() + { + return (List)registeredGasses.clone(); + } + + /** + * Gets the gas associated with the specified name. + * @param name - name of the gas to get + * @return gas associated with the name + */ + public static Gas getGas(String name) + { + for(Gas gas : registeredGasses) + { + if(gas.getName().toLowerCase().equals(name.toLowerCase())) + { + return gas; + } + } + + return null; + } + + /** + * Gets the gas ID of a specified gas. + * @param gas - gas to get the ID from + * @return gas ID + */ + public static int getGasID(Gas gas) + { + if(gas == null || !containsGas(gas.getName())) + { + return -1; + } + + return registeredGasses.indexOf(gas); + } +} diff --git a/src/api/java/mekanism/api/gas/GasStack.java b/src/api/java/mekanism/api/gas/GasStack.java new file mode 100644 index 00000000..0f3f40bf --- /dev/null +++ b/src/api/java/mekanism/api/gas/GasStack.java @@ -0,0 +1,119 @@ +package mekanism.api.gas; + +import net.minecraft.nbt.NBTTagCompound; + +/** + * GasStack - a specified amount of a defined Gas with certain properties. + * @author aidancbrady + * + */ +public class GasStack +{ + private Gas type; + + public int amount; + + /** + * Creates a new GasStack with a defined gas ID and quantity. + * @param id - gas ID to associate this GasStack to, will perform a GasRegistry lookup in the constructor + * @param quantity - amount of gas to be referenced in this GasStack + */ + public GasStack(int id, int quantity) + { + type = GasRegistry.getGas(id); + amount = quantity; + } + + /** + * Creates a new GasStack with a defined Gas type and quantity. + * @param gas - gas type of the stack + * @param quantity - amount of gas to be referenced in this GasStack + */ + public GasStack(Gas gas, int quantity) + { + type = gas; + amount = quantity; + } + + private GasStack() {} + + /** + * Gets the Gas type of this GasStack. + * @return this GasStack's Gas type + */ + public Gas getGas() + { + return type; + } + + /** + * Writes this GasStack to a defined tag compound. + * @param nbtTags - tag compound to write to + * @return tag compound with this GasStack's data + */ + public NBTTagCompound write(NBTTagCompound nbtTags) + { + type.write(nbtTags); + nbtTags.setInteger("amount", amount); + + return nbtTags; + } + + /** + * Reads this GasStack's data from a defined tag compound. + * @param nbtTags - tag compound to read from + */ + public void read(NBTTagCompound nbtTags) + { + type = Gas.readFromNBT(nbtTags); + amount = nbtTags.getInteger("amount"); + } + + /** + * Returns the GasStack stored in the defined tag compound, or null if it doesn't exist. + * @param nbtTags - tag compound to read from + * @return GasStack stored in the tag compound + */ + public static GasStack readFromNBT(NBTTagCompound nbtTags) + { + if(nbtTags == null || nbtTags.hasNoTags()) + { + return null; + } + + GasStack stack = new GasStack(); + stack.read(nbtTags); + + if(stack.getGas() == null) + { + return null; + } + + return stack; + } + + /** + * Returns a copied form of this GasStack. + * @return copied GasStack + */ + public GasStack copy() + { + return new GasStack(type, amount); + } + + /** + * Whether or not this GasStack's gas type is equal to the other defined GasStack. + * @param stack - GasStack to check + * @return if the GasStacks contain the same gas type + */ + public boolean isGasEqual(GasStack stack) + { + return stack != null && getGas() == stack.getGas(); + } + + @Override + public String toString() + { + return "[" + type + ", " + amount + "]"; + } +} diff --git a/src/api/java/mekanism/api/gas/GasTank.java b/src/api/java/mekanism/api/gas/GasTank.java new file mode 100644 index 00000000..7aa5ad5b --- /dev/null +++ b/src/api/java/mekanism/api/gas/GasTank.java @@ -0,0 +1,241 @@ +package mekanism.api.gas; + +import net.minecraft.nbt.NBTTagCompound; + +/** + * An optional way of managing and/or storing gasses. Would be very useful in TileEntity and Entity gas storage. + * @author aidancbrady + * + */ +public class GasTank +{ + public GasStack stored; + + private int maxGas; + + private GasTank() {} + + /** + * Creates a tank with a defined capacity. + * @param max - the maximum amount of gas this GasTank can hold + */ + public GasTank(int max) + { + maxGas = max; + } + + /** + * Sets this tank's GasStack value to a new value. Will cap the amount to this GasTank's capacity. + * @param stack - value to set this tank's GasStack value to + */ + public void setGas(GasStack stack) + { + stored = stack; + + if(stored != null) + { + stored.amount = Math.min(getMaxGas(), stored.amount); + } + } + + /** + * Draws a specified amount of gas out of this tank. + * @param amount - amount to draw + * @param doDraw - if the gas should actually be removed from this tank + * @return gas taken from this GasTank as a GasStack value + */ + public GasStack draw(int amount, boolean doDraw) + { + if(stored == null || amount <= 0) + { + return null; + } + + GasStack ret = new GasStack(getGas().getGas(), Math.min(getStored(), amount)); + + if(ret.amount > 0) + { + if(doDraw) + { + stored.amount -= ret.amount; + + if(stored.amount <= 0) + { + stored = null; + } + } + + return ret; + } + + return null; + } + + /** + * Adds a specified amount of gas to this tank. + * @param amount - the GasStack for this tank to receive + * @param doReceive - if the gas should actually be added to this tank + * @return the amount of gas accepted by this tank + */ + public int receive(GasStack amount, boolean doReceive) + { + if(amount == null || (stored != null && stored.amount == getMaxGas())) + { + return 0; + } + + int toFill = Math.min(getMaxGas()-getStored(), amount.amount); + + if(doReceive) + { + if(stored == null) + { + stored = amount.copy(); + } + else { + stored.amount = Math.min(getMaxGas(), getStored()+amount.amount); + } + } + + return toFill; + } + + /** + * If this GasTank can receive the specified type of gas. Will return false if this tank does not need anymore gas. + * @param gas - gas to check + * @return if this GasTank can accept the defined gas + */ + public boolean canReceive(Gas gas) + { + if(getNeeded() == 0 || stored != null && (gas != null && gas != stored.getGas())) + { + return false; + } + + return true; + } + + /** + * If this GasTank can receive the specified type of gas. Will return TRUE if this tank does not need anymore gas. + * @param gas - gas to check + * @return if this GasTank can accept the defined gas + */ + public boolean canReceiveType(Gas gas) + { + if(stored != null && (gas != null && gas != stored.getGas())) + { + return false; + } + + return true; + } + + /** + * If this GasTank can be drawn of the specified type of gas. Will return false if this tank does not contain any gas. + * @param gas - gas to check + * @return if this GasTank can be drawn of the defined gas + */ + public boolean canDraw(Gas gas) + { + if(stored == null || (gas != null && gas != stored.getGas())) + { + return false; + } + + return true; + } + + /** + * Gets the amount of gas needed by this GasTank. + * @return + */ + public int getNeeded() + { + return getMaxGas()-getStored(); + } + + /** + * Gets the maximum amount of gas this tank can hold. + * @return - max gas + */ + public int getMaxGas() + { + return maxGas; + } + + /** + * Gets the GasStack held by this GasTank. + * @return - GasStakc held by this tank + */ + public GasStack getGas() + { + return stored; + } + + /** + * Gets the type of gas currently stored in this GasTank. + * @return gas type contained + */ + public Gas getGasType() + { + return stored != null ? stored.getGas() : null; + } + + /** + * Gets the amount of gas stored by this GasTank. + * @return amount of gas stored + */ + public int getStored() + { + return stored != null ? stored.amount : 0; + } + + /** + * Writes this tank to a defined tag compound. + * @param nbtTags - tag compound to write to + * @return tag compound with this tank's data + */ + public NBTTagCompound write(NBTTagCompound nbtTags) + { + if(stored != null) + { + nbtTags.setTag("stored", stored.write(new NBTTagCompound())); + } + + nbtTags.setInteger("maxGas", maxGas); + + return nbtTags; + } + + /** + * Reads this tank's data from a defined tag compound. + * @param nbtTags - tag compound to read from + */ + public void read(NBTTagCompound nbtTags) + { + if(nbtTags.hasKey("stored")) + { + stored = GasStack.readFromNBT(nbtTags.getCompoundTag("stored")); + } + + maxGas = nbtTags.getInteger("maxGas"); + } + + /** + * Returns the tank stored in the defined tag compound, or null if it doesn't exist. + * @param nbtTags - tag compound to read from + * @return tank stored in the tag compound + */ + public static GasTank readFromNBT(NBTTagCompound nbtTags) + { + if(nbtTags == null || nbtTags.hasNoTags()) + { + return null; + } + + GasTank tank = new GasTank(); + tank.read(nbtTags); + + return tank; + } +} diff --git a/src/api/java/mekanism/api/gas/GasTransmission.java b/src/api/java/mekanism/api/gas/GasTransmission.java new file mode 100644 index 00000000..c9091411 --- /dev/null +++ b/src/api/java/mekanism/api/gas/GasTransmission.java @@ -0,0 +1,141 @@ +package mekanism.api.gas; + +import mekanism.api.Coord4D; +import mekanism.api.transmitters.IGridTransmitter; +import mekanism.api.transmitters.TransmissionType; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; + +/** + * A handy class containing several utilities for efficient gas transfer. + * @author AidanBrady + * + */ +public final class GasTransmission +{ + /** + * Gets all the tubes around a tile entity. + * @param tileEntity - center tile entity + * @return array of TileEntities + */ + public static TileEntity[] getConnectedTubes(TileEntity tileEntity) + { + TileEntity[] tubes = new TileEntity[] {null, null, null, null, null, null}; + + for(ForgeDirection orientation : ForgeDirection.VALID_DIRECTIONS) + { + TileEntity tube = Coord4D.get(tileEntity).getFromSide(orientation).getTileEntity(tileEntity.getWorldObj()); + + if(TransmissionType.checkTransmissionType(tube, TransmissionType.GAS, tileEntity)) + { + tubes[orientation.ordinal()] = tube; + } + } + + return tubes; + } + + /** + * Gets all the acceptors around a tile entity. + * @param tileEntity - center tile entity + * @return array of IGasAcceptors + */ + public static IGasHandler[] getConnectedAcceptors(TileEntity tileEntity) + { + IGasHandler[] acceptors = new IGasHandler[] {null, null, null, null, null, null}; + + for(ForgeDirection orientation : ForgeDirection.VALID_DIRECTIONS) + { + TileEntity acceptor = Coord4D.get(tileEntity).getFromSide(orientation).getTileEntity(tileEntity.getWorldObj()); + + if(acceptor instanceof IGasHandler) + { + acceptors[orientation.ordinal()] = (IGasHandler)acceptor; + } + } + + return acceptors; + } + + /** + * Gets all the tube connections around a tile entity. + * @param tileEntity - center tile entity + * @return array of ITubeConnections + */ + public static ITubeConnection[] getConnections(TileEntity tileEntity) + { + ITubeConnection[] connections = new ITubeConnection[] {null, null, null, null, null, null}; + + for(ForgeDirection orientation : ForgeDirection.VALID_DIRECTIONS) + { + TileEntity connection = Coord4D.get(tileEntity).getFromSide(orientation).getTileEntity(tileEntity.getWorldObj()); + + if(canConnect(connection, orientation)) + { + connections[orientation.ordinal()] = (ITubeConnection)connection; + } + } + + return connections; + } + + /** + * Whether or not a TileEntity can connect to a specified tile on a specified side. + * @param tileEntity - TileEntity to attempt connection to + * @param side - side to attempt connection on + * @return if this tile and side are connectable + */ + public static boolean canConnect(TileEntity tileEntity, ForgeDirection side) + { + if(tileEntity instanceof ITubeConnection && (!(tileEntity instanceof IGasTransmitter) || TransmissionType.checkTransmissionType(tileEntity, TransmissionType.GAS, tileEntity))) + { + if(((ITubeConnection)tileEntity).canTubeConnect(side.getOpposite())) + { + return true; + } + } + + return false; + } + + /** + * Removes a specified amount of gas from an IGasItem. + * @param itemStack - ItemStack of the IGasItem + * @param type - type of gas to remove from the IGasItem, null if it doesn't matter + * @param amount - amount of gas to remove from the ItemStack + * @return the GasStack removed by the IGasItem + */ + public static GasStack removeGas(ItemStack itemStack, Gas type, int amount) + { + if(itemStack != null && itemStack.getItem() instanceof IGasItem) + { + IGasItem item = (IGasItem)itemStack.getItem(); + + if(type != null && item.getGas(itemStack) != null && item.getGas(itemStack).getGas() != type || !item.canProvideGas(itemStack, type)) + { + return null; + } + + return item.removeGas(itemStack, amount); + } + + return null; + } + + /** + * Adds a specified amount of gas to an IGasItem. + * @param itemStack - ItemStack of the IGasItem + * @param stack - stack to add to the IGasItem + * @return amount of gas accepted by the IGasItem + */ + public static int addGas(ItemStack itemStack, GasStack stack) + { + if(itemStack != null && itemStack.getItem() instanceof IGasItem && ((IGasItem)itemStack.getItem()).canReceiveGas(itemStack, stack.getGas())) + { + return ((IGasItem)itemStack.getItem()).addGas(itemStack, stack.copy()); + } + + return 0; + } +} diff --git a/src/api/java/mekanism/api/gas/IGasHandler.java b/src/api/java/mekanism/api/gas/IGasHandler.java new file mode 100644 index 00000000..8723da69 --- /dev/null +++ b/src/api/java/mekanism/api/gas/IGasHandler.java @@ -0,0 +1,41 @@ +package mekanism.api.gas; + +import net.minecraftforge.common.util.ForgeDirection; + +/** + * Implement this if your tile entity accepts gas from an external source. + * @author AidanBrady + * + */ +public interface IGasHandler +{ + /** + * Transfer a certain amount of gas to this block. + * @param stack - gas to add + * @return gas added + */ + public int receiveGas(ForgeDirection side, GasStack stack); + + /** + * Draws a certain amount of gas from this block. + * @param amount - amount to draw + * @return gas drawn + */ + public GasStack drawGas(ForgeDirection side, int amount); + + /** + * Whether or not this block can accept gas from a certain side. + * @param side - side to check + * @param type - type of gas to check + * @return if block accepts gas + */ + public boolean canReceiveGas(ForgeDirection side, Gas type); + + /** + * Whether or not this block can be drawn of gas from a certain side. + * @param side - side to check + * @param type - type of gas to check + * @return if block can be drawn of gas + */ + public boolean canDrawGas(ForgeDirection side, Gas type); +} diff --git a/src/api/java/mekanism/api/gas/IGasItem.java b/src/api/java/mekanism/api/gas/IGasItem.java new file mode 100644 index 00000000..9c7d3323 --- /dev/null +++ b/src/api/java/mekanism/api/gas/IGasItem.java @@ -0,0 +1,81 @@ +package mekanism.api.gas; + +import net.minecraft.item.ItemStack; + +/** + * Implement this in your item class if it can store or transfer certain gasses. + * @author AidanBrady + * + */ +public interface IGasItem +{ + /** + * Gets the rate of transfer this item can handle. + * @return + */ + public int getRate(ItemStack itemstack); + + /** + * Adds a defined amount of a certain gas to an item. + * @param itemstack - the itemstack to add gas to + * @param type - the type of gas to add + * @param amount - the amount of gas to add + * @return the gas that was accepted by the item + */ + public int addGas(ItemStack itemstack, GasStack stack); + + /** + * Removes the defined amount of a certain gas from the item. + * @param itemstack - the itemstack to remove gas from + * @param type - the type of gas to remove + * @param amount - the amount of gas to remove + * @return the gas that was removed by the item + */ + public GasStack removeGas(ItemStack itemstack, int amount); + + /** + * Whether or not this storage tank be given a specific gas. + * @param itemstack - the itemstack to check + * @param type - the type of gas the tank can possibly receive + * @return if the item be charged + */ + public boolean canReceiveGas(ItemStack itemstack, Gas type); + + /** + * Whether or not this item can give a gas receiver a certain type of gas. + * @param itemstack - the itemstack to check + * @param type - the type of gas the tank can provide + * @return if the item can provide gas + */ + public boolean canProvideGas(ItemStack itemstack, Gas type); + + /** + * Get the gas of a declared type. + * @param type - type of gas + * @param data - ItemStack parameter if necessary + * @return gas stored + */ + public GasStack getGas(ItemStack itemstack); + + /** + * Set the gas of a declared type to a new amount; + * @param type - type of gas + * @param data - ItemStack parameter if necessary + * @param amount - amount to store + */ + public void setGas(ItemStack itemstack, GasStack stack); + + /** + * Gets the maximum amount of gas this tile entity can store. + * @param type - type of gas + * @param data - ItemStack parameter if necessary + * @return maximum gas + */ + public int getMaxGas(ItemStack itemstack); + + /** + * Returns whether or not this item contains metadata-specific subtypes instead of using metadata for damage display. + * @return if the item contains metadata-specific subtypes + */ + public boolean isMetadataSpecific(ItemStack itemstack); +} diff --git a/src/api/java/mekanism/api/gas/IGasTransmitter.java b/src/api/java/mekanism/api/gas/IGasTransmitter.java new file mode 100644 index 00000000..63eb02fd --- /dev/null +++ b/src/api/java/mekanism/api/gas/IGasTransmitter.java @@ -0,0 +1,9 @@ +package mekanism.api.gas; + +import mekanism.api.transmitters.IGridTransmitter; +import net.minecraft.tileentity.TileEntity; + +public interface IGasTransmitter extends IGridTransmitter +{ + public boolean canTransferGasToTube(TileEntity tile); +} diff --git a/src/api/java/mekanism/api/gas/ITubeConnection.java b/src/api/java/mekanism/api/gas/ITubeConnection.java new file mode 100644 index 00000000..b669fedd --- /dev/null +++ b/src/api/java/mekanism/api/gas/ITubeConnection.java @@ -0,0 +1,18 @@ +package mekanism.api.gas; + +import net.minecraftforge.common.util.ForgeDirection; + +/** + * Implement this if your block can connect to Pressurized Tubes. + * @author AidanBrady + * + */ +public interface ITubeConnection +{ + /** + * Whether or not a tube can connect to a certain orientation. + * @param side - orientation to check + * @return if a tube can connect + */ + public boolean canTubeConnect(ForgeDirection side); +} diff --git a/src/api/java/mekanism/api/gas/OreGas.java b/src/api/java/mekanism/api/gas/OreGas.java new file mode 100644 index 00000000..316169c2 --- /dev/null +++ b/src/api/java/mekanism/api/gas/OreGas.java @@ -0,0 +1,38 @@ +package mekanism.api.gas; + +import net.minecraft.util.StatCollector; + +public class OreGas extends Gas +{ + private String oreName; + private OreGas cleanGas; + + public OreGas(String s, String name) + { + super(s); + + oreName = name; + } + + public boolean isClean() + { + return getCleanGas() == null; + } + + public OreGas getCleanGas() + { + return cleanGas; + } + + public OreGas setCleanGas(OreGas gas) + { + cleanGas = gas; + + return this; + } + + public String getOreName() + { + return StatCollector.translateToLocal(oreName); + } +} diff --git a/src/api/java/mekanism/api/infuse/InfuseObject.java b/src/api/java/mekanism/api/infuse/InfuseObject.java new file mode 100644 index 00000000..a86c02f1 --- /dev/null +++ b/src/api/java/mekanism/api/infuse/InfuseObject.java @@ -0,0 +1,21 @@ +package mekanism.api.infuse; + +/** + * InfuseObject - an object associated with an ItemStack that can modify a Metallurgic Infuser's internal infuse. + * @author AidanBrady + * + */ +public class InfuseObject +{ + /** The type of infuse this item stores */ + public InfuseType type; + + /** How much infuse this item stores */ + public int stored; + + public InfuseObject(InfuseType infusion, int i) + { + type = infusion; + stored = i; + } +} diff --git a/src/api/java/mekanism/api/infuse/InfuseRegistry.java b/src/api/java/mekanism/api/infuse/InfuseRegistry.java new file mode 100644 index 00000000..308b9c5b --- /dev/null +++ b/src/api/java/mekanism/api/infuse/InfuseRegistry.java @@ -0,0 +1,113 @@ +package mekanism.api.infuse; + +import java.util.HashMap; +import java.util.Map; + +import net.minecraft.item.ItemStack; + +/** + * Use this class to add a new object that registers as an infuse object. + * @author AidanBrady + * + */ +public class InfuseRegistry +{ + /** The (private) map of ItemStacks and their related InfuseObjects. */ + private static Map infuseObjects = new HashMap(); + + /** The (private) map of infuse names and their corresponding InfuseTypes. */ + private static Map infuseTypes = new HashMap(); + + /** + * Registers an InfuseType into the registry. Call this in PreInit! + * @param infuse + */ + public static void registerInfuseType(InfuseType infuse) + { + if(infuseTypes.containsKey(infuse.name)) + { + return; + } + + infuseTypes.put(infuse.name, infuse); + } + + /** + * Gets an InfuseType from it's name, or null if it doesn't exist. + * @param name - the name of the InfuseType to get + * @return the name's corresponding InfuseType + */ + public static InfuseType get(String name) + { + if(name.equals("null")) + { + return null; + } + + return infuseTypes.get(name); + } + + /** + * Whether or not the registry contains a correspondent InfuseType to a name. + * @param name - the name to check + * @return if the name has a coorespondent InfuseType + */ + public static boolean contains(String name) + { + return get(name) != null; + } + + /** + * Registers a block or item that serves as an infuse object. An infuse object will store a certain type and amount of infuse, + * and will deliver this amount to the Metallurgic Infuser's buffer of infuse. The item's stack size will be decremented when + * it is placed in the Metallurgic Infuser's infuse slot, and the machine can accept the type and amount of infuse stored in the + * object. + * @param itemStack - stack the infuse object is linked to -- stack size is ignored + * @param infuseObject - the infuse object with the type and amount data + */ + public static void registerInfuseObject(ItemStack itemStack, InfuseObject infuseObject) + { + if(getObject(itemStack) != null) + { + return; + } + + infuseObjects.put(itemStack, infuseObject); + } + + /** + * Gets the InfuseObject data from an ItemStack. + * @param itemStack - the ItemStack to check + * @return the ItemStack's InfuseObject + */ + public static InfuseObject getObject(ItemStack itemStack) + { + for(Map.Entry obj : infuseObjects.entrySet()) + { + if(itemStack.isItemEqual(obj.getKey())) + { + return obj.getValue(); + } + } + + return null; + } + + /** + * Gets the private map for InfuseObjects. + * @return private InfuseObject map + */ + public static final Map getObjectMap() + { + return infuseObjects; + } + + /** + * Gets the private map for InfuseTypes. + * @return private InfuseType map + */ + public static final Map getInfuseMap() + { + return infuseTypes; + } +} diff --git a/src/api/java/mekanism/api/infuse/InfuseType.java b/src/api/java/mekanism/api/infuse/InfuseType.java new file mode 100644 index 00000000..1f5215cb --- /dev/null +++ b/src/api/java/mekanism/api/infuse/InfuseType.java @@ -0,0 +1,47 @@ +package mekanism.api.infuse; + +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.StatCollector; + +/** + * The types of infuse currently available in Mekanism. + * @author AidanBrady + * + */ +public final class InfuseType +{ + /** The name of this infusion */ + public String name; + + /** The location of this infuse's GUI texture */ + public ResourceLocation texture; + + /** The infuse's GUI texture X offset. */ + public int texX; + + /** The infuse's GUI texture Y offset. */ + public int texY; + + /** The unlocalized name of this type. */ + public String unlocalizedName; + + public InfuseType(String s, ResourceLocation location, int x, int y) + { + name = s; + texture = location; + texX = x; + texY = y; + } + + public InfuseType setUnlocalizedName(String name) + { + unlocalizedName = name; + + return this; + } + + public String getLocalizedName() + { + return StatCollector.translateToLocal(unlocalizedName); + } +} diff --git a/src/api/java/mekanism/api/infuse/InfusionInput.java b/src/api/java/mekanism/api/infuse/InfusionInput.java new file mode 100644 index 00000000..edbad48c --- /dev/null +++ b/src/api/java/mekanism/api/infuse/InfusionInput.java @@ -0,0 +1,32 @@ +package mekanism.api.infuse; + +import net.minecraft.item.ItemStack; + +/** + * An infusion input, containing the type of and amount of infuse the operation requires, as well as the input ItemStack. + * @author AidanBrady + * + */ +public class InfusionInput +{ + /** The type of this infusion */ + public InfuseType infusionType; + + /** How much infuse it takes to perform this operation */ + public int infuseAmount; + + /** The input ItemStack */ + public ItemStack inputStack; + + public InfusionInput(InfuseType infusiontype, int required, ItemStack itemstack) + { + infusionType = infusiontype; + infuseAmount = required; + inputStack = itemstack; + } + + public static InfusionInput getInfusion(InfuseType type, int stored, ItemStack itemstack) + { + return new InfusionInput(type, stored, itemstack); + } +} diff --git a/src/api/java/mekanism/api/infuse/InfusionOutput.java b/src/api/java/mekanism/api/infuse/InfusionOutput.java new file mode 100644 index 00000000..ad6d79a6 --- /dev/null +++ b/src/api/java/mekanism/api/infuse/InfusionOutput.java @@ -0,0 +1,38 @@ +package mekanism.api.infuse; + +import net.minecraft.item.ItemStack; + +/** + * An infusion output, containing a reference to it's input as well as the output resource. + * @author AidanBrady + * + */ +public class InfusionOutput +{ + /** The input infusion */ + public InfusionInput infusionInput; + + /** The output resource of this infusion */ + public ItemStack resource; + + public InfusionOutput(InfusionInput input, ItemStack itemstack) + { + infusionInput = input; + resource = itemstack; + } + + public static InfusionOutput getInfusion(InfusionInput input, ItemStack itemstack) + { + return new InfusionOutput(input, itemstack); + } + + public int getInfuseRequired() + { + return infusionInput.infuseAmount; + } + + public InfusionOutput copy() + { + return new InfusionOutput(infusionInput, resource); + } +} diff --git a/src/api/java/mekanism/api/transmitters/DynamicNetwork.java b/src/api/java/mekanism/api/transmitters/DynamicNetwork.java new file mode 100644 index 00000000..684a264f --- /dev/null +++ b/src/api/java/mekanism/api/transmitters/DynamicNetwork.java @@ -0,0 +1,537 @@ +package mekanism.api.transmitters; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Set; + +import mekanism.api.Coord4D; +import mekanism.api.IClientTicker; +import mekanism.api.Range4D; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.common.util.ForgeDirection; +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.eventhandler.Event; + +public abstract class DynamicNetwork> implements ITransmitterNetwork, IClientTicker, INetworkDataHandler +{ + public LinkedHashSet> transmitters = new LinkedHashSet>(); + + public HashMap possibleAcceptors = new HashMap(); + public HashMap acceptorDirections = new HashMap(); + + private List updateQueue = new ArrayList(); + + protected Range4D packetRange = null; + + protected int ticksSinceCreate = 0; + + protected int capacity = 0; + protected double meanCapacity = 0; + + protected boolean fixed = false; + + protected boolean needsUpdate = false; + + protected abstract ITransmitterNetwork create(IGridTransmitter... varTransmitters); + + protected abstract ITransmitterNetwork create(Collection> collection); + + protected abstract ITransmitterNetwork create(Set networks); + + protected void clearAround(IGridTransmitter transmitter) + { + for(ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) + { + Coord4D coord = Coord4D.get(transmitter.getTile()).getFromSide(side); + + if(possibleAcceptors.containsKey(coord)) + { + clearIfNecessary(coord, transmitter, side.getOpposite()); + } + } + } + + protected void clearIfNecessary(Coord4D acceptor, IGridTransmitter transmitter, ForgeDirection side) + { + if(getWorld() == null) + { + return; + } + + if(acceptor.getTileEntity(getWorld()) == null || acceptor.getTileEntity(getWorld()).isInvalid() || transmitter.canConnectToAcceptor(side, true)) + { + possibleAcceptors.remove(acceptor); + acceptorDirections.remove(acceptor.getTileEntity(getWorld())); + } + } + + public void addAllTransmitters(Set> newTransmitters) + { + transmitters.addAll(newTransmitters); + updateCapacity(); + } + + public boolean isFirst(IGridTransmitter transmitter) + { + return transmitters.iterator().next().equals(transmitter); + } + + @Override + public void fullRefresh() + { + possibleAcceptors.clear(); + acceptorDirections.clear(); + + for(IGridTransmitter transmitter : transmitters) + { + refresh(transmitter); + } + + refresh(); + } + + public Range4D getPacketRange() + { + if(packetRange == null) + { + return genPacketRange(); + } + + return packetRange; + } + + public World getWorld() + { + if(getSize() == 0) + { + return null; + } + + return transmitters.iterator().next().getTile().getWorldObj(); + } + + protected Range4D genPacketRange() + { + if(getSize() == 0) + { + deregister(); + return null; + } + + Coord4D initCoord = Coord4D.get(transmitters.iterator().next().getTile()); + + int minX = initCoord.xCoord; + int minY = initCoord.yCoord; + int minZ = initCoord.zCoord; + int maxX = initCoord.xCoord; + int maxY = initCoord.yCoord; + int maxZ = initCoord.zCoord; + + for(IGridTransmitter transmitter : transmitters) + { + Coord4D coord = Coord4D.get(transmitter.getTile()); + + if(coord.xCoord < minX) minX = coord.xCoord; + if(coord.yCoord < minY) minY = coord.yCoord; + if(coord.zCoord < minZ) minZ = coord.zCoord; + if(coord.xCoord > maxX) maxX = coord.xCoord; + if(coord.yCoord > maxY) maxY = coord.yCoord; + if(coord.zCoord > maxZ) maxZ = coord.zCoord; + } + + return new Range4D(minX, minY, minZ, maxX, maxY, maxZ, getWorld().provider.dimensionId); + } + + @Override + public void removeTransmitter(IGridTransmitter transmitter) + { + transmitters.remove(transmitter); + updateCapacity(); + + if(transmitters.size() == 0) + { + deregister(); + } + } + + @Override + public void register() + { + try { + IGridTransmitter aTransmitter = transmitters.iterator().next(); + + if(aTransmitter instanceof TileEntity) + { + if(!((TileEntity)aTransmitter).getWorldObj().isRemote) + { + TransmitterNetworkRegistry.getInstance().registerNetwork(this); + } + else { + MinecraftForge.EVENT_BUS.post(new ClientTickUpdate(this, (byte)1)); + } + } + } catch(NoSuchElementException e) {} + } + + @Override + public void deregister() + { + transmitters.clear(); + + if(FMLCommonHandler.instance().getEffectiveSide().isServer()) + { + TransmitterNetworkRegistry.getInstance().removeNetwork(this); + } + else { + MinecraftForge.EVENT_BUS.post(new ClientTickUpdate(this, (byte)0)); + } + } + + @Override + public int getSize() + { + return transmitters.size(); + } + + @Override + public int getAcceptorSize() + { + return possibleAcceptors.size(); + } + + public synchronized void updateCapacity() + { + updateMeanCapacity(); + capacity = (int)meanCapacity * transmitters.size(); + } + + /** + * Override this if things can have variable capacity along the network. + * @return An 'average' value of capacity. Calculate it how you will. + */ + protected synchronized void updateMeanCapacity() + { + if(transmitters.size() > 0) + { + meanCapacity = transmitters.iterator().next().getCapacity(); + } + else { + meanCapacity = 0; + } + } + + public int getCapacity() + { + return capacity; + } + + public double getMeanCapacity() + { + return meanCapacity; + } + + @Override + public void tick() + { + boolean didFix = false; + + if(!fixed) + { + ticksSinceCreate++; + + if(transmitters.size() == 0) + { + deregister(); + return; + } + + if(ticksSinceCreate > 1200) + { + ticksSinceCreate = 0; + fixMessedUpNetwork(transmitters.iterator().next()); + didFix = true; + } + } + + if(!didFix) + { + onUpdate(); + } + } + + public void onUpdate() + { + if(FMLCommonHandler.instance().getEffectiveSide().isServer()) + { + Iterator i = updateQueue.iterator(); + + try { + while(i.hasNext()) + { + DelayQueue q = i.next(); + + if(q.delay > 0) + { + q.delay--; + } + else { + needsUpdate = true; + i.remove(); + } + } + } catch(Exception e) {} + } + } + + @Override + public synchronized void fixMessedUpNetwork(IGridTransmitter transmitter) + { + if(transmitter instanceof TileEntity) + { + NetworkFinder finder = new NetworkFinder(((TileEntity)transmitter).getWorldObj(), getTransmissionType(), Coord4D.get((TileEntity)transmitter)); + List partNetwork = finder.exploreNetwork(); + Set> newTransporters = new HashSet>(); + + for(Coord4D node : partNetwork) + { + TileEntity nodeTile = node.getTileEntity(((TileEntity)transmitter).getWorldObj()); + + if(TransmissionType.checkTransmissionType(nodeTile, getTransmissionType(), (TileEntity)transmitter)) + { + ((IGridTransmitter)nodeTile).removeFromTransmitterNetwork(); + newTransporters.add((IGridTransmitter)nodeTile); + } + } + + ITransmitterNetwork newNetwork = create(newTransporters); + newNetwork.fullRefresh(); + newNetwork.setFixed(true); + deregister(); + } + } + + @Override + public synchronized void split(IGridTransmitter splitPoint) + { + if(splitPoint instanceof TileEntity) + { + removeTransmitter(splitPoint); + + TileEntity[] connectedBlocks = new TileEntity[6]; + boolean[] dealtWith = {false, false, false, false, false, false}; + List> newNetworks = new ArrayList>(); + + for(ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) + { + TileEntity sideTile = Coord4D.get((TileEntity)splitPoint).getFromSide(side).getTileEntity(((TileEntity)splitPoint).getWorldObj()); + + if(sideTile != null) + { + connectedBlocks[side.ordinal()] = sideTile; + } + } + + for(int count = 0; count < connectedBlocks.length; count++) + { + TileEntity connectedBlockA = connectedBlocks[count]; + + if(TransmissionType.checkTransmissionType(connectedBlockA, getTransmissionType()) && !dealtWith[count]) + { + NetworkFinder finder = new NetworkFinder(((TileEntity)splitPoint).getWorldObj(), getTransmissionType(), Coord4D.get(connectedBlockA), Coord4D.get((TileEntity)splitPoint)); + List partNetwork = finder.exploreNetwork(); + + for(int check = count; check < connectedBlocks.length; check++) + { + if(check == count) + { + continue; + } + + TileEntity connectedBlockB = connectedBlocks[check]; + + if(TransmissionType.checkTransmissionType(connectedBlockB, getTransmissionType()) && !dealtWith[check]) + { + if(partNetwork.contains(Coord4D.get(connectedBlockB))) + { + dealtWith[check] = true; + } + } + } + + Set> newNetCables = new HashSet>(); + + for(Coord4D node : finder.iterated) + { + TileEntity nodeTile = node.getTileEntity(((TileEntity)splitPoint).getWorldObj()); + + if(TransmissionType.checkTransmissionType(nodeTile, getTransmissionType())) + { + if(nodeTile != splitPoint) + { + newNetCables.add((IGridTransmitter)nodeTile); + } + } + } + + newNetworks.add(create(newNetCables)); + } + } + + if(newNetworks.size() > 0) + { + onNetworksCreated((List)newNetworks); + + for(ITransmitterNetwork network : newNetworks) + { + network.fullRefresh(); + } + } + + deregister(); + } + } + + @Override + public void onNetworksCreated(List networks) {} + + @Override + public void setFixed(boolean value) + { + fixed = value; + } + + @Override + public boolean needsTicks() + { + return getSize() > 0; + } + + @Override + public void clientTick() + { + ticksSinceCreate++; + + if(ticksSinceCreate == 5 && getSize() > 0) + { + TileEntity tile = (TileEntity)transmitters.iterator().next(); + MinecraftForge.EVENT_BUS.post(new NetworkClientRequest(tile)); + } + } + + @Override + public boolean canMerge(List> networks) + { + return true; + } + + public static class ClientTickUpdate extends Event + { + public DynamicNetwork network; + public byte operation; /*0 remove, 1 add*/ + + public ClientTickUpdate(DynamicNetwork net, byte b) + { + network = net; + operation = b; + } + } + + public static class NetworkClientRequest extends Event + { + public TileEntity tileEntity; + + public NetworkClientRequest(TileEntity tile) + { + tileEntity = tile; + } + } + + public void addUpdate(EntityPlayer player) + { + updateQueue.add(new DelayQueue(player)); + } + + public static class NetworkFinder + { + public TransmissionType transmissionType; + + public World worldObj; + public Coord4D start; + + public List iterated = new ArrayList(); + public List toIgnore = new ArrayList(); + + public NetworkFinder(World world, TransmissionType type, Coord4D location, Coord4D... ignore) + { + worldObj = world; + start = location; + + transmissionType = type; + + if(ignore != null) + { + for(int i = 0; i < ignore.length; i++) + { + toIgnore.add(ignore[i]); + } + } + } + + public void loopAll(Coord4D location) + { + if(TransmissionType.checkTransmissionType(location.getTileEntity(worldObj), transmissionType)) + { + iterated.add(location); + } + else { + toIgnore.add(location); + } + + for(ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS) + { + Coord4D obj = location.getFromSide(direction); + + if(!iterated.contains(obj) && !toIgnore.contains(obj)) + { + TileEntity tileEntity = obj.getTileEntity(worldObj); + + if(!(tileEntity instanceof IBlockableConnection) || ((IBlockableConnection)tileEntity).canConnectMutual(direction.getOpposite())) + { + if(TransmissionType.checkTransmissionType(tileEntity, transmissionType, location.getTileEntity(worldObj))) + { + loopAll(obj); + } + } + } + } + } + + public List exploreNetwork() + { + loopAll(start); + + return iterated; + } + } + + public static class DelayQueue + { + public EntityPlayer player; + public int delay; + + public DelayQueue(EntityPlayer p) + { + player = p; + delay = 5; + } + } +} diff --git a/src/api/java/mekanism/api/transmitters/IBlockableConnection.java b/src/api/java/mekanism/api/transmitters/IBlockableConnection.java new file mode 100644 index 00000000..f6811fbe --- /dev/null +++ b/src/api/java/mekanism/api/transmitters/IBlockableConnection.java @@ -0,0 +1,10 @@ +package mekanism.api.transmitters; + +import net.minecraftforge.common.util.ForgeDirection; + +public interface IBlockableConnection +{ + public boolean canConnectMutual(ForgeDirection side); + + public boolean canConnect(ForgeDirection side); +} diff --git a/src/api/java/mekanism/api/transmitters/IGridTransmitter.java b/src/api/java/mekanism/api/transmitters/IGridTransmitter.java new file mode 100644 index 00000000..ea222d8e --- /dev/null +++ b/src/api/java/mekanism/api/transmitters/IGridTransmitter.java @@ -0,0 +1,66 @@ +package mekanism.api.transmitters; + +import mekanism.api.Coord4D; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; + +public interface IGridTransmitter> extends ITransmitter +{ + /** + * Gets the network currently in use by this transmitter segment. + * @return network this transmitter is using + */ + public N getTransmitterNetwork(); + + /** + * Gets the network currently in use by this transmitter segment. + * @param createIfNull - If true, the transmitter will try and connect to an + * adjacent network, merging several if necessary, or creating a new one + * if none is available + * @return network this transmitter is using + */ + public N getTransmitterNetwork(boolean createIfNull); + + /** + * Sets this transmitter segment's network to a new value. + * @param network - network to set to + */ + public void setTransmitterNetwork(N network); + + /** + * Refreshes the transmitter's network. + */ + public void refreshTransmitterNetwork(); + + /** + * Called when the chunk this transmitter is in is loaded. + */ + public void chunkLoad(); + + /** + * Remove this transmitter from its network. + */ + public void removeFromTransmitterNetwork(); + + public boolean canConnectToAcceptor(ForgeDirection side, boolean ignoreActive); + + /** + * Call this if you're worried a transmitter's network is messed up and you want + * it to try and fix itself. + */ + public void fixTransmitterNetwork(); + + public boolean areTransmitterNetworksEqual(TileEntity tileEntity); + + public int getTransmitterNetworkSize(); + + public int getTransmitterNetworkAcceptorSize(); + + public String getTransmitterNetworkNeeded(); + + public String getTransmitterNetworkFlow(); + + public int getCapacity(); + + public TileEntity getTile(); +} diff --git a/src/api/java/mekanism/api/transmitters/INetworkDataHandler.java b/src/api/java/mekanism/api/transmitters/INetworkDataHandler.java new file mode 100644 index 00000000..38cd6370 --- /dev/null +++ b/src/api/java/mekanism/api/transmitters/INetworkDataHandler.java @@ -0,0 +1,10 @@ +package mekanism.api.transmitters; + +public interface INetworkDataHandler +{ + public String getNeededInfo(); + + public String getStoredInfo(); + + public String getFlowInfo(); +} diff --git a/src/api/java/mekanism/api/transmitters/ITransmitter.java b/src/api/java/mekanism/api/transmitters/ITransmitter.java new file mode 100644 index 00000000..cddc76a7 --- /dev/null +++ b/src/api/java/mekanism/api/transmitters/ITransmitter.java @@ -0,0 +1,11 @@ +package mekanism.api.transmitters; + +public interface ITransmitter +{ + /** + * Get the transmitter's transmission type + * + * @return TransmissionType this transmitter uses + */ + public TransmissionType getTransmissionType(); +} diff --git a/src/api/java/mekanism/api/transmitters/ITransmitterNetwork.java b/src/api/java/mekanism/api/transmitters/ITransmitterNetwork.java new file mode 100644 index 00000000..4bb2e823 --- /dev/null +++ b/src/api/java/mekanism/api/transmitters/ITransmitterNetwork.java @@ -0,0 +1,39 @@ +package mekanism.api.transmitters; + +import java.util.List; +import java.util.Set; + +public interface ITransmitterNetwork> +{ + public void tick(); + + public int getSize(); + + public int getAcceptorSize(); + + public Set getAcceptors(Object... data); + + public void removeTransmitter(IGridTransmitter transmitter); + + public void refresh(); + + public void fullRefresh(); + + public void refresh(IGridTransmitter transmitter); + + public void split(IGridTransmitter splitPoint); + + public void fixMessedUpNetwork(IGridTransmitter transmitter); + + public void register(); + + public void deregister(); + + public void setFixed(boolean value); + + public TransmissionType getTransmissionType(); + + public boolean canMerge(List> networks); + + public void onNetworksCreated(List networks); +} diff --git a/src/api/java/mekanism/api/transmitters/TransmissionType.java b/src/api/java/mekanism/api/transmitters/TransmissionType.java new file mode 100644 index 00000000..ae9388cc --- /dev/null +++ b/src/api/java/mekanism/api/transmitters/TransmissionType.java @@ -0,0 +1,43 @@ +package mekanism.api.transmitters; + +import mekanism.api.gas.IGasTransmitter; +import net.minecraft.tileentity.TileEntity; + +public enum TransmissionType +{ + ENERGY, + FLUID, + GAS, + ITEM; + + public static boolean checkTransmissionType(TileEntity sideTile, TransmissionType type) + { + return checkTransmissionType(sideTile, type, null); + } + + public static boolean checkTransmissionType(TileEntity sideTile, TransmissionType type, TileEntity currentPipe) + { + return type.checkTransmissionType(sideTile, currentPipe); + } + + public boolean checkTransmissionType(TileEntity sideTile, TileEntity currentTile) + { + if(sideTile instanceof ITransmitter) + { + if(((ITransmitter)sideTile).getTransmissionType() == this) + { + return true; + } + } + + if(this == GAS && currentTile instanceof IGasTransmitter) + { + if(((IGasTransmitter)currentTile).canTransferGasToTube(sideTile)) + { + return true; + } + } + + return false; + } +} \ No newline at end of file diff --git a/src/api/java/mekanism/api/transmitters/TransmitterNetworkRegistry.java b/src/api/java/mekanism/api/transmitters/TransmitterNetworkRegistry.java new file mode 100644 index 00000000..f0784f08 --- /dev/null +++ b/src/api/java/mekanism/api/transmitters/TransmitterNetworkRegistry.java @@ -0,0 +1,160 @@ +package mekanism.api.transmitters; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.chunk.IChunkProvider; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.world.ChunkEvent; +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import cpw.mods.fml.common.gameevent.TickEvent.Phase; +import cpw.mods.fml.common.gameevent.TickEvent.ServerTickEvent; +import cpw.mods.fml.relauncher.Side; + +public class TransmitterNetworkRegistry +{ + private static TransmitterNetworkRegistry INSTANCE = new TransmitterNetworkRegistry(); + private static boolean loaderRegistered = false; + + private HashSet networks = new HashSet(); + + public static void initiate() + { + if(!loaderRegistered) + { + loaderRegistered = true; + + MinecraftForge.EVENT_BUS.register(new NetworkLoader()); + FMLCommonHandler.instance().bus().register(INSTANCE); + } + } + + public static TransmitterNetworkRegistry getInstance() + { + return INSTANCE; + } + + public void registerNetwork(ITransmitterNetwork network) + { + networks.add(network); + } + + public void removeNetwork(ITransmitterNetwork network) + { + if(networks.contains(network)) + { + networks.remove(network); + } + } + + public void pruneEmptyNetworks() + { + HashSet copySet = new HashSet(networks); + + for(ITransmitterNetwork e : copySet) + { + if(e.getSize() == 0) + { + removeNetwork(e); + } + } + } + + @SubscribeEvent + public void onTick(ServerTickEvent event) + { + if(event.phase == Phase.END && event.side == Side.SERVER) + { + tickEnd(); + } + } + + public void tickEnd() + { + Set iterNetworks = (Set)networks.clone(); + + for(ITransmitterNetwork net : iterNetworks) + { + if(networks.contains(net)) + { + net.tick(); + } + } + } + + @Override + public String toString() + { + return "Network Registry:\n" + networks; + } + + public String[] toStrings() + { + String[] strings = new String[networks.size()]; + int i = 0; + + for(ITransmitterNetwork network : networks) + { + strings[i] = network.toString(); + ++i; + } + + return strings; + } + + public static class NetworkLoader + { + @SubscribeEvent + public void onChunkLoad(ChunkEvent.Load event) + { + if(event.getChunk() != null && !event.world.isRemote) + { + int x = event.getChunk().xPosition; + int z = event.getChunk().zPosition; + + IChunkProvider cProvider = event.getChunk().worldObj.getChunkProvider(); + Chunk[] neighbors = new Chunk[5]; + + neighbors[0] = event.getChunk(); + + if(cProvider.chunkExists(x + 1, z)) neighbors[1] = cProvider.provideChunk(x + 1, z); + if(cProvider.chunkExists(x - 1, z)) neighbors[2] = cProvider.provideChunk(x - 1, z); + if(cProvider.chunkExists(x, z + 1)) neighbors[3] = cProvider.provideChunk(x, z + 1); + if(cProvider.chunkExists(x, z - 1)) neighbors[4] = cProvider.provideChunk(x, z - 1); + + for(Chunk c : neighbors) + { + refreshChunk(c); + } + } + } + + public synchronized void refreshChunk(Chunk c) + { + try { + if(c != null) + { + Map copy = (Map)((HashMap)c.chunkTileEntityMap).clone(); + + for(Iterator iter = copy.values().iterator(); iter.hasNext();) + { + Object obj = iter.next(); + + if(obj instanceof IGridTransmitter) + { + ((IGridTransmitter)obj).refreshTransmitterNetwork(); + ((IGridTransmitter)obj).chunkLoad(); + } + } + } + } catch(Exception e) { + e.printStackTrace(); + } + } + } +} diff --git a/src/main/java/crazypants/enderio/ClientProxy.java b/src/main/java/crazypants/enderio/ClientProxy.java index 99c8cd6c..449be10d 100644 --- a/src/main/java/crazypants/enderio/ClientProxy.java +++ b/src/main/java/crazypants/enderio/ClientProxy.java @@ -19,6 +19,8 @@ import crazypants.enderio.conduit.BlockConduitBundle; import crazypants.enderio.conduit.IConduit; import crazypants.enderio.conduit.TileConduitBundle; import crazypants.enderio.conduit.facade.FacadeRenderer; +import crazypants.enderio.conduit.gas.GasConduit; +import crazypants.enderio.conduit.gas.GasConduitRenderer; import crazypants.enderio.conduit.item.ItemConduit; import crazypants.enderio.conduit.liquid.AdvancedLiquidConduit; import crazypants.enderio.conduit.liquid.AdvancedLiquidConduitRenderer; @@ -71,7 +73,6 @@ import crazypants.enderio.machine.light.ElectricLightRenderer; import crazypants.enderio.machine.painter.BlockPaintedFenceGate; import crazypants.enderio.machine.painter.BlockPaintedFenceGateRenderer; import crazypants.enderio.machine.painter.BlockPaintedGlowstone; -import crazypants.enderio.machine.painter.BlockPaintedGlowstoneRenderer; import crazypants.enderio.machine.painter.PaintedBlockRenderer; import crazypants.enderio.machine.painter.PaintedItemRenderer; import crazypants.enderio.machine.power.BlockCapacitorBank; @@ -118,6 +119,7 @@ public class ClientProxy extends CommonProxy { AdvancedLiquidConduit.initIcons(); EnderLiquidConduit.initIcons(); ItemConduit.initIcons(); + GasConduit.initIcons(); } private List conduitRenderers = new ArrayList(); @@ -125,7 +127,7 @@ public class ClientProxy extends CommonProxy { private DefaultConduitRenderer dcr = new DefaultConduitRenderer(); private ConduitBundleRenderer cbr; - + private boolean checkedNei = false; private boolean neiInstalled = false; @@ -133,16 +135,16 @@ public class ClientProxy extends CommonProxy { public World getClientWorld() { return FMLClientHandler.instance().getClient().theWorld; } - + @Override - public boolean isNeiInstalled() { + public boolean isNeiInstalled() { if(checkedNei) { return neiInstalled; } - try{ + try { Class.forName("crazypants.enderio.nei.EnchanterRecipeHandler"); neiInstalled = true; - } catch(Exception e) { + } catch (Exception e) { neiInstalled = false; } checkedNei = true; @@ -176,44 +178,43 @@ public class ClientProxy extends CommonProxy { RenderingRegistry.registerBlockHandler(machRen); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockStirlingGenerator), machRen); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockCrusher), machRen); - MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockAlloySmelter), machRen); + MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockAlloySmelter), machRen); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockPowerMonitor), machRen); - MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockPainter), machRen); + MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockPainter), machRen); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockCrafter), machRen); - + MinecraftForgeClient.registerItemRenderer(EnderIO.itemBrokenSpawner, new BrokenSpawnerRenderer()); - + EnchanterModelRenderer emr = new EnchanterModelRenderer(); ClientRegistry.bindTileEntitySpecialRenderer(TileEnchanter.class, emr); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockEnchanter), emr); - BlockFusedQuartz.renderId = RenderingRegistry.getNextAvailableRenderId(); RenderingRegistry.registerBlockHandler(new FusedQuartzRenderer()); BlockFarmStation.renderId = RenderingRegistry.getNextAvailableRenderId(); RenderingRegistry.registerBlockHandler(new FarmingStationRenderer()); - -// BlockWirelessCharger.renderId = RenderingRegistry.getNextAvailableRenderId(); -// RenderingRegistry.registerBlockHandler(new WirelessChargerRenderer()); + + // BlockWirelessCharger.renderId = RenderingRegistry.getNextAvailableRenderId(); + // RenderingRegistry.registerBlockHandler(new WirelessChargerRenderer()); if(Config.useCombustionGenModel) { CombustionGeneratorModelRenderer cgmr = new CombustionGeneratorModelRenderer(); ClientRegistry.bindTileEntitySpecialRenderer(TileCombustionGenerator.class, cgmr); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockCombustionGenerator), cgmr); - } else { + } else { BlockCombustionGenerator.renderId = RenderingRegistry.getNextAvailableRenderId(); CombustionGeneratorRenderer cr = new CombustionGeneratorRenderer(); RenderingRegistry.registerBlockHandler(cr); if(!Config.combustionGeneratorUseOpaqueModel) { ClientRegistry.bindTileEntitySpecialRenderer(TileCombustionGenerator.class, cr); - } + } } - + ZombieGeneratorRenderer zgr = new ZombieGeneratorRenderer(); ClientRegistry.bindTileEntitySpecialRenderer(TileZombieGenerator.class, zgr); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockZombieGenerator), zgr); - + KillerJoeRenderer kjr = new KillerJoeRenderer(); ClientRegistry.bindTileEntitySpecialRenderer(TileKillerJoe.class, kjr); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockKillerJoe), kjr); @@ -246,6 +247,7 @@ public class ClientProxy extends CommonProxy { MinecraftForgeClient.registerItemRenderer(EnderIO.itemPowerConduit, itemConRenderer); MinecraftForgeClient.registerItemRenderer(EnderIO.itemRedstoneConduit, itemConRenderer); MinecraftForgeClient.registerItemRenderer(EnderIO.itemItemConduit, itemConRenderer); + MinecraftForgeClient.registerItemRenderer(EnderIO.itemGasConduit, itemConRenderer); BlockPaintedFenceGateRenderer bcfgr = new BlockPaintedFenceGateRenderer(); BlockPaintedFenceGate.renderId = RenderingRegistry.getNextAvailableRenderId(); @@ -261,14 +263,13 @@ public class ClientProxy extends CommonProxy { MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockPaintedCarpet), pir); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockDarkSteelPressurePlate), pir); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockTravelPlatform), pir); - + BlockPaintedGlowstone.renderId = RenderingRegistry.getNextAvailableRenderId(); RenderingRegistry.registerBlockHandler(new PaintedBlockRenderer(BlockPaintedGlowstone.renderId, Blocks.glowstone)); - + BlockTravelAnchor.renderId = RenderingRegistry.getNextAvailableRenderId(); RenderingRegistry.registerBlockHandler(new PaintedBlockRenderer(BlockTravelAnchor.renderId, EnderIO.blockTravelPlatform)); - - + MinecraftForgeClient.registerItemRenderer(EnderIO.itemMachinePart, new MachinePartRenderer()); MinecraftForgeClient.registerItemRenderer(EnderIO.itemConduitFacade, new FacadeRenderer()); @@ -278,9 +279,9 @@ public class ClientProxy extends CommonProxy { ClientRegistry.bindTileEntitySpecialRenderer(TileConduitBundle.class, cbr); ClientRegistry.bindTileEntitySpecialRenderer(TileTravelAnchor.class, new TravelEntitySpecialRenderer()); - + BlockEndermanSkull.renderId = RenderingRegistry.getNextAvailableRenderId(); - RenderingRegistry.registerBlockHandler(new EndermanSkullRenderer()); + RenderingRegistry.registerBlockHandler(new EndermanSkullRenderer()); conduitRenderers.add(RedstoneSwitchRenderer.getInstance()); conduitRenderers.add(new AdvancedLiquidConduitRenderer()); @@ -289,6 +290,7 @@ public class ClientProxy extends CommonProxy { conduitRenderers.add(new InsulatedRedstoneConduitRenderer()); conduitRenderers.add(new EnderLiquidConduitRenderer()); conduitRenderers.add(new crazypants.enderio.conduit.item.ItemConduitRenderer()); + conduitRenderers.add(new GasConduitRenderer()); EnderIoRenderer eior = new EnderIoRenderer(); ClientRegistry.bindTileEntitySpecialRenderer(TileEnderIO.class, eior); @@ -322,14 +324,12 @@ public class ClientProxy extends CommonProxy { //Ensure it is loaded and registered KeyTracker.instance.isGlideActive(); - RenderingRegistry.registerEntityRenderingHandler(SoundEntity.class, new SoundRenderer()); - - MinecraftForge.EVENT_BUS.register(SoundDetector.instance); - FMLCommonHandler.instance().bus().register(SoundDetector.instance); - - } + MinecraftForge.EVENT_BUS.register(SoundDetector.instance); + FMLCommonHandler.instance().bus().register(SoundDetector.instance); + + } @Override public ConduitRenderer getRendererForConduit(IConduit conduit) { diff --git a/src/main/java/crazypants/enderio/EnderIO.java b/src/main/java/crazypants/enderio/EnderIO.java index 289d49ba..e23a4488 100644 --- a/src/main/java/crazypants/enderio/EnderIO.java +++ b/src/main/java/crazypants/enderio/EnderIO.java @@ -1,6 +1,8 @@ package crazypants.enderio; -import static crazypants.enderio.EnderIO.*; +import static crazypants.enderio.EnderIO.MODID; +import static crazypants.enderio.EnderIO.MOD_NAME; +import static crazypants.enderio.EnderIO.VERSION; import net.minecraft.block.material.Material; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; @@ -30,6 +32,7 @@ import crazypants.enderio.conduit.BlockConduitBundle; import crazypants.enderio.conduit.ConduitRecipes; import crazypants.enderio.conduit.facade.BlockConduitFacade; import crazypants.enderio.conduit.facade.ItemConduitFacade; +import crazypants.enderio.conduit.gas.ItemGasConduit; import crazypants.enderio.conduit.geom.ConduitGeometryUtil; import crazypants.enderio.conduit.item.ItemExtractSpeedUpgrade; import crazypants.enderio.conduit.item.ItemItemConduit; @@ -165,6 +168,7 @@ public class EnderIO { public static ItemPowerConduit itemPowerConduit; public static ItemLiquidConduit itemLiquidConduit; public static ItemItemConduit itemItemConduit; + public static ItemGasConduit itemGasConduit; public static ItemBasicItemFilter itemBasicFilterUpgrade; public static ItemExistingItemFilter itemExistingItemFilter; public static ItemModItemFilter itemModItemFilter; @@ -188,11 +192,11 @@ public class EnderIO { public static BlockCrafter blockCrafter; public static BlockPoweredSpawner blockPoweredSpawner; public static ItemBrokenSpawner itemBrokenSpawner; - + public static BlockKillerJoe blockKillerJoe; public static BlockEnchanter blockEnchanter; - + public static BlockElectricLight blockElectricLight; public static BlockLightNode blockLightNode; @@ -282,9 +286,9 @@ public class EnderIO { blockTank = BlockTank.create(); blockReservoir = BlockReservoir.create(); blockVacuumChest = BlockVacuumChest.create(); - + blockEnchanter = BlockEnchanter.create(); - + blockKillerJoe = BlockKillerJoe.create(); blockDarkSteelPressurePlate = BlockDarkSteelPressurePlate.create(); @@ -304,6 +308,7 @@ public class EnderIO { itemPowerConduit = ItemPowerConduit.create(); itemLiquidConduit = ItemLiquidConduit.create(); itemItemConduit = ItemItemConduit.create(); + itemGasConduit = ItemGasConduit.create(); itemBasicFilterUpgrade = ItemBasicItemFilter.create(); itemExistingItemFilter = ItemExistingItemFilter.create(); @@ -363,7 +368,7 @@ public class EnderIO { blockDarkIronBars = BlockDarkIronBars.create(); itemGliderWing = ItemGliderWing.create(); - + itemDarkSteelHelmet = ItemDarkSteelArmor.create(0); itemDarkSteelChestplate = ItemDarkSteelArmor.create(1); itemDarkSteelLeggings = ItemDarkSteelArmor.create(2); @@ -374,14 +379,13 @@ public class EnderIO { itemDarkSteelAxe = ItemDarkSteelAxe.create(); blockEndermanSkull = BlockEndermanSkull.create(); - + MaterialRecipes.registerOresInDictionary(); - - - int entityID = EntityRegistry.findGlobalUniqueEntityId(); + + int entityID = EntityRegistry.findGlobalUniqueEntityId(); EntityRegistry.registerGlobalEntityID(SoundEntity.class, "soundEntity", entityID); - EntityRegistry.registerModEntity(SoundEntity.class, "soundEntity", entityID, this, 0, 0, false); - + EntityRegistry.registerModEntity(SoundEntity.class, "soundEntity", entityID, this, 0, 0, false); + } @EventHandler @@ -397,7 +401,7 @@ public class EnderIO { //Register Custom Dungeon Loot here ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).addItem( - new WeightedRandomChestContent(new ItemStack(EnderIO.itemAlloy, 1, Alloy.DARK_STEEL.ordinal()), 1, 3, 15)); + new WeightedRandomChestContent(new ItemStack(EnderIO.itemAlloy, 1, Alloy.DARK_STEEL.ordinal()), 1, 3, 15)); ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(EnderIO.itemConduitProbe, 1, 0), 1, 1, 10)); ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(Items.quartz), 3, 16, 20)); diff --git a/src/main/java/crazypants/enderio/ModObject.java b/src/main/java/crazypants/enderio/ModObject.java index 7581a2fc..7c9ec250 100644 --- a/src/main/java/crazypants/enderio/ModObject.java +++ b/src/main/java/crazypants/enderio/ModObject.java @@ -11,7 +11,7 @@ public enum ModObject { itemConduitFacade, itemRedstoneConduit, itemItemConduit, - itemMeConduit, + itemGasConduit, itemBasicFilterUpgrade, itemExistingItemFilter, itemModItemFilter, @@ -48,19 +48,19 @@ public enum ModObject { blockFarmStation, blockTank, blockCrafter, - blockVacuumChest, + blockVacuumChest, blockWirelessCharger, blockEnchanter, - + blockPoweredSpawner, itemBrokenSpawner, - + blockKillerJoe, blockElectricLight, blockLightNode, blockLight, - + //Blocks blockDarkSteelPressurePlate, blockReinforcedObsidian, @@ -80,9 +80,9 @@ public enum ModObject { itemYetaWrench, blockTravelAnchor, - itemTravelStaff, - itemMagnet, - itemGliderWing, + itemTravelStaff, + itemMagnet, + itemGliderWing, blockEndermanSkull; public final String unlocalisedName; diff --git a/src/main/java/crazypants/enderio/conduit/ConduitDisplayMode.java b/src/main/java/crazypants/enderio/conduit/ConduitDisplayMode.java index 3f7f3f48..19831277 100644 --- a/src/main/java/crazypants/enderio/conduit/ConduitDisplayMode.java +++ b/src/main/java/crazypants/enderio/conduit/ConduitDisplayMode.java @@ -8,8 +8,9 @@ public enum ConduitDisplayMode { ALL, POWER, REDSTONE, + FLUID, ITEM, - FLUID; + GAS; public static ConduitDisplayMode next(ConduitDisplayMode mode) { int index = mode.ordinal() + 1; diff --git a/src/main/java/crazypants/enderio/conduit/ConduitRecipes.java b/src/main/java/crazypants/enderio/conduit/ConduitRecipes.java index 89d53773..44c1f67d 100644 --- a/src/main/java/crazypants/enderio/conduit/ConduitRecipes.java +++ b/src/main/java/crazypants/enderio/conduit/ConduitRecipes.java @@ -1,18 +1,18 @@ package crazypants.enderio.conduit; -import static crazypants.enderio.ModObject.*; +import static crazypants.enderio.ModObject.blockPainter; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.oredict.ShapedOreRecipe; +import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.registry.GameRegistry; import crazypants.enderio.EnderIO; import crazypants.enderio.conduit.facade.ItemConduitFacade.FacadePainterRecipe; import crazypants.enderio.conduit.item.filter.ClearFilterRecipe; import crazypants.enderio.conduit.item.filter.CopyFilterRecipe; import crazypants.enderio.config.Config; -import crazypants.enderio.machine.ClearConfigRecipe; import crazypants.enderio.machine.MachineRecipeRegistry; import crazypants.enderio.material.Alloy; import crazypants.enderio.material.BlockFusedQuartz; @@ -43,7 +43,8 @@ public class ConduitRecipes { int numConduits = Config.numConduitsPerRecipe; GameRegistry.addShapedRecipe(new ItemStack(EnderIO.itemLiquidConduit, numConduits, 0), "bbb", "###", "bbb", 'b', conduitBinder, '#', fusedGlass); GameRegistry.addShapedRecipe(new ItemStack(EnderIO.itemLiquidConduit, numConduits, 1), "bbb", "###", "bbb", 'b', conduitBinder, '#', fusedQuartz); - GameRegistry.addShapedRecipe(new ItemStack(EnderIO.itemLiquidConduit, numConduits, 2), "bbb", "#p#", "bbb", 'b', conduitBinder, '#', fusedQuartz, 'p', phasedGold); + GameRegistry.addShapedRecipe(new ItemStack(EnderIO.itemLiquidConduit, numConduits, 2), "bbb", "#p#", "bbb", 'b', conduitBinder, '#', fusedQuartz, 'p', + phasedGold); GameRegistry.addShapedRecipe(new ItemStack(EnderIO.itemPowerConduit, numConduits, 0), "bbb", "###", "bbb", 'b', conduitBinder, '#', conductiveIron); GameRegistry.addShapedRecipe(new ItemStack(EnderIO.itemPowerConduit, numConduits, 1), "bbb", "###", "bbb", 'b', conduitBinder, '#', energeticGold); GameRegistry.addShapedRecipe(new ItemStack(EnderIO.itemPowerConduit, numConduits, 2), "bbb", "###", "bbb", 'b', conduitBinder, '#', phasedGold); @@ -53,33 +54,39 @@ public class ConduitRecipes { GameRegistry.addShapedRecipe(new ItemStack(EnderIO.itemRedstoneConduit, numConduits, 2), "bbb", "###", "bbb", 'b', conduitBinder, '#', redstoneAlloy); + if(Loader.isModLoaded("Mekanism")) { + GameRegistry.addShapedRecipe(new ItemStack(EnderIO.itemGasConduit, numConduits, 0), "bbb", "#g#", "bbb", 'b', conduitBinder, '#', + electricalSteel, 'g', fusedGlass); + } + ItemStack itemConduit = new ItemStack(EnderIO.itemItemConduit, numConduits, 0); GameRegistry.addShapedRecipe(itemConduit, "bbb", "###", "bbb", 'b', conduitBinder, '#', phasedIronNugget); MachineRecipeRegistry.instance.registerRecipe(blockPainter.unlocalisedName, new FacadePainterRecipe()); - + //Filter Recipes ItemStack basicFilter = new ItemStack(EnderIO.itemBasicFilterUpgrade, 1, 0); - GameRegistry.addShapedRecipe(basicFilter, " p ","php"," p ", 'p', Items.paper, 'h', Blocks.hopper); - + GameRegistry.addShapedRecipe(basicFilter, " p ", "php", " p ", 'p', Items.paper, 'h', Blocks.hopper); + ItemStack advFilter = new ItemStack(EnderIO.itemBasicFilterUpgrade, 1, 1); - GameRegistry.addRecipe(new ShapedOreRecipe(advFilter, "rpr","php","rpr", 'p', Items.paper, 'h', "itemSkull", 'r', Items.redstone)); + GameRegistry.addRecipe(new ShapedOreRecipe(advFilter, "rpr", "php", "rpr", 'p', Items.paper, 'h', "itemSkull", 'r', Items.redstone)); ItemStack modFilter = new ItemStack(EnderIO.itemModItemFilter, 1, 0); - GameRegistry.addShapedRecipe(modFilter, " p ","pwp"," p ", 'p', Items.paper, 'w', EnderIO.itemYetaWench); - + GameRegistry.addShapedRecipe(modFilter, " p ", "pwp", " p ", 'p', Items.paper, 'w', EnderIO.itemYetaWench); + ItemStack exFilt = new ItemStack(EnderIO.itemExistingItemFilter); - GameRegistry.addShapedRecipe(exFilt, "rpr","pcp","rpr", 'p', Items.paper, 'c', new ItemStack(Items.comparator, 1, 0), 'r', Items.redstone); - + GameRegistry.addShapedRecipe(exFilt, "rpr", "pcp", "rpr", 'p', Items.paper, 'c', new ItemStack(Items.comparator, 1, 0), 'r', Items.redstone); + ClearFilterRecipe clearRec = new ClearFilterRecipe(); MinecraftForge.EVENT_BUS.register(clearRec); GameRegistry.addRecipe(clearRec); - + CopyFilterRecipe copyRec = new CopyFilterRecipe(); GameRegistry.addRecipe(copyRec); - + ItemStack speedUpgrade = new ItemStack(EnderIO.itemExtractSpeedUpgrade, 1, 0); - GameRegistry.addShapedRecipe(speedUpgrade, "iii","epe","ere", 'p', Blocks.piston, 'e', electricalSteel, 'r', Blocks.redstone_torch, 'i', Items.iron_ingot); + GameRegistry + .addShapedRecipe(speedUpgrade, "iii", "epe", "ere", 'p', Blocks.piston, 'e', electricalSteel, 'r', Blocks.redstone_torch, 'i', Items.iron_ingot); } } diff --git a/src/main/java/crazypants/enderio/conduit/ConduitUtil.java b/src/main/java/crazypants/enderio/conduit/ConduitUtil.java index 386a16bd..2362ccfe 100644 --- a/src/main/java/crazypants/enderio/conduit/ConduitUtil.java +++ b/src/main/java/crazypants/enderio/conduit/ConduitUtil.java @@ -24,6 +24,8 @@ import cpw.mods.fml.relauncher.SideOnly; import crazypants.enderio.EnderIO; import crazypants.enderio.Log; import crazypants.enderio.conduit.IConduitBundle.FacadeRenderState; +import crazypants.enderio.conduit.gas.GasConduitNetwork; +import crazypants.enderio.conduit.gas.IGasConduit; import crazypants.enderio.conduit.item.IItemConduit; import crazypants.enderio.conduit.item.ItemConduitNetwork; import crazypants.enderio.conduit.liquid.AdvancedLiquidConduit; @@ -59,6 +61,8 @@ public class ConduitUtil { return new LiquidConduitNetwork(); } else if(IItemConduit.class.isAssignableFrom(type)) { return new ItemConduitNetwork(); + } else if(IGasConduit.class.isAssignableFrom(type)) { + return new GasConduitNetwork(); } FMLCommonHandler.instance().raiseException(new Exception("Could not determine network type for class " + type), "ConduitUtil.createNetworkForType", false); return null; @@ -206,14 +210,16 @@ public class ConduitUtil { switch (mode) { case ALL: return true; - case FLUID: - return conduitType == ILiquidConduit.class; - case ITEM: - return conduitType == IItemConduit.class; case POWER: return conduitType == IPowerConduit.class; case REDSTONE: return conduitType == IRedstoneConduit.class || conduitType == IInsulatedRedstoneConduit.class; + case FLUID: + return conduitType == ILiquidConduit.class; + case ITEM: + return conduitType == IItemConduit.class; + case GAS: + return conduitType == IGasConduit.class; default: break; } diff --git a/src/main/java/crazypants/enderio/conduit/IConduitBundle.java b/src/main/java/crazypants/enderio/conduit/IConduitBundle.java index dc66b613..88af5ccc 100644 --- a/src/main/java/crazypants/enderio/conduit/IConduitBundle.java +++ b/src/main/java/crazypants/enderio/conduit/IConduitBundle.java @@ -4,11 +4,13 @@ import java.util.Collection; import java.util.List; import java.util.Set; +import mekanism.api.gas.IGasHandler; import net.minecraft.block.Block; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.fluids.IFluidHandler; import cofh.api.transport.IItemDuct; +import cpw.mods.fml.common.Optional; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import crazypants.enderio.conduit.geom.CollidableComponent; @@ -16,7 +18,8 @@ import crazypants.enderio.conduit.geom.Offset; import crazypants.enderio.power.IInternalPowerReceptor; import crazypants.util.BlockCoord; -public interface IConduitBundle extends IInternalPowerReceptor, IFluidHandler, IItemDuct { +@Optional.Interface(iface = "mekanism.api.gas.IGasHandler", modid = "Mekanism") +public interface IConduitBundle extends IInternalPowerReceptor, IFluidHandler, IItemDuct, IGasHandler { TileEntity getEntity(); diff --git a/src/main/java/crazypants/enderio/conduit/TileConduitBundle.java b/src/main/java/crazypants/enderio/conduit/TileConduitBundle.java index 51687f0d..49d2de2e 100644 --- a/src/main/java/crazypants/enderio/conduit/TileConduitBundle.java +++ b/src/main/java/crazypants/enderio/conduit/TileConduitBundle.java @@ -6,6 +6,8 @@ import java.util.HashSet; import java.util.List; import java.util.Set; +import mekanism.api.gas.Gas; +import mekanism.api.gas.GasStack; import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -17,10 +19,12 @@ import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTankInfo; import buildcraft.api.power.PowerHandler; import buildcraft.api.power.PowerHandler.PowerReceiver; +import cpw.mods.fml.common.Optional; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import crazypants.enderio.EnderIO; import crazypants.enderio.TileEntityEio; +import crazypants.enderio.conduit.gas.IGasConduit; import crazypants.enderio.conduit.geom.CollidableCache; import crazypants.enderio.conduit.geom.CollidableComponent; import crazypants.enderio.conduit.geom.ConduitConnectorType; @@ -757,4 +761,46 @@ public class TileConduitBundle extends TileEntityEio implements IConduitBundle { return item; } + // ---- Mekanism Gas Tubes + + @Optional.Method(modid = "Mekanism") + @Override + public int receiveGas(ForgeDirection side, GasStack stack) { + IGasConduit gc = getConduit(IGasConduit.class); + if(gc != null) { + return gc.receiveGas(side, stack); + } + return 0; + } + + @Optional.Method(modid = "Mekanism") + @Override + public GasStack drawGas(ForgeDirection side, int amount) { + IGasConduit gc = getConduit(IGasConduit.class); + if(gc != null) { + return gc.drawGas(side, amount); + } + return null; + } + + @Optional.Method(modid = "Mekanism") + @Override + public boolean canReceiveGas(ForgeDirection side, Gas type) { + IGasConduit gc = getConduit(IGasConduit.class); + if(gc != null) { + return gc.canReceiveGas(side, type); + } + return false; + } + + @Optional.Method(modid = "Mekanism") + @Override + public boolean canDrawGas(ForgeDirection side, Gas type) { + IGasConduit gc = getConduit(IGasConduit.class); + if(gc != null) { + return gc.canDrawGas(side, type); + } + return false; + } + } diff --git a/src/main/java/crazypants/enderio/conduit/gas/AbstractGasConduit.java b/src/main/java/crazypants/enderio/conduit/gas/AbstractGasConduit.java new file mode 100644 index 00000000..9d4417f1 --- /dev/null +++ b/src/main/java/crazypants/enderio/conduit/gas/AbstractGasConduit.java @@ -0,0 +1,197 @@ +package crazypants.enderio.conduit.gas; + +import java.util.EnumMap; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; + +import mekanism.api.gas.IGasHandler; +import net.minecraft.block.Block; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; +import crazypants.enderio.conduit.AbstractConduit; +import crazypants.enderio.conduit.ConduitUtil; +import crazypants.enderio.conduit.ConnectionMode; +import crazypants.enderio.conduit.IConduit; +import crazypants.enderio.conduit.IConduitBundle; +import crazypants.enderio.machine.RedstoneControlMode; +import crazypants.enderio.machine.reservoir.TileReservoir; +import crazypants.util.BlockCoord; +import crazypants.util.DyeColor; + +public abstract class AbstractGasConduit extends AbstractConduit implements IGasConduit { + + protected final EnumMap extractionModes = new EnumMap(ForgeDirection.class); + protected final EnumMap extractionColors = new EnumMap(ForgeDirection.class); + + protected final Map externalRedstoneSignals = new HashMap(); + protected boolean redstoneStateDirty = true; + + public IGasHandler getExternalHandler(ForgeDirection direction) { + IGasHandler con = GasUtil.getExternalGasHandler(getBundle().getWorld(), getLocation().getLocation(direction)); + return (con != null && !(con instanceof IConduitBundle)) ? con : null; + } + + public IGasHandler getTankContainer(BlockCoord bc) { + return GasUtil.getGasHandler(getBundle().getWorld(), bc); + } + + @Override + public boolean canConnectToExternal(ForgeDirection direction, boolean ignoreDisabled) { + IGasHandler h = getExternalHandler(direction); + if(h == null) { + return false; + } + return true; + } + + @Override + public Class getBaseConduitType() { + return IGasConduit.class; + } + + @Override + public boolean onNeighborBlockChange(Block blockId) { + redstoneStateDirty = true; + return super.onNeighborBlockChange(blockId); + } + + @Override + public void setExtractionRedstoneMode(RedstoneControlMode mode, ForgeDirection dir) { + extractionModes.put(dir, mode); + redstoneStateDirty = true; + } + + @Override + public RedstoneControlMode getExtractionRedstoneMode(ForgeDirection dir) { + RedstoneControlMode res = extractionModes.get(dir); + if(res == null) { + res = RedstoneControlMode.ON; + } + return res; + } + + @Override + public void setExtractionSignalColor(ForgeDirection dir, DyeColor col) { + extractionColors.put(dir, col); + } + + @Override + public DyeColor getExtractionSignalColor(ForgeDirection dir) { + DyeColor result = extractionColors.get(dir); + if(result == null) { + return DyeColor.RED; + } + return result; + } + + @Override + public boolean canOutputToDir(ForgeDirection dir) { + if(isExtractingFromDir(dir) || getConectionMode(dir) == ConnectionMode.DISABLED) { + return false; + } + if(conduitConnections.contains(dir)) { + return true; + } + if(!externalConnections.contains(dir)) { + return false; + } + IGasHandler ext = getExternalHandler(dir); + if(ext instanceof TileReservoir) { // dont push to an auto ejecting + // resevoir or we loop + TileReservoir tr = (TileReservoir) ext; + return !tr.isMultiblock() || !tr.isAutoEject(); + } + return true; + } + + protected boolean autoExtractForDir(ForgeDirection dir) { + if(!isExtractingFromDir(dir)) { + return false; + } + RedstoneControlMode mode = getExtractionRedstoneMode(dir); + if(mode == RedstoneControlMode.IGNORE) { + return true; + } + if(mode == RedstoneControlMode.NEVER) { + return false; + } + if(redstoneStateDirty) { + externalRedstoneSignals.clear(); + redstoneStateDirty = false; + } + + DyeColor col = getExtractionSignalColor(dir); + int signal = ConduitUtil.getInternalSignalForColor(getBundle(), col); + if(mode.isConditionMet(mode, signal) && mode != RedstoneControlMode.OFF) { + return true; + } + + return isConditionMetByExternalSignal(dir, mode, col); + } + + private boolean isConditionMetByExternalSignal(ForgeDirection dir, RedstoneControlMode mode, DyeColor col) { + int externalSignal = 0; + if(col == DyeColor.RED) { + Integer val = externalRedstoneSignals.get(dir); + if(val == null) { + TileEntity te = getBundle().getEntity(); + externalSignal = te.getWorldObj().getStrongestIndirectPower(te.xCoord, te.yCoord, te.zCoord); + externalRedstoneSignals.put(dir, externalSignal); + } else { + externalSignal = val; + } + } + + return mode.isConditionMet(mode, externalSignal); + } + + @Override + public boolean isExtractingFromDir(ForgeDirection dir) { + return getConectionMode(dir) == ConnectionMode.INPUT; + } + + @Override + public void writeToNBT(NBTTagCompound nbtRoot) { + super.writeToNBT(nbtRoot); + + for (Entry entry : extractionModes.entrySet()) { + if(entry.getValue() != null) { + short ord = (short) entry.getValue().ordinal(); + nbtRoot.setShort("extRM." + entry.getKey().name(), ord); + } + } + + for (Entry entry : extractionColors.entrySet()) { + if(entry.getValue() != null) { + short ord = (short) entry.getValue().ordinal(); + nbtRoot.setShort("extSC." + entry.getKey().name(), ord); + } + } + + } + + @Override + public void readFromNBT(NBTTagCompound nbtRoot, short nbtVersion) { + super.readFromNBT(nbtRoot, nbtVersion); + + for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + String key = "extRM." + dir.name(); + if(nbtRoot.hasKey(key)) { + short ord = nbtRoot.getShort(key); + if(ord >= 0 && ord < RedstoneControlMode.values().length) { + extractionModes.put(dir, RedstoneControlMode.values()[ord]); + } + } + key = "extSC." + dir.name(); + if(nbtRoot.hasKey(key)) { + short ord = nbtRoot.getShort(key); + if(ord >= 0 && ord < DyeColor.values().length) { + extractionColors.put(dir, DyeColor.values()[ord]); + } + } + } + } + +} diff --git a/src/main/java/crazypants/enderio/conduit/gas/AbstractGasTankConduit.java b/src/main/java/crazypants/enderio/conduit/gas/AbstractGasTankConduit.java new file mode 100644 index 00000000..ca344079 --- /dev/null +++ b/src/main/java/crazypants/enderio/conduit/gas/AbstractGasTankConduit.java @@ -0,0 +1,151 @@ +package crazypants.enderio.conduit.gas; + +import java.util.List; + +import mekanism.api.gas.GasStack; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.common.util.ForgeDirection; +import crazypants.enderio.conduit.AbstractConduitNetwork; +import crazypants.enderio.conduit.ConduitUtil; +import crazypants.enderio.conduit.ConnectionMode; +import crazypants.enderio.conduit.RaytraceResult; +import crazypants.util.BlockCoord; + +public abstract class AbstractGasTankConduit extends AbstractGasConduit { + + protected ConduitGasTank tank = new ConduitGasTank(0); + protected boolean stateDirty = false; + protected long lastEmptyTick = 0; + protected int numEmptyEvents = 0; + + @Override + public boolean onBlockActivated(EntityPlayer player, RaytraceResult res, List all) { + if(player.getCurrentEquippedItem() == null) { + return false; + } + AbstractGasTankConduitNetwork network = getTankNetwork(); + if(ConduitUtil.isToolEquipped(player)) { + + if(!getBundle().getEntity().getWorldObj().isRemote) { + + if(res != null && res.component != null) { + + ForgeDirection connDir = res.component.dir; + ForgeDirection faceHit = ForgeDirection.getOrientation(res.movingObjectPosition.sideHit); + + if(connDir == ForgeDirection.UNKNOWN || connDir == faceHit) { + + if(getConectionMode(faceHit) == ConnectionMode.DISABLED) { + setConnectionMode(faceHit, getNextConnectionMode(faceHit)); + return true; + } + + BlockCoord loc = getLocation().getLocation(faceHit); + IGasConduit n = ConduitUtil.getConduit(getBundle().getEntity().getWorldObj(), loc.x, loc.y, loc.z, IGasConduit.class); + if(n == null) { + return false; + } + if(!canJoinNeighbour(n)) { + return false; + } + if(!(n instanceof AbstractGasTankConduit)) { + return false; + } + AbstractGasTankConduit neighbour = (AbstractGasTankConduit) n; + if(neighbour.getGasType() == null || getGasType() == null) { + GasStack type = getGasType(); + type = type != null ? type : neighbour.getGasType(); + neighbour.setGasTypeOnNetwork(neighbour, type); + setGasTypeOnNetwork(this, type); + } + return ConduitUtil.joinConduits(this, faceHit); + } else if(containsExternalConnection(connDir)) { + // Toggle extraction mode + setConnectionMode(connDir, getNextConnectionMode(connDir)); + } else if(containsConduitConnection(connDir)) { + GasStack curGasType = null; + if(getTankNetwork() != null) { + curGasType = getTankNetwork().getGasType(); + } + ConduitUtil.disconectConduits(this, connDir); + setGasType(curGasType); + + } + } + } + return true; + + } + + return false; + } + + private void setGasTypeOnNetwork(AbstractGasTankConduit con, GasStack type) { + AbstractConduitNetwork n = con.getNetwork(); + if(n != null) { + AbstractGasTankConduitNetwork network = (AbstractGasTankConduitNetwork) n; + network.setGasType(type); + } + + } + + protected abstract boolean canJoinNeighbour(IGasConduit n); + + public abstract AbstractGasTankConduitNetwork getTankNetwork(); + + public void setGasType(GasStack gasType) { + if(tank.getGas() != null && tank.getGas().isGasEqual(gasType)) { + return; + } + if(gasType != null) { + gasType = gasType.copy(); + } else if(tank.getGas() == null) { + return; + } + tank.setGas(gasType); + stateDirty = true; + } + + public ConduitGasTank getTank() { + return tank; + } + + public GasStack getGasType() { + GasStack result = null; + if(getTankNetwork() != null) { + result = getTankNetwork().getGasType(); + } + if(result == null) { + result = tank.getGas(); + } + return result; + } + + protected abstract void updateTank(); + + @Override + public void readFromNBT(NBTTagCompound nbtRoot, short nbtVersion) { + super.readFromNBT(nbtRoot, nbtVersion); + updateTank(); + if(nbtRoot.hasKey("tank")) { + GasStack gas = GasStack.readFromNBT(nbtRoot.getCompoundTag("tank")); + tank.setGas(gas); + } else { + tank.setGas(null); + } + } + + @Override + public void writeToNBT(NBTTagCompound nbtRoot) { + super.writeToNBT(nbtRoot); + GasStack gt = getGasType(); + if(GasUtil.isGasValid(gt)) { + updateTank(); + gt = gt.copy(); + gt.amount = tank.getStored(); + nbtRoot.setTag("tank", gt.write(new NBTTagCompound())); + } + } + +} diff --git a/src/main/java/crazypants/enderio/conduit/gas/AbstractGasTankConduitNetwork.java b/src/main/java/crazypants/enderio/conduit/gas/AbstractGasTankConduitNetwork.java new file mode 100644 index 00000000..1bb2b2ac --- /dev/null +++ b/src/main/java/crazypants/enderio/conduit/gas/AbstractGasTankConduitNetwork.java @@ -0,0 +1,64 @@ +package crazypants.enderio.conduit.gas; + +import mekanism.api.gas.GasStack; +import crazypants.enderio.conduit.AbstractConduitNetwork; + +public class AbstractGasTankConduitNetwork extends AbstractConduitNetwork { + + protected GasStack gasType; + + protected AbstractGasTankConduitNetwork(Class cl) { + super(cl); + } + + public GasStack getGasType() { + return gasType; + } + + @Override + public Class getBaseConduitType() { + return IGasConduit.class; + } + + @Override + public void addConduit(T con) { + super.addConduit(con); + con.setGasType(gasType); + } + + public boolean setGasType(GasStack newType) { + if(gasType != null && gasType.isGasEqual(newType)) { + return false; + } + if(newType != null) { + gasType = newType.copy(); + gasType.amount = 0; + } else { + gasType = null; + } + for (AbstractGasTankConduit conduit : conduits) { + conduit.setGasType(gasType); + } + return true; + } + + public boolean canAcceptGas(GasStack acceptable) { + return areGassCompatable(gasType, acceptable); + } + + public static boolean areGassCompatable(GasStack a, GasStack b) { + if(a == null || b == null) { + return true; + } + return a.isGasEqual(b); + } + + public int getTotalVolume() { + int totalVolume = 0; + for (T con : conduits) { + totalVolume += con.getTank().getStored(); + } + return totalVolume; + } + +} diff --git a/src/main/java/crazypants/enderio/conduit/gas/ConduitGasTank.java b/src/main/java/crazypants/enderio/conduit/gas/ConduitGasTank.java new file mode 100644 index 00000000..9802d496 --- /dev/null +++ b/src/main/java/crazypants/enderio/conduit/gas/ConduitGasTank.java @@ -0,0 +1,153 @@ +package crazypants.enderio.conduit.gas; + +import mekanism.api.gas.GasStack; +import mekanism.api.gas.GasTank; +import net.minecraft.nbt.NBTTagCompound; + +public class ConduitGasTank extends GasTank { + + private int capacity; + + ConduitGasTank(int capacity) { + super(capacity); + this.capacity = capacity; + } + + public float getFilledRatio() { + if(getStored() <= 0) { + return 0; + } + if(getMaxGas() <= 0) { + return -1; + } + float res = (float) getStored() / getMaxGas(); + return res; + } + + public boolean isFull() { + return getStored() >= getMaxGas(); + } + + public void setAmount(int amount) { + if(stored != null) { + stored.amount = amount; + } + } + + public int getAvailableSpace() { + return getMaxGas() - getStored(); + } + + public void addAmount(int amount) { + setAmount(getStored() + amount); + } + + @Override + public int getMaxGas() { + return this.capacity; + } + + public void setCapacity(int capacity) { + this.capacity = capacity; + if(getStored() > capacity) { + setAmount(capacity); + } + } + + @Override + public int receive(GasStack resource, boolean doReceive) { + if(resource == null || resource.getGas().getID() <= 0) { + return 0; + } + + if(stored == null || stored.getGas().getID() <= 0) { + if(resource.amount <= capacity) { + if(doReceive) { + setGas(resource.copy()); + } + return resource.amount; + } else { + if(doReceive) { + stored = resource.copy(); + stored.amount = capacity; + } + return capacity; + } + } + + if(!stored.isGasEqual(resource)) { + return 0; + } + + int space = capacity - stored.amount; + if(resource.amount <= space) { + if(doReceive) { + addAmount(resource.amount); + } + return resource.amount; + } else { + if(doReceive) { + stored.amount = capacity; + } + return space; + } + + } + + @Override + public GasStack draw(int maxDrain, boolean doDraw) { + if(stored == null || stored.getGas().getID() <= 0) { + return null; + } + if(stored.amount <= 0) { + return null; + } + + int used = maxDrain; + if(stored.amount < used) { + used = stored.amount; + } + + if(doDraw) { + addAmount(-used); + } + + GasStack drained = new GasStack(stored.getGas().getID(), used); + + if(stored.amount < 0) { + stored.amount = 0; + } + return drained; + } + + public String getGasName() { + return stored != null ? stored.getGas().getLocalizedName() : null; + } + + public boolean containsValidGas() { + return GasUtil.isGasValid(stored); + } + + public NBTTagCompound write(NBTTagCompound nbt) { + if(containsValidGas()) { + stored.write(nbt); + } else { + nbt.setBoolean("emptyGasTank", true); + } + return nbt; + } + + public void read(NBTTagCompound nbt) { + if(!nbt.hasKey("emptyGasTank")) { + GasStack gas = GasStack.readFromNBT(nbt); + if(gas != null) { + setGas(gas); + } + } + } + + public boolean isEmpty() { + return stored == null || stored.amount == 0; + } + +} diff --git a/src/main/java/crazypants/enderio/conduit/gas/GasConduit.java b/src/main/java/crazypants/enderio/conduit/gas/GasConduit.java new file mode 100644 index 00000000..8cd7387b --- /dev/null +++ b/src/main/java/crazypants/enderio/conduit/gas/GasConduit.java @@ -0,0 +1,265 @@ +package crazypants.enderio.conduit.gas; + +import java.util.HashMap; +import java.util.Map; + +import mekanism.api.gas.Gas; +import mekanism.api.gas.GasStack; +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import crazypants.enderio.EnderIO; +import crazypants.enderio.conduit.AbstractConduitNetwork; +import crazypants.enderio.conduit.ConnectionMode; +import crazypants.enderio.conduit.IConduit; +import crazypants.enderio.conduit.geom.CollidableComponent; +import crazypants.enderio.config.Config; +import crazypants.render.IconUtil; +import crazypants.util.BlockCoord; + +public class GasConduit extends AbstractGasTankConduit { + + public static final int CONDUIT_VOLUME = 1000; + + public static final String ICON_KEY = "enderio:gasConduit"; + public static final String ICON_CORE_KEY = "enderio:gasConduitCore"; + public static final String ICON_EXTRACT_KEY = "enderio:gasConduitInput"; + public static final String ICON_INSERT_KEY = "enderio:gasConduitOutput"; + public static final String ICON_EMPTY_EDGE = "enderio:gasConduitEdge"; + + static final Map ICONS = new HashMap(); + + @SideOnly(Side.CLIENT) + public static void initIcons() { + IconUtil.addIconProvider(new IconUtil.IIconProvider() { + + @Override + public void registerIcons(IIconRegister register) { + ICONS.put(ICON_KEY, register.registerIcon(ICON_KEY)); + ICONS.put(ICON_CORE_KEY, register.registerIcon(ICON_CORE_KEY)); + ICONS.put(ICON_EXTRACT_KEY, register.registerIcon(ICON_EXTRACT_KEY)); + ICONS.put(ICON_INSERT_KEY, register.registerIcon(ICON_INSERT_KEY)); + ICONS.put(ICON_EMPTY_EDGE, register.registerIcon(ICON_EMPTY_EDGE)); + } + + @Override + public int getTextureType() { + return 0; + } + + }); + } + + private GasConduitNetwork network; + + private long ticksSinceFailedExtract = 0; + + public static final int MAX_EXTRACT_PER_TICK = Config.gasConduitExtractRate; + + public static final int MAX_IO_PER_TICK = Config.gasConduitMaxIoRate; + + public GasConduit() { + updateTank(); + } + + @Override + public void updateEntity(World world) { + super.updateEntity(world); + if(world.isRemote) { + return; + } + doExtract(); + if(stateDirty) { + getBundle().dirty(); + stateDirty = false; + } + } + + private void doExtract() { + BlockCoord loc = getLocation(); + if(!hasConnectionMode(ConnectionMode.INPUT)) { + return; + } + if(network == null) { + return; + } + + // assume failure, reset to 0 if we do extract + ticksSinceFailedExtract++; + if(ticksSinceFailedExtract > 25 && ticksSinceFailedExtract % 10 != 0) { + // after 25 ticks of failing, only check every 10 ticks + return; + } + + Gas f = tank.getGas() == null ? null : tank.getGas().getGas(); + for (ForgeDirection dir : externalConnections) { + if(autoExtractForDir(dir)) { + if(network.extractFrom(this, dir, MAX_EXTRACT_PER_TICK)) { + ticksSinceFailedExtract = 0; + } + } + } + + } + + @Override + protected void updateTank() { + tank.setCapacity(CONDUIT_VOLUME); + if(network != null) { + network.updateConduitVolumes(); + } + } + + @Override + public ItemStack createItem() { + return new ItemStack(EnderIO.itemGasConduit); + } + + @Override + public AbstractConduitNetwork getNetwork() { + return network; + } + + @Override + public boolean setNetwork(AbstractConduitNetwork network) { + if(network == null) { + this.network = null; + return true; + } + if(!(network instanceof GasConduitNetwork)) { + return false; + } + + GasConduitNetwork n = (GasConduitNetwork) network; + if(tank.getGas() == null) { + tank.setGas(n.getGasType() == null ? null : n.getGasType().copy()); + } else if(n.getGasType() == null) { + n.setGasType(tank.getGas()); + } else if(!tank.getGas().isGasEqual(n.getGasType())) { + return false; + } + this.network = n; + return true; + + } + + @Override + public boolean canConnectToConduit(ForgeDirection direction, IConduit con) { + if(!super.canConnectToConduit(direction, con)) { + return false; + } + if(!(con instanceof GasConduit)) { + return false; + } + if(getGasType() != null && ((GasConduit) con).getGasType() == null) { + return false; + } + return GasConduitNetwork.areGassCompatable(getGasType(), ((GasConduit) con).getGasType()); + } + + @Override + public void setConnectionMode(ForgeDirection dir, ConnectionMode mode) { + super.setConnectionMode(dir, mode); + refreshInputs(dir); + } + + private void refreshInputs(ForgeDirection dir) { + if(network == null) { + return; + } + GasOutput lo = new GasOutput(getLocation().getLocation(dir), dir.getOpposite()); + network.removeInput(lo); + if(getConectionMode(dir).acceptsOutput() && containsExternalConnection(dir)) { + network.addInput(lo); + } + } + + @Override + public void externalConnectionAdded(ForgeDirection fromDirection) { + super.externalConnectionAdded(fromDirection); + refreshInputs(fromDirection); + } + + @Override + public void externalConnectionRemoved(ForgeDirection fromDirection) { + super.externalConnectionRemoved(fromDirection); + refreshInputs(fromDirection); + } + + @Override + public IIcon getTextureForState(CollidableComponent component) { + if(component.dir == ForgeDirection.UNKNOWN) { + return ICONS.get(ICON_CORE_KEY); + } + return ICONS.get(ICON_KEY); + } + + public IIcon getTextureForInputMode() { + return ICONS.get(ICON_EXTRACT_KEY); + } + + public IIcon getTextureForOutputMode() { + return ICONS.get(ICON_INSERT_KEY); + } + + public IIcon getNotSetEdgeTexture() { + return ICONS.get(ICON_EMPTY_EDGE); + } + + @Override + public IIcon getTransmitionTextureForState(CollidableComponent component) { + if(isActive() && tank.containsValidGas()) { + return tank.getGas().getGas().getIcon(); + } + return null; + } + + // ------------------------------------------- Gas API + + @Override + public int receiveGas(ForgeDirection from, GasStack resource) { + if(network == null || !getConectionMode(from).acceptsInput()) { + return 0; + } + return network.fill(from, resource, true); + } + + @Override + public GasStack drawGas(ForgeDirection from, int maxDrain) { + if(network == null || !getConectionMode(from).acceptsOutput()) { + return null; + } + return network.drain(from, maxDrain, true); + } + + @Override + public boolean canReceiveGas(ForgeDirection from, Gas gas) { + if(network == null) { + return false; + } + return getConectionMode(from).acceptsInput() && GasConduitNetwork.areGassCompatable(getGasType(), new GasStack(gas, 0)); + } + + @Override + public boolean canDrawGas(ForgeDirection from, Gas gas) { + if(network == null) { + return false; + } + return getConectionMode(from).acceptsOutput() && GasConduitNetwork.areGassCompatable(getGasType(), new GasStack(gas, 0)); + } + + @Override + protected boolean canJoinNeighbour(IGasConduit n) { + return n instanceof GasConduit; + } + + @Override + public AbstractGasTankConduitNetwork getTankNetwork() { + return network; + } + +} diff --git a/src/main/java/crazypants/enderio/conduit/gas/GasConduitNetwork.java b/src/main/java/crazypants/enderio/conduit/gas/GasConduitNetwork.java new file mode 100644 index 00000000..6f46685e --- /dev/null +++ b/src/main/java/crazypants/enderio/conduit/gas/GasConduitNetwork.java @@ -0,0 +1,316 @@ +package crazypants.enderio.conduit.gas; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +import mekanism.api.gas.GasStack; +import mekanism.api.gas.IGasHandler; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; +import buildcraft.api.transport.IPipeTile; +import buildcraft.api.transport.IPipeTile.PipeType; +import cpw.mods.fml.common.gameevent.TickEvent.ServerTickEvent; +import crazypants.enderio.conduit.ConduitNetworkTickHandler; +import crazypants.enderio.conduit.ConduitNetworkTickHandler.TickListener; +import crazypants.enderio.conduit.IConduit; +import crazypants.util.BlockCoord; + +public class GasConduitNetwork extends AbstractGasTankConduitNetwork { + + private final ConduitGasTank tank = new ConduitGasTank(0); + + private final Set outputs = new HashSet(); + + private Iterator outputIterator; + + private int ticksActiveUnsynced; + + private boolean lastSyncedActive = false; + + private int lastSyncedVolume = -1; + + private long timeAtLastApply; + + private final InnerTickHandler tickHandler = new InnerTickHandler(); + + public GasConduitNetwork() { + super(GasConduit.class); + } + + @Override + public Class getBaseConduitType() { + return IGasConduit.class; + } + + @Override + public void addConduit(GasConduit con) { + tank.setCapacity(tank.getMaxGas() + GasConduit.CONDUIT_VOLUME); + if(con.getTank().containsValidGas()) { + tank.addAmount(con.getTank().getStored()); + } + for (ForgeDirection dir : con.getExternalConnections()) { + if(con.getConectionMode(dir).acceptsOutput()) { + outputs.add(new GasOutput(con.getLocation().getLocation(dir), dir.getOpposite())); + } + } + outputIterator = null; + super.addConduit(con); + } + + @Override + public boolean setGasType(GasStack newType) { + if(super.setGasType(newType)) { + + GasStack ft = getGasType(); + tank.setGas(ft == null ? null : ft.copy()); + return true; + } + return false; + } + + @Override + public void destroyNetwork() { + setConduitVolumes(); + outputs.clear(); + super.destroyNetwork(); + } + + private void setConduitVolumes() { + if(tank.containsValidGas() && !conduits.isEmpty()) { + GasStack gasPerConduit = tank.getGas().copy(); + int numCons = conduits.size(); + int leftOvers = gasPerConduit.amount % numCons; + gasPerConduit.amount = gasPerConduit.amount / numCons; + + for (GasConduit con : conduits) { + GasStack f = gasPerConduit.copy(); + if(leftOvers > 0) { + f.amount += 1; + leftOvers--; + } + con.getTank().setGas(f); + BlockCoord bc = con.getLocation(); + con.getBundle().getEntity().getWorldObj().markTileEntityChunkModified(bc.x, bc.y, bc.z, con.getBundle().getEntity()); + } + + } + } + + @Override + public void onUpdateEntity(IConduit conduit) { + World world = conduit.getBundle().getEntity().getWorldObj(); + if(world == null) { + return; + } + if(world.isRemote) { + return; + } + + long curTime = world.getTotalWorldTime(); + if(curTime > 0 && curTime != timeAtLastApply) { + timeAtLastApply = curTime; + ConduitNetworkTickHandler.instance.addListener(tickHandler); + } + + } + + private void doTick() { + if(gasType == null || outputs.isEmpty() || !tank.containsValidGas() || tank.isEmpty()) { + updateActiveState(); + return; + } + + if(outputIterator == null || !outputIterator.hasNext()) { + outputIterator = outputs.iterator(); + } + + updateActiveState(); + + int numVisited = 0; + while (!tank.isEmpty() && numVisited < outputs.size()) { + if(!outputIterator.hasNext()) { + outputIterator = outputs.iterator(); + } + GasOutput output = outputIterator.next(); + if(output != null) { + IGasHandler cont = getTankContainer(output.location); + if(cont != null) { + GasStack offer = tank.getGas().copy(); + int filled = cont.receiveGas(output.dir, offer); + if(filled > 0) { + tank.addAmount(-filled); + + } + } + } + numVisited++; + } + + } + + private void updateActiveState() { + boolean isActive = tank.containsValidGas() && !tank.isEmpty(); + if(lastSyncedActive != isActive) { + ticksActiveUnsynced++; + } else { + ticksActiveUnsynced = 0; + } + if(ticksActiveUnsynced >= 10 || ticksActiveUnsynced > 0 && isActive) { + if(!isActive) { + setGasType(null); + } + for (IConduit con : conduits) { + con.setActive(isActive); + } + lastSyncedActive = isActive; + ticksActiveUnsynced = 0; + } + } + + public int fill(ForgeDirection from, GasStack resource, boolean doFill) { + if(resource == null) { + return 0; + } + resource.amount = Math.min(resource.amount, GasConduit.MAX_IO_PER_TICK); + boolean gasWasValid = !tank.containsValidGas(); + int res = tank.receive(resource, doFill); + if(doFill && res > 0 && !gasWasValid) { + int vol = tank.getStored(); + setGasType(resource); + tank.setAmount(vol); + } + return res; + } + + public GasStack drain(ForgeDirection from, GasStack resource, boolean doDrain) { + if(resource == null || tank.isEmpty() || !tank.containsValidGas() || !GasConduitNetwork.areGassCompatable(getGasType(), resource)) { + return null; + } + int amount = Math.min(resource.amount, tank.getStored()); + amount = Math.min(amount, GasConduit.MAX_IO_PER_TICK); + GasStack result = resource.copy(); + result.amount = amount; + if(doDrain) { + tank.addAmount(-amount); + } + return result; + } + + public GasStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + if(tank.isEmpty() || !tank.containsValidGas()) { + return null; + } + int amount = Math.min(maxDrain, tank.getStored()); + GasStack result = tank.getGas().copy(); + result.amount = amount; + if(doDrain) { + tank.addAmount(-amount); + } + return result; + } + + public boolean extractFrom(GasConduit advancedGasConduit, ForgeDirection dir, int maxExtractPerTick) { + + if(tank.isFull()) { + return false; + } + + IGasHandler extTank = getTankContainer(advancedGasConduit, dir); + if(extTank != null) { + int maxExtract = Math.min(maxExtractPerTick, tank.getAvailableSpace()); + + if(gasType == null || !tank.containsValidGas()) { + GasStack drained = extTank.drawGas(dir.getOpposite(), maxExtract); + if(drained == null || drained.amount <= 0) { + return false; + } + setGasType(drained); + tank.setGas(drained.copy()); + return true; + } + + GasStack couldDrain = gasType.copy(); + couldDrain.amount = maxExtract; + + // GasStack drained = extTank.drain(dir.getOpposite(), couldDrain, true); + // if(drained == null || drained.amount <= 0) { + // return false; + // } + // tank.addAmount(drained.amount); + + //Have to use this 'double handle' approach to work around an issue with TiC + GasStack drained = extTank.drawGas(dir.getOpposite(), maxExtract); + if(drained == null || drained.amount == 0) { + return false; + } else { + if(drained.isGasEqual(getGasType())) { + tank.addAmount(drained.amount); + } + } + return true; + } + return false; + } + + public IGasHandler getTankContainer(BlockCoord bc) { + World w = getWorld(); + if(w == null) { + return null; + } + TileEntity te = w.getTileEntity(bc.x, bc.y, bc.z); + if(te instanceof IGasHandler) { + if(te instanceof IPipeTile) { + if(((IPipeTile) te).getPipeType() != PipeType.FLUID) { + return null; + } + } + return (IGasHandler) te; + } + return null; + } + + public IGasHandler getTankContainer(GasConduit con, ForgeDirection dir) { + BlockCoord bc = con.getLocation().getLocation(dir); + return getTankContainer(bc); + } + + World getWorld() { + if(conduits.isEmpty()) { + return null; + } + return conduits.get(0).getBundle().getWorld(); + } + + public void removeInput(GasOutput lo) { + outputs.remove(lo); + outputIterator = null; + } + + public void addInput(GasOutput lo) { + outputs.add(lo); + outputIterator = null; + } + + public void updateConduitVolumes() { + if(tank.getStored() == lastSyncedVolume) { + return; + } + setConduitVolumes(); + lastSyncedVolume = tank.getStored(); + } + + private class InnerTickHandler implements TickListener { + + @Override + public void tickStart(ServerTickEvent evt) { + } + + @Override + public void tickEnd(ServerTickEvent evt) { + doTick(); + } + } + +} diff --git a/src/main/java/crazypants/enderio/conduit/gas/GasConduitRenderer.java b/src/main/java/crazypants/enderio/conduit/gas/GasConduitRenderer.java new file mode 100644 index 00000000..9753698d --- /dev/null +++ b/src/main/java/crazypants/enderio/conduit/gas/GasConduitRenderer.java @@ -0,0 +1,179 @@ +package crazypants.enderio.conduit.gas; + +import static crazypants.render.CubeRenderer.addVecWithUV; + +import java.util.List; + +import mekanism.api.gas.GasStack; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.util.IIcon; +import net.minecraftforge.common.util.ForgeDirection; +import crazypants.enderio.EnderIO; +import crazypants.enderio.conduit.ConnectionMode; +import crazypants.enderio.conduit.IConduit; +import crazypants.enderio.conduit.IConduitBundle; +import crazypants.enderio.conduit.geom.CollidableComponent; +import crazypants.enderio.conduit.geom.ConnectionModeGeometry; +import crazypants.enderio.conduit.geom.Offset; +import crazypants.enderio.conduit.render.ConduitBundleRenderer; +import crazypants.enderio.conduit.render.DefaultConduitRenderer; +import crazypants.render.BoundingBox; +import crazypants.render.RenderUtil; +import crazypants.vecmath.Vector3d; +import crazypants.vecmath.Vertex; + +public class GasConduitRenderer extends DefaultConduitRenderer { + + @Override + public boolean isRendererForConduit(IConduit conduit) { + return conduit instanceof GasConduit; + } + + @Override + public void renderEntity(ConduitBundleRenderer conduitBundleRenderer, IConduitBundle te, IConduit conduit, double x, double y, double z, float partialTick, + float worldLight) { + super.renderEntity(conduitBundleRenderer, te, conduit, x, y, z, partialTick, worldLight); + + if(!conduit.hasConnectionMode(ConnectionMode.INPUT) && !conduit.hasConnectionMode(ConnectionMode.OUTPUT)) { + return; + } + GasConduit pc = (GasConduit) conduit; + for (ForgeDirection dir : conduit.getExternalConnections()) { + IIcon tex = null; + if(conduit.getConectionMode(dir) == ConnectionMode.INPUT) { + tex = pc.getTextureForInputMode(); + } else if(conduit.getConectionMode(dir) == ConnectionMode.OUTPUT) { + tex = pc.getTextureForOutputMode(); + } + if(tex != null) { + Offset offset = te.getOffset(IGasConduit.class, dir); + ConnectionModeGeometry.renderModeConnector(dir, offset, tex, true); + } + } + } + + @Override + protected void renderConduit(IIcon tex, IConduit conduit, CollidableComponent component, float brightness) { + super.renderConduit(tex, conduit, component, brightness); + + if(isNSEWUD(component.dir)) { + GasConduit lc = (GasConduit) conduit; + + GasStack gas = lc.getGasType(); + IIcon texture = null; + if(gas != null) { + texture = gas.getGas().getIcon(); + } + + if(texture == null) { + texture = lc.getNotSetEdgeTexture(); + } + + float scaleFactor = 0.75f; + float xLen = Math.abs(component.dir.offsetX) == 1 ? 1 : scaleFactor; + float yLen = Math.abs(component.dir.offsetY) == 1 ? 1 : scaleFactor; + float zLen = Math.abs(component.dir.offsetZ) == 1 ? 1 : scaleFactor; + + BoundingBox cube = component.bound; + BoundingBox bb = cube.scale(xLen, yLen, zLen); + + for (ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) { + if(d != component.dir && d != component.dir.getOpposite()) { + + ForgeDirection vDir = RenderUtil.getVDirForFace(d); + if(component.dir == ForgeDirection.UP || component.dir == ForgeDirection.DOWN) { + vDir = RenderUtil.getUDirForFace(d); + } else if((component.dir == ForgeDirection.NORTH || component.dir == ForgeDirection.SOUTH) && d.offsetY != 0) { + vDir = RenderUtil.getUDirForFace(d); + } + + float minU = texture.getMinU(); + float maxU = texture.getMaxU(); + float minV = texture.getMinV(); + float maxV = texture.getMaxV(); + + float sideScale = Math.max(bb.sizeX(), bb.sizeY()) * 2 / 16f; + sideScale = Math.max(sideScale, bb.sizeZ() * 2 / 16f); + float width = Math.min(bb.sizeX(), bb.sizeY()) * 15f / 16f; + + List corners = bb.getCornersWithUvForFace(d, minU, maxU, minV, maxV); + moveEdgeCorners(corners, vDir, width); + moveEdgeCorners(corners, component.dir.getOpposite(), sideScale); + for (Vertex c : corners) { + addVecWithUV(c.xyz, c.uv.x, c.uv.y); + } + + corners = bb.getCornersWithUvForFace(d, minU, maxU, minV, maxV); + moveEdgeCorners(corners, vDir.getOpposite(), width); + moveEdgeCorners(corners, component.dir.getOpposite(), sideScale); + for (Vertex c : corners) { + addVecWithUV(c.xyz, c.uv.x, c.uv.y); + } + + } + } + + if(conduit.getConectionMode(component.dir) == ConnectionMode.DISABLED) { + tex = EnderIO.blockConduitBundle.getConnectorIcon(); + List corners = component.bound.getCornersWithUvForFace(component.dir, tex.getMinU(), tex.getMaxU(), tex.getMinV(), tex.getMaxV()); + Tessellator tessellator = Tessellator.instance; + for (Vertex c : corners) { + addVecWithUV(c.xyz, c.uv.x, c.uv.y); + } + //back face + for (int i = corners.size() - 1; i >= 0; i--) { + Vertex c = corners.get(i); + addVecWithUV(c.xyz, c.uv.x, c.uv.y); + } + } + + } + + } + + @Override + protected void renderTransmission(IConduit conduit, IIcon tex, CollidableComponent component, float selfIllum) { + super.renderTransmission(conduit, tex, component, selfIllum); + } + + private void moveEdgeCorners(List vertices, ForgeDirection edge, float scaleFactor) { + int[] indices = getClosest(edge, vertices); + vertices.get(indices[0]).xyz.x -= scaleFactor * edge.offsetX; + vertices.get(indices[1]).xyz.x -= scaleFactor * edge.offsetX; + vertices.get(indices[0]).xyz.y -= scaleFactor * edge.offsetY; + vertices.get(indices[1]).xyz.y -= scaleFactor * edge.offsetY; + vertices.get(indices[0]).xyz.z -= scaleFactor * edge.offsetZ; + vertices.get(indices[1]).xyz.z -= scaleFactor * edge.offsetZ; + } + + private int[] getClosest(ForgeDirection edge, List vertices) { + int[] res = new int[] { -1, -1 }; + boolean highest = edge.offsetX > 0 || edge.offsetY > 0 || edge.offsetZ > 0; + double minMax = highest ? -Double.MAX_VALUE : Double.MAX_VALUE; + int index = 0; + for (Vertex v : vertices) { + double val = get(v.xyz, edge); + if(highest ? val >= minMax : val <= minMax) { + if(val != minMax) { + res[0] = index; + } else { + res[1] = index; + } + minMax = val; + } + index++; + } + return res; + } + + private double get(Vector3d xyz, ForgeDirection edge) { + if(edge == ForgeDirection.EAST || edge == ForgeDirection.WEST) { + return xyz.x; + } + if(edge == ForgeDirection.UP || edge == ForgeDirection.DOWN) { + return xyz.y; + } + return xyz.z; + } + +} diff --git a/src/main/java/crazypants/enderio/conduit/gas/GasOutput.java b/src/main/java/crazypants/enderio/conduit/gas/GasOutput.java new file mode 100644 index 00000000..c2ca8b06 --- /dev/null +++ b/src/main/java/crazypants/enderio/conduit/gas/GasOutput.java @@ -0,0 +1,49 @@ +package crazypants.enderio.conduit.gas; + +import net.minecraftforge.common.util.ForgeDirection; +import crazypants.util.BlockCoord; + +public class GasOutput { + + final ForgeDirection dir; + final BlockCoord location; + + public GasOutput(BlockCoord bc, ForgeDirection dir) { + this.dir = dir; + this.location = bc; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((location == null) ? 0 : location.hashCode()); + result = prime * result + ((dir == null) ? 0 : dir.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if(this == obj) + return true; + if(obj == null) + return false; + if(getClass() != obj.getClass()) + return false; + GasOutput other = (GasOutput) obj; + if(location == null) { + if(other.location != null) + return false; + } else if(!location.equals(other.location)) + return false; + if(dir != other.dir) + return false; + return true; + } + + @Override + public String toString() { + return "GasOutput [dir=" + dir + ", location=" + location + "]"; + } + +} \ No newline at end of file diff --git a/src/main/java/crazypants/enderio/conduit/gas/GasUtil.java b/src/main/java/crazypants/enderio/conduit/gas/GasUtil.java new file mode 100644 index 00000000..4fe14ed5 --- /dev/null +++ b/src/main/java/crazypants/enderio/conduit/gas/GasUtil.java @@ -0,0 +1,50 @@ +package crazypants.enderio.conduit.gas; + +import mekanism.api.gas.GasStack; +import mekanism.api.gas.IGasHandler; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.IBlockAccess; +import buildcraft.api.transport.IPipeTile; +import buildcraft.api.transport.IPipeTile.PipeType; +import crazypants.enderio.conduit.IConduitBundle; +import crazypants.util.BlockCoord; + +public class GasUtil { + + public static IGasHandler getExternalGasHandler(IBlockAccess world, BlockCoord bc) { + IGasHandler con = getGasHandler(world, bc); + return (con != null && !(con instanceof IConduitBundle)) ? con : null; + } + + public static IGasHandler getGasHandler(IBlockAccess world, BlockCoord bc) { + return getGasHandler(world, bc.x, bc.y, bc.z); + } + + public static IGasHandler getGasHandler(IBlockAccess world, int x, int y, int z) { + TileEntity te = world.getTileEntity(x, y, z); + return getGasHandler(te); + } + + public static IGasHandler getGasHandler(TileEntity te) { + if(te instanceof IGasHandler) { + if(te instanceof IPipeTile) { + if(((IPipeTile) te).getPipeType() != PipeType.FLUID) { + return null; + } + } + return (IGasHandler) te; + } + return null; + } + + public static boolean isGasValid(GasStack gas) { + if(gas != null) { + String name = gas.getGas().getLocalizedName(); + if(name != null && !name.trim().isEmpty()) { + return true; + } + } + return false; + } + +} diff --git a/src/main/java/crazypants/enderio/conduit/gas/IGasConduit.java b/src/main/java/crazypants/enderio/conduit/gas/IGasConduit.java new file mode 100644 index 00000000..ad992a9f --- /dev/null +++ b/src/main/java/crazypants/enderio/conduit/gas/IGasConduit.java @@ -0,0 +1,14 @@ +package crazypants.enderio.conduit.gas; + +import mekanism.api.gas.IGasHandler; +import net.minecraftforge.common.util.ForgeDirection; +import crazypants.enderio.conduit.IConduit; +import crazypants.enderio.conduit.IExtractor; + +public interface IGasConduit extends IConduit, IGasHandler, IExtractor { + + boolean canOutputToDir(ForgeDirection dir); + + boolean isExtractingFromDir(ForgeDirection dir); + +} diff --git a/src/main/java/crazypants/enderio/conduit/gas/ItemGasConduit.java b/src/main/java/crazypants/enderio/conduit/gas/ItemGasConduit.java new file mode 100644 index 00000000..c26bfbeb --- /dev/null +++ b/src/main/java/crazypants/enderio/conduit/gas/ItemGasConduit.java @@ -0,0 +1,66 @@ +package crazypants.enderio.conduit.gas; + +import java.util.List; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import crazypants.enderio.ModObject; +import crazypants.enderio.conduit.AbstractItemConduit; +import crazypants.enderio.conduit.IConduit; +import crazypants.enderio.conduit.ItemConduitSubtype; +import crazypants.enderio.config.Config; +import crazypants.enderio.gui.IAdvancedTooltipProvider; +import crazypants.enderio.gui.TooltipAddera; +import crazypants.util.Lang; + +public class ItemGasConduit extends AbstractItemConduit implements IAdvancedTooltipProvider { + + private static ItemConduitSubtype[] subtypes = new ItemConduitSubtype[] { + new ItemConduitSubtype(ModObject.itemGasConduit.name(), "enderio:itemGasConduit"), + }; + + public static ItemGasConduit create() { + ItemGasConduit result = new ItemGasConduit(); + result.init(subtypes); + return result; + } + + protected ItemGasConduit() { + super(ModObject.itemGasConduit); + } + + @Override + public Class getBaseConduitType() { + return IGasConduit.class; + } + + @Override + public IConduit createConduit(ItemStack stack) { + return new GasConduit(); + } + + @Override + @SideOnly(Side.CLIENT) + public void addCommonEntries(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag) { + } + + @Override + @SideOnly(Side.CLIENT) + public void addBasicEntries(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag) { + + } + + @Override + @SideOnly(Side.CLIENT) + public void addDetailedEntries(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag) { + String gpt = " " + Lang.localize("gas.gasTick"); + int extractRate = Config.gasConduitExtractRate; + int maxIo = Config.gasConduitMaxIoRate; + list.add(Lang.localize("itemGasConduit.tooltip.maxExtract") + " " + extractRate + gpt); + list.add(Lang.localize("itemGasConduit.tooltip.maxIo") + " " + maxIo + gpt); + TooltipAddera.addDetailedTooltipFromResources(list, "enderio.itemGasConduit"); + } + +} diff --git a/src/main/java/crazypants/enderio/conduit/gas/PacketGasLevel.java b/src/main/java/crazypants/enderio/conduit/gas/PacketGasLevel.java new file mode 100644 index 00000000..f2de0d85 --- /dev/null +++ b/src/main/java/crazypants/enderio/conduit/gas/PacketGasLevel.java @@ -0,0 +1,43 @@ +package crazypants.enderio.conduit.gas; + +import io.netty.buffer.ByteBuf; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import cpw.mods.fml.common.network.ByteBufUtils; +import cpw.mods.fml.common.network.simpleimpl.IMessage; +import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; +import cpw.mods.fml.common.network.simpleimpl.MessageContext; +import crazypants.enderio.network.MessageTileEntity; +import crazypants.util.ClientUtil; + +public class PacketGasLevel extends MessageTileEntity implements IMessageHandler { + + public NBTTagCompound tc; + + public PacketGasLevel() { + } + + public PacketGasLevel(IGasConduit conduit) { + super(conduit.getBundle().getEntity()); + tc = new NBTTagCompound(); + conduit.writeToNBT(tc); + } + + @Override + public void toBytes(ByteBuf buf) { + super.toBytes(buf); + ByteBufUtils.writeTag(buf, tc); + } + + @Override + public void fromBytes(ByteBuf buf) { + super.fromBytes(buf); + tc = ByteBufUtils.readTag(buf); + } + + @Override + public IMessage onMessage(PacketGasLevel message, MessageContext ctx) { + ClientUtil.doGasLevelUpdate(message.x, message.y, message.z, message); + return null; + } +} diff --git a/src/main/java/crazypants/enderio/conduit/geom/Offsets.java b/src/main/java/crazypants/enderio/conduit/geom/Offsets.java index 978063a7..4e40df29 100644 --- a/src/main/java/crazypants/enderio/conduit/geom/Offsets.java +++ b/src/main/java/crazypants/enderio/conduit/geom/Offsets.java @@ -5,6 +5,7 @@ import java.util.Map; import net.minecraftforge.common.util.ForgeDirection; import crazypants.enderio.conduit.IConduit; +import crazypants.enderio.conduit.gas.IGasConduit; import crazypants.enderio.conduit.item.IItemConduit; import crazypants.enderio.conduit.liquid.ILiquidConduit; import crazypants.enderio.conduit.power.IPowerConduit; @@ -35,6 +36,11 @@ public class Offsets { OFFSETS.put(key(IItemConduit.class, Axis.Y), Offset.EAST); OFFSETS.put(key(IItemConduit.class, Axis.Z), Offset.EAST); + OFFSETS.put(key(IGasConduit.class, Axis.NONE), Offset.NONE); + OFFSETS.put(key(IGasConduit.class, Axis.X), Offset.NONE); + OFFSETS.put(key(IGasConduit.class, Axis.Y), Offset.NONE); + OFFSETS.put(key(IGasConduit.class, Axis.Z), Offset.NONE); + } public static Offset get(Class type, ForgeDirection dir) { diff --git a/src/main/java/crazypants/enderio/conduit/gui/GasSettings.java b/src/main/java/crazypants/enderio/conduit/gui/GasSettings.java new file mode 100644 index 00000000..8680b881 --- /dev/null +++ b/src/main/java/crazypants/enderio/conduit/gui/GasSettings.java @@ -0,0 +1,126 @@ +package crazypants.enderio.conduit.gui; + +import java.awt.Color; + +import mekanism.api.gas.Gas; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.util.IIcon; +import crazypants.enderio.conduit.ConnectionMode; +import crazypants.enderio.conduit.IConduit; +import crazypants.enderio.conduit.gas.IGasConduit; +import crazypants.enderio.conduit.packet.PacketExtractMode; +import crazypants.enderio.gui.ColorButton; +import crazypants.enderio.gui.IconEIO; +import crazypants.enderio.gui.RedstoneModeButton; +import crazypants.enderio.machine.IRedstoneModeControlable; +import crazypants.enderio.machine.RedstoneControlMode; +import crazypants.enderio.network.PacketHandler; +import crazypants.render.ColorUtil; +import crazypants.render.RenderUtil; +import crazypants.util.DyeColor; +import crazypants.util.Lang; + +public class GasSettings extends BaseSettingsPanel { + + static final int ID_REDSTONE_BUTTON = GuiExternalConnection.nextButtonId(); + + private static final int ID_COLOR_BUTTON = GuiExternalConnection.nextButtonId(); + + private RedstoneModeButton rsB; + + private ColorButton colorB; + + private String autoExtractStr = Lang.localize("gui.conduit.gas.autoExtract"); + + private IGasConduit conduit; + + protected GasSettings(final GuiExternalConnection gui, IConduit con) { + super(IconEIO.WRENCH_OVERLAY_GAS, Lang.localize("itemGasConduit.name"), gui, con); + + conduit = (IGasConduit) con; + gui.getContainer().setInventorySlotsVisible(false); + + int x = gap + gui.getFontRenderer().getStringWidth(autoExtractStr) + gap * 2; + int y = customTop; + + rsB = new RedstoneModeButton(gui, ID_REDSTONE_BUTTON, x, y, new IRedstoneModeControlable() { + + @Override + public void setRedstoneControlMode(RedstoneControlMode mode) { + RedstoneControlMode curMode = getRedstoneControlMode(); + conduit.setExtractionRedstoneMode(mode, gui.getDir()); + if(curMode != mode) { + PacketHandler.INSTANCE.sendToServer(new PacketExtractMode(conduit, gui.getDir())); + } + + } + + @Override + public RedstoneControlMode getRedstoneControlMode() { + return conduit.getExtractionRedstoneMode(gui.getDir()); + } + }); + + x += rsB.getWidth() + gap; + colorB = new ColorButton(gui, ID_COLOR_BUTTON, x, y); + colorB.setToolTipHeading(Lang.localize("gui.conduit.redstone.signalColor")); + colorB.setColorIndex(conduit.getExtractionSignalColor(gui.getDir()).ordinal()); + } + + @Override + public void actionPerformed(GuiButton guiButton) { + super.actionPerformed(guiButton); + if(guiButton.id == ID_COLOR_BUTTON) { + conduit.setExtractionSignalColor(gui.getDir(), DyeColor.values()[colorB.getColorIndex()]); + PacketHandler.INSTANCE.sendToServer(new PacketExtractMode(conduit, gui.getDir())); + } + } + + @Override + protected void connectionModeChanged(ConnectionMode conectionMode) { + super.connectionModeChanged(conectionMode); + if(conectionMode == ConnectionMode.INPUT) { + rsB.onGuiInit(); + colorB.onGuiInit(); + } else { + rsB.detach(); + colorB.detach(); + } + + } + + @Override + public void mouseClicked(int x, int y, int par3) { + } + + @Override + public void deactivate() { + super.deactivate(); + rsB.setToolTip((String[]) null); + colorB.setToolTip((String[]) null); + } + + @Override + protected void renderCustomOptions(int top, float par1, int par2, int par3) { + boolean isInput = isInput(); + if(isInput) { + int x = gui.getGuiLeft() + gap + gui.getFontRenderer().getStringWidth(autoExtractStr) + gap + 2; + int y = customTop; + gui.getFontRenderer().drawString(autoExtractStr, left, top, ColorUtil.getRGB(Color.DARK_GRAY)); + } + } + + private void renderGas(Gas f, int x, int y) { + IIcon icon = f.getIcon(); + if(icon != null) { + RenderUtil.bindBlockTexture(); + gui.drawTexturedModelRectFromIcon(x + 1, y + 1, icon, 16, 16); + } + + } + + private boolean isInput() { + return conduit.getConectionMode(gui.getDir()) == ConnectionMode.INPUT; + } + +} diff --git a/src/main/java/crazypants/enderio/conduit/gui/GuiExternalConnection.java b/src/main/java/crazypants/enderio/conduit/gui/GuiExternalConnection.java index 605d855f..e6a6aab8 100644 --- a/src/main/java/crazypants/enderio/conduit/gui/GuiExternalConnection.java +++ b/src/main/java/crazypants/enderio/conduit/gui/GuiExternalConnection.java @@ -16,6 +16,7 @@ import org.lwjgl.opengl.GL11; import crazypants.enderio.conduit.IConduit; import crazypants.enderio.conduit.IConduitBundle; +import crazypants.enderio.conduit.gas.IGasConduit; import crazypants.enderio.conduit.item.IItemConduit; import crazypants.enderio.conduit.liquid.ILiquidConduit; import crazypants.enderio.conduit.power.IPowerConduit; @@ -27,19 +28,20 @@ import crazypants.render.RenderUtil; public class GuiExternalConnection extends GuiContainerBase { private static final int TAB_HEIGHT = 24; - + private static int nextButtonId = 1; - + public static int nextButtonId() { return nextButtonId++; } - + private static final Map, Integer> TAB_ORDER = new HashMap, Integer>(); static { TAB_ORDER.put(IItemConduit.class, 0); TAB_ORDER.put(ILiquidConduit.class, 1); TAB_ORDER.put(IRedstoneConduit.class, 2); TAB_ORDER.put(IPowerConduit.class, 3); + TAB_ORDER.put(IGasConduit.class, 4); } final InventoryPlayer playerInv; @@ -60,14 +62,14 @@ public class GuiExternalConnection extends GuiContainerBase { this.playerInv = playerInv; this.bundle = bundle; this.dir = dir; - + ySize = 166 + 29; xSize = 206; - + getContainer().setInputSlotsVisible(false); getContainer().setOutputSlotsVisible(false); getContainer().setInventorySlotsVisible(false); - + List cons = new ArrayList(bundle.getConduits()); Collections.sort(cons, new Comparator() { @@ -83,10 +85,10 @@ public class GuiExternalConnection extends GuiContainerBase { } //NB: using Double.comp instead of Integer.comp as the int version is only from Java 1.7+ return Double.compare(int1, int2); - + } }); - + for (IConduit con : cons) { if(con.containsExternalConnection(dir) || con.canConnectToExternal(dir, true)) { ISettingsPanel tab = TabFactory.instance.createPanelForConduit(this, con); @@ -96,7 +98,7 @@ public class GuiExternalConnection extends GuiContainerBase { } } } - + } @Override @@ -138,7 +140,7 @@ public class GuiExternalConnection extends GuiContainerBase { return; } } - tabs.get(activeTab).mouseClicked(x,y,par3); + tabs.get(activeTab).mouseClicked(x, y, par3); } diff --git a/src/main/java/crazypants/enderio/conduit/gui/TabFactory.java b/src/main/java/crazypants/enderio/conduit/gui/TabFactory.java index 507a36b5..34cfc2f5 100644 --- a/src/main/java/crazypants/enderio/conduit/gui/TabFactory.java +++ b/src/main/java/crazypants/enderio/conduit/gui/TabFactory.java @@ -1,6 +1,7 @@ package crazypants.enderio.conduit.gui; import crazypants.enderio.conduit.IConduit; +import crazypants.enderio.conduit.gas.IGasConduit; import crazypants.enderio.conduit.gui.item.ItemSettings; import crazypants.enderio.conduit.item.IItemConduit; import crazypants.enderio.conduit.liquid.ILiquidConduit; @@ -24,6 +25,8 @@ public class TabFactory { return new ItemSettings(gui, con); } else if(baseType.isAssignableFrom(IRedstoneConduit.class)) { return new RedstoneSettings(gui, con); + } else if(baseType.isAssignableFrom(IGasConduit.class)) { + return new GasSettings(gui, con); } return null; } diff --git a/src/main/java/crazypants/enderio/conduit/packet/ConTypeEnum.java b/src/main/java/crazypants/enderio/conduit/packet/ConTypeEnum.java index 47718c1c..c4faa6cb 100644 --- a/src/main/java/crazypants/enderio/conduit/packet/ConTypeEnum.java +++ b/src/main/java/crazypants/enderio/conduit/packet/ConTypeEnum.java @@ -1,6 +1,7 @@ package crazypants.enderio.conduit.packet; import crazypants.enderio.conduit.IConduit; +import crazypants.enderio.conduit.gas.IGasConduit; import crazypants.enderio.conduit.item.IItemConduit; import crazypants.enderio.conduit.liquid.ILiquidConduit; import crazypants.enderio.conduit.power.IPowerConduit; @@ -11,7 +12,8 @@ public enum ConTypeEnum { POWER(IPowerConduit.class), FLUID(ILiquidConduit.class), ITEM(IItemConduit.class), - REDSTONE(IRedstoneConduit.class); + REDSTONE(IRedstoneConduit.class), + GAS(IGasConduit.class); final Class baseType; diff --git a/src/main/java/crazypants/enderio/config/Config.java b/src/main/java/crazypants/enderio/config/Config.java index fc78399c..5ad2a111 100644 --- a/src/main/java/crazypants/enderio/config/Config.java +++ b/src/main/java/crazypants/enderio/config/Config.java @@ -14,21 +14,21 @@ import crazypants.enderio.Log; import crazypants.vecmath.VecmathUtil; public final class Config { - + public static class Section { public final String name; public final String lang; - + public Section(String name, String lang) { this.name = name; this.lang = lang; register(); } - + private void register() { sections.add(this); } - + public String lc() { return name.toLowerCase(); } @@ -41,7 +41,7 @@ public final class Config { } public static Configuration config; - + public static final Section sectionPower = new Section("Power Settings", "power"); public static final Section sectionRecipe = new Section("Recipe Settings", "recipe"); public static final Section sectionItems = new Section("Item Enabling", "item"); @@ -57,11 +57,11 @@ public final class Config { public static final Section sectionFluid = new Section("Fluid Settings", "fluid"); public static final Section sectionSpawner = new Section("PoweredSpawner Settings", "spawner"); public static final Section sectionKiller = new Section("Killer Joe Settings", "killerjoe"); - + public static final double DEFAULT_CONDUIT_SCALE = 0.5; - public static boolean reinforcedObsidianEnabled = true; - + public static boolean reinforcedObsidianEnabled = true; + public static boolean useAlternateBinderRecipe; public static boolean useAlternateTesseractModel; @@ -102,6 +102,9 @@ public final class Config { public static int fluidConduitExtractRate = 50; public static int fluidConduitMaxIoRate = 200; + public static int gasConduitExtractRate = 100; + public static int gasConduitMaxIoRate = 400; + public static boolean updateLightingWhenHidingFacades = false; public static boolean travelAnchorEnabled = true; @@ -161,7 +164,7 @@ public final class Config { public static int darkSteelAxePowerUsePerDamagePointMultiHarvest = 1500; public static float darkSteelAxeEffeciencyBoostWhenPowered = 2; public static float darkSteelAxeSpeedPenaltyMultiHarvest = 8; - + public static int darkSteelUpgradeVibrantCost = 20; public static int darkSteelUpgradePowerOneCost = 10; public static int darkSteelUpgradePowerTwoCost = 20; @@ -171,11 +174,11 @@ public final class Config { public static double darkSteelGliderHorizontalSpeed = 0.03; public static double darkSteelGliderVerticalSpeed = -0.05; public static double darkSteelGliderVerticalSpeedSprinting = -0.15; - + public static int darkSteelSwimCost = 15; - + public static int darkSteelNightVisionCost = 15; - + public static int darkSteelSoundLocatorCost = 10; public static int darkSteelSoundLocatorRange = 40; public static int darkSteelSoundLocatorLifespan = 40; @@ -228,7 +231,7 @@ public final class Config { public static int powerSpawnerAddSpawnerCost = 30; public static double vacuumChestRange = 6; - + public static boolean useModMetals = true; public static int wirelessChargerRange = 24; @@ -236,18 +239,18 @@ public final class Config { public static long nutrientFoodBoostDelay = 400; public static int enchanterBaseLevelCost = 4; - + public static boolean machineSoundsEnabled = true; - public static float machineSoundVolume = 1.0f; + public static float machineSoundVolume = 1.0f; - public static int killerJoeNutrientUsePerAttackMb = 5; + public static int killerJoeNutrientUsePerAttackMb = 5; public static double killerJoeAttackHeight = 2; public static double killerJoeAttackWidth = 2; public static double killerJoeAttackLength = 4; public static void load(FMLPreInitializationEvent event) { - + FMLCommonHandler.instance().bus().register(new Config()); configDirectory = new File(event.getModConfigurationDirectory(), EnderIO.MODID.toLowerCase()); if(!configDirectory.exists()) { @@ -258,11 +261,11 @@ public final class Config { config = new Configuration(configFile); syncConfig(); } - + public static void syncConfig() { try { Config.processConfig(config); - } catch (Exception e) { + } catch (Exception e) { Log.error("EnderIO has a problem loading it's configuration"); e.printStackTrace(); } finally { @@ -271,17 +274,18 @@ public final class Config { } } } - + @SubscribeEvent public void onConfigChanged(OnConfigChangedEvent event) { - if (event.modID.equals(EnderIO.MODID)) { + if(event.modID.equals(EnderIO.MODID)) { Log.info("Updating config..."); syncConfig(); } } public static void processConfig(Configuration config) { - useRfAsDefault = config.get(sectionPower.name, "displayPowerAsRedstoneFlux", useRfAsDefault, "If true, all power is displayed in RF, otherwise MJ is used.") + useRfAsDefault = config + .get(sectionPower.name, "displayPowerAsRedstoneFlux", useRfAsDefault, "If true, all power is displayed in RF, otherwise MJ is used.") .getBoolean(useRfAsDefault); capacitorBankMaxIoMJ = config.get(sectionPower.name, "capacitorBankMaxIoMJ", capacitorBankMaxIoMJ, "The maximum IO for a single capacitor in MJ/t") @@ -298,8 +302,8 @@ public final class Config { numConduitsPerRecipe = config.get(sectionRecipe.name, "numConduitsPerRecipe", numConduitsPerRecipe, "The number of conduits crafted per recipe.").getInt(numConduitsPerRecipe); - - enchanterBaseLevelCost= config.get(sectionRecipe.name, "enchanterBaseLevelCost", enchanterBaseLevelCost, + + enchanterBaseLevelCost = config.get(sectionRecipe.name, "enchanterBaseLevelCost", enchanterBaseLevelCost, "Base level cost added to all recipes in the enchanter.").getInt(enchanterBaseLevelCost); photovoltaicCellEnabled = config.get(sectionItems.name, "photovoltaicCellEnabled", photovoltaicCellEnabled, @@ -321,7 +325,7 @@ public final class Config { wirelessChargerRange = config.get(sectionEfficiency.name, "wirelessChargerRange", wirelessChargerRange, "The range of the wireless charger").getInt(wirelessChargerRange); - + fluidConduitExtractRate = config.get(sectionEfficiency.name, "fluidConduitExtractRate", fluidConduitExtractRate, "Number of millibuckects per tick extracted by a fluid conduits auto extracting").getInt(fluidConduitExtractRate); @@ -340,6 +344,12 @@ public final class Config { enderFluidConduitMaxIoRate = config.get(sectionEfficiency.name, "enderFluidConduitMaxIoRate", enderFluidConduitMaxIoRate, "Number of millibuckects per tick that can pass through a single connection to an ender fluid conduit.").getInt(enderFluidConduitMaxIoRate); + gasConduitExtractRate = config.get(sectionEfficiency.name, "gasConduitExtractRate", gasConduitExtractRate, + "Amount of gas per tick extracted by gas conduits auto extracting").getInt(gasConduitExtractRate); + + gasConduitMaxIoRate = config.get(sectionEfficiency.name, "gasConduitMaxIoRate", gasConduitMaxIoRate, + "Amount of gas per tick that can pass through a single connection to a gas conduit.").getInt(gasConduitMaxIoRate); + useAlternateTesseractModel = config.get(sectionAesthetic.name, "useAlternateTransceiverModel", useAlternateTesseractModel, "Use TheKazador's alternative model for the Dimensional Transceiver") .getBoolean(false); @@ -370,12 +380,13 @@ public final class Config { useSneakRightClickYetaWrench = config.get(sectionPersonal.name, "useSneakRightClickYetaWrench", useSneakRightClickYetaWrench, "If true, shift-clicking the YetaWrench on a null or non wrenchable object will change the conduit display mode.") .getBoolean(useSneakRightClickYetaWrench); - + machineSoundsEnabled = config.get(sectionPersonal.name, "useMachineSounds", machineSoundsEnabled, "If true, machines will make sounds.") .getBoolean(machineSoundsEnabled); - - machineSoundVolume= (float)config.get(sectionPersonal.name, "machineSoundVolume", machineSoundVolume,"Volume of machine sounds.").getDouble(machineSoundVolume); + + machineSoundVolume = (float) config.get(sectionPersonal.name, "machineSoundVolume", machineSoundVolume, "Volume of machine sounds.").getDouble( + machineSoundVolume); itemConduitUsePhyscialDistance = config.get(sectionEfficiency.name, "itemConduitUsePhyscialDistance", itemConduitUsePhyscialDistance, "If true, " + "'line of sight' distance rather than conduit path distance is used to calculate priorities.") @@ -390,7 +401,7 @@ public final class Config { reinforcedObsidianEnabled = config.get(sectionItems.name, "reinforcedObsidianEnabled", reinforcedObsidianEnabled, "When set to false reinforced obsidian is not craftable.").getBoolean(reinforcedObsidianEnabled); - + travelAnchorEnabled = config.get(sectionItems.name, "travelAnchorEnabled", travelAnchorEnabled, "When set to false: the travel anchor will not be craftable.").getBoolean(travelAnchorEnabled); @@ -482,54 +493,52 @@ public final class Config { "Base amount of power used per jump (RF) dark steel boots. The second jump in a 'double jump' uses 2x this etc").getInt(darkSteelBootsJumpPowerCost); darkSteelFallDistanceCost = config.get(sectionDarkSteel.name, "darkSteelFallDistanceCost", darkSteelFallDistanceCost, - "Amount of power used (RF) per block height of fall distance damage negated.").getInt(darkSteelFallDistanceCost); + "Amount of power used (RF) per block height of fall distance damage negated.").getInt(darkSteelFallDistanceCost); darkSteelSwimCost = config.get(sectionDarkSteel.name, "darkSteelSwimCost", darkSteelSwimCost, "Number of levels required for the 'Swim' upgrade.").getInt(darkSteelSwimCost); - + darkSteelNightVisionCost = config.get(sectionDarkSteel.name, "darkSteelNightVisionCost", darkSteelNightVisionCost, "Number of levels required for the 'Night Vision' upgrade.").getInt(darkSteelNightVisionCost); - - darkSteelGliderCost = config.get(sectionDarkSteel.name, "darkSteelGliderCost", darkSteelGliderCost, + + darkSteelGliderCost = config.get(sectionDarkSteel.name, "darkSteelGliderCost", darkSteelGliderCost, "Number of levels required for the 'Glider' upgrade.").getInt(darkSteelGliderCost); darkSteelGliderHorizontalSpeed = config.get(sectionDarkSteel.name, "darkSteelGliderHorizontalSpeed", darkSteelGliderHorizontalSpeed, "Horizontal movement speed modifier when gliding.").getDouble(darkSteelGliderHorizontalSpeed); darkSteelGliderVerticalSpeed = config.get(sectionDarkSteel.name, "darkSteelGliderVerticalSpeed", darkSteelGliderVerticalSpeed, "Rate of altitude loss when gliding.").getDouble(darkSteelGliderVerticalSpeed); darkSteelGliderVerticalSpeedSprinting = config.get(sectionDarkSteel.name, "darkSteelGliderVerticalSpeedSprinting", darkSteelGliderVerticalSpeedSprinting, - "Rate of altitude loss when sprinting and gliding.").getDouble(darkSteelGliderVerticalSpeedSprinting); - + "Rate of altitude loss when sprinting and gliding.").getDouble(darkSteelGliderVerticalSpeedSprinting); + darkSteelSoundLocatorCost = config.get(sectionDarkSteel.name, "darkSteelSoundLocatorCost", darkSteelSoundLocatorCost, "Number of levels required for the 'Sound Locator' upgrade.").getInt(darkSteelSoundLocatorCost); darkSteelSoundLocatorRange = config.get(sectionDarkSteel.name, "darkSteelSoundLocatorRange", darkSteelSoundLocatorRange, "Range of the 'Sound Locator' upgrade.").getInt(darkSteelSoundLocatorRange); darkSteelSoundLocatorLifespan = config.get(sectionDarkSteel.name, "darkSteelSoundLocatorLifespan", darkSteelSoundLocatorLifespan, "Number of ticks the 'Sound Locator' icons are displayed for.").getInt(darkSteelSoundLocatorLifespan); - - + darkSteelSwordSkullChance = (float) config.get(sectionDarkSteel.name, "darkSteelSwordSkullChance", darkSteelSwordSkullChance, "The base chance that a skull will be dropped when using a powered dark steel sword (0 = no chance, 1 = 100% chance)").getDouble( - darkSteelSwordSkullChance); + darkSteelSwordSkullChance); darkSteelSwordSkullLootingModifier = (float) config.get(sectionDarkSteel.name, "darkSteelSwordSkullLootingModifier", darkSteelSwordSkullLootingModifier, "The chance per looting level that a skull will be dropped when using a powered dark steel sword (0 = no chance, 1 = 100% chance)").getDouble( darkSteelSwordSkullLootingModifier); - + darkSteelSwordWitherSkullChance = (float) config.get(sectionDarkSteel.name, "darkSteelSwordWitherSkullChance", darkSteelSwordWitherSkullChance, "The base chance that a wither skull will be dropped when using a powered dark steel sword (0 = no chance, 1 = 100% chance)").getDouble( - darkSteelSwordWitherSkullChance); + darkSteelSwordWitherSkullChance); darkSteelSwordWitherSkullLootingModifier = (float) config.get(sectionDarkSteel.name, "darkSteelSwordWitherSkullLootingModifie", darkSteelSwordWitherSkullLootingModifier, "The chance per looting level that a wither skull will be dropped when using a powered dark steel sword (0 = no chance, 1 = 100% chance)").getDouble( - darkSteelSwordWitherSkullLootingModifier); - - - vanillaSwordSkullChance = (float) config.get(sectionDarkSteel.name, "vanillaSwordSkullChance", vanillaSwordSkullChance, + darkSteelSwordWitherSkullLootingModifier); + + vanillaSwordSkullChance = (float) config.get(sectionDarkSteel.name, "vanillaSwordSkullChance", vanillaSwordSkullChance, "The base chance that a skull will be dropped when using a non dark steel sword (0 = no chance, 1 = 100% chance)").getDouble( - vanillaSwordSkullChance); + vanillaSwordSkullChance); vanillaSwordSkullLootingModifier = (float) config.get(sectionPersonal.name, "vanillaSwordSkullLootingModifier", vanillaSwordSkullLootingModifier, "The chance per looting level that a skull will be dropped when using a non-dark steel sword (0 = no chance, 1 = 100% chance)").getDouble( vanillaSwordSkullLootingModifier); - + darkSteelSwordPowerUsePerHit = config.get(sectionDarkSteel.name, "darkSteelSwordPowerUsePerHit", darkSteelSwordPowerUsePerHit, "The amount of power (RF) used per hit.").getInt(darkSteelSwordPowerUsePerHit); darkSteelSwordEnderPearlDropChance = config.get(sectionDarkSteel.name, "darkSteelSwordEnderPearlDropChance", darkSteelSwordEnderPearlDropChance, @@ -555,7 +564,8 @@ public final class Config { darkSteelAxePowerUsePerDamagePointMultiHarvest = config.get(sectionDarkSteel.name, "darkSteelPickAxeUsePerDamagePointMultiHarvest", darkSteelAxePowerUsePerDamagePointMultiHarvest, "Power use (RF) per damage/durability point avoided when shift-harvesting multiple logs").getInt(darkSteelAxePowerUsePerDamagePointMultiHarvest); - darkSteelAxeSpeedPenaltyMultiHarvest = (float) config.get(sectionDarkSteel.name, "darkSteelAxeSpeedPenaltyMultiHarvest", darkSteelAxeSpeedPenaltyMultiHarvest, + darkSteelAxeSpeedPenaltyMultiHarvest = (float) config.get(sectionDarkSteel.name, "darkSteelAxeSpeedPenaltyMultiHarvest", + darkSteelAxeSpeedPenaltyMultiHarvest, "How much slower shift-harvesting logs is.").getDouble(darkSteelAxeSpeedPenaltyMultiHarvest); darkSteelAxeEffeciencyBoostWhenPowered = (float) config.get(sectionDarkSteel.name, "darkSteelAxeEffeciencyBoostWhenPowered", darkSteelAxeEffeciencyBoostWhenPowered, "The increase in effciency when powered.").getDouble(darkSteelAxeEffeciencyBoostWhenPowered); @@ -595,10 +605,10 @@ public final class Config { "The amount of power used by a farm per action (eg plant, till, harvest) ").getDouble(farmActionEnergyUse); farmDefaultSize = config.get(sectionFarm.name, "farmDefaultSize", farmDefaultSize, "The number of blocks a farm will extend from its center").getInt(farmDefaultSize); - farmAxeDamageOnLeafBreak = config.get(sectionFarm.name, "farmAxeDamageOnLeafBreak", farmAxeDamageOnLeafBreak, - "Should axes in a farm take damage when breaking leaves?").getBoolean(farmAxeDamageOnLeafBreak); - farmToolTakeDamageChance = (float) config.get(sectionFarm.name, "farmToolTakeDamageChance", farmToolTakeDamageChance, - "The chance that a tool in the farm will take damage.").getDouble(farmToolTakeDamageChance); + farmAxeDamageOnLeafBreak = config.get(sectionFarm.name, "farmAxeDamageOnLeafBreak", farmAxeDamageOnLeafBreak, + "Should axes in a farm take damage when breaking leaves?").getBoolean(farmAxeDamageOnLeafBreak); + farmToolTakeDamageChance = (float) config.get(sectionFarm.name, "farmToolTakeDamageChance", farmToolTakeDamageChance, + "The chance that a tool in the farm will take damage.").getDouble(farmToolTakeDamageChance); combustionGeneratorUseOpaqueModel = config.get(sectionAesthetic.name, "combustionGeneratorUseOpaqueModel", combustionGeneratorUseOpaqueModel, "If set to true: fluid will not be shown in combustion generator tanks. Improves FPS. ").getBoolean(combustionGeneratorUseOpaqueModel); @@ -617,32 +627,34 @@ public final class Config { "MJ used per autocrafted recipe").getInt(crafterMjPerCraft); poweredSpawnerMinDelayTicks = config.get(sectionSpawner.name, "poweredSpawnerMinDelayTicks", poweredSpawnerMinDelayTicks, - "Min tick delay between spawns for a non-upgraded spawner").getInt(poweredSpawnerMinDelayTicks); + "Min tick delay between spawns for a non-upgraded spawner").getInt(poweredSpawnerMinDelayTicks); poweredSpawnerMaxDelayTicks = config.get(sectionSpawner.name, "poweredSpawnerMaxDelayTicks", poweredSpawnerMaxDelayTicks, - "Min tick delay between spawns for a non-upgraded spawner").getInt(poweredSpawnerMaxDelayTicks); - poweredSpawnerLevelOnePowerPerTick = (float)config.get(sectionSpawner.name, "poweredSpawnerLevelOnePowerPerTick", poweredSpawnerLevelOnePowerPerTick, + "Min tick delay between spawns for a non-upgraded spawner").getInt(poweredSpawnerMaxDelayTicks); + poweredSpawnerLevelOnePowerPerTick = (float) config.get(sectionSpawner.name, "poweredSpawnerLevelOnePowerPerTick", poweredSpawnerLevelOnePowerPerTick, "MJ per tick for a level 1 (non-upgraded) spawner").getDouble(poweredSpawnerLevelOnePowerPerTick); - poweredSpawnerLevelTwoPowerPerTick = (float)config.get(sectionSpawner.name, "poweredSpawnerLevelTwoPowerPerTick", poweredSpawnerLevelTwoPowerPerTick, + poweredSpawnerLevelTwoPowerPerTick = (float) config.get(sectionSpawner.name, "poweredSpawnerLevelTwoPowerPerTick", poweredSpawnerLevelTwoPowerPerTick, "MJ per tick for a level 2 spawner").getDouble(poweredSpawnerLevelTwoPowerPerTick); - poweredSpawnerLevelThreePowerPerTick = (float)config.get(sectionSpawner.name, "poweredSpawnerLevelThreePowerPerTick", poweredSpawnerLevelThreePowerPerTick, + poweredSpawnerLevelThreePowerPerTick = (float) config.get(sectionSpawner.name, "poweredSpawnerLevelThreePowerPerTick", + poweredSpawnerLevelThreePowerPerTick, "MJ per tick for a level 3 spawner").getDouble(poweredSpawnerLevelThreePowerPerTick); poweredSpawnerMaxPlayerDistance = config.get(sectionSpawner.name, "poweredSpawnerMaxPlayerDistance", poweredSpawnerMaxPlayerDistance, "Max distance of the closest player for the spawner to be active. A zero value will remove the player check").getInt(poweredSpawnerMaxPlayerDistance); poweredSpawnerUseVanillaSpawChecks = config.get(sectionSpawner.name, "poweredSpawnerUseVanillaSpawChecks", poweredSpawnerUseVanillaSpawChecks, "If true, regular spawn checks such as lighting level and dimension will be made before spawning mobs").getBoolean(poweredSpawnerUseVanillaSpawChecks); - brokenSpawnerDropChance = (float)config.get(sectionSpawner.name, "brokenSpawnerDropChance", brokenSpawnerDropChance, + brokenSpawnerDropChance = (float) config.get(sectionSpawner.name, "brokenSpawnerDropChance", brokenSpawnerDropChance, "The chance a brokne spawner will be dropped when a spawner is broken. 1 = 100% chance, 0 = 0% chance").getDouble(brokenSpawnerDropChance); powerSpawnerAddSpawnerCost = config.get(sectionSpawner.name, "powerSpawnerAddSpawnerCost", powerSpawnerAddSpawnerCost, "The number of levels it costs to add a broken spawner").getInt(powerSpawnerAddSpawnerCost); - + useModMetals = config.get(sectionRecipe.name, "useModMetals", useModMetals, "If true copper and tin will be used in recipes when registered in the ore dictionary").getBoolean(useModMetals); - - nutrientFoodBoostDelay = config.get(sectionFluid.name, "nutrientFluidFoodBoostDelay", nutrientFoodBoostDelay, "The delay in ticks between when nutrient distillation boosts your food value.").getInt((int)nutrientFoodBoostDelay); - + + nutrientFoodBoostDelay = config.get(sectionFluid.name, "nutrientFluidFoodBoostDelay", nutrientFoodBoostDelay, + "The delay in ticks between when nutrient distillation boosts your food value.").getInt((int) nutrientFoodBoostDelay); + killerJoeNutrientUsePerAttackMb = config.get(sectionKiller.name, "killerJoeNutrientUsePerAttackMb", killerJoeNutrientUsePerAttackMb, "The number of millibuckets of nutrient fluid used per attack.").getInt(killerJoeNutrientUsePerAttackMb); - + killerJoeAttackHeight = config.get(sectionKiller.name, "killerJoeAttackHeight", killerJoeAttackHeight, "The reach of attacks above and bellow Joe.").getDouble(killerJoeAttackHeight); killerJoeAttackWidth = config.get(sectionKiller.name, "killerJoeAttackWidth", killerJoeAttackWidth, diff --git a/src/main/java/crazypants/enderio/gui/IconEIO.java b/src/main/java/crazypants/enderio/gui/IconEIO.java index 14dac3d5..1c9343ba 100644 --- a/src/main/java/crazypants/enderio/gui/IconEIO.java +++ b/src/main/java/crazypants/enderio/gui/IconEIO.java @@ -20,19 +20,23 @@ public final class IconEIO { public static final IconEIO BUTTON_DOWN = new IconEIO(48, 116); public static final IconEIO BUTTON_DOWN_HIGHLIGHT = new IconEIO(64, 116); - public static final IconEIO WRENCH_OVERLAY_ALL_ON = new IconEIO(0, 148, 64, 64); - public static final IconEIO WRENCH_OVERLAY_ALL_OFF = new IconEIO(96, 148, 64, 64); + public static final IconEIO WRENCH_OVERLAY_ALL_ON = new IconEIO(0, 148, 96, 64); + public static final IconEIO WRENCH_OVERLAY_ALL_OFF = new IconEIO(96, 148, 96, 64); - public static final IconEIO WRENCH_OVERLAY_POWER = new IconEIO(0, 148, 32, 32); - public static final IconEIO WRENCH_OVERLAY_POWER_OFF = new IconEIO(96, 148, 32, 32); + public static final IconEIO WRENCH_OVERLAY_POWER = new IconEIO(16, 148, 32, 32); + public static final IconEIO WRENCH_OVERLAY_POWER_OFF = new IconEIO(16 + 96, 148, 32, 32); - public static final IconEIO WRENCH_OVERLAY_REDSTONE = new IconEIO(32, 148, 32, 32); + public static final IconEIO WRENCH_OVERLAY_REDSTONE = new IconEIO(48, 148, 32, 32); + public static final IconEIO WRENCH_OVERLAY_REDSTONE_OFF = new IconEIO(48 + 96, 148, 32, 32); + + public static final IconEIO WRENCH_OVERLAY_FLUID = new IconEIO(0, 180, 32, 32); + public static final IconEIO WRENCH_OVERLAY_FLUID_OFF = new IconEIO(96, 180, 32, 32); public static final IconEIO WRENCH_OVERLAY_ITEM = new IconEIO(32, 180, 32, 32); public static final IconEIO WRENCH_OVERLAY_ITEM_OFF = new IconEIO(32 + 96, 180, 32, 32); - public static final IconEIO WRENCH_OVERLAY_FLUID = new IconEIO(0, 180, 32, 32); - public static final IconEIO WRENCH_OVERLAY_FLUID_OFF = new IconEIO(96, 180, 32, 32); + public static final IconEIO WRENCH_OVERLAY_GAS = new IconEIO(64, 180, 32, 32); + public static final IconEIO WRENCH_OVERLAY_GAS_OFF = new IconEIO(64 + 96, 180, 32, 32); public static final IconEIO ACTIVE_TAB = new IconEIO(237, 0, 19, 24); public static final IconEIO INACTIVE_TAB = new IconEIO(237, 25, 19, 24); @@ -89,7 +93,7 @@ public final class IconEIO { public static final IconEIO MINUS_BUT = new IconEIO(129, 246, 10, 10); public static final IconEIO SOUND = new IconEIO(209, 172, 22, 22); - + public static final IconEIO XP = new IconEIO(235, 60, 22, 22); private static final int TEX_SIZE = 256; diff --git a/src/main/java/crazypants/enderio/item/YetaWrenchOverlayRenderer.java b/src/main/java/crazypants/enderio/item/YetaWrenchOverlayRenderer.java index 4a67639e..292d3c69 100644 --- a/src/main/java/crazypants/enderio/item/YetaWrenchOverlayRenderer.java +++ b/src/main/java/crazypants/enderio/item/YetaWrenchOverlayRenderer.java @@ -47,22 +47,24 @@ public class YetaWrenchOverlayRenderer { if(mode == ConduitDisplayMode.ALL) { GL11.glColor4f(1, 1, 1, 0.75f); - IconEIO.WRENCH_OVERLAY_ALL_ON.renderIcon(offsetX, offsetY - 32, 32, 32, 0, true); + IconEIO.WRENCH_OVERLAY_ALL_ON.renderIcon(offsetX, offsetY - 32, 48, 32, 0, true); return; } float c = 0.6f; GL11.glColor4f(c, c, c, 0.33f); - IconEIO.WRENCH_OVERLAY_ALL_OFF.renderIcon(offsetX, offsetY - 32, 32, 32, 0, true); + IconEIO.WRENCH_OVERLAY_ALL_OFF.renderIcon(offsetX, offsetY - 32, 48, 32, 0, true); GL11.glColor4f(1, 1, 1, 0.75f); if(mode == ConduitDisplayMode.POWER) { - IconEIO.WRENCH_OVERLAY_POWER.renderIcon(offsetX, offsetY - 32, 16, 16, 0, true); + IconEIO.WRENCH_OVERLAY_POWER.renderIcon(offsetX + 8, offsetY - 32, 16, 16, 0, true); + } else if(mode == ConduitDisplayMode.REDSTONE) { + IconEIO.WRENCH_OVERLAY_REDSTONE.renderIcon(offsetX + 24, offsetY - 32, 16, 16, 0, true); } else if(mode == ConduitDisplayMode.FLUID) { - IconEIO.WRENCH_OVERLAY_FLUID.renderIcon(offsetX , offsetY - 16, 16, 16, 0, true); + IconEIO.WRENCH_OVERLAY_FLUID.renderIcon(offsetX, offsetY - 16, 16, 16, 0, true); } else if(mode == ConduitDisplayMode.ITEM) { IconEIO.WRENCH_OVERLAY_ITEM.renderIcon(offsetX + 16, offsetY - 16, 16, 16, 0, true); - } else if(mode == ConduitDisplayMode.REDSTONE) { - IconEIO.WRENCH_OVERLAY_REDSTONE.renderIcon(offsetX + 16, offsetY - 32, 16, 16, 0, true); + } else if(mode == ConduitDisplayMode.GAS) { + IconEIO.WRENCH_OVERLAY_GAS.renderIcon(offsetX + 32, offsetY - 16, 16, 16, 0, true); } } diff --git a/src/main/java/crazypants/enderio/nei/NEIEnderIOConfig.java b/src/main/java/crazypants/enderio/nei/NEIEnderIOConfig.java index cdb0d0a6..45e5f122 100644 --- a/src/main/java/crazypants/enderio/nei/NEIEnderIOConfig.java +++ b/src/main/java/crazypants/enderio/nei/NEIEnderIOConfig.java @@ -3,6 +3,7 @@ package crazypants.enderio.nei; import net.minecraft.item.ItemStack; import codechicken.nei.api.API; import codechicken.nei.api.IConfigureNEI; +import cpw.mods.fml.common.Loader; import crazypants.enderio.EnderIO; import crazypants.enderio.config.Config; @@ -17,7 +18,7 @@ public class NEIEnderIOConfig implements IConfigureNEI { API.registerRecipeHandler(new VatRecipeHandler()); API.registerUsageHandler(new VatRecipeHandler()); - + API.registerRecipeHandler(new EnchanterRecipeHandler()); API.registerUsageHandler(new EnchanterRecipeHandler()); @@ -33,6 +34,10 @@ public class NEIEnderIOConfig implements IConfigureNEI { if(!Config.reinforcedObsidianEnabled) { API.hideItem(new ItemStack(EnderIO.blockReinforcedObsidian)); } + + if(!Loader.isModLoaded("Mekanism")) { + API.hideItem(new ItemStack(EnderIO.itemGasConduit)); + } } @Override diff --git a/src/main/java/crazypants/util/ClientUtil.java b/src/main/java/crazypants/util/ClientUtil.java index 8ab0d978..e85f520a 100644 --- a/src/main/java/crazypants/util/ClientUtil.java +++ b/src/main/java/crazypants/util/ClientUtil.java @@ -7,6 +7,8 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import crazypants.enderio.conduit.IConduitBundle; import crazypants.enderio.conduit.TileConduitBundle; +import crazypants.enderio.conduit.gas.IGasConduit; +import crazypants.enderio.conduit.gas.PacketGasLevel; import crazypants.enderio.conduit.liquid.ILiquidConduit; import crazypants.enderio.conduit.liquid.PacketFluidLevel; import crazypants.enderio.machine.generator.combustion.PacketCombustionTank; @@ -20,7 +22,7 @@ import crazypants.enderio.machine.generator.stirling.TileEntityStirlingGenerator * @author Garrett Spicer-Davis */ public class ClientUtil { - + public static void doFluidLevelUpdate(int x, int y, int z, PacketFluidLevel pkt) { TileEntity tile = Minecraft.getMinecraft().theWorld.getTileEntity(x, y, z); if(pkt.tc == null || !(tile instanceof IConduitBundle)) { @@ -34,6 +36,19 @@ public class ClientUtil { con.readFromNBT(pkt.tc, TileConduitBundle.NBT_VERSION); } + public static void doGasLevelUpdate(int x, int y, int z, PacketGasLevel pkt) { + TileEntity tile = Minecraft.getMinecraft().theWorld.getTileEntity(x, y, z); + if(pkt.tc == null || !(tile instanceof IConduitBundle)) { + return; + } + IConduitBundle bundle = (IConduitBundle) tile; + IGasConduit con = bundle.getConduit(IGasConduit.class); + if(con == null) { + return; + } + con.readFromNBT(pkt.tc, TileConduitBundle.NBT_VERSION); + } + public static void spawnFarmParcticles(Random rand, BlockCoord bc) { double xOff = 0.5 + (rand.nextDouble() - 0.5) * 1.1; double yOff = 0.5 + (rand.nextDouble() - 0.5) * 0.2; @@ -42,13 +57,13 @@ public class ClientUtil { (rand.nextDouble() - 0.5) * 1.5); } - public static void setTankNBT(PacketCombustionTank message, int x, int y, int z) { - TileCombustionGenerator tile = (TileCombustionGenerator) Minecraft.getMinecraft().theWorld.getTileEntity(x, y, z); + public static void setTankNBT(PacketCombustionTank message, int x, int y, int z) { + TileCombustionGenerator tile = (TileCombustionGenerator) Minecraft.getMinecraft().theWorld.getTileEntity(x, y, z); if(tile == null) { //no loaded on client when receiving message, can happen when loading the chunks return; } - + if(message.nbtRoot.hasKey("coolantTank")) { NBTTagCompound tankRoot = message.nbtRoot.getCompoundTag("coolantTank"); tile.getCoolantTank().readFromNBT(tankRoot);