diff --git a/.classpath b/.classpath
new file mode 100644
index 00000000..4a9e7474
--- /dev/null
+++ b/.classpath
@@ -0,0 +1,9 @@
+
+
+
+
+
+
+
+
+
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..ff007088
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,3 @@
+/bin
+/build
+/download
diff --git a/.project b/.project
new file mode 100644
index 00000000..97fca3a4
--- /dev/null
+++ b/.project
@@ -0,0 +1,17 @@
+
+
+ EnderIO
+
+
+
+
+
+ org.eclipse.jdt.core.javabuilder
+
+
+
+
+
+ org.eclipse.jdt.core.javanature
+
+
diff --git a/README.md b/README.md
index f554c7c6..658dabc9 100644
--- a/README.md
+++ b/README.md
@@ -1,2 +1,6 @@
EnderIO
=======
+
+All code (excluding the build craft API, which is covered by the build craft liscence) is 'unliscenced' into the public domain.
+Do what you want with it, as long as you smile while doing so. While it is not a requirement, it would be nice to know if it is being used and how, so send me hello to crazypants.mc at gmail.com.
+
diff --git a/build.xml b/build.xml
new file mode 100644
index 00000000..e510b19c
--- /dev/null
+++ b/build.xml
@@ -0,0 +1,170 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/common/buildcraft/api/blueprints/BlockSignature.java b/common/buildcraft/api/blueprints/BlockSignature.java
new file mode 100644
index 00000000..51db24d4
--- /dev/null
+++ b/common/buildcraft/api/blueprints/BlockSignature.java
@@ -0,0 +1,77 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.blueprints;
+
+public class BlockSignature {
+
+ public String blockClassName;
+ public String tileClassName;
+ public String blockName;
+ public String mod;
+ public String modVersion;
+ public String customField;
+
+ public BlockSignature(String str) {
+ String[] values = str.split("/");
+
+ int i = 0;
+
+ if (values[0].equals("#B")) {
+ i++;
+ }
+
+ blockClassName = values[i];
+ tileClassName = values[i + 1];
+ blockName = values[i + 2];
+ mod = values[i + 3];
+ modVersion = values[i + 4];
+ customField = values[i + 5];
+
+ replaceNullWithStar();
+
+ }
+
+ public BlockSignature() {
+ replaceNullWithStar();
+ }
+
+ @Override
+ public String toString() {
+ replaceNullWithStar();
+
+ return "#B/" + blockClassName + "/" + tileClassName + "/" + blockName + "/" + mod + "/" + modVersion + "/" + customField;
+ }
+
+ public void replaceNullWithStar() {
+ if (blockClassName == null) {
+ blockClassName = "*";
+ }
+
+ if (tileClassName == null) {
+ tileClassName = "*";
+ }
+
+ if (blockName == null) {
+ blockName = "*";
+ }
+
+ if (mod == null) {
+ mod = "*";
+ }
+
+ if (modVersion == null) {
+ modVersion = "*";
+ }
+
+ if (customField == null) {
+ customField = "*";
+ }
+ }
+}
diff --git a/common/buildcraft/api/blueprints/BlueprintManager.java b/common/buildcraft/api/blueprints/BlueprintManager.java
new file mode 100644
index 00000000..c71b710e
--- /dev/null
+++ b/common/buildcraft/api/blueprints/BlueprintManager.java
@@ -0,0 +1,35 @@
+package buildcraft.api.blueprints;
+
+import buildcraft.api.core.BuildCraftAPI;
+import net.minecraft.block.Block;
+import net.minecraft.item.Item;
+import net.minecraft.item.ItemStack;
+
+@Deprecated
+public class BlueprintManager {
+
+ public static BptBlock[] blockBptProps = new BptBlock[Block.blocksList.length];
+
+ public static ItemSignature getItemSignature(Item item) {
+ ItemSignature sig = new ItemSignature();
+
+ if (item.itemID >= Block.blocksList.length + BuildCraftAPI.LAST_ORIGINAL_ITEM) {
+ sig.itemClassName = item.getClass().getSimpleName();
+ }
+
+ sig.itemName = item.getUnlocalizedName(new ItemStack(item));
+
+ return sig;
+ }
+
+ public static BlockSignature getBlockSignature(Block block) {
+ return BlueprintManager.blockBptProps[0].getSignature(block);
+ }
+
+ static {
+ // Initialize defaults for block properties.
+ for (int i = 0; i < BlueprintManager.blockBptProps.length; ++i) {
+ new BptBlock(i);
+ }
+ }
+}
diff --git a/common/buildcraft/api/blueprints/BptBlock.java b/common/buildcraft/api/blueprints/BptBlock.java
new file mode 100644
index 00000000..4f48d35e
--- /dev/null
+++ b/common/buildcraft/api/blueprints/BptBlock.java
@@ -0,0 +1,234 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.blueprints;
+
+import buildcraft.api.core.BuildCraftAPI;
+import java.util.ArrayList;
+import java.util.LinkedList;
+import net.minecraft.block.Block;
+import net.minecraft.block.BlockContainer;
+import net.minecraft.item.Item;
+import net.minecraft.item.ItemStack;
+import net.minecraft.tileentity.TileEntity;
+
+/**
+ * This class allow to specify specific behavior for blocks stored in blueprints:
+ *
+ * - what items needs to be used to create that block - how the block has to be built on the world - how to rotate the block - what extra data to store / load
+ * in the blueprint
+ *
+ * Default implementations of this can be seen in the package buildcraft.api.bptblocks. The class BptBlockUtils provide some additional utilities.
+ *
+ * Blueprints perform "id translation" in case the block ids between a blueprint and the world installation are different. In order to translate block ids,
+ * blocks needs to be uniquely identified. By default, this identification is done by:
+ *
+ * - the block simple class name - the tile simple class name (if any) - the block name
+ *
+ * In certain circumstances, the above is not enough (e.g. if several blocks share the same class and the same name, with no tile). In this case, additional
+ * data may be provided by children of this class:
+ *
+ * - mod name - custom signature
+ *
+ * At blueprint load time, BuildCraft will check that each block id of the blueprint corresponds to the block id in the installation. If not, it will perform a
+ * search through the block list, and upon matching signature, it will translate all blocks ids of the blueprint to the installation ones. If no such block id
+ * is found, BuildCraft will assume that the block is not installed and will not load the blueprint.
+ */
+
+@Deprecated
+public class BptBlock {
+
+ public final int blockId;
+
+ public BptBlock(int blockId) {
+ this.blockId = blockId;
+
+ BlueprintManager.blockBptProps[blockId] = this;
+ }
+
+ /**
+ * Returns the requirements needed to build this block. When the requirements are met, they will be removed all at once from the builder, before calling
+ * buildBlock.
+ */
+ public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) {
+ if (slot.blockId != 0) {
+ if (slot.storedRequirements.size() != 0) {
+ requirements.addAll(slot.storedRequirements);
+ } else {
+ requirements.add(new ItemStack(slot.blockId, 1, slot.meta));
+ }
+ }
+ }
+
+ /**
+ * This is called each time an item matches a reqquirement, that is: (req id == stack id) for damageable items (req id == stack id && req dmg == stack dmg)
+ * for other items by default, it will increase damage of damageable items by the amount of damage of the requirement, and remove the intended amount of non
+ * damageable item.
+ *
+ * Client may override this behavior for default items. Note that this subprogram may be called twice with the same parameters, once with a copy of
+ * requirements and stack to check if the entire requirements can be fullfilled, and once with the real inventory. Implementer is responsible for updating
+ * req (with the remaining requirements if any) and stack (after usage)
+ *
+ * returns: what was used (similer to req, but created from stack, so that any NBT based differences are drawn from the correct source)
+ */
+ public ItemStack useItem(BptSlotInfo slot, IBptContext context, ItemStack req, ItemStack stack) {
+ ItemStack result = stack.copy();
+ if (stack.isItemStackDamageable()) {
+ if (req.getItemDamage() + stack.getItemDamage() <= stack.getMaxDamage()) {
+ stack.setItemDamage(req.getItemDamage() + stack.getItemDamage());
+ result.setItemDamage(req.getItemDamage());
+ req.stackSize = 0;
+ }
+
+ if (stack.getItemDamage() >= stack.getMaxDamage()) {
+ stack.stackSize = 0;
+ }
+ } else {
+ if (stack.stackSize >= req.stackSize) {
+ result.stackSize = req.stackSize;
+ stack.stackSize -= req.stackSize;
+ req.stackSize = 0;
+ } else {
+ req.stackSize -= stack.stackSize;
+ stack.stackSize = 0;
+ }
+ }
+
+ if (stack.stackSize == 0 && stack.getItem().getContainerItem() != null) {
+ Item container = stack.getItem().getContainerItem();
+
+ stack.itemID = container.itemID;
+ stack.stackSize = 1;
+ stack.setItemDamage(0);
+ }
+ return result;
+ }
+
+ /**
+ * Return true if the block on the world correspond to the block stored in the blueprint at the location given by the slot. By default, this subprogram is
+ * permissive and doesn't take into account metadata.
+ *
+ * Added metadata sensitivity //Krapht
+ */
+ public boolean isValid(BptSlotInfo slot, IBptContext context) {
+ return slot.blockId == context.world().getBlockId(slot.x, slot.y, slot.z) && slot.meta == context.world().getBlockMetadata(slot.x, slot.y, slot.z);
+ }
+
+ /**
+ * Perform a 90 degree rotation to the slot.
+ */
+ public void rotateLeft(BptSlotInfo slot, IBptContext context) {
+
+ }
+
+ /**
+ * Places the block in the world, at the location specified in the slot.
+ */
+ public void buildBlock(BptSlotInfo slot, IBptContext context) {
+ // Meta needs to be specified twice, depending on the block behavior
+ context.world().setBlock(slot.x, slot.y, slot.z, slot.blockId, slot.meta,3);
+ context.world().setBlockMetadataWithNotify(slot.x, slot.y, slot.z, slot.meta,3);
+
+ if (Block.blocksList[slot.blockId] instanceof BlockContainer) {
+ TileEntity tile = context.world().getBlockTileEntity(slot.x, slot.y, slot.z);
+
+ slot.cpt.setInteger("x", slot.x);
+ slot.cpt.setInteger("y", slot.y);
+ slot.cpt.setInteger("z", slot.z);
+
+ if (tile != null) {
+ tile.readFromNBT(slot.cpt);
+ }
+ }
+ }
+
+ /**
+ * Return true if the block should not be placed to the world. Requirements will not be asked on such a block, and building will not be called.
+ */
+ public boolean ignoreBuilding(BptSlotInfo slot) {
+ return false;
+ }
+
+ /**
+ * Initializes a slot from the blueprint according to an objet placed on {x, y, z} on the world. This typically means adding entries in slot.cpt. Note that
+ * "id" and "meta" will be set automatically, corresponding to the block id and meta.
+ *
+ * By default, if the block is a BlockContainer, tile information will be to save / load the block.
+ */
+ public void initializeFromWorld(BptSlotInfo slot, IBptContext context, int x, int y, int z) {
+ if (Block.blocksList[slot.blockId] instanceof BlockContainer) {
+ TileEntity tile = context.world().getBlockTileEntity(x, y, z);
+
+ if (tile != null) {
+ tile.writeToNBT(slot.cpt);
+ }
+ }
+
+ if (Block.blocksList[slot.blockId] != null) {
+ ArrayList req = Block.blocksList[slot.blockId].getBlockDropped(context.world(), x, y, z, context.world().getBlockMetadata(x, y, z), 0);
+
+ if (req != null) {
+ slot.storedRequirements.addAll(req);
+ }
+ }
+ }
+
+ /**
+ * Called on a block when the blueprint has finished to place all the blocks. This may be useful to adjust variable depending on surrounding blocks that may
+ * not be there already at initial building.
+ */
+ public void postProcessing(BptSlotInfo slot, IBptContext context) {
+
+ }
+
+ /**
+ * By default, block class name, block tile name and block name are used to define block signature. Overriding this subprogram may allow to replace some of
+ * these with stars, specify the mod that this block kind is coming from or add custom data to the signature.
+ */
+ public BlockSignature getSignature(Block block) {
+ BlockSignature sig = new BlockSignature();
+
+ if (block.blockID > BuildCraftAPI.LAST_ORIGINAL_BLOCK) {
+ sig.blockClassName = block.getClass().getSimpleName();
+
+ if (block instanceof BlockContainer) {
+ // TODO: Try to see if we can get a world instance to call with instead of null
+ TileEntity tile = ((BlockContainer) block).createNewTileEntity(null);
+
+ if (tile != null) {
+ sig.tileClassName = tile.getClass().getSimpleName();
+ }
+ }
+ }
+
+ sig.blockName = block.getUnlocalizedName();
+ sig.replaceNullWithStar();
+
+ return sig;
+ }
+
+ /**
+ * By default, block name, block and tile classes, mod name and custom signature are matched to verify if a blueprint block corresponds to the installation
+ * block - except for the default blocks which don't check for classes. For any value, * means match with anything. For compatibilty and evolution reasons,
+ * mods may want to write a different policy, allowing to migrate one format to the other.
+ */
+ public boolean match(Block block, BlockSignature sig) {
+ if (block == null)
+ return false;
+
+ BlockSignature inst = BlueprintManager.getBlockSignature(block);
+
+ return starMatch(sig.blockName, inst.blockName) && starMatch(sig.blockClassName, inst.blockClassName)
+ && starMatch(sig.tileClassName, inst.tileClassName) && starMatch(sig.customField, inst.customField) && starMatch(sig.mod, inst.mod);
+ }
+
+ private boolean starMatch(String s1, String s2) {
+ return s1.equals("*") || s2.equals("*") || s1.equals(s2);
+ }
+}
diff --git a/common/buildcraft/api/blueprints/BptBlockUtils.java b/common/buildcraft/api/blueprints/BptBlockUtils.java
new file mode 100644
index 00000000..a46d9b12
--- /dev/null
+++ b/common/buildcraft/api/blueprints/BptBlockUtils.java
@@ -0,0 +1,85 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.blueprints;
+
+import java.util.LinkedList;
+import net.minecraft.inventory.IInventory;
+import net.minecraft.item.ItemStack;
+import net.minecraft.nbt.NBTTagCompound;
+import net.minecraft.nbt.NBTTagList;
+
+@Deprecated
+public class BptBlockUtils {
+
+ public static void requestInventoryContents(BptSlotInfo slot, IBptContext context, LinkedList requirements) {
+ ItemStack[] stacks = getItemStacks(slot, context);
+
+ for (ItemStack stack : stacks) {
+ if (stack != null) {
+ requirements.add(stack);
+ }
+ }
+ }
+
+ public static void initializeInventoryContents(BptSlotInfo slot, IBptContext context, IInventory inventory) {
+ ItemStack[] stacks = new ItemStack[inventory.getSizeInventory()];
+
+ for (int i = 0; i < inventory.getSizeInventory(); ++i) {
+ stacks[i] = inventory.getStackInSlot(i);
+ }
+
+ setItemStacks(slot, context, stacks);
+ }
+
+ public static void buildInventoryContents(BptSlotInfo slot, IBptContext context, IInventory inventory) {
+ ItemStack[] stacks = getItemStacks(slot, context);
+
+ for (int i = 0; i < stacks.length; ++i) {
+ inventory.setInventorySlotContents(i, stacks[i]);
+ }
+ }
+
+ public static ItemStack[] getItemStacks(BptSlotInfo slot, IBptContext context) {
+ NBTTagList list = (NBTTagList) slot.cpt.getTag("inv");
+
+ if (list == null)
+ return new ItemStack[0];
+
+ ItemStack stacks[] = new ItemStack[list.tagCount()];
+
+ for (int i = 0; i < list.tagCount(); ++i) {
+ ItemStack stack = ItemStack.loadItemStackFromNBT((NBTTagCompound) list.tagAt(i));
+
+ if (stack != null && stack.itemID != 0 && stack.stackSize > 0) {
+ stacks[i] = context.mapItemStack(stack);
+ }
+ }
+
+ return stacks;
+ }
+
+ public static void setItemStacks(BptSlotInfo slot, IBptContext context, ItemStack[] stacks) {
+ NBTTagList nbttaglist = new NBTTagList();
+
+ for (int i = 0; i < stacks.length; ++i) {
+ NBTTagCompound cpt = new NBTTagCompound();
+ nbttaglist.appendTag(cpt);
+ ItemStack stack = stacks[i];
+
+ if (stack != null && stack.stackSize != 0) {
+ stack.writeToNBT(cpt);
+ context.storeId(stack.itemID);
+ }
+ }
+
+ slot.cpt.setTag("inv", nbttaglist);
+ }
+
+}
diff --git a/common/buildcraft/api/blueprints/BptSlotInfo.java b/common/buildcraft/api/blueprints/BptSlotInfo.java
new file mode 100644
index 00000000..799a3b4f
--- /dev/null
+++ b/common/buildcraft/api/blueprints/BptSlotInfo.java
@@ -0,0 +1,54 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.blueprints;
+
+import java.util.LinkedList;
+import net.minecraft.item.ItemStack;
+import net.minecraft.nbt.NBTTagCompound;
+
+/**
+ * This class records a slot, either from a blueprint or from a block placed in the world.
+ */
+
+@Deprecated
+public class BptSlotInfo {
+
+ public int blockId = 0;
+ public int meta = 0;
+ public int x;
+ public int y;
+ public int z;
+
+ /**
+ * This field contains requirements for a given block when stored in the blueprint. Modders can either rely on this list or compute their own int BptBlock.
+ */
+ public LinkedList storedRequirements = new LinkedList();
+
+ /**
+ * This tree contains additional data to be stored in the blueprint. By default, it will be initialized from BptBlock.initializeFromWorld with the standard
+ * readNBT function of the corresponding tile (if any) and will be loaded from BptBlock.buildBlock using the standard writeNBT function.
+ */
+ public NBTTagCompound cpt = new NBTTagCompound();
+
+ @Override
+ public BptSlotInfo clone() {
+ BptSlotInfo obj = new BptSlotInfo();
+
+ obj.x = x;
+ obj.y = y;
+ obj.z = z;
+ obj.blockId = blockId;
+ obj.meta = meta;
+ obj.cpt = (NBTTagCompound) cpt.copy();
+
+ return obj;
+ }
+
+}
diff --git a/common/buildcraft/api/blueprints/IBptContext.java b/common/buildcraft/api/blueprints/IBptContext.java
new file mode 100644
index 00000000..8498bfd3
--- /dev/null
+++ b/common/buildcraft/api/blueprints/IBptContext.java
@@ -0,0 +1,48 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.blueprints;
+
+import buildcraft.api.core.IBox;
+import buildcraft.api.core.Position;
+import net.minecraft.item.ItemStack;
+import net.minecraft.world.World;
+
+/**
+ * This interface provide contextual information when building or initializing blueprint slots.
+ */
+
+@Deprecated
+public interface IBptContext {
+
+ /**
+ * If bptItemStack is an ItemStack extracted from the blueprint containing this mapping, this will return an item stack with the id of the current world
+ */
+ public ItemStack mapItemStack(ItemStack bptItemStack);
+
+ /**
+ * Blueprints may be created in a world with a given id setting, and then ported to a world with different ids. Heuristics are used to retreive these new
+ * ids automatically. This interface provide services to map ids from a blueprints to current ids in the world, and should be used whenever storing block
+ * numbers or item stacks in blueprints..
+ */
+ public int mapWorldId(int bptWorldId);
+
+ /**
+ * This asks the id mapping to store a mapping from this Id, which may be either an itemId or a blockId. In effect, the blueprint will record it and make it
+ * available upon blueprint load. Note that block present in the blueprint are automatically stored upon blueprint save, so this is really only needed when
+ * writing ids that are e.g. in inventory stacks.
+ */
+ public void storeId(int worldId);
+
+ public Position rotatePositionLeft(Position pos);
+
+ public IBox surroundingBox();
+
+ public World world();
+}
diff --git a/common/buildcraft/api/blueprints/ItemSignature.java b/common/buildcraft/api/blueprints/ItemSignature.java
new file mode 100644
index 00000000..d6bd0310
--- /dev/null
+++ b/common/buildcraft/api/blueprints/ItemSignature.java
@@ -0,0 +1,48 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.blueprints;
+
+@Deprecated
+public class ItemSignature {
+
+ public String itemClassName;
+ public String itemName;
+
+ public ItemSignature(String str) {
+ String[] values = str.split("/");
+
+ itemClassName = values[1];
+ itemName = values[2];
+
+ replaceNullWithStar();
+
+ }
+
+ public ItemSignature() {
+ replaceNullWithStar();
+ }
+
+ @Override
+ public String toString() {
+ replaceNullWithStar();
+
+ return "#I/" + itemClassName + "/" + itemName;
+ }
+
+ public void replaceNullWithStar() {
+ if (itemClassName == null) {
+ itemClassName = "*";
+ }
+
+ if (itemName == null) {
+ itemName = "*";
+ }
+ }
+}
diff --git a/common/buildcraft/api/bptblocks/BptBlockBed.java b/common/buildcraft/api/bptblocks/BptBlockBed.java
new file mode 100644
index 00000000..e2dae05c
--- /dev/null
+++ b/common/buildcraft/api/bptblocks/BptBlockBed.java
@@ -0,0 +1,86 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.bptblocks;
+
+import buildcraft.api.blueprints.BptBlock;
+import buildcraft.api.blueprints.BptSlotInfo;
+import buildcraft.api.blueprints.IBptContext;
+import java.util.LinkedList;
+import net.minecraft.item.Item;
+import net.minecraft.item.ItemStack;
+
+@Deprecated
+public class BptBlockBed extends BptBlock {
+
+ public BptBlockBed(int blockId) {
+ super(blockId);
+ }
+
+ @Override
+ public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) {
+ if ((slot.meta & 8) == 0) {
+ requirements.add(new ItemStack(Item.bed));
+ }
+ }
+
+ @Override
+ public void rotateLeft(BptSlotInfo slot, IBptContext context) {
+ int orientation = (slot.meta & 7);
+ int others = slot.meta - orientation;
+
+ switch (orientation) {
+ case 0:
+ slot.meta = 1 + others;
+ break;
+ case 1:
+ slot.meta = 2 + others;
+ break;
+ case 2:
+ slot.meta = 3 + others;
+ break;
+ case 3:
+ slot.meta = 0 + others;
+ break;
+ }
+ }
+
+ @Override
+ public void buildBlock(BptSlotInfo slot, IBptContext context) {
+ if ((slot.meta & 8) != 0)
+ return;
+
+ context.world().setBlock(slot.x, slot.y, slot.z, slot.blockId, slot.meta,1);
+
+ int x2 = slot.x;
+ int z2 = slot.z;
+
+ switch (slot.meta) {
+ case 0:
+ z2++;
+ break;
+ case 1:
+ x2--;
+ break;
+ case 2:
+ z2--;
+ break;
+ case 3:
+ x2++;
+ break;
+ }
+
+ context.world().setBlock(x2, slot.y, z2, slot.blockId, slot.meta + 8,1);
+ }
+
+ @Override
+ public boolean ignoreBuilding(BptSlotInfo slot) {
+ return (slot.meta & 8) != 0;
+ }
+}
diff --git a/common/buildcraft/api/bptblocks/BptBlockCustomStack.java b/common/buildcraft/api/bptblocks/BptBlockCustomStack.java
new file mode 100644
index 00000000..79aef15c
--- /dev/null
+++ b/common/buildcraft/api/bptblocks/BptBlockCustomStack.java
@@ -0,0 +1,34 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.bptblocks;
+
+import buildcraft.api.blueprints.BptBlock;
+import buildcraft.api.blueprints.BptSlotInfo;
+import buildcraft.api.blueprints.IBptContext;
+import java.util.LinkedList;
+import net.minecraft.item.ItemStack;
+
+@Deprecated
+public class BptBlockCustomStack extends BptBlock {
+
+ final ItemStack customStack;
+
+ public BptBlockCustomStack(int blockId, ItemStack customStack) {
+ super(blockId);
+
+ this.customStack = customStack;
+ }
+
+ @Override
+ public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) {
+ requirements.add(customStack.copy());
+ }
+
+}
diff --git a/common/buildcraft/api/bptblocks/BptBlockDelegate.java b/common/buildcraft/api/bptblocks/BptBlockDelegate.java
new file mode 100644
index 00000000..035dc556
--- /dev/null
+++ b/common/buildcraft/api/bptblocks/BptBlockDelegate.java
@@ -0,0 +1,65 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.bptblocks;
+
+import buildcraft.api.blueprints.BlueprintManager;
+import buildcraft.api.blueprints.BptBlock;
+import buildcraft.api.blueprints.BptSlotInfo;
+import buildcraft.api.blueprints.IBptContext;
+import java.util.LinkedList;
+import net.minecraft.item.ItemStack;
+
+@Deprecated
+public class BptBlockDelegate extends BptBlock {
+
+ final int delegateTo;
+
+ public BptBlockDelegate(int blockId, int delegateTo) {
+ super(blockId);
+
+ this.delegateTo = delegateTo;
+ }
+
+ @Override
+ public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) {
+ BptSlotInfo newSlot = slot.clone();
+ slot.blockId = delegateTo;
+
+ if (BlueprintManager.blockBptProps[delegateTo] != null) {
+ BlueprintManager.blockBptProps[delegateTo].addRequirements(newSlot, context, requirements);
+ } else {
+ super.addRequirements(newSlot, context, requirements);
+ }
+ }
+
+ @Override
+ public boolean isValid(BptSlotInfo slot, IBptContext context) {
+ BptSlotInfo newSlot = slot.clone();
+ slot.blockId = delegateTo;
+
+ if (BlueprintManager.blockBptProps[delegateTo] != null)
+ return BlueprintManager.blockBptProps[delegateTo].isValid(newSlot, context);
+ else
+ return super.isValid(newSlot, context);
+ }
+
+ @Override
+ public void rotateLeft(BptSlotInfo slot, IBptContext context) {
+ BptSlotInfo newSlot = slot.clone();
+ slot.blockId = delegateTo;
+
+ if (BlueprintManager.blockBptProps[delegateTo] != null) {
+ BlueprintManager.blockBptProps[delegateTo].rotateLeft(newSlot, context);
+ } else {
+ super.rotateLeft(newSlot, context);
+ }
+ }
+
+}
diff --git a/common/buildcraft/api/bptblocks/BptBlockDirt.java b/common/buildcraft/api/bptblocks/BptBlockDirt.java
new file mode 100644
index 00000000..365cbc45
--- /dev/null
+++ b/common/buildcraft/api/bptblocks/BptBlockDirt.java
@@ -0,0 +1,42 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.bptblocks;
+
+import buildcraft.api.blueprints.BptBlock;
+import buildcraft.api.blueprints.BptSlotInfo;
+import buildcraft.api.blueprints.IBptContext;
+import java.util.LinkedList;
+import net.minecraft.block.Block;
+import net.minecraft.item.ItemStack;
+
+@Deprecated
+public class BptBlockDirt extends BptBlock {
+
+ public BptBlockDirt(int blockId) {
+ super(blockId);
+ }
+
+ @Override
+ public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) {
+ requirements.add(new ItemStack(Block.dirt));
+ }
+
+ @Override
+ public void buildBlock(BptSlotInfo slot, IBptContext context) {
+ context.world().setBlock(slot.x, slot.y, slot.z, Block.dirt.blockID, slot.meta,1);
+ }
+
+ @Override
+ public boolean isValid(BptSlotInfo slot, IBptContext context) {
+ int id = context.world().getBlockId(slot.x, slot.y, slot.z);
+
+ return id == Block.dirt.blockID || id == Block.grass.blockID || id == Block.tilledField.blockID;
+ }
+}
diff --git a/common/buildcraft/api/bptblocks/BptBlockDoor.java b/common/buildcraft/api/bptblocks/BptBlockDoor.java
new file mode 100644
index 00000000..196e83b3
--- /dev/null
+++ b/common/buildcraft/api/bptblocks/BptBlockDoor.java
@@ -0,0 +1,71 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.bptblocks;
+
+import buildcraft.api.blueprints.BptBlock;
+import buildcraft.api.blueprints.BptSlotInfo;
+import buildcraft.api.blueprints.IBptContext;
+import java.util.LinkedList;
+import net.minecraft.item.ItemStack;
+
+@Deprecated
+public class BptBlockDoor extends BptBlock {
+
+ final ItemStack stack;
+
+ public BptBlockDoor(int blockId, ItemStack stack) {
+ super(blockId);
+
+ this.stack = stack;
+ }
+
+ @Override
+ public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) {
+ if ((slot.meta & 8) == 0) {
+ requirements.add(stack.copy());
+ }
+ }
+
+ @Override
+ public void rotateLeft(BptSlotInfo slot, IBptContext context) {
+ int orientation = (slot.meta & 3);
+ int others = slot.meta - orientation;
+
+ switch (orientation) {
+ case 0:
+ slot.meta = 1 + others;
+ break;
+ case 1:
+ slot.meta = 2 + others;
+ break;
+ case 2:
+ slot.meta = 3 + others;
+ break;
+ case 3:
+ slot.meta = 0 + others;
+ break;
+ }
+ }
+
+ @Override
+ public boolean ignoreBuilding(BptSlotInfo slot) {
+ return (slot.meta & 8) != 0;
+ }
+
+ @Override
+ public void buildBlock(BptSlotInfo slot, IBptContext context) {
+ context.world().setBlock(slot.x, slot.y, slot.z, slot.blockId, slot.meta,1);
+ context.world().setBlock(slot.x, slot.y + 1, slot.z, slot.blockId, slot.meta + 8,1);
+
+ context.world().setBlockMetadataWithNotify(slot.x, slot.y + 1, slot.z, slot.meta + 8,1);
+ context.world().setBlockMetadataWithNotify(slot.x, slot.y, slot.z, slot.meta,1);
+
+ }
+}
diff --git a/common/buildcraft/api/bptblocks/BptBlockFluid.java b/common/buildcraft/api/bptblocks/BptBlockFluid.java
new file mode 100644
index 00000000..1769c394
--- /dev/null
+++ b/common/buildcraft/api/bptblocks/BptBlockFluid.java
@@ -0,0 +1,61 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.bptblocks;
+
+import buildcraft.api.blueprints.BptBlock;
+import buildcraft.api.blueprints.BptSlotInfo;
+import buildcraft.api.blueprints.IBptContext;
+import java.util.LinkedList;
+import net.minecraft.item.ItemStack;
+
+@Deprecated
+public class BptBlockFluid extends BptBlock {
+
+ private final ItemStack bucketStack;
+
+ public BptBlockFluid(int blockId, ItemStack bucketStack) {
+ super(blockId);
+
+ this.bucketStack = bucketStack;
+ }
+
+ @Override
+ public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) {
+ if (slot.meta == 0) {
+ requirements.add(bucketStack.copy());
+ }
+ }
+
+ @Override
+ public boolean isValid(BptSlotInfo slot, IBptContext context) {
+ if (slot.meta == 0)
+ return slot.blockId == context.world().getBlockId(slot.x, slot.y, slot.z) && context.world().getBlockMetadata(slot.x, slot.y, slot.z) == 0;
+ else
+ return true;
+ }
+
+ @Override
+ public void rotateLeft(BptSlotInfo slot, IBptContext context) {
+
+ }
+
+ @Override
+ public boolean ignoreBuilding(BptSlotInfo slot) {
+ return slot.meta != 0;
+ }
+
+ @Override
+ public void buildBlock(BptSlotInfo slot, IBptContext context) {
+ if (slot.meta == 0) {
+ context.world().setBlock(slot.x, slot.y, slot.z, slot.blockId, 0,1);
+ }
+ }
+
+}
diff --git a/common/buildcraft/api/bptblocks/BptBlockIgnore.java b/common/buildcraft/api/bptblocks/BptBlockIgnore.java
new file mode 100644
index 00000000..12a058bc
--- /dev/null
+++ b/common/buildcraft/api/bptblocks/BptBlockIgnore.java
@@ -0,0 +1,45 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.bptblocks;
+
+import buildcraft.api.blueprints.BptBlock;
+import buildcraft.api.blueprints.BptSlotInfo;
+import buildcraft.api.blueprints.IBptContext;
+import java.util.LinkedList;
+import net.minecraft.item.ItemStack;
+
+@Deprecated
+public class BptBlockIgnore extends BptBlock {
+
+ public BptBlockIgnore(int blockId) {
+ super(blockId);
+ }
+
+ @Override
+ public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) {
+ requirements.add(new ItemStack(slot.blockId, 0, 0));
+ }
+
+ @Override
+ public boolean isValid(BptSlotInfo slot, IBptContext context) {
+ return true;
+ }
+
+ @Override
+ public void rotateLeft(BptSlotInfo slot, IBptContext context) {
+
+ }
+
+ @Override
+ public boolean ignoreBuilding(BptSlotInfo slot) {
+ return true;
+ }
+
+}
diff --git a/common/buildcraft/api/bptblocks/BptBlockIgnoreMeta.java b/common/buildcraft/api/bptblocks/BptBlockIgnoreMeta.java
new file mode 100644
index 00000000..7f39f637
--- /dev/null
+++ b/common/buildcraft/api/bptblocks/BptBlockIgnoreMeta.java
@@ -0,0 +1,34 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.bptblocks;
+
+import buildcraft.api.blueprints.BptBlock;
+import buildcraft.api.blueprints.BptSlotInfo;
+import buildcraft.api.blueprints.IBptContext;
+import java.util.LinkedList;
+import net.minecraft.item.ItemStack;
+
+@Deprecated
+public class BptBlockIgnoreMeta extends BptBlock {
+
+ public BptBlockIgnoreMeta(int blockId) {
+ super(blockId);
+ }
+
+ @Override
+ public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) {
+ requirements.add(new ItemStack(slot.blockId, 1, 0));
+ }
+
+ @Override
+ public boolean isValid(BptSlotInfo slot, IBptContext context) {
+ return slot.blockId == context.world().getBlockId(slot.x, slot.y, slot.z);
+ }
+}
diff --git a/common/buildcraft/api/bptblocks/BptBlockInventory.java b/common/buildcraft/api/bptblocks/BptBlockInventory.java
new file mode 100644
index 00000000..0cebe58f
--- /dev/null
+++ b/common/buildcraft/api/bptblocks/BptBlockInventory.java
@@ -0,0 +1,28 @@
+package buildcraft.api.bptblocks;
+
+import buildcraft.api.blueprints.BptBlock;
+import buildcraft.api.blueprints.BptSlotInfo;
+import buildcraft.api.blueprints.IBptContext;
+import net.minecraft.inventory.IInventory;
+
+@Deprecated
+public class BptBlockInventory extends BptBlock {
+
+ public BptBlockInventory(int blockId) {
+ super(blockId);
+
+ }
+
+ @Override
+ public void buildBlock(BptSlotInfo slot, IBptContext context) {
+ super.buildBlock(slot, context);
+
+ IInventory inv = (IInventory) context.world().getBlockTileEntity(slot.x, slot.y, slot.z);
+
+ for (int i = 0; i < inv.getSizeInventory(); ++i) {
+ inv.setInventorySlotContents(i, null);
+ }
+
+ }
+
+}
diff --git a/common/buildcraft/api/bptblocks/BptBlockLever.java b/common/buildcraft/api/bptblocks/BptBlockLever.java
new file mode 100644
index 00000000..b9a8e1c4
--- /dev/null
+++ b/common/buildcraft/api/bptblocks/BptBlockLever.java
@@ -0,0 +1,38 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.bptblocks;
+
+import buildcraft.api.blueprints.BptSlotInfo;
+import buildcraft.api.blueprints.IBptContext;
+import java.util.LinkedList;
+import net.minecraft.item.ItemStack;
+
+@Deprecated
+public class BptBlockLever extends BptBlockWallSide {
+
+ public BptBlockLever(int blockId) {
+ super(blockId);
+ }
+
+ @Override
+ public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) {
+ requirements.add(new ItemStack(slot.blockId, 1, 0));
+ }
+
+ @Override
+ public void rotateLeft(BptSlotInfo slot, IBptContext context) {
+ int status = slot.meta - (slot.meta & 7);
+
+ slot.meta -= status;
+ super.rotateLeft(slot, context);
+ slot.meta += status;
+
+ }
+}
diff --git a/common/buildcraft/api/bptblocks/BptBlockPiston.java b/common/buildcraft/api/bptblocks/BptBlockPiston.java
new file mode 100644
index 00000000..b12693bd
--- /dev/null
+++ b/common/buildcraft/api/bptblocks/BptBlockPiston.java
@@ -0,0 +1,29 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.bptblocks;
+
+import buildcraft.api.blueprints.BptSlotInfo;
+import buildcraft.api.blueprints.IBptContext;
+
+@Deprecated
+public class BptBlockPiston extends BptBlockRotateMeta {
+
+ public BptBlockPiston(int blockId) {
+ super(blockId, new int[] { 2, 5, 3, 4 }, true);
+ }
+
+ @Override
+ public void buildBlock(BptSlotInfo slot, IBptContext context) {
+ int meta = slot.meta & 7;
+
+ context.world().setBlock(slot.x, slot.y, slot.z, slot.blockId, meta,1);
+ }
+
+}
diff --git a/common/buildcraft/api/bptblocks/BptBlockPumpkin.java b/common/buildcraft/api/bptblocks/BptBlockPumpkin.java
new file mode 100644
index 00000000..16049346
--- /dev/null
+++ b/common/buildcraft/api/bptblocks/BptBlockPumpkin.java
@@ -0,0 +1,53 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.bptblocks;
+
+import buildcraft.api.blueprints.BptBlock;
+import buildcraft.api.blueprints.BptSlotInfo;
+import buildcraft.api.blueprints.IBptContext;
+import java.util.LinkedList;
+import net.minecraft.item.ItemStack;
+
+@Deprecated
+public class BptBlockPumpkin extends BptBlock {
+
+ public BptBlockPumpkin(int blockId) {
+ super(blockId);
+ }
+
+ @Override
+ public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) {
+ requirements.add(new ItemStack(slot.blockId, 1, 0));
+ }
+
+ @Override
+ public boolean isValid(BptSlotInfo slot, IBptContext context) {
+ return slot.blockId == context.world().getBlockId(slot.x, slot.y, slot.z);
+ }
+
+ @Override
+ public void rotateLeft(BptSlotInfo slot, IBptContext context) {
+ switch (slot.meta) {
+ case 0:
+ slot.meta = 1;
+ break;
+ case 1:
+ slot.meta = 2;
+ break;
+ case 2:
+ slot.meta = 3;
+ break;
+ case 3:
+ slot.meta = 0;
+ break;
+ }
+ }
+
+}
diff --git a/common/buildcraft/api/bptblocks/BptBlockRedstoneRepeater.java b/common/buildcraft/api/bptblocks/BptBlockRedstoneRepeater.java
new file mode 100644
index 00000000..8ac4f023
--- /dev/null
+++ b/common/buildcraft/api/bptblocks/BptBlockRedstoneRepeater.java
@@ -0,0 +1,50 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.bptblocks;
+
+import buildcraft.api.blueprints.BptBlock;
+import buildcraft.api.blueprints.BptSlotInfo;
+import buildcraft.api.blueprints.IBptContext;
+import java.util.LinkedList;
+import net.minecraft.item.Item;
+import net.minecraft.item.ItemStack;
+
+@Deprecated
+public class BptBlockRedstoneRepeater extends BptBlock {
+
+ public BptBlockRedstoneRepeater(int blockId) {
+ super(blockId);
+ }
+
+ @Override
+ public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) {
+ requirements.add(new ItemStack(Item.redstoneRepeater));
+ }
+
+ @Override
+ public void rotateLeft(BptSlotInfo slot, IBptContext context) {
+ int step = slot.meta - (slot.meta & 3);
+
+ switch (slot.meta - step) {
+ case 0:
+ slot.meta = 1 + step;
+ break;
+ case 1:
+ slot.meta = 2 + step;
+ break;
+ case 2:
+ slot.meta = 3 + step;
+ break;
+ case 3:
+ slot.meta = 0 + step;
+ break;
+ }
+ }
+}
diff --git a/common/buildcraft/api/bptblocks/BptBlockRotateInventory.java b/common/buildcraft/api/bptblocks/BptBlockRotateInventory.java
new file mode 100644
index 00000000..6fcc30a8
--- /dev/null
+++ b/common/buildcraft/api/bptblocks/BptBlockRotateInventory.java
@@ -0,0 +1,27 @@
+package buildcraft.api.bptblocks;
+
+import buildcraft.api.blueprints.BptSlotInfo;
+import buildcraft.api.blueprints.IBptContext;
+import net.minecraft.inventory.IInventory;
+
+@Deprecated
+public class BptBlockRotateInventory extends BptBlockRotateMeta {
+
+ public BptBlockRotateInventory(int blockId, int[] rotations, boolean rotateForward) {
+ super(blockId, rotations, rotateForward);
+
+ }
+
+ @Override
+ public void buildBlock(BptSlotInfo slot, IBptContext context) {
+ super.buildBlock(slot, context);
+
+ IInventory inv = (IInventory) context.world().getBlockTileEntity(slot.x, slot.y, slot.z);
+
+ for (int i = 0; i < inv.getSizeInventory(); ++i) {
+ inv.setInventorySlotContents(i, null);
+ }
+
+ }
+
+}
diff --git a/common/buildcraft/api/bptblocks/BptBlockRotateMeta.java b/common/buildcraft/api/bptblocks/BptBlockRotateMeta.java
new file mode 100644
index 00000000..4352b660
--- /dev/null
+++ b/common/buildcraft/api/bptblocks/BptBlockRotateMeta.java
@@ -0,0 +1,84 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.bptblocks;
+
+import buildcraft.api.blueprints.BptBlock;
+import buildcraft.api.blueprints.BptSlotInfo;
+import buildcraft.api.blueprints.IBptContext;
+import java.util.LinkedList;
+import net.minecraft.item.ItemStack;
+
+@Deprecated
+public class BptBlockRotateMeta extends BptBlock {
+
+ int[] rot;
+ boolean rotateForward;
+
+ int infoMask = 0;
+
+ public BptBlockRotateMeta(int blockId, int[] rotations, boolean rotateForward) {
+ super(blockId);
+
+ rot = rotations;
+
+ for (int i = 0; i < rot.length; ++i) {
+ if (rot[i] < 4) {
+ infoMask = (infoMask < 3 ? 3 : infoMask);
+ } else if (rot[i] < 8) {
+ infoMask = (infoMask < 7 ? 7 : infoMask);
+ } else if (rot[i] < 16) {
+ infoMask = (infoMask < 15 ? 15 : infoMask);
+ }
+ }
+
+ this.rotateForward = rotateForward;
+ }
+
+ @Override
+ public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) {
+ requirements.add(new ItemStack(slot.blockId, 1, 0));
+ }
+
+ @Override
+ public boolean isValid(BptSlotInfo slot, IBptContext context) {
+ return slot.blockId == context.world().getBlockId(slot.x, slot.y, slot.z);
+ }
+
+ @Override
+ public void rotateLeft(BptSlotInfo slot, IBptContext context) {
+ int pos = slot.meta & infoMask;
+ int others = slot.meta - pos;
+
+ if (rotateForward) {
+ if (pos == rot[0]) {
+ pos = rot[1];
+ } else if (pos == rot[1]) {
+ pos = rot[2];
+ } else if (pos == rot[2]) {
+ pos = rot[3];
+ } else if (pos == rot[3]) {
+ pos = rot[0];
+ }
+ } else {
+ if (pos == rot[0]) {
+ pos = rot[3];
+ } else if (pos == rot[1]) {
+ pos = rot[2];
+ } else if (pos == rot[2]) {
+ pos = rot[0];
+ } else if (pos == rot[3]) {
+ pos = rot[1];
+ }
+ }
+
+ slot.meta = pos + others;
+ }
+
+}
diff --git a/common/buildcraft/api/bptblocks/BptBlockSign.java b/common/buildcraft/api/bptblocks/BptBlockSign.java
new file mode 100644
index 00000000..f7bd1338
--- /dev/null
+++ b/common/buildcraft/api/bptblocks/BptBlockSign.java
@@ -0,0 +1,64 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.bptblocks;
+
+import buildcraft.api.blueprints.BlockSignature;
+import buildcraft.api.blueprints.BptBlock;
+import buildcraft.api.blueprints.BptSlotInfo;
+import buildcraft.api.blueprints.IBptContext;
+import java.util.LinkedList;
+import net.minecraft.block.Block;
+import net.minecraft.item.Item;
+import net.minecraft.item.ItemStack;
+
+@Deprecated
+public class BptBlockSign extends BptBlock {
+
+ boolean isWall;
+
+ public BptBlockSign(int blockId, boolean isWall) {
+ super(blockId);
+
+ this.isWall = isWall;
+ }
+
+ @Override
+ public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) {
+ requirements.add(new ItemStack(Item.sign));
+ }
+
+ @Override
+ public void rotateLeft(BptSlotInfo slot, IBptContext context) {
+ if (!isWall) {
+ double angle = ((slot.meta) * 360.0) / 16.0;
+ angle += 90.0;
+ if (angle >= 360) {
+ angle -= 360;
+ }
+ slot.meta = (int) (angle / 360.0 * 16.0);
+ } else {
+ // slot.meta = ForgeDirection.values()[slot.meta].rotateLeft().ordinal();
+ }
+ }
+
+ @Override
+ public BlockSignature getSignature(Block block) {
+ BlockSignature sig = super.getSignature(block);
+
+ if (isWall) {
+ sig.customField = "wall";
+ } else {
+ sig.customField = "floor";
+ }
+
+ return sig;
+ }
+
+}
diff --git a/common/buildcraft/api/bptblocks/BptBlockStairs.java b/common/buildcraft/api/bptblocks/BptBlockStairs.java
new file mode 100644
index 00000000..4dc061a4
--- /dev/null
+++ b/common/buildcraft/api/bptblocks/BptBlockStairs.java
@@ -0,0 +1,53 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.bptblocks;
+
+import buildcraft.api.blueprints.BptBlock;
+import buildcraft.api.blueprints.BptSlotInfo;
+import buildcraft.api.blueprints.IBptContext;
+import java.util.LinkedList;
+import net.minecraft.item.ItemStack;
+
+@Deprecated
+public class BptBlockStairs extends BptBlock {
+
+ public BptBlockStairs(int blockId) {
+ super(blockId);
+ }
+
+ @Override
+ public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) {
+ requirements.add(new ItemStack(slot.blockId, 1, 0));
+ }
+
+ @Override
+ public boolean isValid(BptSlotInfo slot, IBptContext context) {
+ return slot.blockId == context.world().getBlockId(slot.x, slot.y, slot.z);
+ }
+
+ @Override
+ public void rotateLeft(BptSlotInfo slot, IBptContext context) {
+ switch (slot.meta) {
+ case 0:
+ slot.meta = 2;
+ break;
+ case 1:
+ slot.meta = 3;
+ break;
+ case 2:
+ slot.meta = 1;
+ break;
+ case 3:
+ slot.meta = 0;
+ break;
+ }
+ }
+
+}
diff --git a/common/buildcraft/api/bptblocks/BptBlockWallSide.java b/common/buildcraft/api/bptblocks/BptBlockWallSide.java
new file mode 100644
index 00000000..74ff3f0f
--- /dev/null
+++ b/common/buildcraft/api/bptblocks/BptBlockWallSide.java
@@ -0,0 +1,52 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.bptblocks;
+
+import buildcraft.api.blueprints.BptBlock;
+import buildcraft.api.blueprints.BptSlotInfo;
+import buildcraft.api.blueprints.IBptContext;
+import java.util.LinkedList;
+import net.minecraft.item.ItemStack;
+
+@Deprecated
+public class BptBlockWallSide extends BptBlock {
+
+ public BptBlockWallSide(int blockId) {
+ super(blockId);
+ }
+
+ @Override
+ public void addRequirements(BptSlotInfo slot, IBptContext context, LinkedList requirements) {
+ requirements.add(new ItemStack(slot.blockId, 1, 0));
+ }
+
+ @Override
+ public void rotateLeft(BptSlotInfo slot, IBptContext context) {
+ final int XPos = 2;
+ final int XNeg = 1;
+ final int ZPos = 4;
+ final int ZNeg = 3;
+
+ switch (slot.meta) {
+ case XPos:
+ slot.meta = ZPos;
+ break;
+ case ZNeg:
+ slot.meta = XPos;
+ break;
+ case XNeg:
+ slot.meta = ZNeg;
+ break;
+ case ZPos:
+ slot.meta = XNeg;
+ break;
+ }
+ }
+}
diff --git a/common/buildcraft/api/core/BuildCraftAPI.java b/common/buildcraft/api/core/BuildCraftAPI.java
new file mode 100644
index 00000000..87c45fdf
--- /dev/null
+++ b/common/buildcraft/api/core/BuildCraftAPI.java
@@ -0,0 +1,20 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.core;
+
+import net.minecraft.block.Block;
+
+public class BuildCraftAPI {
+
+ public static final int LAST_ORIGINAL_BLOCK = 122;
+ public static final int LAST_ORIGINAL_ITEM = 126;
+
+ public static final boolean[] softBlocks = new boolean[Block.blocksList.length];
+}
diff --git a/common/buildcraft/api/core/IAreaProvider.java b/common/buildcraft/api/core/IAreaProvider.java
new file mode 100644
index 00000000..fa905d2c
--- /dev/null
+++ b/common/buildcraft/api/core/IAreaProvider.java
@@ -0,0 +1,34 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.core;
+
+/**
+ * To be implemented by TileEntities able to provide a square area on the world, typically BuildCraft markers.
+ */
+public interface IAreaProvider {
+
+ public int xMin();
+
+ public int yMin();
+
+ public int zMin();
+
+ public int xMax();
+
+ public int yMax();
+
+ public int zMax();
+
+ /**
+ * Remove from the world all objects used to define the area.
+ */
+ public void removeFromWorld();
+
+}
diff --git a/common/buildcraft/api/core/IBox.java b/common/buildcraft/api/core/IBox.java
new file mode 100644
index 00000000..6337a96c
--- /dev/null
+++ b/common/buildcraft/api/core/IBox.java
@@ -0,0 +1,30 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.core;
+
+import net.minecraft.world.World;
+
+public interface IBox {
+
+ public void expand(int amount);
+
+ public void contract(int amount);
+
+ public boolean contains(int x, int y, int z);
+
+ public Position pMin();
+
+ public Position pMax();
+
+ public void createLasers(World world, LaserKind kind);
+
+ public void deleteLasers();
+
+}
diff --git a/common/buildcraft/api/core/IIconProvider.java b/common/buildcraft/api/core/IIconProvider.java
new file mode 100644
index 00000000..666d32e3
--- /dev/null
+++ b/common/buildcraft/api/core/IIconProvider.java
@@ -0,0 +1,24 @@
+package buildcraft.api.core;
+
+import cpw.mods.fml.relauncher.Side;
+import cpw.mods.fml.relauncher.SideOnly;
+import net.minecraft.client.renderer.texture.IconRegister;
+import net.minecraft.util.Icon;
+
+public interface IIconProvider {
+
+ /**
+ * @param iconIndex
+ * @return
+ */
+ @SideOnly(Side.CLIENT)
+ public Icon getIcon(int iconIndex);
+
+ /**
+ * A call for the provider to register its Icons. This may be called multiple times but should only be executed once per provider
+ * @param iconRegister
+ */
+ @SideOnly(Side.CLIENT)
+ public void registerIcons(IconRegister iconRegister);
+
+}
diff --git a/common/buildcraft/api/core/LaserKind.java b/common/buildcraft/api/core/LaserKind.java
new file mode 100644
index 00000000..24e66dba
--- /dev/null
+++ b/common/buildcraft/api/core/LaserKind.java
@@ -0,0 +1,14 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.core;
+
+public enum LaserKind {
+ Red, Blue, Stripes
+}
diff --git a/common/buildcraft/api/core/Position.java b/common/buildcraft/api/core/Position.java
new file mode 100644
index 00000000..5cdddbc8
--- /dev/null
+++ b/common/buildcraft/api/core/Position.java
@@ -0,0 +1,142 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.core;
+
+import net.minecraft.nbt.NBTTagCompound;
+import net.minecraft.tileentity.TileEntity;
+import net.minecraftforge.common.ForgeDirection;
+
+public class Position {
+
+ public double x, y, z;
+ public ForgeDirection orientation;
+
+ public Position(double ci, double cj, double ck) {
+ x = ci;
+ y = cj;
+ z = ck;
+ orientation = ForgeDirection.UNKNOWN;
+ }
+
+ public Position(double ci, double cj, double ck, ForgeDirection corientation) {
+ x = ci;
+ y = cj;
+ z = ck;
+ orientation = corientation;
+ }
+
+ public Position(Position p) {
+ x = p.x;
+ y = p.y;
+ z = p.z;
+ orientation = p.orientation;
+ }
+
+ public Position(NBTTagCompound nbttagcompound) {
+ x = nbttagcompound.getDouble("i");
+ y = nbttagcompound.getDouble("j");
+ z = nbttagcompound.getDouble("k");
+
+ orientation = ForgeDirection.UNKNOWN;
+ }
+
+ public Position(TileEntity tile) {
+ x = tile.xCoord;
+ y = tile.yCoord;
+ z = tile.zCoord;
+ }
+
+ public void moveRight(double step) {
+ switch (orientation) {
+ case SOUTH:
+ x = x - step;
+ break;
+ case NORTH:
+ x = x + step;
+ break;
+ case EAST:
+ z = z + step;
+ break;
+ case WEST:
+ z = z - step;
+ break;
+ default:
+ }
+ }
+
+ public void moveLeft(double step) {
+ moveRight(-step);
+ }
+
+ public void moveForwards(double step) {
+ switch (orientation) {
+ case UP:
+ y = y + step;
+ break;
+ case DOWN:
+ y = y - step;
+ break;
+ case SOUTH:
+ z = z + step;
+ break;
+ case NORTH:
+ z = z - step;
+ break;
+ case EAST:
+ x = x + step;
+ break;
+ case WEST:
+ x = x - step;
+ break;
+ default:
+ }
+ }
+
+ public void moveBackwards(double step) {
+ moveForwards(-step);
+ }
+
+ public void moveUp(double step) {
+ switch (orientation) {
+ case SOUTH:
+ case NORTH:
+ case EAST:
+ case WEST:
+ y = y + step;
+ break;
+ default:
+ }
+
+ }
+
+ public void moveDown(double step) {
+ moveUp(-step);
+ }
+
+ public void writeToNBT(NBTTagCompound nbttagcompound) {
+ nbttagcompound.setDouble("i", x);
+ nbttagcompound.setDouble("j", y);
+ nbttagcompound.setDouble("k", z);
+ }
+
+ @Override
+ public String toString() {
+ return "{" + x + ", " + y + ", " + z + "}";
+ }
+
+ public Position min(Position p) {
+ return new Position(p.x > x ? x : p.x, p.y > y ? y : p.y, p.z > z ? z : p.z);
+ }
+
+ public Position max(Position p) {
+ return new Position(p.x < x ? x : p.x, p.y < y ? y : p.y, p.z < z ? z : p.z);
+ }
+
+}
diff --git a/common/buildcraft/api/core/SafeTimeTracker.java b/common/buildcraft/api/core/SafeTimeTracker.java
new file mode 100644
index 00000000..44e1531e
--- /dev/null
+++ b/common/buildcraft/api/core/SafeTimeTracker.java
@@ -0,0 +1,46 @@
+/**
+ * Copyright (c) SpaceToad, 2011 http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public License
+ * 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+package buildcraft.api.core;
+
+import net.minecraft.world.World;
+
+public class SafeTimeTracker {
+
+ private long lastMark = Long.MIN_VALUE;
+ private long duration = -1;
+
+ /**
+ * Return true if a given delay has passed since last time marked was called
+ * successfully.
+ */
+ public boolean markTimeIfDelay(World world, long delay) {
+ if (world == null)
+ return false;
+
+ long currentTime = world.getTotalWorldTime();
+
+ if (currentTime < lastMark) {
+ lastMark = currentTime;
+ return false;
+ } else if (lastMark + delay <= currentTime) {
+ duration = currentTime - lastMark;
+ lastMark = currentTime;
+ return true;
+ } else
+ return false;
+
+ }
+
+ public long durationOfLastDelay() {
+ return duration > 0 ? duration : 0;
+ }
+
+ public void markTime(World world) {
+ lastMark = world.getTotalWorldTime();
+ }
+}
diff --git a/common/buildcraft/api/core/StackWrapper.java b/common/buildcraft/api/core/StackWrapper.java
new file mode 100644
index 00000000..f46652c4
--- /dev/null
+++ b/common/buildcraft/api/core/StackWrapper.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) SpaceToad, 2011-2012
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+package buildcraft.api.core;
+
+import net.minecraft.item.ItemStack;
+
+/**
+ *
+ * @author CovertJaguar
+ */
+public class StackWrapper {
+
+ public final ItemStack stack;
+
+ public StackWrapper(ItemStack stack) {
+ this.stack = stack;
+ }
+
+ @Override
+ public int hashCode() {
+ int hash = 5;
+ hash = 67 * hash + stack.itemID;
+ hash = 67 * hash + stack.getItemDamage();
+ if (stack.stackTagCompound != null)
+ hash = 67 * hash + stack.stackTagCompound.hashCode();
+ return hash;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ final StackWrapper other = (StackWrapper) obj;
+ if (stack.itemID != other.stack.itemID)
+ return false;
+ if (stack.getHasSubtypes() && stack.getItemDamage() != other.stack.getItemDamage())
+ return false;
+ if (stack.stackTagCompound != null && !stack.stackTagCompound.equals(other.stack.stackTagCompound))
+ return false;
+ return true;
+ }
+}
diff --git a/common/buildcraft/api/filler/FillerManager.java b/common/buildcraft/api/filler/FillerManager.java
new file mode 100644
index 00000000..ae104c59
--- /dev/null
+++ b/common/buildcraft/api/filler/FillerManager.java
@@ -0,0 +1,7 @@
+package buildcraft.api.filler;
+
+public class FillerManager {
+
+ public static IFillerRegistry registry;
+
+}
diff --git a/common/buildcraft/api/filler/IFillerPattern.java b/common/buildcraft/api/filler/IFillerPattern.java
new file mode 100644
index 00000000..dd5862bb
--- /dev/null
+++ b/common/buildcraft/api/filler/IFillerPattern.java
@@ -0,0 +1,23 @@
+package buildcraft.api.filler;
+
+import buildcraft.api.core.IBox;
+import cpw.mods.fml.relauncher.Side;
+import cpw.mods.fml.relauncher.SideOnly;
+import net.minecraft.item.ItemStack;
+import net.minecraft.tileentity.TileEntity;
+import net.minecraft.util.Icon;
+
+public interface IFillerPattern {
+
+ public int getId();
+
+ public void setId(int id);
+
+ public boolean iteratePattern(TileEntity tile, IBox box, ItemStack stackToPlace);
+
+ @SideOnly(Side.CLIENT)
+ public Icon getTexture();
+
+ public String getName();
+
+}
diff --git a/common/buildcraft/api/filler/IFillerRegistry.java b/common/buildcraft/api/filler/IFillerRegistry.java
new file mode 100644
index 00000000..12bf9799
--- /dev/null
+++ b/common/buildcraft/api/filler/IFillerRegistry.java
@@ -0,0 +1,15 @@
+package buildcraft.api.filler;
+
+import net.minecraft.inventory.IInventory;
+
+public interface IFillerRegistry {
+
+ public void addRecipe(IFillerPattern pattern, Object aobj[]);
+
+ public IFillerPattern findMatchingRecipe(IInventory inventorycrafting);
+
+ public int getPatternNumber(IFillerPattern pattern);
+
+ public IFillerPattern getPattern(int n);
+
+}
diff --git a/common/buildcraft/api/fuels/IronEngineCoolant.java b/common/buildcraft/api/fuels/IronEngineCoolant.java
new file mode 100644
index 00000000..347fabd7
--- /dev/null
+++ b/common/buildcraft/api/fuels/IronEngineCoolant.java
@@ -0,0 +1,83 @@
+/**
+ * Copyright (c) SpaceToad, 2011 http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public License
+ * 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+package buildcraft.api.fuels;
+
+import buildcraft.api.core.StackWrapper;
+import java.util.HashMap;
+import java.util.Map;
+import net.minecraft.item.Item;
+import net.minecraft.item.ItemStack;
+import net.minecraftforge.fluids.Fluid;
+import net.minecraftforge.fluids.FluidStack;
+
+public final class IronEngineCoolant {
+
+ public static Map liquidCoolants = new HashMap();
+ public static Map solidCoolants = new HashMap();
+
+ public static FluidStack getFluidCoolant(ItemStack stack) {
+ return solidCoolants.get(new StackWrapper(stack));
+ }
+
+ public static Coolant getCoolant(ItemStack stack) {
+ return getCoolant(getFluidCoolant(stack));
+ }
+
+ public static Coolant getCoolant(FluidStack fluidStack) {
+ return fluidStack != null ? liquidCoolants.get(fluidStack.getFluid().getName()) : null;
+ }
+
+ private IronEngineCoolant() {
+ }
+
+ public static interface Coolant {
+
+ float getDegreesCoolingPerMB(float currentHeat);
+ }
+
+ public static void addCoolant(final Fluid fluid, final float degreesCoolingPerMB) {
+ if (fluid != null) {
+ liquidCoolants.put(fluid.getName(), new Coolant() {
+ @Override
+ public float getDegreesCoolingPerMB(float currentHeat) {
+ return degreesCoolingPerMB;
+ }
+ });
+ }
+ }
+
+ /**
+ * Adds a solid coolant like Ice Blocks. The FluidStack must contain a registered
+ * Coolant Fluid or nothing will happen. You do not need to call this for
+ * Fluid Containers.
+ *
+ * @param stack
+ * @param coolant
+ */
+ public static void addCoolant(final ItemStack stack, final FluidStack coolant) {
+ if (stack != null && Item.itemsList[stack.itemID] != null && coolant != null) {
+ solidCoolants.put(new StackWrapper(stack), coolant);
+ }
+ }
+
+ /**
+ * Adds a solid coolant like Ice Blocks. The FluidStack must contain a registered
+ * Coolant Fluid or nothing will happen. You do not need to call this for
+ * Fluid Containers.
+ *
+ * @param stack
+ * @param coolant
+ */
+ public static void addCoolant(final int itemId, final int metadata, final FluidStack coolant) {
+ addCoolant(new ItemStack(itemId, 1, metadata), coolant);
+ }
+
+ public static boolean isCoolant(Fluid fluid) {
+ return liquidCoolants.containsKey(fluid.getName());
+ }
+}
diff --git a/common/buildcraft/api/fuels/IronEngineFuel.java b/common/buildcraft/api/fuels/IronEngineFuel.java
new file mode 100644
index 00000000..3ab5ca2a
--- /dev/null
+++ b/common/buildcraft/api/fuels/IronEngineFuel.java
@@ -0,0 +1,50 @@
+/**
+ * Copyright (c) SpaceToad, 2011 http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public License
+ * 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+package buildcraft.api.fuels;
+
+import java.util.HashMap;
+import java.util.Map;
+import net.minecraftforge.fluids.Fluid;
+import net.minecraftforge.fluids.FluidRegistry;
+
+public class IronEngineFuel {
+
+ public static Map fuels = new HashMap();
+
+ public static Fuel getFuelForFluid(Fluid liquid) {
+ return liquid == null ? null : fuels.get(liquid.getName());
+ }
+
+ private IronEngineFuel() {
+ }
+
+ public static class Fuel {
+
+ public final Fluid liquid;
+ public final float powerPerCycle;
+ public final int totalBurningTime;
+
+ private Fuel(String fluidName, float powerPerCycle, int totalBurningTime) {
+ this(FluidRegistry.getFluid(fluidName), powerPerCycle, totalBurningTime);
+ }
+
+ private Fuel(Fluid liquid, float powerPerCycle, int totalBurningTime) {
+ this.liquid = liquid;
+ this.powerPerCycle = powerPerCycle;
+ this.totalBurningTime = totalBurningTime;
+ }
+ }
+
+ public static void addFuel(Fluid fluid, float powerPerCycle, int totalBurningTime) {
+ fuels.put(fluid.getName(), new Fuel(fluid, powerPerCycle, totalBurningTime));
+ }
+
+ public static void addFuel(String fluidName, float powerPerCycle, int totalBurningTime) {
+ fuels.put(fluidName, new Fuel(fluidName, powerPerCycle, totalBurningTime));
+ }
+}
diff --git a/common/buildcraft/api/gates/ActionManager.java b/common/buildcraft/api/gates/ActionManager.java
new file mode 100644
index 00000000..26cfd2c7
--- /dev/null
+++ b/common/buildcraft/api/gates/ActionManager.java
@@ -0,0 +1,106 @@
+package buildcraft.api.gates;
+
+import buildcraft.api.transport.IPipe;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.Map;
+import net.minecraft.block.Block;
+import net.minecraft.tileentity.TileEntity;
+
+public class ActionManager {
+
+ public static Map triggers = new HashMap();
+ public static Map actions = new HashMap();
+ private static LinkedList triggerProviders = new LinkedList();
+ private static LinkedList actionProviders = new LinkedList();
+
+ public static void registerTriggerProvider(ITriggerProvider provider) {
+ if (provider != null && !triggerProviders.contains(provider)) {
+ triggerProviders.add(provider);
+ }
+ }
+
+ public static void registerTrigger(ITrigger trigger){
+ triggers.put(trigger.getUniqueTag(), trigger);
+ }
+
+ public static void registerAction(IAction action){
+ actions.put(action.getUniqueTag(), action);
+ }
+
+ public static LinkedList getNeighborTriggers(Block block, TileEntity entity) {
+ LinkedList triggers = new LinkedList();
+
+ for (ITriggerProvider provider : triggerProviders) {
+ LinkedList toAdd = provider.getNeighborTriggers(block, entity);
+
+ if (toAdd != null) {
+ for (ITrigger t : toAdd) {
+ if (!triggers.contains(t)) {
+ triggers.add(t);
+ }
+ }
+ }
+ }
+
+ return triggers;
+ }
+
+ public static void registerActionProvider(IActionProvider provider) {
+ if (provider != null && !actionProviders.contains(provider)) {
+ actionProviders.add(provider);
+ }
+ }
+
+ public static LinkedList getNeighborActions(Block block, TileEntity entity) {
+ LinkedList actions = new LinkedList();
+
+ for (IActionProvider provider : actionProviders) {
+ LinkedList toAdd = provider.getNeighborActions(block, entity);
+
+ if (toAdd != null) {
+ for (IAction t : toAdd) {
+ if (!actions.contains(t)) {
+ actions.add(t);
+ }
+ }
+ }
+ }
+
+ return actions;
+ }
+
+ public static LinkedList getPipeTriggers(IPipe pipe) {
+ LinkedList triggers = new LinkedList();
+
+ for (ITriggerProvider provider : triggerProviders) {
+ LinkedList toAdd = provider.getPipeTriggers(pipe);
+
+ if (toAdd != null) {
+ for (ITrigger t : toAdd) {
+ if (!triggers.contains(t)) {
+ triggers.add(t);
+ }
+ }
+ }
+ }
+
+ return triggers;
+ }
+
+ public static ITrigger getTriggerFromLegacyId(int legacyId){
+ for(ITrigger trigger : triggers.values()){
+ if(trigger.getLegacyId() == legacyId)
+ return trigger;
+ }
+ return null;
+ }
+
+ public static IAction getActionFromLegacyId(int legacyId){
+ for(IAction action : actions.values()){
+ if(action.getLegacyId() == legacyId)
+ return action;
+ }
+ return null;
+ }
+}
diff --git a/common/buildcraft/api/gates/IAction.java b/common/buildcraft/api/gates/IAction.java
new file mode 100644
index 00000000..90547d58
--- /dev/null
+++ b/common/buildcraft/api/gates/IAction.java
@@ -0,0 +1,27 @@
+package buildcraft.api.gates;
+
+import cpw.mods.fml.relauncher.Side;
+import cpw.mods.fml.relauncher.SideOnly;
+import net.minecraft.client.renderer.texture.IconRegister;
+import net.minecraft.util.Icon;
+
+public interface IAction {
+
+ /**
+ * Return your ID from the old API here, this is only used to convert old
+ * saves to the new format.
+ */
+ int getLegacyId();
+
+ String getUniqueTag();
+
+ @SideOnly(Side.CLIENT)
+ Icon getIcon();
+
+ @SideOnly(Side.CLIENT)
+ void registerIcons(IconRegister iconRegister);
+
+ boolean hasParameter();
+
+ String getDescription();
+}
diff --git a/common/buildcraft/api/gates/IActionProvider.java b/common/buildcraft/api/gates/IActionProvider.java
new file mode 100644
index 00000000..6c64b57e
--- /dev/null
+++ b/common/buildcraft/api/gates/IActionProvider.java
@@ -0,0 +1,23 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.gates;
+
+import java.util.LinkedList;
+import net.minecraft.block.Block;
+import net.minecraft.tileentity.TileEntity;
+
+public interface IActionProvider {
+
+ /**
+ * Returns the list of actions available to a gate next to the given block.
+ */
+ public abstract LinkedList getNeighborActions(Block block, TileEntity tile);
+
+}
diff --git a/common/buildcraft/api/gates/IActionReceptor.java b/common/buildcraft/api/gates/IActionReceptor.java
new file mode 100644
index 00000000..c4637adc
--- /dev/null
+++ b/common/buildcraft/api/gates/IActionReceptor.java
@@ -0,0 +1,16 @@
+/**
+ * Copyright (c) SpaceToad, 2012
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.gates;
+
+public interface IActionReceptor {
+
+ public void actionActivated(IAction action);
+
+}
diff --git a/common/buildcraft/api/gates/IOverrideDefaultTriggers.java b/common/buildcraft/api/gates/IOverrideDefaultTriggers.java
new file mode 100644
index 00000000..8a2e47c6
--- /dev/null
+++ b/common/buildcraft/api/gates/IOverrideDefaultTriggers.java
@@ -0,0 +1,21 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.gates;
+
+import java.util.LinkedList;
+
+/**
+ * This interface has to be implemented by a TileEntity or a Pipe that wants to provide triggers different from the ones installed by default with BuildCraft.
+ */
+public interface IOverrideDefaultTriggers {
+
+ LinkedList getTriggers();
+
+}
diff --git a/common/buildcraft/api/gates/ITrigger.java b/common/buildcraft/api/gates/ITrigger.java
new file mode 100644
index 00000000..ab59616b
--- /dev/null
+++ b/common/buildcraft/api/gates/ITrigger.java
@@ -0,0 +1,47 @@
+package buildcraft.api.gates;
+
+import cpw.mods.fml.relauncher.Side;
+import cpw.mods.fml.relauncher.SideOnly;
+import net.minecraft.client.renderer.texture.IconRegister;
+import net.minecraft.tileentity.TileEntity;
+import net.minecraft.util.Icon;
+import net.minecraftforge.common.ForgeDirection;
+
+public interface ITrigger {
+
+ /**
+ * Return your ID from the old API here, this is only used to convert old
+ * saves to the new format.
+ */
+ int getLegacyId();
+
+ String getUniqueTag();
+
+ @SideOnly(Side.CLIENT)
+ Icon getIcon();
+
+ @SideOnly(Side.CLIENT)
+ void registerIcons(IconRegister iconRegister);
+
+ /**
+ * Return true if this trigger can accept parameters
+ */
+ boolean hasParameter();
+
+ /**
+ * Return the trigger description in the UI
+ */
+ String getDescription();
+
+ /**
+ * Return true if the tile given in parameter activates the trigger, given
+ * the parameters.
+ */
+ boolean isTriggerActive(ForgeDirection side, TileEntity tile, ITriggerParameter parameter);
+
+ /**
+ * Create parameters for the trigger. As for now, there is only one kind of
+ * trigger parameter available so this subprogram is final.
+ */
+ ITriggerParameter createParameter();
+}
diff --git a/common/buildcraft/api/gates/ITriggerParameter.java b/common/buildcraft/api/gates/ITriggerParameter.java
new file mode 100644
index 00000000..cef436a6
--- /dev/null
+++ b/common/buildcraft/api/gates/ITriggerParameter.java
@@ -0,0 +1,18 @@
+package buildcraft.api.gates;
+
+import net.minecraft.item.ItemStack;
+import net.minecraft.nbt.NBTTagCompound;
+
+public interface ITriggerParameter {
+
+ public abstract ItemStack getItemStack();
+
+ public abstract void set(ItemStack stack);
+
+ public abstract void writeToNBT(NBTTagCompound compound);
+
+ public abstract void readFromNBT(NBTTagCompound compound);
+
+ public abstract ItemStack getItem();
+
+}
diff --git a/common/buildcraft/api/gates/ITriggerProvider.java b/common/buildcraft/api/gates/ITriggerProvider.java
new file mode 100644
index 00000000..fe2271e0
--- /dev/null
+++ b/common/buildcraft/api/gates/ITriggerProvider.java
@@ -0,0 +1,29 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.gates;
+
+import buildcraft.api.transport.IPipe;
+import java.util.LinkedList;
+import net.minecraft.block.Block;
+import net.minecraft.tileentity.TileEntity;
+
+public interface ITriggerProvider {
+
+ /**
+ * Returns the list of triggers that are available from the pipe holding the gate.
+ */
+ public abstract LinkedList getPipeTriggers(IPipe pipe);
+
+ /**
+ * Returns the list of triggers available to a gate next to the given block.
+ */
+ public abstract LinkedList getNeighborTriggers(Block block, TileEntity tile);
+
+}
diff --git a/common/buildcraft/api/gates/TriggerParameter.java b/common/buildcraft/api/gates/TriggerParameter.java
new file mode 100644
index 00000000..c76ce99a
--- /dev/null
+++ b/common/buildcraft/api/gates/TriggerParameter.java
@@ -0,0 +1,79 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.gates;
+
+import net.minecraft.item.ItemStack;
+import net.minecraft.nbt.NBTTagCompound;
+
+public class TriggerParameter implements ITriggerParameter {
+
+ protected ItemStack stack;
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see net.minecraft.src.buildcraft.api.gates.ITriggerParameter#getItemStack()
+ */
+ @Override
+ public ItemStack getItemStack() {
+ return stack;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see net.minecraft.src.buildcraft.api.gates.ITriggerParameter#set(net.minecraft.src.ItemStack)
+ */
+ @Override
+ public void set(ItemStack stack) {
+ if (stack != null) {
+ this.stack = stack.copy();
+ this.stack.stackSize = 1;
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see net.minecraft.src.buildcraft.api.gates.ITriggerParameter#writeToNBT(net.minecraft.src.NBTTagCompound)
+ */
+ @Override
+ public void writeToNBT(NBTTagCompound compound) {
+ if (stack != null) {
+ compound.setInteger("itemID", stack.itemID);
+ compound.setInteger("itemDMG", stack.getItemDamage());
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see net.minecraft.src.buildcraft.api.gates.ITriggerParameter#readFromNBT(net.minecraft.src.NBTTagCompound)
+ */
+ @Override
+ public void readFromNBT(NBTTagCompound compound) {
+ int itemID = compound.getInteger("itemID");
+
+ if (itemID != 0) {
+ stack = new ItemStack(itemID, 1, compound.getInteger("itemDMG"));
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see net.minecraft.src.buildcraft.api.gates.ITriggerParameter#getItem()
+ */
+ @Override
+ public ItemStack getItem() {
+ return stack;
+ }
+
+}
diff --git a/common/buildcraft/api/inventory/ISecuredInventory.java b/common/buildcraft/api/inventory/ISecuredInventory.java
new file mode 100644
index 00000000..6ebb99b6
--- /dev/null
+++ b/common/buildcraft/api/inventory/ISecuredInventory.java
@@ -0,0 +1,23 @@
+package buildcraft.api.inventory;
+
+import net.minecraftforge.common.ForgeDirection;
+
+public interface ISecuredInventory {
+
+ /**
+ * @param name
+ * @return true if the user/player with the given name has access permissions on this machine.
+ */
+ boolean canAccess(String name);
+
+ /**
+ * Informs the inventory with whose permissions the next item or liquid transaction will be performed. It is up to the inventory to determine the effect.
+ *
+ * @param orientation
+ * Orientation the transaction will be performed from.
+ * @param name
+ * Name of the user/player who owns the transaction.
+ */
+ void prepareTransaction(ForgeDirection orientation, String name);
+
+}
diff --git a/common/buildcraft/api/inventory/ISelectiveInventory.java b/common/buildcraft/api/inventory/ISelectiveInventory.java
new file mode 100644
index 00000000..0e4d7045
--- /dev/null
+++ b/common/buildcraft/api/inventory/ISelectiveInventory.java
@@ -0,0 +1,23 @@
+package buildcraft.api.inventory;
+
+import net.minecraft.item.ItemStack;
+import net.minecraftforge.common.ForgeDirection;
+
+public interface ISelectiveInventory extends ISpecialInventory {
+ /**
+ * Requests specified items to be extracted from the inventory
+ *
+ * @param desired
+ * Array which can contain ItemStacks, Items, or classes describing the type of item accepted or excluded.
+ * @param exclusion
+ * If true desired items are not eligible for returning.
+ * @param doRemove
+ * If false no actual extraction may occur.
+ * @param from
+ * Orientation the ItemStack is requested from.
+ * @param maxItemCount
+ * Maximum amount of items to extract (spread over all returned item stacks)
+ * @return Array of item stacks extracted from the inventory
+ */
+ ItemStack[] extractItem(Object[] desired, boolean exclusion, boolean doRemove, ForgeDirection from, int maxItemCount);
+}
diff --git a/common/buildcraft/api/inventory/ISpecialInventory.java b/common/buildcraft/api/inventory/ISpecialInventory.java
new file mode 100644
index 00000000..27b735d4
--- /dev/null
+++ b/common/buildcraft/api/inventory/ISpecialInventory.java
@@ -0,0 +1,36 @@
+package buildcraft.api.inventory;
+
+import net.minecraft.inventory.IInventory;
+import net.minecraft.item.ItemStack;
+import net.minecraftforge.common.ForgeDirection;
+
+public interface ISpecialInventory extends IInventory {
+
+ /**
+ * Offers an ItemStack for addition to the inventory.
+ *
+ * @param stack
+ * ItemStack offered for addition. Do not manipulate this!
+ * @param doAdd
+ * If false no actual addition should take place. Implementors should simulate.
+ * @param from
+ * Orientation the ItemStack is offered from.
+ * @return Amount of items used from the passed stack.
+ */
+ int addItem(ItemStack stack, boolean doAdd, ForgeDirection from);
+
+ /**
+ * Requests items to be extracted from the inventory
+ *
+ * @param doRemove
+ * If false no actual extraction may occur. Implementors should simulate.
+ * Can be used to "peek" at what the result would be
+ * @param from
+ * Orientation the ItemStack is requested from.
+ * @param maxItemCount
+ * Maximum amount of items to extract (spread over all returned item stacks)
+ * @return Array of item stacks that were/would be extracted from the inventory
+ */
+ ItemStack[] extractItem(boolean doRemove, ForgeDirection from, int maxItemCount);
+
+}
diff --git a/common/buildcraft/api/power/IPowerEmitter.java b/common/buildcraft/api/power/IPowerEmitter.java
new file mode 100644
index 00000000..7ccf62b9
--- /dev/null
+++ b/common/buildcraft/api/power/IPowerEmitter.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) SpaceToad, 2011-2012
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+package buildcraft.api.power;
+
+import net.minecraftforge.common.ForgeDirection;
+
+/**
+ * Essentially only used for Wooden Power Pipe connection rules.
+ *
+ * This Tile Entity interface allows you to indicate that a block can emit power
+ * from a specific side.
+ *
+ * @author CovertJaguar
+ */
+public interface IPowerEmitter {
+
+ public boolean canEmitPowerFrom(ForgeDirection side);
+}
diff --git a/common/buildcraft/api/power/IPowerReceptor.java b/common/buildcraft/api/power/IPowerReceptor.java
new file mode 100644
index 00000000..a7f6c421
--- /dev/null
+++ b/common/buildcraft/api/power/IPowerReceptor.java
@@ -0,0 +1,47 @@
+/**
+ * Copyright (c) SpaceToad, 2011 http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public License
+ * 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+package buildcraft.api.power;
+
+import buildcraft.api.power.PowerHandler.PowerReceiver;
+import net.minecraft.world.World;
+import net.minecraftforge.common.ForgeDirection;
+
+/**
+ * This interface should be implemented by any Tile Entity that wishes to be
+ * able to receive power.
+ *
+ * @author CovertJaguar
+ */
+public interface IPowerReceptor {
+
+ /**
+ * Get the PowerReceiver for this side of the block. You can return the same
+ * PowerReceiver for all sides or one for each side.
+ *
+ * You should NOT return null to this method unless you mean to NEVER
+ * receive power from that side. Returning null, after previous returning a
+ * PowerReceiver, will most likely cause pipe connections to derp out and
+ * engines to eventually explode.
+ *
+ * @param side
+ * @return
+ */
+ public PowerReceiver getPowerReceiver(ForgeDirection side);
+
+ /**
+ * Call back from the PowerHandler that is called when the stored power
+ * exceeds the activation power.
+ *
+ * It can be triggered by update() calls or power modification calls.
+ *
+ * @param workProvider
+ */
+ public void doWork(PowerHandler workProvider);
+
+ public World getWorld();
+}
diff --git a/common/buildcraft/api/power/PowerHandler.java b/common/buildcraft/api/power/PowerHandler.java
new file mode 100644
index 00000000..0751065b
--- /dev/null
+++ b/common/buildcraft/api/power/PowerHandler.java
@@ -0,0 +1,389 @@
+/**
+ * Copyright (c) SpaceToad, 2011 http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public License
+ * 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+package buildcraft.api.power;
+
+import buildcraft.api.core.SafeTimeTracker;
+import net.minecraft.nbt.NBTTagCompound;
+import net.minecraftforge.common.ForgeDirection;
+
+public final class PowerHandler {
+
+ public static enum Type {
+
+ ENGINE, GATE, MACHINE, PIPE, STORAGE;
+
+ public boolean canReceiveFromPipes() {
+ switch (this) {
+ case MACHINE:
+ case STORAGE:
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ public boolean eatsEngineExcess() {
+ switch (this) {
+ case MACHINE:
+ case STORAGE:
+ return true;
+ default:
+ return false;
+ }
+ }
+ }
+
+ public static class PerditionCalculator {
+
+ public static final float DEFAULT_POWERLOSS = 1F;
+ public static final float MIN_POWERLOSS = 0.01F;
+ private final float powerLoss;
+
+ public PerditionCalculator() {
+ powerLoss = DEFAULT_POWERLOSS;
+ }
+
+ public PerditionCalculator(float powerLoss) {
+ if (powerLoss < MIN_POWERLOSS) {
+ powerLoss = MIN_POWERLOSS;
+ }
+ this.powerLoss = powerLoss;
+ }
+
+ /**
+ * Apply the perdition algorithm to the current stored energy. This
+ * function can only be called once per tick, but it might not be called
+ * every tick. It is triggered by any manipulation of the stored energy.
+ *
+ * @param powerHandler the PowerHandler requesting the perdition update
+ * @param current the current stored energy
+ * @param ticksPassed ticks since the last time this function was called
+ * @return
+ */
+ public float applyPerdition(PowerHandler powerHandler, float current, long ticksPassed) {
+ current -= powerLoss * ticksPassed;
+ if (current < 0) {
+ current = 0;
+ }
+ return current;
+ }
+ }
+ public static final PerditionCalculator DEFAULT_PERDITION = new PerditionCalculator();
+ private float minEnergyReceived;
+ private float maxEnergyReceived;
+ private float maxEnergyStored;
+ private float activationEnergy;
+ private float energyStored = 0;
+ private final SafeTimeTracker doWorkTracker = new SafeTimeTracker();
+ private final SafeTimeTracker sourcesTracker = new SafeTimeTracker();
+ private final SafeTimeTracker perditionTracker = new SafeTimeTracker();
+ public final int[] powerSources = new int[6];
+ public final IPowerReceptor receptor;
+ private PerditionCalculator perdition;
+ private final PowerReceiver receiver;
+ private final Type type;
+
+ public PowerHandler(IPowerReceptor receptor, Type type) {
+ this.receptor = receptor;
+ this.type = type;
+ this.receiver = new PowerReceiver();
+ this.perdition = DEFAULT_PERDITION;
+ }
+
+ public PowerReceiver getPowerReceiver() {
+ return receiver;
+ }
+
+ public float getMinEnergyReceived() {
+ return minEnergyReceived;
+ }
+
+ public float getMaxEnergyReceived() {
+ return maxEnergyReceived;
+ }
+
+ public float getMaxEnergyStored() {
+ return maxEnergyStored;
+ }
+
+ public float getActivationEnergy() {
+ return activationEnergy;
+ }
+
+ public float getEnergyStored() {
+ return energyStored;
+ }
+
+ /**
+ * Setup your PowerHandler's settings.
+ *
+ * @param minEnergyReceived This is the minimum about of power that will be
+ * accepted by the PowerHandler. This should generally be greater than the
+ * activationEnergy if you plan to use the doWork() callback. Anything
+ * greater than 1 will prevent Redstone Engines from powering this Provider.
+ * @param maxEnergyReceived The maximum amount of power accepted by the
+ * PowerHandler. This should generally be less than 500. Too low and larger
+ * engines will overheat while trying to power the machine. Too high, and
+ * the engines will never warm up. Greater values also place greater strain
+ * on the power net.
+ * @param activationEnergy If the stored energy is greater than this value,
+ * the doWork() callback is called (once per tick).
+ * @param maxStoredEnergy The maximum amount of power this PowerHandler can
+ * store. Values tend to range between 100 and 5000. With 1000 and 1500
+ * being common.
+ */
+ public void configure(float minEnergyReceived, float maxEnergyReceived, float activationEnergy, float maxStoredEnergy) {
+ if (minEnergyReceived > maxEnergyReceived) {
+ maxEnergyReceived = minEnergyReceived;
+ }
+ this.minEnergyReceived = minEnergyReceived;
+ this.maxEnergyReceived = maxEnergyReceived;
+ this.maxEnergyStored = maxStoredEnergy;
+ this.activationEnergy = activationEnergy;
+ }
+
+ public void configurePowerPerdition(int powerLoss, int powerLossRegularity) {
+ if (powerLoss == 0 || powerLossRegularity == 0) {
+ perdition = new PerditionCalculator(0);
+ return;
+ }
+ perdition = new PerditionCalculator((float) powerLoss / (float) powerLossRegularity);
+ }
+
+ /**
+ * Allows you to define a new PerditionCalculator class to handler perdition
+ * calculations.
+ *
+ * For example if you want exponentially increasing loss based on amount
+ * stored.
+ *
+ * @param perdition
+ */
+ public void setPerdition(PerditionCalculator perdition) {
+ if (perdition == null)
+ perdition = DEFAULT_PERDITION;
+ this.perdition = perdition;
+ }
+
+ public PerditionCalculator getPerdition() {
+ if (perdition == null)
+ return DEFAULT_PERDITION;
+ return perdition;
+ }
+
+ /**
+ * Ticks the power handler. You should call this if you can, but its not
+ * required.
+ *
+ * If you don't call it, the possibility exists for some weirdness with the
+ * perdition algorithm and work callback as its possible they will not be
+ * called on every tick they otherwise would be. You should be able to
+ * design around this though if you are aware of the limitations.
+ */
+ public void update() {
+ applyPerdition();
+ applyWork();
+ validateEnergy();
+ }
+
+ private void applyPerdition() {
+ if (perditionTracker.markTimeIfDelay(receptor.getWorld(), 1) && energyStored > 0) {
+ float newEnergy = getPerdition().applyPerdition(this, energyStored, perditionTracker.durationOfLastDelay());
+ if (newEnergy == 0 || newEnergy < energyStored)
+ energyStored = newEnergy;
+ else
+ energyStored = DEFAULT_PERDITION.applyPerdition(this, energyStored, perditionTracker.durationOfLastDelay());
+ validateEnergy();
+ }
+ }
+
+ private void applyWork() {
+ if (energyStored >= activationEnergy) {
+ if (doWorkTracker.markTimeIfDelay(receptor.getWorld(), 1)) {
+ receptor.doWork(this);
+ }
+ }
+ }
+
+ private void updateSources(ForgeDirection source) {
+ if (sourcesTracker.markTimeIfDelay(receptor.getWorld(), 1)) {
+ for (int i = 0; i < 6; ++i) {
+ powerSources[i] -= sourcesTracker.durationOfLastDelay();
+ if (powerSources[i] < 0) {
+ powerSources[i] = 0;
+ }
+ }
+ }
+
+ if (source != null)
+ powerSources[source.ordinal()] = 10;
+ }
+
+ /**
+ * Extract energy from the PowerHandler. You must call this even if doWork()
+ * triggers.
+ *
+ * @param min
+ * @param max
+ * @param doUse
+ * @return amount used
+ */
+ public float useEnergy(float min, float max, boolean doUse) {
+ applyPerdition();
+
+ float result = 0;
+
+ if (energyStored >= min) {
+ if (energyStored <= max) {
+ result = energyStored;
+ if (doUse) {
+ energyStored = 0;
+ }
+ } else {
+ result = max;
+ if (doUse) {
+ energyStored -= max;
+ }
+ }
+ }
+
+ validateEnergy();
+
+ return result;
+ }
+
+ public void readFromNBT(NBTTagCompound data) {
+ readFromNBT(data, "powerProvider");
+ }
+
+ public void readFromNBT(NBTTagCompound data, String tag) {
+ NBTTagCompound nbt = data.getCompoundTag(tag);
+ energyStored = nbt.getFloat("storedEnergy");
+ }
+
+ public void writeToNBT(NBTTagCompound data) {
+ writeToNBT(data, "powerProvider");
+ }
+
+ public void writeToNBT(NBTTagCompound data, String tag) {
+ NBTTagCompound nbt = new NBTTagCompound();
+ nbt.setFloat("storedEnergy", energyStored);
+ data.setCompoundTag(tag, nbt);
+ }
+
+ public final class PowerReceiver {
+
+ private PowerReceiver() {
+ }
+
+ public float getMinEnergyReceived() {
+ return minEnergyReceived;
+ }
+
+ public float getMaxEnergyReceived() {
+ return maxEnergyReceived;
+ }
+
+ public float getMaxEnergyStored() {
+ return maxEnergyStored;
+ }
+
+ public float getActivationEnergy() {
+ return activationEnergy;
+ }
+
+ public float getEnergyStored() {
+ return energyStored;
+ }
+
+ public Type getType() {
+ return type;
+ }
+
+ public void update() {
+ PowerHandler.this.update();
+ }
+
+ /**
+ * The amount of power that this PowerHandler currently needs.
+ *
+ * @return
+ */
+ public float powerRequest() {
+ return Math.min(maxEnergyReceived, maxEnergyStored - energyStored);
+ }
+
+ /**
+ * Add power to the PowerReceiver from an external source.
+ *
+ * @param quantity
+ * @param from
+ * @return the amount of power used
+ */
+ public float receiveEnergy(Type source, final float quantity, ForgeDirection from) {
+ float used = quantity;
+ if (source == Type.ENGINE) {
+ if (used < minEnergyReceived) {
+ return 0;
+ } else if (used > maxEnergyReceived) {
+ used = maxEnergyReceived;
+ }
+ }
+
+ updateSources(from);
+
+ used = addEnergy(used);
+
+ applyWork();
+
+ if (source == Type.ENGINE && type.eatsEngineExcess()) {
+ return Math.min(quantity, maxEnergyReceived);
+ }
+
+ return used;
+ }
+ }
+
+ /**
+ *
+ * @return the amount the power changed by
+ */
+ public float addEnergy(float quantity) {
+ energyStored += quantity;
+
+ if (energyStored > maxEnergyStored) {
+ quantity -= energyStored - maxEnergyStored;
+ energyStored = maxEnergyStored;
+ } else if (energyStored < 0) {
+ quantity -= energyStored;
+ energyStored = 0;
+ }
+
+ applyPerdition();
+
+ return quantity;
+ }
+
+ public void setEnergy(float quantity) {
+ this.energyStored = quantity;
+ validateEnergy();
+ }
+
+ public boolean isPowerSource(ForgeDirection from) {
+ return powerSources[from.ordinal()] != 0;
+ }
+
+ private void validateEnergy() {
+ if (energyStored < 0) {
+ energyStored = 0;
+ }
+ if (energyStored > maxEnergyStored) {
+ energyStored = maxEnergyStored;
+ }
+ }
+}
diff --git a/common/buildcraft/api/recipes/AssemblyRecipe.java b/common/buildcraft/api/recipes/AssemblyRecipe.java
new file mode 100644
index 00000000..573db282
--- /dev/null
+++ b/common/buildcraft/api/recipes/AssemblyRecipe.java
@@ -0,0 +1,48 @@
+package buildcraft.api.recipes;
+
+import java.util.LinkedList;
+import net.minecraft.item.ItemStack;
+
+public class AssemblyRecipe {
+
+ public static LinkedList assemblyRecipes = new LinkedList();
+
+ public final ItemStack[] input;
+ public final ItemStack output;
+ public final float energy;
+
+ public AssemblyRecipe(ItemStack[] input, int energy, ItemStack output) {
+ this.input = input;
+ this.output = output;
+ this.energy = energy;
+ }
+
+ public boolean canBeDone(ItemStack[] items) {
+
+ for (ItemStack in : input) {
+
+ if (in == null) {
+ continue;
+ }
+
+ int found = 0; // Amount of ingredient found in inventory
+
+ for (ItemStack item : items) {
+ if (item == null) {
+ continue;
+ }
+
+ if (item.isItemEqual(in)) {
+ found += item.stackSize; // Adds quantity of stack to amount
+ // found
+ }
+ }
+
+ if (found < in.stackSize)
+ return false; // Return false if the amount of ingredient found
+ // is not enough
+ }
+
+ return true;
+ }
+}
diff --git a/common/buildcraft/api/recipes/RefineryRecipes.java b/common/buildcraft/api/recipes/RefineryRecipes.java
new file mode 100644
index 00000000..64985bf7
--- /dev/null
+++ b/common/buildcraft/api/recipes/RefineryRecipes.java
@@ -0,0 +1,126 @@
+/**
+ * Copyright (c) SpaceToad, 2011 http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public License
+ * 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+package buildcraft.api.recipes;
+
+import com.google.common.base.Objects;
+import java.util.Collections;
+import java.util.SortedSet;
+import java.util.TreeSet;
+import net.minecraftforge.fluids.FluidStack;
+
+public final class RefineryRecipes {
+
+ private static SortedSet recipes = new TreeSet();
+
+ public static void addRecipe(FluidStack ingredient, FluidStack result, int energy, int delay) {
+ addRecipe(ingredient, null, result, energy, delay);
+ }
+
+ public static void addRecipe(FluidStack ingredient1, FluidStack ingredient2, FluidStack result, int energy, int delay) {
+ Recipe recipe = new Recipe(ingredient1, ingredient2, result, energy, delay);
+ recipes.add(recipe);
+ }
+
+ public static SortedSet getRecipes() {
+ return Collections.unmodifiableSortedSet(recipes);
+ }
+
+ public static Recipe findRefineryRecipe(FluidStack liquid1, FluidStack liquid2) {
+ for (Recipe recipe : recipes) {
+ if (recipe.matches(liquid1, liquid2))
+ return recipe;
+ }
+
+ return null;
+ }
+
+ private RefineryRecipes() {
+ }
+
+ public static final class Recipe implements Comparable {
+
+ public final FluidStack ingredient1;
+ public final FluidStack ingredient2;
+ public final FluidStack result;
+ public final int energy;
+ public final int delay;
+
+ private Recipe(FluidStack ingredient1, FluidStack ingredient2, FluidStack result, int energy, int delay) {
+ if (ingredient1 == null)
+ throw new IllegalArgumentException("First Ingredient cannot be null!");
+ this.ingredient1 = ingredient1;
+ this.ingredient2 = ingredient2;
+ this.result = result;
+ this.energy = energy;
+ this.delay = delay;
+ }
+
+ public boolean matches(FluidStack liquid1, FluidStack liquid2) {
+
+ // No inputs, return.
+ if (liquid1 == null && liquid2 == null)
+ return false;
+
+ // Return if two ingredients are required but only one was supplied.
+ if ((ingredient1 != null && ingredient2 != null) && (liquid1 == null || liquid2 == null))
+ return false;
+
+ if (liquid1 != null && liquid2 != null) {
+ if (liquid1.containsFluid(ingredient1) && liquid1.containsFluid(ingredient2))
+ return true;
+ if (liquid1.containsFluid(ingredient2) && liquid1.containsFluid(ingredient1))
+ return true;
+ }
+
+ if (liquid1 != null)
+ return liquid1.containsFluid(ingredient1) || liquid1.containsFluid(ingredient2);
+
+ if (liquid2 != null)
+ return liquid2.containsFluid(ingredient1) || liquid2.containsFluid(ingredient2);
+
+ return false;
+ }
+
+ // Compares to only the types of source materials.
+ // We consider non-null < null in order that one-ingredient recipe is checked after
+ // the failure of matching two-ingredient recipes which include that liquid.
+ @Override
+ public int compareTo(Recipe other) {
+ if (other == null)
+ return -1;
+ else if (ingredient1.getFluid() != other.ingredient1.getFluid())
+ return ingredient1.getFluid().getName().compareTo(other.ingredient1.getFluid().getName());
+ else if (ingredient1.amount != other.ingredient1.amount)
+ return other.ingredient1.amount - ingredient1.amount;
+ else if (ingredient2 == null)
+ return other.ingredient2 == null ? 0 : 1;
+ else if (other.ingredient2 == null)
+ return -1;
+ else if (ingredient2.getFluid() != other.ingredient2.getFluid())
+ return ingredient2.getFluid().getName().compareTo(other.ingredient2.getFluid().getName());
+ else if (ingredient2.amount != other.ingredient2.amount)
+ return other.ingredient2.amount - ingredient2.amount;
+
+ return 0;
+ }
+
+ // equals() should be consistent with compareTo().
+ @Override
+ public boolean equals(Object obj) {
+ return obj instanceof Recipe
+ && Objects.equal(ingredient1, ((Recipe) obj).ingredient1)
+ && Objects.equal(ingredient2, ((Recipe) obj).ingredient2);
+ }
+
+ // hashCode() should be overridden because equals() was overridden.
+ @Override
+ public int hashCode() {
+ return Objects.hashCode(ingredient1, ingredient2);
+ }
+ }
+}
diff --git a/common/buildcraft/api/tools/IToolPipette.java b/common/buildcraft/api/tools/IToolPipette.java
new file mode 100644
index 00000000..d636523d
--- /dev/null
+++ b/common/buildcraft/api/tools/IToolPipette.java
@@ -0,0 +1,40 @@
+package buildcraft.api.tools;
+
+import net.minecraft.item.ItemStack;
+import net.minecraftforge.fluids.FluidStack;
+
+public interface IToolPipette {
+
+ /**
+ * @param pipette
+ * ItemStack of the pipette.
+ * @return Capacity of the pipette.
+ */
+ int getCapacity(ItemStack pipette);
+
+ /**
+ * @param pipette
+ * @return true if the pipette can pipette.
+ */
+ boolean canPipette(ItemStack pipette);
+
+ /**
+ * Fills the pipette with the given liquid stack.
+ *
+ * @param pipette
+ * @param liquid
+ * @param doFill
+ * @return Amount of liquid used in filling the pipette.
+ */
+ int fill(ItemStack pipette, FluidStack liquid, boolean doFill);
+
+ /**
+ * Drains liquid from the pipette
+ *
+ * @param pipette
+ * @param maxDrain
+ * @param doDrain
+ * @return Fluid stack representing the liquid and amount drained from the pipette.
+ */
+ FluidStack drain(ItemStack pipette, int maxDrain, boolean doDrain);
+}
diff --git a/common/buildcraft/api/tools/IToolWrench.java b/common/buildcraft/api/tools/IToolWrench.java
new file mode 100644
index 00000000..bd0c3c59
--- /dev/null
+++ b/common/buildcraft/api/tools/IToolWrench.java
@@ -0,0 +1,32 @@
+package buildcraft.api.tools;
+
+import net.minecraft.entity.player.EntityPlayer;
+
+/***
+ * Implement this interface on subclasses of Item to have that item work as a wrench for buildcraft
+ */
+public interface IToolWrench {
+
+ /***
+ * Called to ensure that the wrench can be used. To get the ItemStack that is used, check player.inventory.getCurrentItem()
+ *
+ * @param player
+ * - The player doing the wrenching
+ * @param x
+ * ,y,z - The coordinates for the block being wrenched
+ *
+ * @return true if wrenching is allowed, false if not
+ */
+ public boolean canWrench(EntityPlayer player, int x, int y, int z);
+
+ /***
+ * Callback after the wrench has been used. This can be used to decrease durability or for other purposes. To get the ItemStack that was used, check
+ * player.inventory.getCurrentItem()
+ *
+ * @param player
+ * - The player doing the wrenching
+ * @param x
+ * ,y,z - The coordinates of the block being wrenched
+ */
+ public void wrenchUsed(EntityPlayer player, int x, int y, int z);
+}
diff --git a/common/buildcraft/api/transport/FacadeManager.java b/common/buildcraft/api/transport/FacadeManager.java
new file mode 100644
index 00000000..28cbdd1a
--- /dev/null
+++ b/common/buildcraft/api/transport/FacadeManager.java
@@ -0,0 +1,25 @@
+package buildcraft.api.transport;
+
+import java.lang.reflect.Method;
+import net.minecraft.item.ItemStack;
+
+/**
+ * You can use this if you wish, but FML InterModComms are recommended.
+ *
+ * SYNTAX: add-facade:id@meta
+ */
+public class FacadeManager {
+ private static Method addFacade;
+
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ public static void addFacade(ItemStack is) {
+ try {
+ if (addFacade == null) {
+ Class facade = Class.forName("buildcraft.transport.ItemFacade");
+ addFacade = facade.getMethod("addFacade", ItemStack.class);
+ }
+ addFacade.invoke(null, is);
+ } catch (Exception ex) {
+ }
+ }
+}
diff --git a/common/buildcraft/api/transport/IExtractionHandler.java b/common/buildcraft/api/transport/IExtractionHandler.java
new file mode 100644
index 00000000..e912f65b
--- /dev/null
+++ b/common/buildcraft/api/transport/IExtractionHandler.java
@@ -0,0 +1,21 @@
+package buildcraft.api.transport;
+
+import net.minecraft.world.World;
+
+/**
+ * Implement and register with the PipeManager if you want to suppress connections from wooden pipes.
+ */
+public interface IExtractionHandler {
+
+ /**
+ * Can this pipe extract items from the block located at these coordinates?
+ * param extractor can be null
+ */
+ boolean canExtractItems(Object extractor, World world, int i, int j, int k);
+
+ /**
+ * Can this pipe extract liquids from the block located at these coordinates?
+ * param extractor can be null
+ */
+ boolean canExtractFluids(Object extractor, World world, int i, int j, int k);
+}
diff --git a/common/buildcraft/api/transport/IPipe.java b/common/buildcraft/api/transport/IPipe.java
new file mode 100644
index 00000000..20096b76
--- /dev/null
+++ b/common/buildcraft/api/transport/IPipe.java
@@ -0,0 +1,45 @@
+/**
+ * Copyright (c) SpaceToad, 2011
+ * http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public
+ * License 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+
+package buildcraft.api.transport;
+
+import net.minecraft.tileentity.TileEntity;
+
+public interface IPipe {
+
+ enum DrawingState {
+ DrawingPipe, DrawingRedWire, DrawingBlueWire, DrawingGreenWire, DrawingYellowWire, DrawingGate
+ }
+
+ enum WireColor {
+ Red, Blue, Green, Yellow;
+
+ public WireColor reverse() {
+ switch (this) {
+ case Red:
+ return Yellow;
+ case Blue:
+ return Green;
+ case Green:
+ return Blue;
+ default:
+ return Red;
+ }
+ }
+ }
+
+ public boolean isWired(WireColor color);
+
+ public boolean hasGate();
+
+ public TileEntity getContainer();
+
+ public boolean isWireConnectedTo(TileEntity tile, WireColor color);
+
+}
diff --git a/common/buildcraft/api/transport/IPipeConnection.java b/common/buildcraft/api/transport/IPipeConnection.java
new file mode 100644
index 00000000..cbb1d003
--- /dev/null
+++ b/common/buildcraft/api/transport/IPipeConnection.java
@@ -0,0 +1,29 @@
+/**
+ * Copyright (c) SpaceToad, 2011 http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public License
+ * 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+package buildcraft.api.transport;
+
+import buildcraft.api.transport.IPipeTile.PipeType;
+import net.minecraftforge.common.ForgeDirection;
+
+public interface IPipeConnection {
+
+ enum ConnectOverride {
+
+ CONNECT, DISCONNECT, DEFAULT
+ };
+
+ /**
+ * Allows you to override pipe connection logic.
+ *
+ * @param type
+ * @param with
+ * @return CONNECT to force a connection, DISCONNECT to force no connection,
+ * and DEFAULT to let the pipe decide.
+ */
+ public ConnectOverride overridePipeConnection(PipeType type, ForgeDirection with);
+}
diff --git a/common/buildcraft/api/transport/IPipeTile.java b/common/buildcraft/api/transport/IPipeTile.java
new file mode 100644
index 00000000..13aa8d76
--- /dev/null
+++ b/common/buildcraft/api/transport/IPipeTile.java
@@ -0,0 +1,39 @@
+/**
+ * Copyright (c) SpaceToad, 2011 http://www.mod-buildcraft.com
+ *
+ * BuildCraft is distributed under the terms of the Minecraft Mod Public License
+ * 1.0, or MMPL. Please check the contents of the license located in
+ * http://www.mod-buildcraft.com/MMPL-1.0.txt
+ */
+package buildcraft.api.transport;
+
+import net.minecraft.item.ItemStack;
+import net.minecraftforge.common.ForgeDirection;
+import net.minecraftforge.fluids.IFluidHandler;
+
+public interface IPipeTile extends ISolidSideTile, IFluidHandler {
+
+ public enum PipeType {
+
+ ITEM, FLUID, POWER, STRUCTURE;
+ }
+
+ @Deprecated
+ IPipe getPipe();
+
+ PipeType getPipeType();
+
+ /**
+ * Offers an ItemStack for addition to the pipe. Will be rejected if the
+ * pipe doesn't accept items from that side.
+ *
+ * @param stack ItemStack offered for addition. Do not manipulate this!
+ * @param doAdd If false no actual addition should take place. Implementors
+ * should simulate.
+ * @param from Orientation the ItemStack is offered from.
+ * @return Amount of items used from the passed stack.
+ */
+ int injectItem(ItemStack stack, boolean doAdd, ForgeDirection from);
+
+ boolean isPipeConnected(ForgeDirection with);
+}
diff --git a/common/buildcraft/api/transport/ISolidSideTile.java b/common/buildcraft/api/transport/ISolidSideTile.java
new file mode 100644
index 00000000..627b0d88
--- /dev/null
+++ b/common/buildcraft/api/transport/ISolidSideTile.java
@@ -0,0 +1,7 @@
+package buildcraft.api.transport;
+
+import net.minecraftforge.common.ForgeDirection;
+
+public interface ISolidSideTile {
+ public boolean isSolidOnSide(ForgeDirection side);
+}
diff --git a/common/buildcraft/api/transport/PipeManager.java b/common/buildcraft/api/transport/PipeManager.java
new file mode 100644
index 00000000..c78c86e2
--- /dev/null
+++ b/common/buildcraft/api/transport/PipeManager.java
@@ -0,0 +1,36 @@
+package buildcraft.api.transport;
+
+import java.util.ArrayList;
+import java.util.List;
+import net.minecraft.world.World;
+
+public abstract class PipeManager {
+
+ public static List extractionHandlers = new ArrayList();
+
+ public static void registerExtractionHandler(IExtractionHandler handler) {
+ extractionHandlers.add(handler);
+ }
+
+ /**
+ * param extractor can be null
+ */
+ public static boolean canExtractItems(Object extractor, World world, int i, int j, int k) {
+ for (IExtractionHandler handler : extractionHandlers)
+ if (!handler.canExtractItems(extractor, world, i, j, k))
+ return false;
+
+ return true;
+ }
+
+ /**
+ * param extractor can be null
+ */
+ public static boolean canExtractFluids(Object extractor, World world, int i, int j, int k) {
+ for (IExtractionHandler handler : extractionHandlers)
+ if (!handler.canExtractFluids(extractor, world, i, j, k))
+ return false;
+
+ return true;
+ }
+}
diff --git a/common/crazypants/enderio/ClientProxy.java b/common/crazypants/enderio/ClientProxy.java
new file mode 100644
index 00000000..f08a6a63
--- /dev/null
+++ b/common/crazypants/enderio/ClientProxy.java
@@ -0,0 +1,120 @@
+package crazypants.enderio;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import net.minecraft.client.Minecraft;
+import net.minecraft.entity.player.EntityPlayer;
+import net.minecraft.world.World;
+import net.minecraftforge.client.MinecraftForgeClient;
+import cpw.mods.fml.client.FMLClientHandler;
+import cpw.mods.fml.client.registry.ClientRegistry;
+import cpw.mods.fml.client.registry.RenderingRegistry;
+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.liquid.LiquidConduitRenderer;
+import crazypants.enderio.conduit.redstone.RedstoneSwitchRenderer;
+import crazypants.enderio.conduit.render.ConduitBundleRenderer;
+import crazypants.enderio.conduit.render.ConduitRenderer;
+import crazypants.enderio.conduit.render.DefaultConduitRenderer;
+import crazypants.enderio.conduit.render.ItemConduitRenderer;
+import crazypants.enderio.enderface.EnderIoRenderer;
+import crazypants.enderio.enderface.TileEnderIO;
+import crazypants.enderio.machine.painter.BlockCustomFenceGate;
+import crazypants.enderio.machine.painter.BlockCustomFenceGateRenderer;
+import crazypants.enderio.machine.painter.PaintedItemRenderer;
+import crazypants.enderio.machine.reservoir.ReservoirRenderer;
+import crazypants.enderio.machine.reservoir.TileReservoir;
+import crazypants.enderio.material.BlockFusedQuartz;
+import crazypants.enderio.material.FusedQuartzFrameRenderer;
+import crazypants.enderio.material.FusedQuartzRenderer;
+
+
+public class ClientProxy extends CommonProxy {
+
+ //@formatter:off
+ public static int[][] sideAndFacingToSpriteOffset = new int[][] {
+
+ { 3, 2, 0, 0, 0, 0 },
+ { 2, 3, 1, 1, 1, 1 },
+ { 1, 1, 3, 2, 5, 4 },
+ { 0, 0, 2, 3, 4, 5 },
+ { 4, 5, 4, 5, 3, 2 },
+ { 5, 4, 5, 4, 2, 3 } };
+//@formatter:on
+
+
+ private List conduitRenderers = new ArrayList();
+
+ private DefaultConduitRenderer dcr = new DefaultConduitRenderer();
+
+ @Override
+ public World getClientWorld() {
+ return FMLClientHandler.instance().getClient().theWorld;
+ }
+
+ @Override
+ public EntityPlayer getClientPlayer() {
+ return Minecraft.getMinecraft().thePlayer;
+ }
+
+ @Override
+ public void load() {
+ super.load();
+
+ //Renderers
+
+ ConduitBundleRenderer cbr = new ConduitBundleRenderer();
+ BlockConduitBundle.rendererId = RenderingRegistry.getNextAvailableRenderId();
+ RenderingRegistry.registerBlockHandler(cbr);
+
+ BlockCustomFenceGateRenderer bcfgr = new BlockCustomFenceGateRenderer();
+ BlockCustomFenceGate.renderId = RenderingRegistry.getNextAvailableRenderId();;
+ RenderingRegistry.registerBlockHandler(bcfgr);
+
+ FusedQuartzRenderer fqr = new FusedQuartzRenderer();
+ BlockFusedQuartz.renderId = RenderingRegistry.getNextAvailableRenderId();;
+ RenderingRegistry.registerBlockHandler(fqr);
+
+ FusedQuartzFrameRenderer fqfr = new FusedQuartzFrameRenderer();
+ MinecraftForgeClient.registerItemRenderer(EnderIO.itemFusedQuartzFrame.itemID, fqfr);
+
+ ItemConduitRenderer itemConRenderer = new ItemConduitRenderer();
+ MinecraftForgeClient.registerItemRenderer(EnderIO.itemLiquidConduit.itemID, itemConRenderer);
+ MinecraftForgeClient.registerItemRenderer(EnderIO.itemPowerConduit.itemID, itemConRenderer);
+ MinecraftForgeClient.registerItemRenderer(EnderIO.itemRedstoneConduit.itemID, itemConRenderer);
+
+
+ PaintedItemRenderer pir = new PaintedItemRenderer();
+ MinecraftForgeClient.registerItemRenderer(EnderIO.blockCustomFence.blockID, pir);
+ MinecraftForgeClient.registerItemRenderer(EnderIO.blockCustomFenceGate.blockID, pir);
+ MinecraftForgeClient.registerItemRenderer(EnderIO.blockCustomWall.blockID, pir);
+ MinecraftForgeClient.registerItemRenderer(EnderIO.blockCustomStair.blockID, pir);
+
+ MinecraftForgeClient.registerItemRenderer(EnderIO.itemConduitFacade.itemID, new FacadeRenderer());
+
+ ClientRegistry.bindTileEntitySpecialRenderer(TileConduitBundle.class, cbr);
+ conduitRenderers.add(RedstoneSwitchRenderer.instance);
+ conduitRenderers.add(new LiquidConduitRenderer());
+
+ EnderIoRenderer eior = new EnderIoRenderer();
+ ClientRegistry.bindTileEntitySpecialRenderer(TileEnderIO.class, eior);
+ MinecraftForgeClient.registerItemRenderer(EnderIO.blockEnderIo.blockID, eior);
+
+ ClientRegistry.bindTileEntitySpecialRenderer(TileReservoir.class, new ReservoirRenderer(EnderIO.blockReservoir));
+
+ }
+
+ @Override
+ public ConduitRenderer getRendererForConduit(IConduit conduit) {
+ for(ConduitRenderer renderer : conduitRenderers) {
+ if(renderer.isRendererForConduit(conduit)) {
+ return renderer;
+ }
+ }
+ return dcr;
+ }
+
+}
diff --git a/common/crazypants/enderio/ClientTickHandler.java b/common/crazypants/enderio/ClientTickHandler.java
new file mode 100644
index 00000000..91fc614c
--- /dev/null
+++ b/common/crazypants/enderio/ClientTickHandler.java
@@ -0,0 +1,60 @@
+package crazypants.enderio;
+
+import java.util.EnumSet;
+import java.util.List;
+
+import net.minecraft.client.multiplayer.WorldClient;
+import net.minecraft.entity.player.EntityPlayer;
+import net.minecraft.tileentity.TileEntity;
+import cpw.mods.fml.client.FMLClientHandler;
+import cpw.mods.fml.common.ITickHandler;
+import cpw.mods.fml.common.TickType;
+import crazypants.enderio.conduit.ConduitUtil;
+
+public class ClientTickHandler implements ITickHandler {
+
+ private boolean hidingConduits = false;
+ private boolean first = true;
+
+ @Override
+ public void tickStart(EnumSet type, Object... tickData) {
+ EntityPlayer player = (EntityPlayer) tickData[0];
+ boolean curVal = ConduitUtil.isToolEquipped(player) || ConduitUtil.isConduitEquipped(player);
+ if(first) {
+ hidingConduits = curVal;
+ first = false;
+ }
+ if(curVal != hidingConduits) {
+ hidingConduits = curVal;
+ WorldClient world = FMLClientHandler.instance().getClient().theWorld;
+
+ @SuppressWarnings("unchecked")
+ List checkList = world.loadedTileEntityList;
+ for(TileEntity o : checkList) {
+ if(o.blockType != null && o.blockType.blockID == EnderIO.blockConduitBundle.blockID) {
+ if(o.getDistanceFrom(player.posX, player.posY, player.posZ) < o.getMaxRenderDistanceSquared()) {
+ world.markBlockForRenderUpdate(o.xCoord, o.yCoord, o.zCoord);
+ }
+ }
+ }
+ }
+
+
+ }
+
+ @Override
+ public void tickEnd(EnumSet type, Object... tickData) {
+ }
+
+ @Override
+ public EnumSet ticks() {
+ return EnumSet.of(TickType.PLAYER);
+ }
+
+ @Override
+ public String getLabel() {
+ return "EnderIO Client Tick Handler";
+ }
+
+
+}
diff --git a/common/crazypants/enderio/CommonProxy.java b/common/crazypants/enderio/CommonProxy.java
new file mode 100644
index 00000000..a741a2b2
--- /dev/null
+++ b/common/crazypants/enderio/CommonProxy.java
@@ -0,0 +1,38 @@
+package crazypants.enderio;
+
+import net.minecraft.entity.player.EntityPlayer;
+import net.minecraft.world.World;
+import cpw.mods.fml.common.registry.TickRegistry;
+import cpw.mods.fml.relauncher.Side;
+import crazypants.enderio.conduit.IConduit;
+import crazypants.enderio.conduit.render.ConduitRenderer;
+
+public class CommonProxy {
+
+ private final ServerTickHandler serverTickHandler = new ServerTickHandler();
+
+ public World getClientWorld() {
+ return null;
+ }
+
+ public EntityPlayer getClientPlayer() {
+ return null;
+ }
+
+ public void load() {
+ TickRegistry.registerTickHandler(serverTickHandler, Side.SERVER);
+ }
+
+ public ConduitRenderer getRendererForConduit(IConduit conduit) {
+ return null;
+ }
+
+ public ServerTickHandler getServerTickHandler() {
+ return serverTickHandler;
+ }
+
+ public void serverStopped() {
+ serverTickHandler.serverStopped();
+ }
+
+}
diff --git a/common/crazypants/enderio/Config.java b/common/crazypants/enderio/Config.java
new file mode 100644
index 00000000..3d44f4b4
--- /dev/null
+++ b/common/crazypants/enderio/Config.java
@@ -0,0 +1,19 @@
+package crazypants.enderio;
+
+import net.minecraftforge.common.Configuration;
+
+public final class Config {
+
+ static int BID = 700;
+ static int IID = 8524;
+
+ public static void load(Configuration config) {
+ for (ModObject e : ModObject.values()) {
+ e.load(config);
+ }
+ }
+
+ private Config() {
+ }
+
+}
diff --git a/common/crazypants/enderio/EnderIO.java b/common/crazypants/enderio/EnderIO.java
new file mode 100644
index 00000000..e2ae2ca1
--- /dev/null
+++ b/common/crazypants/enderio/EnderIO.java
@@ -0,0 +1,172 @@
+package crazypants.enderio;
+
+import java.util.logging.Level;
+
+import net.minecraftforge.common.Configuration;
+import net.minecraftforge.common.MinecraftForge;
+import cpw.mods.fml.common.FMLLog;
+import cpw.mods.fml.common.Mod;
+import cpw.mods.fml.common.Mod.Init;
+import cpw.mods.fml.common.Mod.Instance;
+import cpw.mods.fml.common.Mod.PostInit;
+import cpw.mods.fml.common.Mod.PreInit;
+import cpw.mods.fml.common.Mod.ServerStopped;
+import cpw.mods.fml.common.SidedProxy;
+import cpw.mods.fml.common.event.FMLInitializationEvent;
+import cpw.mods.fml.common.event.FMLPostInitializationEvent;
+import cpw.mods.fml.common.event.FMLPreInitializationEvent;
+import cpw.mods.fml.common.event.FMLServerStoppedEvent;
+import cpw.mods.fml.common.network.NetworkMod;
+import cpw.mods.fml.common.network.NetworkRegistry;
+import cpw.mods.fml.common.registry.TickRegistry;
+import cpw.mods.fml.relauncher.Side;
+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.liquid.ItemLiquidConduit;
+import crazypants.enderio.conduit.power.ItemPowerConduit;
+import crazypants.enderio.conduit.redstone.ItemRedstoneConduit;
+import crazypants.enderio.enderface.BlockEnderIO;
+import crazypants.enderio.enderface.ItemEnderface;
+import crazypants.enderio.machine.BlockElectricLight;
+import crazypants.enderio.machine.MachineRecipes;
+import crazypants.enderio.machine.alloy.BlockAlloySmelter;
+import crazypants.enderio.machine.generator.BlockStirlingGenerator;
+import crazypants.enderio.machine.painter.BlockCustomFence;
+import crazypants.enderio.machine.painter.BlockCustomFenceGate;
+import crazypants.enderio.machine.painter.BlockCustomStair;
+import crazypants.enderio.machine.painter.BlockCustomWall;
+import crazypants.enderio.machine.painter.BlockPainter;
+import crazypants.enderio.machine.reservoir.BlockReservoir;
+import crazypants.enderio.machine.solor.BlockSolarPanel;
+import crazypants.enderio.material.BlockFusedQuartz;
+import crazypants.enderio.material.ItemAlloy;
+import crazypants.enderio.material.ItemCapacitor;
+import crazypants.enderio.material.ItemFusedQuartzFrame;
+import crazypants.enderio.material.ItemIndustrialBinder;
+import crazypants.enderio.material.ItemYetaWrench;
+import crazypants.enderio.material.MaterialRecipes;
+
+@Mod(name = "EnderIO", modid = "EnderIO", version = "0.1.0", dependencies = "required-after:Forge@[7.1,);required-after:FML@[5.0.5,)")
+@NetworkMod(clientSideRequired = true, serverSideRequired = true, channels = { "EnderIO" }, packetHandler = PacketHandler.class)
+public class EnderIO {
+
+ @Instance("EnderIO")
+ public static EnderIO instance;
+
+ @SidedProxy(clientSide = "crazypants.enderio.ClientProxy", serverSide = "crazypants.enderio.CommonProxy")
+ public static CommonProxy proxy;
+
+ public static GuiHandler guiHandler = new GuiHandler();
+
+ //Materials
+ public static ItemIndustrialBinder itemIndustrialBinder;
+ public static ItemCapacitor itemBasicCapacitor;
+ public static ItemAlloy itemAlloy;
+ public static BlockFusedQuartz blockFusedQuartz;
+ public static ItemFusedQuartzFrame itemFusedQuartzFrame;
+
+ // Enderface
+ public static BlockEnderIO blockEnderIo;
+ public static ItemEnderface itemEnderface;
+
+ // Painter
+ public static BlockPainter blockPainter;
+ public static BlockCustomFence blockCustomFence;
+ public static BlockCustomFenceGate blockCustomFenceGate;
+ public static BlockCustomWall blockCustomWall;
+ public static BlockCustomStair blockCustomStair;
+
+ // Conduits
+ public static BlockConduitBundle blockConduitBundle;
+ public static BlockConduitFacade blockConduitFacade;
+ public static ItemConduitFacade itemConduitFacade;
+ public static ItemRedstoneConduit itemRedstoneConduit;
+ public static ItemPowerConduit itemPowerConduit;
+ public static ItemLiquidConduit itemLiquidConduit;
+
+ //Machines
+ public static BlockStirlingGenerator blockStirlingGenerator;
+ public static BlockSolarPanel blockSolarPanel;
+ public static BlockElectricLight blockElectricLight;
+ public static BlockReservoir blockReservoir;
+ public static BlockAlloySmelter blockAlloySmelter;
+
+ public static ItemYetaWrench itemYetaWench;
+
+ @PreInit
+ public void preInit(FMLPreInitializationEvent event) {
+ Configuration cfg = new Configuration(event.getSuggestedConfigurationFile());
+ try {
+ cfg.load();
+ Config.load(cfg);
+ } catch (Exception e) {
+ FMLLog.log(Level.SEVERE, e, "EnderIO has a problem loading it's configuration");
+ } finally {
+ if (cfg.hasChanged()) {
+ cfg.save();
+ }
+ }
+
+ itemIndustrialBinder= ItemIndustrialBinder.create();
+ itemBasicCapacitor = ItemCapacitor.create();
+ itemAlloy = ItemAlloy.create();
+ blockFusedQuartz = BlockFusedQuartz.create();
+ itemFusedQuartzFrame = ItemFusedQuartzFrame.create();
+
+ blockEnderIo = BlockEnderIO.create();
+ itemEnderface = ItemEnderface.create();
+
+ blockPainter = BlockPainter.create();
+ blockCustomFence = BlockCustomFence.create();
+ blockCustomFenceGate = BlockCustomFenceGate.create();
+ blockCustomWall = BlockCustomWall.create();
+ blockCustomStair = BlockCustomStair.create();
+
+ blockStirlingGenerator = BlockStirlingGenerator.create();
+ blockSolarPanel = BlockSolarPanel.create();
+ blockReservoir = BlockReservoir.create();
+ blockAlloySmelter = BlockAlloySmelter.create();
+
+
+ blockConduitBundle = BlockConduitBundle.create();
+ blockConduitFacade = BlockConduitFacade.create();
+ itemConduitFacade = ItemConduitFacade.create();
+
+ itemRedstoneConduit = ItemRedstoneConduit.create();
+ itemPowerConduit = ItemPowerConduit.create();
+ itemLiquidConduit = ItemLiquidConduit.create();
+
+ //blockElectricLight = BlockElectricLight.create();
+
+ itemYetaWench = ItemYetaWrench.create();
+ }
+
+
+ @Init
+ public void load(FMLInitializationEvent event) {
+
+ instance = this;
+
+ NetworkRegistry.instance().registerGuiHandler(this, guiHandler);
+ MinecraftForge.EVENT_BUS.register(this);
+
+ MaterialRecipes.addRecipes();
+ ConduitRecipes.addRecipes();
+ MachineRecipes.addRecipes();
+
+ proxy.load();
+ }
+
+ @PostInit
+ public void postInit(FMLPostInitializationEvent event) {
+ TickRegistry.registerTickHandler(new ClientTickHandler(), Side.CLIENT);
+ }
+
+ @ServerStopped
+ public void serverStopped(FMLServerStoppedEvent event) {
+ proxy.serverStopped();
+ }
+
+}
diff --git a/common/crazypants/enderio/EnderIOTab.java b/common/crazypants/enderio/EnderIOTab.java
new file mode 100644
index 00000000..0640fb35
--- /dev/null
+++ b/common/crazypants/enderio/EnderIOTab.java
@@ -0,0 +1,36 @@
+package crazypants.enderio;
+
+import net.minecraft.creativetab.CreativeTabs;
+import cpw.mods.fml.relauncher.Side;
+import cpw.mods.fml.relauncher.SideOnly;
+
+public class EnderIOTab extends CreativeTabs {
+
+
+ public static final CreativeTabs tabEnderIO = new EnderIOTab();
+
+ public EnderIOTab() {
+ super("EnderIO");
+ }
+
+ /**
+ * the itemID for the item to be displayed on the tab
+ */
+ @Override
+ public int getTabIconItemIndex() {
+ return EnderIO.itemEnderface.itemID;
+ }
+
+ @Override
+ @SideOnly(Side.CLIENT)
+ public String getTabLabel() {
+ return "EnderIO";
+ }
+
+ @Override
+ @SideOnly(Side.CLIENT)
+ public String getTranslatedTabLabel() {
+ return "EnderIO";
+ }
+
+}
diff --git a/common/crazypants/enderio/GuiHandler.java b/common/crazypants/enderio/GuiHandler.java
new file mode 100644
index 00000000..312b7e7b
--- /dev/null
+++ b/common/crazypants/enderio/GuiHandler.java
@@ -0,0 +1,41 @@
+package crazypants.enderio;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import net.minecraft.entity.player.EntityPlayer;
+import net.minecraft.world.World;
+import cpw.mods.fml.common.network.IGuiHandler;
+
+public class GuiHandler implements IGuiHandler {
+
+ public static final int GUI_ID_ENDERFACE = 1;
+ public static final int GUI_ID_PAINTER = 2;
+ public static final int GUI_ID_STIRLING_GEN = 3;
+ public static final int GUI_ID_ALLOY_SMELTER = 4;
+
+ protected final Map guiHandlers = new HashMap();
+
+ public void registerGuiHandler(int id, IGuiHandler handler) {
+ guiHandlers.put(id, handler);
+ }
+
+ @Override
+ public Object getServerGuiElement(int id, EntityPlayer player, World world, int x, int y, int z) {
+ IGuiHandler handler = guiHandlers.get(id);
+ if(handler != null) {
+ return handler.getServerGuiElement(id, player, world, x, y, z);
+ }
+ return null;
+ }
+
+ @Override
+ public Object getClientGuiElement(int id, EntityPlayer player, World world, int x, int y, int z) {
+ IGuiHandler handler = guiHandlers.get(id);
+ if(handler != null) {
+ return handler.getClientGuiElement(id, player, world, x, y, z);
+ }
+ return null;
+ }
+
+}
diff --git a/common/crazypants/enderio/ModObject.java b/common/crazypants/enderio/ModObject.java
new file mode 100644
index 00000000..997e84cb
--- /dev/null
+++ b/common/crazypants/enderio/ModObject.java
@@ -0,0 +1,80 @@
+package crazypants.enderio;
+
+import static net.minecraftforge.common.Configuration.CATEGORY_BLOCK;
+import static net.minecraftforge.common.Configuration.CATEGORY_ITEM;
+import net.minecraftforge.common.Configuration;
+
+public enum ModObject {
+ // Enderface
+ blockEnderIo(++Config.BID, CATEGORY_BLOCK, "Ender IO"),
+ itemEnderface(++Config.IID, CATEGORY_ITEM, "Enderface"),
+
+ // Conduits
+ blockConduitBundle(++Config.BID, CATEGORY_BLOCK, "Conduit Bundle"),
+ blockConduitFacade(++Config.BID, CATEGORY_BLOCK, "Conduit Facade"),
+ itemConduitFacade(++Config.IID, CATEGORY_ITEM, "Conduit Facade"),
+ itemRedstoneConduit(++Config.IID, CATEGORY_ITEM, "Redstone Conduit"),
+
+ // Power
+ itemPowerConduit(++Config.IID, CATEGORY_ITEM, "Power Conduit"),
+
+ // Liquid
+ itemLiquidConduit(++Config.IID, CATEGORY_ITEM, "Liquid Conduit"),
+
+ // Materials
+ itemIndustrialBinder(++Config.IID, CATEGORY_ITEM, "Industrial Binder"),
+ itemBasicCapacitor(++Config.IID, CATEGORY_ITEM, "Basic Capacitor"),
+ itemAlloy(++Config.IID, CATEGORY_ITEM, "Alloy"),
+ blockFusedQuartz(++Config.BID, CATEGORY_BLOCK, "Fused Quartz"),
+
+ // Stirling Gen
+ blockStirlingGenerator(++Config.BID, CATEGORY_BLOCK, "Strirling Generator"),
+ blockReservoir(++Config.BID, CATEGORY_BLOCK, "Reservoir"),
+ blockAlloySmelter(++Config.BID, CATEGORY_BLOCK, "Alloy Smelter"),
+
+ // Painter
+ blockPainter(++Config.BID, CATEGORY_BLOCK, "Painter"),
+ blockCustomFence(++Config.BID, CATEGORY_BLOCK, "Fence"),
+ blockCustomFenceGate(++Config.BID, CATEGORY_BLOCK, "Gate"),
+ blockCustomWall(++Config.BID, CATEGORY_BLOCK, "Wall"),
+ blockCustomStair(++Config.BID, CATEGORY_BLOCK, "Stair"),
+ itemFusedQuartzFrame(++Config.IID, CATEGORY_ITEM, "Fused Quartz Frame"),
+
+ // Solar Panel
+ blockSolarPanel(++Config.BID, CATEGORY_BLOCK, "Photovoltaic Panel"),
+
+ blockElectricLight(++Config.BID, CATEGORY_BLOCK, "Electric Light"),
+
+ itemYetaWrench(++Config.IID, CATEGORY_ITEM, "Yeta Wrench");
+
+ public final String unlocalisedName;
+ public final String name;
+ public final int defaultId;
+ public final String category;
+ public int id;
+ public int actualId;
+
+ private ModObject(int defaultId, String category, String name) {
+ this.unlocalisedName = "enderIO:" + toString();
+ this.defaultId = defaultId;
+ this.name = name;
+ this.category = category;
+ id = -1;
+ actualId = -1;
+ }
+
+ void load(Configuration config) {
+ if (CATEGORY_ITEM.equals(category)) {
+ id = config.getItem(unlocalisedName, defaultId).getInt();
+ } else if (CATEGORY_BLOCK.equals(category)) {
+ id = config.getBlock(unlocalisedName, defaultId).getInt();
+ } else {
+ throw new RuntimeException("Unknown category " + category);
+ }
+ actualId = id;
+ if (CATEGORY_ITEM.equals(category)) {
+ actualId += 256;
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/common/crazypants/enderio/PacketHandler.java b/common/crazypants/enderio/PacketHandler.java
new file mode 100644
index 00000000..3bf27911
--- /dev/null
+++ b/common/crazypants/enderio/PacketHandler.java
@@ -0,0 +1,264 @@
+package crazypants.enderio;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.util.HashSet;
+import java.util.Set;
+
+import net.minecraft.entity.player.EntityPlayer;
+import net.minecraft.entity.player.EntityPlayerMP;
+import net.minecraft.inventory.ContainerBeacon;
+import net.minecraft.inventory.ContainerRepair;
+import net.minecraft.item.ItemInWorldManager;
+import net.minecraft.nbt.NBTTagCompound;
+import net.minecraft.network.INetworkManager;
+import net.minecraft.network.packet.Packet;
+import net.minecraft.network.packet.Packet100OpenWindow;
+import net.minecraft.network.packet.Packet250CustomPayload;
+import net.minecraft.server.MinecraftServer;
+import net.minecraft.tileentity.TileEntity;
+import net.minecraft.tileentity.TileEntityBeacon;
+import net.minecraft.world.World;
+import net.sf.cglib.proxy.Enhancer;
+import net.sf.cglib.proxy.MethodInterceptor;
+import net.sf.cglib.proxy.MethodProxy;
+import cpw.mods.fml.common.FMLCommonHandler;
+import cpw.mods.fml.common.network.IPacketHandler;
+import cpw.mods.fml.common.network.Player;
+import crazypants.enderio.enderface.ContainerWrapper;
+import crazypants.enderio.machine.AbstractMachineEntity;
+import crazypants.enderio.machine.RedstoneControlMode;
+import crazypants.util.PacketUtil;
+
+public class PacketHandler implements IPacketHandler {
+
+ public static int ID_ENDERFACE = 1;
+ private static final int ID_TILE_ENTITY = 4;
+ private static final int ID_MACHINE_REDSTONE_PACKET = 2;
+
+ private static final String CHANNEL = "EnderIO";
+
+
+ @Override
+ public void onPacketData(INetworkManager manager, Packet250CustomPayload packet, Player player) {
+ if (packet.data != null && packet.data.length <= 0) {
+ return;
+ }
+
+ DataInputStream data = new DataInputStream(new ByteArrayInputStream(packet.data));
+ try {
+ int id = data.readInt();
+ if (id == ID_ENDERFACE) {
+ handleEnderfacePacket(data, manager, player);
+ } else if(id == ID_TILE_ENTITY) {
+ PacketUtil.handleTileEntityPacket(false, data);
+ } else if(id == ID_MACHINE_REDSTONE_PACKET) {
+ handleRedstoneControlPacket(data, manager, player);
+ } else {
+ System.out.println("PacketHandler.onPacketData: Recieved packet of unknown type: " + id);
+ }
+ } catch (IOException ex) {
+ FMLCommonHandler.instance().raiseException(ex, "PacketHandler.onPacketData", true);
+ }
+ }
+
+
+
+ public static Packet getPacket(TileEntity te) {
+ return PacketUtil.createTileEntityPacket(CHANNEL, ID_TILE_ENTITY, te);
+ }
+
+ // ---------------- Redstone Control --------------------------------------------------------
+
+ private void handleRedstoneControlPacket(DataInputStream data, INetworkManager manager, Player player) throws IOException {
+ int x = data.readInt();
+ int y = data.readInt();
+ int z = data.readInt();
+ short ordinal = data.readShort();
+ EntityPlayerMP p = (EntityPlayerMP) player;
+ TileEntity te = p.worldObj.getBlockTileEntity(x, y, z);
+ if(te instanceof AbstractMachineEntity) {
+ AbstractMachineEntity me = (AbstractMachineEntity)te;
+ me.setRedstoneControlMode(RedstoneControlMode.values()[ordinal]);
+ p.worldObj.markBlockForUpdate(x, y, z);
+ }
+
+ }
+
+ public static Packet getRedstoneControlPacket(AbstractMachineEntity te) {
+ ByteArrayOutputStream bos = new ByteArrayOutputStream(140);
+ DataOutputStream dos = new DataOutputStream(bos);
+ try {
+ dos.writeInt(ID_MACHINE_REDSTONE_PACKET);
+ dos.writeInt(te.xCoord);
+ dos.writeInt(te.yCoord);
+ dos.writeInt(te.zCoord);
+ dos.writeShort((short)te.getRedstoneControlMode().ordinal());
+ } catch (IOException e) {
+ // never thrown
+ }
+
+ Packet250CustomPayload pkt = new Packet250CustomPayload();
+ pkt.channel = CHANNEL;
+ pkt.data = bos.toByteArray();
+ pkt.length = bos.size();
+ pkt.isChunkDataPacket = true;
+ return pkt;
+
+ }
+
+
+ // ---------------- Enderface
+ // ------------------------------------------------------------
+
+ public static Packet250CustomPayload getPacketEnderface(int x, int y, int z) {
+ ByteArrayOutputStream bos = new ByteArrayOutputStream(16);
+ DataOutputStream dos = new DataOutputStream(bos);
+ try {
+ dos.writeInt(ID_ENDERFACE);
+ dos.writeInt(x);
+ dos.writeInt(y);
+ dos.writeInt(z);
+ } catch (IOException e) {
+ // never thrown
+ }
+ Packet250CustomPayload pkt = new Packet250CustomPayload();
+ pkt.channel = CHANNEL;
+ pkt.data = bos.toByteArray();
+ pkt.length = bos.size();
+ pkt.isChunkDataPacket = true;
+ return pkt;
+ }
+
+ private void handleEnderfacePacket(DataInputStream data, INetworkManager manager, Player p) throws IOException {
+ if (!(p instanceof EntityPlayerMP)) {
+ System.out.println("kitchenbench.PacketHandler.handleEnderfacePacket: Not an EntityPlayerMP");
+ return;
+ }
+ int x = data.readInt();
+ int y = data.readInt();
+ int z = data.readInt();
+
+ EntityPlayerMP player = (EntityPlayerMP) p;
+ EntityPlayerMP proxy = createPlayerProxy(player);
+ player.theItemInWorldManager.activateBlockOrUseItem(proxy, player.worldObj, null, x, y, z, 0, 0, 0, 0);
+ player.theItemInWorldManager.thisPlayerMP = player;
+
+ }
+
+ public static T createPlayerProxy(EntityPlayerMP player) {
+ Enhancer e = new Enhancer();
+ e.setCallback(new PlayerProxy(player));
+
+ e.setSuperclass(player.getClass());
+ Class>[] argTypes = new Class[] { MinecraftServer.class, World.class, String.class, ItemInWorldManager.class };
+ Object[] args = new Object[] { player.mcServer, player.worldObj, player.username, player.theItemInWorldManager };
+
+ e.setInterceptDuringConstruction(false);
+ @SuppressWarnings("unchecked")
+ T proxifiedObj = (T) e.create(argTypes, args);
+
+ return proxifiedObj;
+ }
+
+ public static class PlayerProxy implements MethodInterceptor {
+
+ private EntityPlayerMP realObj;
+
+ private Set interceptNames = new HashSet();
+
+ private Set beaconNames = new HashSet();
+ private Set anvilNames = new HashSet();
+
+ public PlayerProxy(EntityPlayerMP obj) {
+ // TODO: Move to config?
+ this.realObj = obj;
+ interceptNames.add("openGui");
+
+ interceptNames.add("displayGUIBrewingStand");
+ interceptNames.add("func_71017_a");
+
+ interceptNames.add("displayGUIChest");
+ interceptNames.add("func_71007_a");
+
+ interceptNames.add("displayGUIDispenser");
+ interceptNames.add("func_71006_a");
+
+ interceptNames.add("displayGUIEnchantment");
+ interceptNames.add("func_71002_c");
+
+ interceptNames.add("displayGUIFurnace");
+ interceptNames.add("func_71042_a");
+
+ interceptNames.add("displayGUIWorkbench");
+ interceptNames.add("func_71058_b");
+
+ interceptNames.add("displayGuiHopper"); // for when its added
+ interceptNames.add("func_94064_a"); // displayGuiHopper
+
+ interceptNames.add("displayGUIHopper");
+
+ beaconNames.add("displayGUIBeacon");
+ beaconNames.add("func_82240_a");
+
+ anvilNames.add("displayGUIAnvil");
+ anvilNames.add("func_82244_d");
+
+
+ }
+
+ @Override
+ public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
+ if (interceptNames.contains(method.getName())) {
+
+ Object res = method.invoke(realObj, objects);
+ if (realObj.openContainer != null) {
+ realObj.openContainer = new ContainerWrapper(realObj.openContainer);
+ }
+ return res;
+
+ } else if (beaconNames.contains(method.getName())) {
+
+ // Beacon needs to be done manually for some reason to work properly
+ TileEntityBeacon par1TileEntityBeacon = (TileEntityBeacon) objects[0];
+ realObj.incrementWindowID();
+ realObj.playerNetServerHandler.sendPacketToPlayer(new Packet100OpenWindow(realObj.currentWindowId, 7, par1TileEntityBeacon.getInvName(),
+ par1TileEntityBeacon.getSizeInventory(), par1TileEntityBeacon.isInvNameLocalized()));
+ realObj.openContainer = new ContainerBeacon(realObj.inventory, par1TileEntityBeacon) {
+ @Override
+ public boolean canInteractWith(EntityPlayer par1EntityPlayer) {
+ return true;
+ }
+ };
+ realObj.openContainer.windowId = realObj.currentWindowId;
+ realObj.openContainer.addCraftingToCrafters(realObj);
+ return null;
+
+ } else if (anvilNames.contains(method.getName())) {
+
+ realObj.incrementWindowID();
+ realObj.playerNetServerHandler.sendPacketToPlayer(new Packet100OpenWindow(realObj.currentWindowId, 8, "Repairing", 9, true));
+ realObj.openContainer = new ContainerRepair(realObj.inventory, realObj.worldObj, ((Integer)objects[0]).intValue(), ((Integer)objects[1]).intValue(), ((Integer)objects[2]).intValue(), realObj) {
+ @Override
+ public boolean canInteractWith(EntityPlayer par1EntityPlayer) {
+ return true;
+ }
+ };
+ realObj.openContainer.windowId = realObj.currentWindowId;
+ realObj.openContainer.addCraftingToCrafters(realObj);
+ return null;
+
+ } else if(method.getName().equals("getDistanceSq")) { //for forestry
+ return 6;
+ }
+ method.setAccessible(true);
+ return method.invoke(realObj, objects);
+ }
+
+ }
+
+}
diff --git a/common/crazypants/enderio/ServerTickHandler.java b/common/crazypants/enderio/ServerTickHandler.java
new file mode 100644
index 00000000..9494caff
--- /dev/null
+++ b/common/crazypants/enderio/ServerTickHandler.java
@@ -0,0 +1,81 @@
+package crazypants.enderio;
+
+import java.lang.ref.WeakReference;
+import java.util.ArrayList;
+import java.util.EnumSet;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+import cpw.mods.fml.common.ITickHandler;
+import cpw.mods.fml.common.TickType;
+
+public class ServerTickHandler implements ITickHandler {
+
+ private static final EnumSet TICKS = EnumSet.of(TickType.SERVER);
+
+ private final List> listeners = new CopyOnWriteArrayList>();
+
+ public void addListener(TickListener listener) {
+ listeners.add(new WeakReference(listener));
+ }
+
+ public void removeListener(TickListener listener) {
+ WeakReference toRemove = null;
+ for(WeakReference ref : listeners) {
+ if(ref.get() == listener) {
+ toRemove = ref;
+ break;
+ }
+ }
+ if(toRemove != null) {
+ listeners.remove(toRemove);
+ }
+ }
+
+
+ @Override
+ public void tickStart(EnumSet type, Object... tickData) {
+ List lists = processListeners();
+ for(TickListener listener : lists) {
+ listener.tickStart(type, tickData);
+ }
+ }
+
+ @Override
+ public void tickEnd(EnumSet type, Object... tickData) {
+ List lists = processListeners();
+ for(TickListener listener : lists) {
+ listener.tickEnd(type, tickData);
+ }
+ }
+
+ private List processListeners() {
+ List result = new ArrayList(listeners.size());
+ List> toRemove = new ArrayList>();
+ for(WeakReference ref : listeners) {
+ TickListener l = ref.get();
+ if(l == null) {
+ toRemove.add(ref);
+ } else {
+ result.add(l);
+ }
+ }
+ return result;
+ }
+
+ public void serverStopped() {
+ listeners.clear();
+ }
+
+ @Override
+ public EnumSet ticks() {
+ return TICKS;
+ }
+
+ @Override
+ public String getLabel() {
+ return "EnderIO Server Tick Handler";
+ }
+
+
+}
diff --git a/common/crazypants/enderio/TickListener.java b/common/crazypants/enderio/TickListener.java
new file mode 100644
index 00000000..3f40b8c0
--- /dev/null
+++ b/common/crazypants/enderio/TickListener.java
@@ -0,0 +1,13 @@
+package crazypants.enderio;
+
+import java.util.EnumSet;
+
+import cpw.mods.fml.common.TickType;
+
+public interface TickListener {
+
+ void tickStart(EnumSet type, Object... tickData);
+
+ void tickEnd(EnumSet type, Object... tickData);
+
+}
diff --git a/common/crazypants/enderio/Tst.java b/common/crazypants/enderio/Tst.java
new file mode 100644
index 00000000..35b49ba6
--- /dev/null
+++ b/common/crazypants/enderio/Tst.java
@@ -0,0 +1,22 @@
+package crazypants.enderio;
+
+import crazypants.vecmath.Matrix4d;
+import crazypants.vecmath.VecmathUtil;
+import crazypants.vecmath.Vector3d;
+
+
+public class Tst {
+
+
+ /**
+ * @param args
+ */
+ public static void main(String[] args) {
+ }
+
+
+
+
+
+
+}
diff --git a/common/crazypants/enderio/conduit/AbstractConduit.java b/common/crazypants/enderio/conduit/AbstractConduit.java
new file mode 100644
index 00000000..974c2ef4
--- /dev/null
+++ b/common/crazypants/enderio/conduit/AbstractConduit.java
@@ -0,0 +1,368 @@
+package crazypants.enderio.conduit;
+
+import java.util.*;
+
+import crazypants.enderio.EnderIO;
+import crazypants.enderio.conduit.geom.*;
+import crazypants.enderio.conduit.geom.CollidableCache.CacheKey;
+import crazypants.util.BlockCoord;
+
+import net.minecraft.entity.player.EntityPlayer;
+import net.minecraft.nbt.NBTTagCompound;
+import net.minecraft.tileentity.TileEntity;
+import net.minecraft.world.World;
+import net.minecraftforge.common.ForgeDirection;
+
+public abstract class AbstractConduit implements IConduit {
+
+ protected final Set conduitConnections = new HashSet();
+
+ protected final Set externalConnections = new HashSet();
+
+ public static final float STUB_WIDTH = 0.2f;
+
+ public static final float STUB_HEIGHT = 0.2f;
+
+ public static final float TRANSMISSION_SCALE = 0.3f;
+
+ // NB: This is a transient field controlled by the owning bundle. It is not
+ // written to the NBT etc
+ protected IConduitBundle bundle;
+
+ protected boolean active;
+
+ protected List collidables;
+
+ protected boolean collidablesDirty = true;
+
+ private boolean clientStateDirty = true;
+
+ private boolean dodgyChangeSinceLastCallFlagForBundle = true;
+
+ protected AbstractConduit() {
+ }
+
+ private int lastNumConections = -1;
+
+ @Override
+ public boolean haveCollidablesChangedSinceLastCall() {
+ if(dodgyChangeSinceLastCallFlagForBundle) {
+ dodgyChangeSinceLastCallFlagForBundle = false;
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public BlockCoord getLocation() {
+ if (bundle == null) {
+ return null;
+ }
+ TileEntity te = bundle.getEntity();
+ if (te == null) {
+ return null;
+ }
+ return new BlockCoord(te.xCoord, te.yCoord, te.zCoord);
+ }
+
+ @Override
+ public void setBundle(IConduitBundle tileConduitBundle) {
+ bundle = tileConduitBundle;
+ }
+
+ @Override
+ public IConduitBundle getBundle() {
+ return bundle;
+ }
+
+ // Connections
+ @Override
+ public Set getConduitConnections() {
+ return conduitConnections;
+ }
+
+ @Override
+ public boolean containsConduitConnection(ForgeDirection dir) {
+ return conduitConnections.contains(dir);
+ }
+
+ @Override
+ public void conduitConnectionAdded(ForgeDirection fromDirection) {
+ conduitConnections.add(fromDirection);
+ connectionsChanged();
+ }
+
+ @Override
+ public void conduitConnectionRemoved(ForgeDirection fromDirection) {
+ conduitConnections.remove(fromDirection);
+ connectionsChanged();
+ }
+
+ @Override
+ public boolean canConnectToConduit(ForgeDirection direction, IConduit conduit) {
+ return true;
+ }
+
+ @Override
+ public boolean canConnectToExternal(ForgeDirection direction) {
+ return false;
+ }
+
+ @Override
+ public Set getExternalConnections() {
+ return externalConnections;
+ }
+
+ @Override
+ public boolean containsExternalConnection(ForgeDirection dir) {
+ return externalConnections.contains(dir);
+ }
+
+ @Override
+ public void externalConnectionAdded(ForgeDirection fromDirection) {
+ externalConnections.add(fromDirection);
+ connectionsChanged();
+ }
+
+ @Override
+ public void externalConnectionRemoved(ForgeDirection fromDirection) {
+ externalConnections.remove(fromDirection);
+ connectionsChanged();
+ }
+
+ @Override
+ public boolean isConnectedTo(ForgeDirection dir) {
+ return containsConduitConnection(dir) || containsExternalConnection(dir);
+ }
+
+ @Override
+ public boolean isActive() {
+ return active;
+ }
+
+ @Override
+ public void setActive(boolean active) {
+ if(active != this.active) {
+ clientStateDirty = true;
+ }
+ this.active = active;
+ }
+
+ @Override
+ public void writeToNBT(NBTTagCompound nbtRoot) {
+ int[] dirs = new int[conduitConnections.size()];
+ Iterator cons = conduitConnections.iterator();
+ for (int i = 0; i < dirs.length; i++) {
+ dirs[i] = cons.next().ordinal();
+ }
+ nbtRoot.setIntArray("connections", dirs);
+
+ dirs = new int[externalConnections.size()];
+ cons = externalConnections.iterator();
+ for (int i = 0; i < dirs.length; i++) {
+ dirs[i] = cons.next().ordinal();
+ }
+ nbtRoot.setIntArray("externalConnections", dirs);
+ nbtRoot.setBoolean("signalActive", active);
+ }
+
+ @Override
+ public void readFromNBT(NBTTagCompound nbtRoot) {
+ conduitConnections.clear();
+ int[] dirs = nbtRoot.getIntArray("connections");
+ for (int i = 0; i < dirs.length; i++) {
+ conduitConnections.add(ForgeDirection.values()[dirs[i]]);
+ }
+
+ externalConnections.clear();
+ dirs = nbtRoot.getIntArray("externalConnections");
+ for (int i = 0; i < dirs.length; i++) {
+ externalConnections.add(ForgeDirection.values()[dirs[i]]);
+ }
+ active = nbtRoot.getBoolean("signalActive");
+ //collidablesDirty = true;
+ }
+
+ @Override
+ public int getLightValue() {
+ return 0;
+ }
+
+ @Override
+ public boolean onBlockActivated(EntityPlayer player, RaytraceResult res) {
+ return false;
+ }
+
+ @Override
+ public float getSelfIlluminationForState(CollidableComponent component) {
+ return isActive() ? 1 : 0;
+ }
+
+ @Override
+ public float getTransmitionGeometryScale() {
+ return TRANSMISSION_SCALE;
+ }
+
+ @Override
+ public void onChunkUnload(World worldObj) {
+ AbstractConduitNetwork> network = getNetwork();
+ if (network != null) {
+ System.out.println("AbstractConduit.onChunkUnload: Destroyed network on chunk unload.");
+ network.destroyNetwork();
+ }
+ }
+
+ @Override
+ public void updateEntity(World world) {
+ if (world.isRemote) {
+ return;
+ }
+ updateNetwork(world);
+
+ if(clientStateDirty) {
+ getBundle().dirty();
+ clientStateDirty = false;
+ }
+ }
+
+
+ protected void connectionsChanged() {
+ collidablesDirty = true;
+ clientStateDirty = true;
+ dodgyChangeSinceLastCallFlagForBundle = true;
+ }
+
+ protected void updateNetwork(World world) {
+ if (getNetwork() == null) {
+ ConduitUtil.ensureValidNetwork(this);
+ }
+ getNetwork().onUpdateEntity(this);
+ }
+
+ @Override
+ public void onAddedToBundle() {
+
+ TileEntity te = bundle.getEntity();
+ World world = te.worldObj;
+
+ conduitConnections.clear();
+ for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) {
+ IConduit neighbour = ConduitUtil.getConduit(world, te, dir, getBaseConduitType());
+ if (neighbour != null && neighbour.canConnectToConduit(dir.getOpposite(), this)) {
+ conduitConnections.add(dir);
+ neighbour.conduitConnectionAdded(dir.getOpposite());
+ }
+ }
+
+ externalConnections.clear();
+ for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) {
+ if (!containsConduitConnection(dir) && canConnectToExternal(dir)) {
+ externalConnectionAdded(dir);
+ }
+ }
+
+ connectionsChanged();
+ }
+
+ @Override
+ public void onRemovedFromBundle() {
+ TileEntity te = bundle.getEntity();
+ World world = te.worldObj;
+
+ for (ForgeDirection dir : conduitConnections) {
+ IConduit neighbour = ConduitUtil.getConduit(world, te, dir, getBaseConduitType());
+ if (neighbour != null) {
+ neighbour.conduitConnectionRemoved(dir.getOpposite());
+ }
+ }
+ conduitConnections.clear();
+
+ if (!externalConnections.isEmpty()) {
+ world.notifyBlocksOfNeighborChange(te.xCoord, te.yCoord, te.zCoord, EnderIO.blockConduitBundle.blockID);
+ }
+ externalConnections.clear();
+
+ AbstractConduitNetwork> network = getNetwork();
+ if (network != null) {
+ network.destroyNetwork();
+ }
+ connectionsChanged();
+ }
+
+ @Override
+ public boolean onNeighborBlockChange(int blockId) {
+ // Check for changes to external connections, connections to conduits are
+ // handled by the bundle
+
+ //NB: No need to check externals if the neighbour that changed was a conduit bundle as this
+ //can't effect external connections.
+ if(blockId == EnderIO.blockConduitBundle.blockID) {
+ return false;
+ }
+
+ boolean externalConnectionsChanged = false;
+ List copy = new ArrayList(externalConnections);
+ // remove any no longer valid connections
+ for (ForgeDirection dir : copy) {
+ if (!canConnectToExternal(dir)) {
+ externalConnectionRemoved(dir);
+ externalConnectionsChanged = true;
+ }
+ }
+
+ // then check for new ones
+ for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) {
+ if (!conduitConnections.contains(dir) && !externalConnections.contains(dir)) {
+ if (canConnectToExternal(dir)) {
+ externalConnectionAdded(dir);
+ externalConnectionsChanged = true;
+ }
+ }
+ }
+ if (externalConnectionsChanged) {
+ connectionsChanged();
+ }
+ return externalConnectionsChanged;
+ }
+
+ @Override
+ public Collection createCollidables(CacheKey key) {
+ return Collections.singletonList(new CollidableComponent(getBaseConduitType(),ConduitGeometryUtil.instance.getBoundingBox(getBaseConduitType(), key.dir, key.isStub, key.offset),key.dir,null));
+ }
+
+ @Override
+ public List getCollidableComponents() {
+
+ if (collidables != null && !collidablesDirty) {
+ return collidables;
+ }
+
+ List result = new ArrayList();
+ CollidableCache cc = CollidableCache.instance;
+
+ for(ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) {
+ Collection col = getCollidables(dir);
+ if(col != null) {
+ result.addAll(col);
+ }
+ }
+ collidables = result;
+
+ collidablesDirty = false;
+
+ return result;
+ }
+
+
+ private Collection getCollidables(ForgeDirection dir) {
+ CollidableCache cc = CollidableCache.instance;
+ Class extends IConduit> type = getBaseConduitType();
+
+ if (isConnectedTo(dir)) {
+ return cc.getCollidables(cc.createKey(type, getBundle().getOffset(type, dir), dir, false), this);
+ }
+ return null;
+ }
+
+
+}
diff --git a/common/crazypants/enderio/conduit/AbstractConduitNetwork.java b/common/crazypants/enderio/conduit/AbstractConduitNetwork.java
new file mode 100644
index 00000000..2f3b89c3
--- /dev/null
+++ b/common/crazypants/enderio/conduit/AbstractConduitNetwork.java
@@ -0,0 +1,84 @@
+package crazypants.enderio.conduit;
+
+import java.util.*;
+
+import net.minecraft.tileentity.TileEntity;
+import net.minecraft.world.World;
+
+public abstract class AbstractConduitNetwork {
+
+ protected final List conduits = new ArrayList();
+
+ protected AbstractConduitNetwork() {
+ }
+
+ public void init(IConduitBundle tile, Collection connections, World world) {
+
+ if (world.isRemote) {
+ throw new UnsupportedOperationException();
+ }
+
+ // Destroy all existing redstone networks around this block
+ for (T con : connections) {
+ AbstractConduitNetwork> network = con.getNetwork();
+ if (network != null) {
+ network.destroyNetwork();
+ }
+ }
+ setNetwork(world, tile);
+ notifyNetworkOfUpdate();
+ }
+
+ public abstract Class extends T> getBaseConduitType();
+
+ protected void setNetwork(World world, IConduitBundle tile) {
+
+ T conduit = tile.getConduit(getBaseConduitType());
+ if (conduit.setNetwork(this)) {
+ addConduit(conduit);
+ TileEntity te = tile.getEntity();
+ Collection extends T> connections = ConduitUtil.getConnectedConduits(world, te.xCoord, te.yCoord, te.zCoord, getBaseConduitType());
+ for (T con : connections) {
+ if (con.getNetwork() == null) {
+ setNetwork(world, con.getBundle());
+ }
+ }
+ }
+ }
+
+ public void addConduit(T con) {
+ conduits.add(con);
+ }
+
+ public void destroyNetwork() {
+ for (T con : conduits) {
+ con.setNetwork(null);
+ }
+ conduits.clear();
+ }
+
+ public List getConduits() {
+ return conduits;
+ }
+
+ public void notifyNetworkOfUpdate() {
+ for (T con : conduits) {
+ TileEntity te = con.getBundle().getEntity();
+ te.worldObj.markBlockForUpdate(te.xCoord, te.yCoord, te.zCoord);
+ }
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ for (IConduit con : conduits) {
+ sb.append(con.getLocation());
+ sb.append(", ");
+ }
+ return "AbstractConduitNetwork [conduits=" + sb.toString() + "]";
+ }
+
+ public void onUpdateEntity(IConduit conduit) {
+ }
+
+}
diff --git a/common/crazypants/enderio/conduit/AbstractItemConduit.java b/common/crazypants/enderio/conduit/AbstractItemConduit.java
new file mode 100644
index 00000000..1e23d2fa
--- /dev/null
+++ b/common/crazypants/enderio/conduit/AbstractItemConduit.java
@@ -0,0 +1,121 @@
+package crazypants.enderio.conduit;
+
+import java.util.List;
+
+import net.minecraft.client.renderer.texture.IconRegister;
+import net.minecraft.creativetab.CreativeTabs;
+import net.minecraft.entity.player.EntityPlayer;
+import net.minecraft.item.*;
+import net.minecraft.util.Icon;
+import net.minecraft.util.MathHelper;
+import net.minecraft.world.World;
+import net.minecraftforge.common.ForgeDirection;
+import cpw.mods.fml.common.registry.*;
+import crazypants.enderio.*;
+import crazypants.enderio.material.Alloy;
+
+public abstract class AbstractItemConduit extends Item implements IConduitItem {
+
+ protected ModObject modObj;
+
+ protected ItemConduitSubtype[] subtypes;
+
+ protected Icon[] icons;
+
+ protected AbstractItemConduit(ModObject modObj) {
+ super(modObj.id);
+ this.modObj = modObj;
+ setCreativeTab(EnderIOTab.tabEnderIO);
+ setUnlocalizedName(modObj.unlocalisedName);
+ setMaxStackSize(64);
+ setHasSubtypes(true);
+ }
+
+ protected void init(ItemConduitSubtype[] subtypes) {
+ this.subtypes = subtypes;
+ icons = new Icon[subtypes.length];
+
+ LanguageRegistry.addName(this, modObj.name);
+ GameRegistry.registerItem(this, modObj.unlocalisedName);
+ for(ItemConduitSubtype subtype : subtypes) {
+ LanguageRegistry.instance().addStringLocalization(getUnlocalizedName() + "." + subtype.unlocalisedName + ".name", subtype.uiName);
+ }
+
+ }
+
+ @Override
+ public void registerIcons(IconRegister iconRegister) {
+ int index = 0;
+ for(ItemConduitSubtype subtype : subtypes) {
+ icons[index] = iconRegister.registerIcon(subtype.iconKey);
+ index++;
+ }
+ }
+
+ @Override
+ public boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) {
+
+ ForgeDirection dir = ForgeDirection.values()[side];
+ int placeX = x + dir.offsetX;
+ int placeY = y + dir.offsetY;
+ int placeZ = z + dir.offsetZ;
+
+ int blockID = world.getBlockId(placeX, placeY, placeZ);
+ if (blockID == 0) {
+ if(!world.isRemote) {
+ if(world.setBlock(placeX, placeY, placeZ, ModObject.blockConduitBundle.actualId,0,1)) {
+ IConduitBundle bundle = (IConduitBundle) world.getBlockTileEntity(placeX, placeY, placeZ);
+ bundle.addConduit(createConduit(stack));
+ }
+ }
+ if (!player.capabilities.isCreativeMode) {
+ stack.stackSize--;
+ }
+ return true;
+ } else if(blockID == ModObject.blockConduitBundle.actualId) {
+
+ IConduitBundle bundle = (TileConduitBundle)world.getBlockTileEntity(placeX, placeY, placeZ);
+ if(bundle == null) {
+ System.out.println("AbstractItemConduit.onItemUse: Bunle null");
+ return false;
+ }
+ IConduit con = createConduit(stack);
+ if(con == null) {
+ System.out.println("AbstractItemConduit.onItemUse: Conduit null.");
+ return false;
+ }
+ if(bundle.getConduit(con.getBaseConduitType()) == null) {
+ if(!world.isRemote) {
+ bundle.addConduit(con);
+ }
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+
+ @Override
+ public Icon getIconFromDamage(int damage) {
+ damage = MathHelper.clamp_int(damage, 0, subtypes.length);
+ return icons[damage];
+ }
+
+
+ @Override
+ public String getUnlocalizedName(ItemStack par1ItemStack) {
+ int i = MathHelper.clamp_int(par1ItemStack.getItemDamage(), 0, subtypes.length);
+ return super.getUnlocalizedName() + "." + subtypes[i].unlocalisedName;
+
+ }
+
+ @Override
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ public void getSubItems(int par1, CreativeTabs par2CreativeTabs, List par3List) {
+ for (int j = 0; j < subtypes.length; ++j) {
+ par3List.add(new ItemStack(par1, 1, j));
+ }
+ }
+
+}
diff --git a/common/crazypants/enderio/conduit/BlockConduitBundle.java b/common/crazypants/enderio/conduit/BlockConduitBundle.java
new file mode 100644
index 00000000..94ebb740
--- /dev/null
+++ b/common/crazypants/enderio/conduit/BlockConduitBundle.java
@@ -0,0 +1,601 @@
+package crazypants.enderio.conduit;
+
+import static net.minecraftforge.common.ForgeDirection.getOrientation;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Random;
+
+import net.minecraft.block.Block;
+import net.minecraft.block.ITileEntityProvider;
+import net.minecraft.block.material.Material;
+import net.minecraft.client.Minecraft;
+import net.minecraft.client.particle.EffectRenderer;
+import net.minecraft.client.particle.EntityDiggingFX;
+import net.minecraft.client.renderer.texture.IconRegister;
+import net.minecraft.entity.Entity;
+import net.minecraft.entity.player.EntityPlayer;
+import net.minecraft.entity.player.EntityPlayerMP;
+import net.minecraft.item.ItemStack;
+import net.minecraft.tileentity.TileEntity;
+import net.minecraft.util.AxisAlignedBB;
+import net.minecraft.util.Icon;
+import net.minecraft.util.MovingObjectPosition;
+import net.minecraft.util.Vec3;
+import net.minecraft.world.IBlockAccess;
+import net.minecraft.world.World;
+import net.minecraftforge.common.ForgeDirection;
+import buildcraft.api.tools.IToolWrench;
+import cpw.mods.fml.common.registry.GameRegistry;
+import cpw.mods.fml.common.registry.LanguageRegistry;
+import cpw.mods.fml.relauncher.Side;
+import cpw.mods.fml.relauncher.SideOnly;
+import crazypants.enderio.EnderIO;
+import crazypants.enderio.ModObject;
+import crazypants.enderio.conduit.geom.CollidableComponent;
+import crazypants.enderio.conduit.geom.ConduitConnectorType;
+import crazypants.enderio.conduit.liquid.LiquidConduit;
+import crazypants.enderio.conduit.power.PowerConduit;
+import crazypants.enderio.conduit.redstone.IRedstoneConduit;
+import crazypants.enderio.conduit.redstone.RedstoneConduit;
+import crazypants.enderio.conduit.redstone.RedstoneSwitch;
+import crazypants.enderio.machine.painter.PainterUtil;
+import crazypants.render.BoundingBox;
+
+public class BlockConduitBundle extends Block implements ITileEntityProvider {
+
+ // private static final String KEY_BLOCK_ICON = "enderio:conduitBundle";
+
+ private static final String KEY_CONNECTOR_ICON = "enderIO:conduitConnector";
+
+ public static BlockConduitBundle create() {
+ BlockConduitBundle result = new BlockConduitBundle();
+ result.init();
+ return result;
+ }
+
+ public static int rendererId = -1;
+
+ private Icon connectorIcon;
+
+ private Icon lastRemovedComponetIcon = null;
+
+ private Random rand = new Random();
+
+ protected BlockConduitBundle() {
+ super(ModObject.blockConduitBundle.id, Material.ground);
+ setHardness(0.5F);
+ setBlockBounds(0.334f, 0.334f, 0.334f, 0.667f, 0.667f, 0.667f);
+ setStepSound(Block.soundStoneFootstep);
+ setUnlocalizedName(ModObject.blockConduitBundle.unlocalisedName);
+ setCreativeTab(null);
+
+ RedstoneConduit.initIcons();
+ RedstoneSwitch.initIcons();
+ PowerConduit.initIcons();
+ LiquidConduit.initIcons();
+
+ }
+
+ // public float getPlayerRelativeBlockHardness(EntityPlayer par1EntityPlayer,
+ // World par2World, int par3, int par4, int par5)
+
+ @Override
+ public boolean addBlockHitEffects(World world, MovingObjectPosition target, EffectRenderer effectRenderer) {
+ Icon tex = null;
+
+ TileConduitBundle cb = (TileConduitBundle) world.getBlockTileEntity(target.blockX, target.blockY, target.blockZ);
+ if (ConduitUtil.renderFacade(cb, Minecraft.getMinecraft().thePlayer)) {
+ if (cb.getFacadeId() > 0) {
+ tex = Block.blocksList[cb.getFacadeId()].getIcon(target.sideHit, cb.getFacadeMetadata());
+ }
+ } else if (target.hitInfo instanceof CollidableComponent) {
+ CollidableComponent cc = (CollidableComponent) target.hitInfo;
+ IConduit con = cb.getConduit(cc.conduitType);
+ if (con != null) {
+ tex = con.getTextureForState(cc);
+ }
+ }
+ if (tex == null) {
+ tex = blockIcon;
+ }
+ lastRemovedComponetIcon = tex;
+ addBlockHitEffects(world, effectRenderer, target.blockX, target.blockY, target.blockZ, target.sideHit, tex);
+ return true;
+ }
+
+ @Override
+ @SideOnly(Side.CLIENT)
+ public boolean addBlockDestroyEffects(World world, int x, int y, int z, int meta, EffectRenderer effectRenderer) {
+ Icon tex = lastRemovedComponetIcon;
+ byte b0 = 4;
+ for (int j1 = 0; j1 < b0; ++j1) {
+ for (int k1 = 0; k1 < b0; ++k1) {
+ for (int l1 = 0; l1 < b0; ++l1) {
+ double d0 = x + (j1 + 0.5D) / b0;
+ double d1 = y + (k1 + 0.5D) / b0;
+ double d2 = z + (l1 + 0.5D) / b0;
+ int i2 = this.rand.nextInt(6);
+ EntityDiggingFX fx = new EntityDiggingFX(world, d0, d1, d2, d0 - x - 0.5D, d1 - y - 0.5D, d2 - z - 0.5D, this, i2, 0).applyColourMultiplier(x, y, z);
+ fx.func_110125_a(tex);
+ effectRenderer.addEffect(fx);
+ }
+ }
+ }
+ return true;
+
+ }
+
+ @SideOnly(Side.CLIENT)
+ private void addBlockHitEffects(World world, EffectRenderer effectRenderer, int x, int y, int z, int side, Icon tex) {
+ float f = 0.1F;
+ double d0 = x + rand.nextDouble() * (getBlockBoundsMaxX() - getBlockBoundsMinX() - f * 2.0F) + f + getBlockBoundsMinX();
+ double d1 = y + rand.nextDouble() * (getBlockBoundsMaxY() - getBlockBoundsMinY() - f * 2.0F) + f + getBlockBoundsMinY();
+ double d2 = z + rand.nextDouble() * (getBlockBoundsMaxZ() - getBlockBoundsMinZ() - f * 2.0F) + f + getBlockBoundsMinZ();
+ if (side == 0) {
+ d1 = y + getBlockBoundsMinY() - f;
+ } else if (side == 1) {
+ d1 = y + getBlockBoundsMaxY() + f;
+ } else if (side == 2) {
+ d2 = z + getBlockBoundsMinZ() - f;
+ } else if (side == 3) {
+ d2 = z + getBlockBoundsMaxZ() + f;
+ } else if (side == 4) {
+ d0 = x + getBlockBoundsMinX() - f;
+ } else if (side == 5) {
+ d0 = x + getBlockBoundsMaxX() + f;
+ }
+ EntityDiggingFX digFX = new EntityDiggingFX(world, d0, d1, d2, 0.0D, 0.0D, 0.0D, this, side, 0);
+ digFX.applyColourMultiplier(x, y, z).multiplyVelocity(0.2F).multipleParticleScaleBy(0.6F);
+ digFX.func_110125_a(tex);
+ effectRenderer.addEffect(digFX);
+ }
+
+ private void init() {
+ LanguageRegistry.addName(this, ModObject.blockConduitBundle.name);
+ GameRegistry.registerBlock(this, ModObject.blockConduitBundle.unlocalisedName);
+ GameRegistry.registerTileEntity(TileConduitBundle.class, ModObject.blockConduitBundle.unlocalisedName + "TileEntity");
+ }
+
+ @Override
+ public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) {
+ if (target != null && target.hitInfo instanceof CollidableComponent) {
+ CollidableComponent cc = (CollidableComponent) target.hitInfo;
+ TileConduitBundle bundle = (TileConduitBundle) world.getBlockTileEntity(x, y, z);
+ IConduit conduit = bundle.getConduit(cc.conduitType);
+ if (conduit != null) {
+ return conduit.createItem();
+ } else if(cc.conduitType == null && bundle.getFacadeId() > 0) {
+ //use the facde
+ ItemStack fac = new ItemStack(ModObject.itemConduitFacade.actualId, 1, 0);
+ PainterUtil.setSourceBlock(fac, bundle.getFacadeId(), bundle.getFacadeMetadata());
+ return fac;
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public int getDamageValue(World world, int x, int y, int z) {
+ TileEntity te = world.getBlockTileEntity(x, y, z);
+ if (!(te instanceof IConduitBundle)) {
+ return 0;
+ }
+ IConduitBundle bun = (IConduitBundle) te;
+ return bun.getFacadeId() > 0 ? bun.getFacadeMetadata() : 0;
+ }
+
+
+ @Override
+ public int idDropped(int par1, Random par2Random, int par3) {
+ return 0;
+ }
+
+ @Override
+ public int quantityDropped(Random r) {
+ return 0;
+ }
+
+ public Icon getConnectorIcon() {
+ return connectorIcon;
+ }
+
+ @Override
+ public void registerIcons(IconRegister iconRegister) {
+ connectorIcon = iconRegister.registerIcon(KEY_CONNECTOR_ICON);
+ blockIcon = connectorIcon;
+ }
+
+ @Override
+ public boolean isBlockSolidOnSide(World world, int x, int y, int z, ForgeDirection side) {
+ TileEntity te = world.getBlockTileEntity(x, y, z);
+ if (!(te instanceof IConduitBundle)) {
+ return false;
+ }
+ IConduitBundle con = (IConduitBundle) te;
+ if (con.getFacadeId() > 0) {
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public boolean isOpaqueCube() {
+ return false;
+ }
+
+ @Override
+ public int getRenderType() {
+ return rendererId;
+ }
+
+ @Override
+ public boolean renderAsNormalBlock() {
+ return false;
+ }
+
+ @Override
+ public TileEntity createNewTileEntity(World world) {
+ return null;
+ }
+
+ @Override
+ public TileEntity createTileEntity(World world, int metadata) {
+ return new TileConduitBundle();
+ }
+
+ @Override
+ public int getLightValue(IBlockAccess world, int x, int y, int z) {
+ TileEntity te = world.getBlockTileEntity(x, y, z);
+ if (!(te instanceof IConduitBundle)) {
+ return super.getLightValue(world, x, y, z);
+ }
+ IConduitBundle con = (IConduitBundle) te;
+ if (con.getFacadeId() > 0) {
+ return 0;
+ }
+ Collection conduits = con.getConduits();
+ int result = 0;
+ for (IConduit conduit : conduits) {
+ result += conduit.getLightValue();
+ }
+ return result;
+ }
+
+ @Override
+ public int isProvidingStrongPower(IBlockAccess world, int x, int y, int z, int par5) {
+ TileEntity te = world.getBlockTileEntity(x, y, z);
+ if (!(te instanceof IConduitBundle)) {
+ return 0;
+ }
+ IConduitBundle bundle = (IConduitBundle) te;
+ IRedstoneConduit con = bundle.getConduit(IRedstoneConduit.class);
+ if (con == null) {
+ return 0;
+ }
+ return con.isProvidingStrongPower(getOrientation(par5));
+ }
+
+ @Override
+ public int isProvidingWeakPower(IBlockAccess world, int x, int y, int z, int par5) {
+ TileEntity te = world.getBlockTileEntity(x, y, z);
+ if (!(te instanceof IConduitBundle)) {
+ return 0;
+ }
+ IConduitBundle bundle = (IConduitBundle) te;
+ IRedstoneConduit con = bundle.getConduit(IRedstoneConduit.class);
+ if (con == null) {
+ return 0;
+ }
+ return con.isProvidingWeakPower(getOrientation(par5));
+ }
+
+ @Override
+ public boolean canProvidePower() {
+ return true;
+ }
+ @Override
+ public boolean removeBlockByPlayer(World world, EntityPlayer player, int x, int y, int z) {
+ IConduitBundle te = (IConduitBundle) world.getBlockTileEntity(x, y, z);
+ if (te == null) {
+ return true;
+ }
+
+ boolean breakBlock = true;
+ List drop = new ArrayList();
+ if (ConduitUtil.renderFacade(te, player)) {
+ breakBlock = false;
+ ItemStack fac = new ItemStack(ModObject.itemConduitFacade.actualId, 1, 0);
+ PainterUtil.setSourceBlock(fac, te.getFacadeId(), te.getFacadeMetadata());
+ drop.add(fac);
+ te.setFacadeId(-1);
+ te.setFacadeMetadata(0);
+ }
+
+ if (breakBlock) {
+ RaytraceResult rt = doRayTrace(world, x, y, z, player);
+ if (rt != null && rt.component != null) {
+ Class extends IConduit> type = rt.component.conduitType;
+ if (type == null) {
+ // broke a conector so drop any conduits with no connections as there
+ // is no other way to remove these
+ List cons = new ArrayList(te.getConduits());
+ boolean droppedUnconected = false;
+ for (IConduit con : cons) {
+ if (con.getConduitConnections().isEmpty() && con.getExternalConnections().isEmpty()) {
+ te.removeConduit(con);
+ drop.add(con.createItem());
+ droppedUnconected = true;
+ }
+ }
+ // If there isn't, then drop em all
+ if (!droppedUnconected) {
+ for (IConduit con : cons) {
+ te.removeConduit(con);
+ drop.add(con.createItem());
+ }
+ }
+ } else {
+ IConduit con = te.getConduit(type);
+ te.removeConduit(con);
+ drop.add(con.createItem());
+
+ }
+ }
+ }
+
+ breakBlock = te.getConduits().isEmpty() && !te.hasFacade();
+
+ if (!world.isRemote && !player.capabilities.isCreativeMode) {
+ for (ItemStack st : drop) {
+ ConduitUtil.dropItems(world, st, x, y, z);
+ }
+ }
+
+ if (!breakBlock) {
+ world.markBlockForUpdate(x, y, z);
+ return false;
+ }
+ world.setBlockToAir(x, y, z);
+ return true;
+ }
+
+ @Override
+ public void breakBlock(World world, int x, int y, int z, int par5, int par6) {
+ IConduitBundle te = (IConduitBundle) world.getBlockTileEntity(x, y, z);
+ if (te != null) {
+ te.onBlockRemoved();
+ }
+ world.removeBlockTileEntity(x, y, z);
+ }
+
+ @Override
+ public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int par6, float par7, float par8, float par9) {
+
+ IConduitBundle bundle = (IConduitBundle) world.getBlockTileEntity(x, y, z);
+ if (bundle == null) {
+ return false;
+ }
+
+ ItemStack stack = player.getCurrentEquippedItem();
+ if (stack != null && stack.itemID == ModObject.itemConduitFacade.actualId && !bundle.hasFacade()) {
+ // Add facade
+ if (player.isSneaking()) {
+ return false;
+ }
+
+ bundle.setFacadeId(PainterUtil.getSourceBlockId(player.getCurrentEquippedItem()));
+ bundle.setFacadeMetadata(PainterUtil.getSourceBlockMetadata(player.getCurrentEquippedItem()));
+ if (!player.capabilities.isCreativeMode) {
+ stack.stackSize--;
+ }
+ world.markBlockForUpdate(x, y, z);
+ world.updateTileEntityChunkAndDoNothing(x, y, z, bundle.getEntity());
+ return true;
+
+ } else if (ConduitUtil.isConduitEquipped(player)) {
+ // Add conduit
+ if (player.isSneaking()) {
+ return false;
+ }
+
+ IConduitItem equipped = (IConduitItem) stack.getItem();
+ if (!bundle.hasType(equipped.getBaseConduitType())) {
+ bundle.addConduit(equipped.createConduit(stack));
+ if (!player.capabilities.isCreativeMode) {
+ player.getCurrentEquippedItem().stackSize--;
+ }
+ return true;
+ }
+
+ }
+
+ // Break conduit with tool
+ if (ConduitUtil.isToolEquipped(player) && player.isSneaking()) {
+ if (!world.isRemote) {
+ removeBlockByPlayer(world, player, x, y, z);
+ if (player.getCurrentEquippedItem().getItem() instanceof IToolWrench) {
+ ((IToolWrench) player.getCurrentEquippedItem().getItem()).wrenchUsed(player, x, y, z);
+ }
+ }
+ return true;
+ }
+
+ // Check conduit defined actions
+ RaytraceResult res = doRayTrace(world, x, y, z, player);
+
+ if(res != null && res.component != null && res.component.data instanceof ConduitConnectorType) {
+ //if its a connector pass the event on to all conduits
+ for(IConduit con : bundle.getConduits()) {
+ if(con.onBlockActivated(player, res)) {
+ world.updateTileEntityChunkAndDoNothing(x, y, z, bundle.getEntity());
+ return true;
+ }
+
+ }
+ return false;
+ }
+
+ if (res == null || res.component == null || res.component.conduitType == null) {
+ // Nothing of interest hit
+ return false;
+ }
+
+ // Conduit specific actions
+ if (bundle.getConduit(res.component.conduitType).onBlockActivated(player, res)) {
+ world.updateTileEntityChunkAndDoNothing(x, y, z, bundle.getEntity());
+ return true;
+ }
+ return false;
+
+ }
+
+ @Override
+ public void onNeighborBlockChange(World world, int x, int y, int z, int blockId) {
+ TileEntity tile = world.getBlockTileEntity(x, y, z);
+ if ((tile instanceof IConduitBundle)) {
+ ((IConduitBundle) tile).onNeighborBlockChange(blockId);
+ }
+ }
+
+ @Override
+ public void addCollisionBoxesToList(World world, int x, int y, int z, AxisAlignedBB axisalignedbb, @SuppressWarnings("rawtypes") List arraylist,
+ Entity par7Entity) {
+
+ TileEntity te = world.getBlockTileEntity(x, y, z);
+ if (!(te instanceof IConduitBundle)) {
+ return;
+ }
+ IConduitBundle con = (IConduitBundle) te;
+ if (con.getFacadeId() > 0) {
+ setBlockBounds(0, 0, 0, 1, 1, 1);
+ super.addCollisionBoxesToList(world, x, y, z, axisalignedbb, arraylist, par7Entity);
+ } else {
+
+ Collection bounds = con.getCollidableComponents();
+ for (CollidableComponent bnd : bounds) {
+ setBlockBounds(bnd.bound.minX, bnd.bound.minY, bnd.bound.minZ, bnd.bound.maxX, bnd.bound.maxY, bnd.bound.maxZ);
+ super.addCollisionBoxesToList(world, x, y, z, axisalignedbb, arraylist, par7Entity);
+ }
+
+ if (con.getConduits().isEmpty()) { // just in case
+ setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
+ super.addCollisionBoxesToList(world, x, y, z, axisalignedbb, arraylist, par7Entity);
+ }
+ }
+
+ setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
+
+ }
+
+ @Override
+ public AxisAlignedBB getSelectedBoundingBoxFromPool(World world, int x, int y, int z) {
+
+ TileEntity te = world.getBlockTileEntity(x, y, z);
+ if (!(te instanceof IConduitBundle)) {
+ return null;
+ }
+ IConduitBundle con = (IConduitBundle) te;
+
+ BoundingBox minBB = new BoundingBox(1, 1, 1, 0, 0, 0);
+ if (!ConduitUtil.renderFacade(con, EnderIO.proxy.getClientPlayer())) {
+
+ Collection bounds = con.getCollidableComponents();
+ for (CollidableComponent bnd : bounds) {
+ minBB = minBB.expandBy(bnd.bound);
+ }
+
+ } else {
+ minBB = new BoundingBox(0, 0, 0, 1, 1, 1);
+ }
+
+ if (!minBB.isValid()) {
+ minBB = new BoundingBox(0, 0, 0, 1, 1, 1);
+ }
+
+ return AxisAlignedBB.getBoundingBox(x + minBB.minX, y + minBB.minY,
+ z + minBB.minZ, x + minBB.maxX, y + minBB.maxY, z +
+ minBB.maxZ);
+ }
+
+ @Override
+ public MovingObjectPosition collisionRayTrace(World world, int x, int y, int z, Vec3 origin, Vec3 direction) {
+ RaytraceResult raytraceResult = doRayTrace(world, x, y, z, origin, direction, null);
+ if (raytraceResult == null) {
+ return null;
+ }
+
+ if (raytraceResult.movingObjectPosition != null) {
+ raytraceResult.movingObjectPosition.hitInfo = raytraceResult.component;
+
+ }
+ return raytraceResult.movingObjectPosition;
+ }
+
+ public RaytraceResult doRayTrace(World world, int x, int y, int z, EntityPlayer entityPlayer) {
+ double pitch = Math.toRadians(entityPlayer.rotationPitch);
+ double yaw = Math.toRadians(entityPlayer.rotationYaw);
+
+ double dirX = -Math.sin(yaw) * Math.cos(pitch);
+ double dirY = -Math.sin(pitch);
+ double dirZ = Math.cos(yaw) * Math.cos(pitch);
+
+ double reachDistance = 5;
+
+ if (entityPlayer instanceof EntityPlayerMP) {
+ reachDistance = ((EntityPlayerMP) entityPlayer).theItemInWorldManager.getBlockReachDistance();
+ }
+
+ double posY = entityPlayer.posY + 1.62 - entityPlayer.yOffset;
+ if (!world.isRemote && entityPlayer.isSneaking()) {
+ posY -= 0.08;
+ }
+ Vec3 origin = Vec3.fakePool.getVecFromPool(entityPlayer.posX, posY, entityPlayer.posZ);
+ Vec3 direction = origin.addVector(dirX * reachDistance, dirY * reachDistance, dirZ * reachDistance);
+ RaytraceResult res = doRayTrace(world, x, y, z, origin, direction, entityPlayer);
+ return res;
+ }
+
+ protected RaytraceResult doRayTrace(World world, int x, int y, int z, Vec3 origin, Vec3 direction, EntityPlayer player) {
+
+ TileEntity te = world.getBlockTileEntity(x, y, z);
+ if (!(te instanceof IConduitBundle)) {
+ return null;
+ }
+ IConduitBundle bundle = (IConduitBundle) te;
+ List hits = new ArrayList();
+
+ if (ConduitUtil.renderFacade(bundle, player)) {
+ setBlockBounds(0, 0, 0, 1, 1, 1);
+ MovingObjectPosition hitPos = super.collisionRayTrace(world, x, y, z, origin, direction);
+ if (hitPos != null) {
+ hits.add(new RaytraceResult(new CollidableComponent(null, BoundingBox.UNIT_CUBE, ForgeDirection.UNKNOWN, null), hitPos));
+ }
+ } else {
+
+ Collection components = bundle.getCollidableComponents();
+ for (CollidableComponent component : components) {
+ setBlockBounds(component.bound.minX, component.bound.minY, component.bound.minZ, component.bound.maxX, component.bound.maxY, component.bound.maxZ);
+ MovingObjectPosition hitPos = super.collisionRayTrace(world, x, y, z, origin, direction);
+ if (hitPos != null) {
+ hits.add(new RaytraceResult(component, hitPos));
+ }
+ }
+
+ // safety to prevent unbreakable empty bundles in case of a bug
+ if (bundle.getConduits().isEmpty() && !ConduitUtil.isFacadeHidden(bundle, player)) {
+ setBlockBounds(0, 0, 0, 1, 1, 1);
+ MovingObjectPosition hitPos = super.collisionRayTrace(world, x, y, z, origin, direction);
+ if (hitPos != null) {
+ hits.add(new RaytraceResult(null, hitPos));
+ }
+ }
+ }
+
+ setBlockBounds(0, 0, 0, 1, 1, 1);
+
+ return RaytraceResult.getClosestHit(origin, hits);
+ }
+
+}
diff --git a/common/crazypants/enderio/conduit/ConduitRecipes.java b/common/crazypants/enderio/conduit/ConduitRecipes.java
new file mode 100644
index 00000000..166009a2
--- /dev/null
+++ b/common/crazypants/enderio/conduit/ConduitRecipes.java
@@ -0,0 +1,41 @@
+package crazypants.enderio.conduit;
+
+import static crazypants.enderio.ModObject.*;
+import net.minecraft.block.Block;
+import net.minecraft.item.*;
+import cpw.mods.fml.common.registry.GameRegistry;
+import crazypants.enderio.ModObject;
+import crazypants.enderio.conduit.facade.ItemConduitFacade.FacadePainterRecipe;
+import crazypants.enderio.machine.MachineRecipeRegistry;
+import crazypants.enderio.material.Alloy;
+
+public class ConduitRecipes {
+
+ public static void addRecipes() {
+ ItemStack industialBinder = new ItemStack(itemIndustrialBinder.actualId, 1, 0);
+ //ItemStack glassPane = new ItemStack(Block.thinGlass, 1, 0);
+ ItemStack fusedQuartz = new ItemStack(ModObject.blockFusedQuartz.actualId, 1, 0);
+
+ //Facade
+ GameRegistry.addShapedRecipe(new ItemStack(itemConduitFacade.actualId,1,0), "bbb", "b b", "bbb", 'b', industialBinder);
+ MachineRecipeRegistry.instance.registerRecipe(blockPainter.unlocalisedName, new FacadePainterRecipe());
+
+ //Liquids
+ GameRegistry.addShapedRecipe(new ItemStack(itemLiquidConduit.actualId,4,0), "bgb", "g g", "bgb", 'b', industialBinder, 'g', fusedQuartz);
+
+ //Power
+ GameRegistry.addShapedRecipe(new ItemStack(itemPowerConduit.actualId,4,0), " b ", "bib", " b ", 'b', industialBinder, 'i', new ItemStack(Item.ingotIron));
+ ItemStack activatedIron = new ItemStack(ModObject.itemAlloy.actualId,1,Alloy.ACTIVATED_IRON.ordinal());
+ GameRegistry.addShapedRecipe(new ItemStack(itemPowerConduit.actualId,4,1), " b ", "bib", " b ", 'b', industialBinder, 'i', activatedIron);
+ GameRegistry.addShapedRecipe(new ItemStack(itemPowerConduit.actualId,4,2), " b ", "bib", " b ", 'b', industialBinder, 'i', new ItemStack(ModObject.itemAlloy.actualId,1,Alloy.ENDER_IRON.ordinal()));
+
+
+ //Redstone
+ ItemStack redstoneConduit = new ItemStack(itemRedstoneConduit.actualId,1,0);
+ GameRegistry.addShapedRecipe(redstoneConduit , " b ", "brb", " b ", 'b', industialBinder, 'r', new ItemStack(Item.redstone));
+ GameRegistry.addShapedRecipe(new ItemStack(itemRedstoneConduit.actualId,1,1), " l ", "lcl", " l ", 'c', redstoneConduit, 'l', Block.lever);
+
+
+ }
+
+}
diff --git a/common/crazypants/enderio/conduit/ConduitUtil.java b/common/crazypants/enderio/conduit/ConduitUtil.java
new file mode 100644
index 00000000..b924b762
--- /dev/null
+++ b/common/crazypants/enderio/conduit/ConduitUtil.java
@@ -0,0 +1,196 @@
+package crazypants.enderio.conduit;
+
+import java.util.*;
+
+import net.minecraft.entity.item.EntityItem;
+import net.minecraft.entity.player.EntityPlayer;
+import net.minecraft.inventory.IInventory;
+import net.minecraft.item.ItemStack;
+import net.minecraft.nbt.NBTTagCompound;
+import net.minecraft.tileentity.TileEntity;
+import net.minecraft.world.*;
+import net.minecraftforge.common.ForgeDirection;
+import buildcraft.api.tools.IToolWrench;
+import cpw.mods.fml.common.FMLCommonHandler;
+import crazypants.enderio.EnderIO;
+import crazypants.enderio.conduit.liquid.*;
+import crazypants.enderio.conduit.power.*;
+import crazypants.enderio.conduit.redstone.*;
+
+public class ConduitUtil {
+
+
+ public static final Random RANDOM = new Random();
+
+
+ public static AbstractConduitNetwork> createNetworkForType(Class extends IConduit> type) {
+ if(IRedstoneConduit.class.isAssignableFrom(type)) {
+ return new RedstoneConduitNetwork();
+ } else if(IPowerConduit.class.isAssignableFrom(type)) {
+ return new PowerConduitNetwork();
+ } else if(ILiquidConduit.class.isAssignableFrom(type)) {
+ return new LiquidConduitNetwork();
+ }
+ FMLCommonHandler.instance().raiseException(new Exception("Could not determine network type for class " + type), "ConduitUtil.createNetworkForType", false);
+ return null;
+ }
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ public static void ensureValidNetwork(IConduit conduit) {
+ TileEntity te = conduit.getBundle().getEntity();
+ World world = te.worldObj;
+ Collection extends IConduit> connections = ConduitUtil.getConnectedConduits(world, te.xCoord, te.yCoord, te.zCoord, conduit.getBaseConduitType());
+
+ if (reuseNetwork(conduit, connections, world)) {
+ return;
+ }
+
+ AbstractConduitNetwork res = createNetworkForType(conduit.getBaseConduitType());
+ res.init(conduit.getBundle(), connections, world);
+ return;
+ }
+
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ private static boolean reuseNetwork(IConduit con, Collection extends IConduit> connections, World world) {
+ AbstractConduitNetwork network = null;
+ for (IConduit conduit : connections) {
+ if (network == null) {
+ network = conduit.getNetwork();
+ } else if (network != conduit.getNetwork()) {
+ return false;
+ }
+ }
+ if (network == null) {
+ return false;
+ }
+ con.setNetwork(network);
+ network.addConduit(con);
+ network.notifyNetworkOfUpdate();
+ return true;
+ }
+
+ public static void dropConduit(World world, IConduit conduit, int x, int y, int z) {
+ dropItems(world, conduit.createItem(), x, y, z);
+ }
+
+ public static void dropItems(World world, ItemStack stack, int x, int y, int z) {
+ if (stack.stackSize <= 0) {
+ return;
+ }
+
+ float f1 = 0.7F;
+ double d = (world.rand.nextFloat() * f1) + (1.0F - f1) * 0.5D;
+ double d1 = (world.rand.nextFloat() * f1) + (1.0F - f1) * 0.5D;
+ double d2 = (world.rand.nextFloat() * f1) + (1.0F - f1) * 0.5D;
+ EntityItem entityitem = new EntityItem(world, x + d, y + d1, z + d2, stack);
+ entityitem.delayBeforeCanPickup = 10;
+
+ world.spawnEntityInWorld(entityitem);
+ }
+
+ public static void dropItems(World world, IInventory inventory, int x, int y, int z) {
+ for (int l = 0; l < inventory.getSizeInventory(); ++l) {
+ ItemStack items = inventory.getStackInSlot(l);
+
+ if (items != null && items.stackSize > 0) {
+ dropItems(world, inventory.getStackInSlot(l).copy(), x, y, z);
+ }
+ }
+ }
+
+ public static boolean renderFacade(IConduitBundle bundle, EntityPlayer player) {
+ return bundle.getFacadeId() > 0 && !isFacadeHidden(bundle, player);
+ }
+
+ public static boolean isFacadeHidden(IConduitBundle bundle, EntityPlayer player) {
+ return bundle.getFacadeId() > 0 && (isToolEquipped(player) || isConduitEquipped(player));
+ }
+
+ public static boolean isConduitEquipped(EntityPlayer player) {
+ player = player == null ? EnderIO.proxy.getClientPlayer() : player;
+ if(player == null) {
+ return false;
+ }
+ ItemStack equipped = player.getCurrentEquippedItem();
+ if (equipped == null) {
+ return false;
+ }
+ return equipped.getItem() instanceof IConduitItem ;
+ }
+
+ public static boolean isToolEquipped(EntityPlayer player) {
+ player = player == null ? EnderIO.proxy.getClientPlayer() : player;
+ if(player == null) {
+ return false;
+ }
+ ItemStack equipped = player.getCurrentEquippedItem();
+ if (equipped == null) {
+ return false;
+ }
+ return /*equipped.itemID == Block.stone.blockID ||*/ equipped.getItem() instanceof IToolWrench;
+ }
+
+ public static T getConduit(IBlockAccess world, int x, int y, int z, Class type) {
+ if(world == null) {
+ return null;
+ }
+ TileEntity te = world.getBlockTileEntity(x, y, z);
+ if (te instanceof IConduitBundle) {
+ IConduitBundle con = (IConduitBundle) te;
+ return con.getConduit(type);
+ }
+ return null;
+ }
+
+ public static T getConduit(IBlockAccess world, TileEntity te, ForgeDirection dir, Class type) {
+ return ConduitUtil.getConduit(world, te.xCoord + dir.offsetX, te.yCoord + dir.offsetY, te.zCoord + dir.offsetZ, type);
+ }
+
+ public static Collection getConnectedConduits(IBlockAccess world, int x, int y, int z, Class type) {
+ TileEntity te = world.getBlockTileEntity(x, y, z);
+ if (!(te instanceof IConduitBundle)) {
+ return Collections.emptyList();
+ }
+ List result = new ArrayList();
+ IConduitBundle root = (IConduitBundle) te;
+ for (ForgeDirection dir : root.getAllConnections()) {
+ T con = getConduit(world, root.getEntity(), dir, type);
+ if (con != null) {
+ result.add(con);
+ }
+ }
+ return result;
+ }
+
+ public static void writeToNBT(IConduit conduit, NBTTagCompound conduitRoot) {
+ if (conduit == null) {
+ return;
+ }
+
+ NBTTagCompound conduitBody = new NBTTagCompound();
+ conduit.writeToNBT(conduitBody);
+
+ conduitRoot.setString("conduitType", conduit.getClass().getCanonicalName());
+ conduitRoot.setCompoundTag("conduit", conduitBody);
+ }
+
+ public static IConduit readConduitFromNBT(NBTTagCompound conduitRoot) {
+ String typeName = conduitRoot.getString("conduitType");
+ NBTTagCompound conduitBody = conduitRoot.getCompoundTag("conduit");
+ if(typeName == null || conduitBody == null) {
+ return null;
+ }
+ IConduit result;
+ try {
+ result = (IConduit) Class.forName(typeName).newInstance();
+ } catch (Exception e) {
+ throw new RuntimeException("Could not create an instance of the conduit with name: " + typeName, e);
+ }
+ result.readFromNBT(conduitBody);
+ return result;
+
+ }
+
+
+
+}
diff --git a/common/crazypants/enderio/conduit/IConduit.java b/common/crazypants/enderio/conduit/IConduit.java
new file mode 100644
index 00000000..7163eeee
--- /dev/null
+++ b/common/crazypants/enderio/conduit/IConduit.java
@@ -0,0 +1,103 @@
+package crazypants.enderio.conduit;
+
+import java.util.*;
+
+import crazypants.enderio.conduit.geom.*;
+import crazypants.enderio.conduit.geom.CollidableCache.CacheKey;
+import crazypants.util.BlockCoord;
+
+import net.minecraft.entity.player.EntityPlayer;
+import net.minecraft.item.ItemStack;
+import net.minecraft.nbt.NBTTagCompound;
+import net.minecraft.util.Icon;
+import net.minecraft.world.World;
+import net.minecraftforge.common.ForgeDirection;
+
+public interface IConduit {
+
+ // Base functionality
+ Class extends IConduit> getBaseConduitType();
+
+ ItemStack createItem();
+
+ int getLightValue();
+
+ boolean isActive();
+
+ void setActive(boolean active);
+
+ void writeToNBT(NBTTagCompound conduitBody);
+
+ void readFromNBT(NBTTagCompound conduitBody);
+
+ // Container
+
+ void setBundle(IConduitBundle tileConduitBundle);
+
+ IConduitBundle getBundle();
+
+ void onAddedToBundle();
+
+ void onRemovedFromBundle();
+
+ BlockCoord getLocation();
+
+ // Conduit Connections
+
+ boolean canConnectToConduit(ForgeDirection direction, IConduit conduit);
+
+ Set getConduitConnections();
+
+ boolean containsConduitConnection(ForgeDirection dir);
+
+ void conduitConnectionAdded(ForgeDirection fromDirection);
+
+ void conduitConnectionRemoved(ForgeDirection fromDirection);
+
+ AbstractConduitNetwork> getNetwork();
+
+ boolean setNetwork(AbstractConduitNetwork> network);
+
+ // External Connections
+
+ boolean canConnectToExternal(ForgeDirection direction);
+
+ Set getExternalConnections();
+
+ boolean containsExternalConnection(ForgeDirection dir);
+
+ void externalConnectionAdded(ForgeDirection fromDirection);
+
+ void externalConnectionRemoved(ForgeDirection fromDirection);
+
+ boolean isConnectedTo(ForgeDirection dir);
+
+ // rendering, only needed us default rendering is used
+
+ Icon getTextureForState(CollidableComponent component);
+
+ Icon getTransmitionTextureForState(CollidableComponent component);
+
+ float getTransmitionGeometryScale();
+
+ float getSelfIlluminationForState(CollidableComponent component);
+
+ // geometry
+
+ boolean haveCollidablesChangedSinceLastCall();
+
+ Collection getCollidableComponents();
+
+ Collection createCollidables(CacheKey key);
+
+ // Actions
+
+ boolean onBlockActivated(EntityPlayer player, RaytraceResult res);
+
+ void onChunkUnload(World worldObj);
+
+ void updateEntity(World worldObj);
+
+ boolean onNeighborBlockChange(int blockId);
+
+}
diff --git a/common/crazypants/enderio/conduit/IConduitBundle.java b/common/crazypants/enderio/conduit/IConduitBundle.java
new file mode 100644
index 00000000..32f270ca
--- /dev/null
+++ b/common/crazypants/enderio/conduit/IConduitBundle.java
@@ -0,0 +1,68 @@
+package crazypants.enderio.conduit;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Set;
+
+import crazypants.enderio.conduit.geom.CollidableComponent;
+import crazypants.enderio.conduit.geom.Offset;
+import crazypants.enderio.power.IInternalPowerReceptor;
+
+import net.minecraft.tileentity.TileEntity;
+import net.minecraftforge.common.ForgeDirection;
+import net.minecraftforge.fluids.IFluidHandler;
+import buildcraft.api.power.IPowerReceptor;
+
+public interface IConduitBundle extends IInternalPowerReceptor, IFluidHandler {
+
+ TileEntity getEntity();
+
+ //conduits
+
+ boolean hasType(Class extends IConduit> type);
+
+ T getConduit(Class type);
+
+ void addConduit(IConduit conduit);
+
+ void removeConduit(IConduit conduit);
+
+ Collection getConduits();
+
+ Offset getOffset(Class extends IConduit> type, ForgeDirection dir);
+
+ // connections
+
+ Set getConnections(Class extends IConduit> type);
+
+ boolean containsConnection(Class extends IConduit> type, ForgeDirection west);
+
+ Set getAllConnections();
+
+ boolean containsConnection(ForgeDirection dir);
+
+ // events
+
+ void onNeighborBlockChange(int blockId);
+
+ void onBlockRemoved();
+
+ // Facade
+
+ boolean hasFacade();
+
+ void setFacadeId(int blockID);
+
+ int getFacadeId();
+
+ void setFacadeMetadata(int meta);
+
+ int getFacadeMetadata();
+
+ List getCollidableComponents();
+
+ List getConnectors();
+
+ void dirty();
+
+}
diff --git a/common/crazypants/enderio/conduit/IConduitItem.java b/common/crazypants/enderio/conduit/IConduitItem.java
new file mode 100644
index 00000000..b36514da
--- /dev/null
+++ b/common/crazypants/enderio/conduit/IConduitItem.java
@@ -0,0 +1,11 @@
+package crazypants.enderio.conduit;
+
+import net.minecraft.item.ItemStack;
+
+public interface IConduitItem {
+
+ Class extends IConduit> getBaseConduitType();
+
+ IConduit createConduit(ItemStack item);
+
+}
diff --git a/common/crazypants/enderio/conduit/ItemConduitSubtype.java b/common/crazypants/enderio/conduit/ItemConduitSubtype.java
new file mode 100644
index 00000000..6332c66e
--- /dev/null
+++ b/common/crazypants/enderio/conduit/ItemConduitSubtype.java
@@ -0,0 +1,18 @@
+package crazypants.enderio.conduit;
+
+public class ItemConduitSubtype {
+
+ public final String unlocalisedName;
+
+ public final String uiName;
+
+ public final String iconKey;
+
+ public ItemConduitSubtype(String unlocalisedName, String uiName, String iconKey) {
+ super();
+ this.unlocalisedName = unlocalisedName;
+ this.uiName = uiName;
+ this.iconKey = iconKey;
+ }
+
+}
diff --git a/common/crazypants/enderio/conduit/RaytraceResult.java b/common/crazypants/enderio/conduit/RaytraceResult.java
new file mode 100644
index 00000000..80c0a1e7
--- /dev/null
+++ b/common/crazypants/enderio/conduit/RaytraceResult.java
@@ -0,0 +1,38 @@
+package crazypants.enderio.conduit;
+
+import java.util.Collection;
+
+import crazypants.enderio.conduit.geom.CollidableComponent;
+
+
+import net.minecraft.util.MovingObjectPosition;
+import net.minecraft.util.Vec3;
+
+public class RaytraceResult {
+
+ public static RaytraceResult getClosestHit(Vec3 origin, Collection candidates) {
+ double minLengthSquared = Double.POSITIVE_INFINITY;
+ RaytraceResult closest = null;
+
+ for (RaytraceResult candidate : candidates) {
+ MovingObjectPosition hit = candidate.movingObjectPosition;
+ if (hit != null) {
+ double lengthSquared = hit.hitVec.squareDistanceTo(origin);
+ if (lengthSquared < minLengthSquared) {
+ minLengthSquared = lengthSquared;
+ closest = candidate;
+ }
+ }
+ }
+ return closest;
+ }
+
+ public final CollidableComponent component;
+ public final MovingObjectPosition movingObjectPosition;
+
+ public RaytraceResult(CollidableComponent component, MovingObjectPosition movingObjectPosition) {
+ this.component = component;
+ this.movingObjectPosition = movingObjectPosition;
+ }
+
+}
diff --git a/common/crazypants/enderio/conduit/TileConduitBundle.java b/common/crazypants/enderio/conduit/TileConduitBundle.java
new file mode 100644
index 00000000..c6528cb2
--- /dev/null
+++ b/common/crazypants/enderio/conduit/TileConduitBundle.java
@@ -0,0 +1,517 @@
+package crazypants.enderio.conduit;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import crazypants.enderio.EnderIO;
+import crazypants.enderio.PacketHandler;
+import crazypants.enderio.conduit.geom.CollidableCache;
+import crazypants.enderio.conduit.geom.CollidableComponent;
+import crazypants.enderio.conduit.geom.ConduitConnectorType;
+import crazypants.enderio.conduit.geom.ConduitGeometryUtil;
+import crazypants.enderio.conduit.geom.Offset;
+import crazypants.enderio.conduit.geom.Offsets;
+import crazypants.enderio.conduit.liquid.ILiquidConduit;
+import crazypants.enderio.conduit.power.IPowerConduit;
+import crazypants.util.BlockCoord;
+
+import net.minecraft.nbt.NBTTagCompound;
+import net.minecraft.nbt.NBTTagList;
+import net.minecraft.network.packet.Packet;
+import net.minecraft.tileentity.TileEntity;
+import net.minecraft.world.World;
+import net.minecraftforge.common.ForgeDirection;
+import net.minecraftforge.fluids.Fluid;
+import net.minecraftforge.fluids.FluidStack;
+import net.minecraftforge.fluids.FluidTankInfo;
+import buildcraft.api.power.PowerHandler;
+import buildcraft.api.power.PowerHandler.PowerReceiver;
+
+public class TileConduitBundle extends TileEntity implements IConduitBundle {
+
+
+ private final List conduits = new ArrayList();
+
+ private int facadeId = -1;
+ private int facadeMeta = 0;
+
+ private boolean facadeChanged;
+
+ private final List cachedCollidables = new ArrayList();
+
+ private boolean conduitsDirty = true;
+ private boolean collidablesDirty = true;
+
+ public TileConduitBundle() {
+ blockType = EnderIO.blockConduitBundle;
+ }
+
+ @Override
+ public void dirty() {
+ conduitsDirty = true;
+ collidablesDirty = true;
+ }
+
+ @Override
+ public void writeToNBT(NBTTagCompound nbtRoot) {
+ super.writeToNBT(nbtRoot);
+
+ NBTTagList conduitTags = new NBTTagList();
+ for (IConduit conduit : conduits) {
+ NBTTagCompound conduitRoot = new NBTTagCompound();
+ ConduitUtil.writeToNBT(conduit, conduitRoot);
+ conduitTags.appendTag(conduitRoot);
+ }
+ nbtRoot.setTag("conduits", conduitTags);
+ nbtRoot.setInteger("facadeId", facadeId);
+ nbtRoot.setInteger("facadeMeta", facadeMeta);
+ }
+
+ @Override
+ public void readFromNBT(NBTTagCompound nbtRoot) {
+ super.readFromNBT(nbtRoot);
+
+ conduits.clear();
+ NBTTagList conduitTags = nbtRoot.getTagList("conduits");
+ for (int i = 0; i < conduitTags.tagCount(); i++) {
+ NBTTagCompound conduitTag = (NBTTagCompound) conduitTags.tagAt(i);
+ IConduit conduit = ConduitUtil.readConduitFromNBT(conduitTag);
+ if (conduit != null) {
+ conduit.setBundle(this);
+ conduits.add(conduit);
+ }
+ }
+ facadeId = nbtRoot.getInteger("facadeId");
+ facadeMeta = nbtRoot.getInteger("facadeMeta");
+
+ }
+
+ @Override
+ public boolean hasFacade() {
+ return facadeId > 0;
+ }
+
+ @Override
+ public void setFacadeId(int blockID) {
+ this.facadeId = blockID;
+ facadeChanged = true;
+ }
+
+ @Override
+ public int getFacadeId() {
+ return facadeId;
+ }
+
+ @Override
+ public void setFacadeMetadata(int meta) {
+ facadeMeta = meta;
+ }
+
+ @Override
+ public int getFacadeMetadata() {
+ return facadeMeta;
+ }
+
+ @Override
+ public Packet getDescriptionPacket() {
+ return PacketHandler.getPacket(this);
+ }
+
+ @Override
+ public void onChunkUnload() {
+ for (IConduit conduit : conduits) {
+ conduit.onChunkUnload(worldObj);
+ }
+ }
+
+ @Override
+ public void updateEntity() {
+ for (IConduit conduit : conduits) {
+ conduit.updateEntity(worldObj);
+ }
+
+ if(worldObj != null && !worldObj.isRemote && conduitsDirty) {
+ worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
+ conduitsDirty = false;
+ }
+
+ if(worldObj != null && facadeChanged) {
+ worldObj.markBlockForRenderUpdate(xCoord, yCoord, zCoord);
+ facadeChanged = false;
+ }
+ }
+
+ public BlockCoord getLocation() {
+ return new BlockCoord(xCoord, yCoord, zCoord);
+ }
+
+ @Override
+ public void onNeighborBlockChange(int blockId) {
+ boolean needsUpdate = false;
+ for (IConduit conduit : conduits) {
+ needsUpdate |= conduit.onNeighborBlockChange(blockId);
+ }
+ if (needsUpdate) {
+ dirty();
+ }
+ }
+
+ @Override
+ public TileConduitBundle getEntity() {
+ return this;
+ }
+
+ @Override
+ public boolean hasType(Class extends IConduit> type) {
+ return getConduit(type) != null;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public T getConduit(Class type) {
+ if (type == null) {
+ return null;
+ }
+ for (IConduit conduit : conduits) {
+ if (type.isInstance(conduit)) {
+ return (T) conduit;
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public void addConduit(IConduit conduit) {
+ if (worldObj.isRemote) {
+ return;
+ }
+ conduits.add(conduit);
+ conduit.setBundle(this);
+ conduit.onAddedToBundle();
+ dirty();
+ }
+
+ @Override
+ public void removeConduit(IConduit conduit) {
+ if(conduit != null) {
+ removeConduit(conduit, true);
+ }
+ }
+
+ public void removeConduit(IConduit conduit, boolean notify) {
+ if (worldObj.isRemote) {
+ return;
+ }
+ conduit.onRemovedFromBundle();
+ conduits.remove(conduit);
+ conduit.setBundle(null);
+ if (notify) {
+ dirty();
+ }
+ }
+
+ @Override
+ public void onBlockRemoved() {
+ if (worldObj.isRemote) {
+ return;
+ }
+ List copy = new ArrayList(conduits);
+ for (IConduit con : copy) {
+ removeConduit(con, false);
+ }
+ dirty();
+ }
+
+ @Override
+ public Collection getConduits() {
+ return conduits;
+ }
+
+ @Override
+ public Set getConnections(Class extends IConduit> type) {
+ IConduit con = getConduit(type);
+ if (con != null) {
+ return con.getConduitConnections();
+ }
+ return null;
+ }
+
+ @Override
+ public boolean containsConnection(Class extends IConduit> type, ForgeDirection dir) {
+ IConduit con = getConduit(type);
+ if (con != null) {
+ return con.containsConduitConnection(dir);
+ }
+ return false;
+ }
+
+ @Override
+ public boolean containsConnection(ForgeDirection dir) {
+ for (IConduit con : conduits) {
+ if (con.containsConduitConnection(dir)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public Set getAllConnections() {
+ Set result = new HashSet();
+ for (IConduit con : conduits) {
+ result.addAll(con.getConduitConnections());
+ }
+ return result;
+ }
+
+ // Geometry
+
+ @Override
+ public Offset getOffset(Class extends IConduit> type, ForgeDirection dir) {
+
+ if (getConnectionCount(dir) < 2) {
+ return Offset.NONE;
+ }
+
+ if (dir == ForgeDirection.UNKNOWN) {
+ if (containsOnlySingleVerticalConnections()) {
+ return Offsets.get(type, true, false);
+ }
+ if (containsOnlySingleHorizontalConnections()) {
+ return Offsets.get(type, false, true);
+ }
+ return Offsets.get(type, true, true);
+ }
+
+ boolean isVertical = dir == ForgeDirection.UP || dir == ForgeDirection.DOWN;
+ if (isVertical) {
+ return Offsets.get(type, false, true);
+ }
+ return Offsets.get(type, true, false);
+ }
+
+ @Override
+ public List getCollidableComponents() {
+
+ for(IConduit con : conduits) {
+ collidablesDirty = collidablesDirty || con.haveCollidablesChangedSinceLastCall();
+ }
+ if(!collidablesDirty && !cachedCollidables.isEmpty()) {
+ return cachedCollidables;
+ }
+ cachedCollidables.clear();
+ for (IConduit conduit : conduits) {
+ cachedCollidables.addAll(conduit.getCollidableComponents());
+ }
+
+ addConnectors(cachedCollidables);
+
+ collidablesDirty = false;
+
+ return cachedCollidables;
+ }
+
+ @Override
+ public List getConnectors() {
+ List result = new ArrayList();
+ addConnectors(result);
+ return result;
+ }
+
+ private void addConnectors(List result) {
+ if (conduits.isEmpty()) {
+ return;
+ }
+ CollidableCache cc = CollidableCache.instance;
+ if (conduits.size() == 1) {
+
+ IConduit con = conduits.get(0);
+ result.addAll(cc.getCollidables(cc.createKey(con.getBaseConduitType(), Offset.NONE, ForgeDirection.UNKNOWN, false), con));
+
+ } else if (containsOnlySingleVerticalConnections()) {
+
+ if (allDirectionsHaveSameConnectionCount()) {
+ for (IConduit con : conduits) {
+ Class extends IConduit> type = con.getBaseConduitType();
+ result.addAll(cc.getCollidables(cc.createKey(type, getOffset(type, ForgeDirection.UNKNOWN), ForgeDirection.UNKNOWN, false), con));
+ }
+ } else {
+ // vertical box
+ result.add(new CollidableComponent(null, ConduitGeometryUtil.instance.getBoundingBox(ConduitConnectorType.VERTICAL), ForgeDirection.UNKNOWN, ConduitConnectorType.VERTICAL));
+ }
+
+ } else if (containsOnlySingleHorizontalConnections()) {
+
+ if (allDirectionsHaveSameConnectionCount()) {
+ for (IConduit con : conduits) {
+ Class extends IConduit> type = con.getBaseConduitType();
+ result.addAll(cc.getCollidables(cc.createKey(type, getOffset(type, ForgeDirection.UNKNOWN), ForgeDirection.UNKNOWN, false), con));
+ }
+
+ } else {
+ // vertical box
+ result
+ .add(new CollidableComponent(null, ConduitGeometryUtil.instance.getBoundingBox(ConduitConnectorType.HORIZONTAL), ForgeDirection.UNKNOWN, ConduitConnectorType.HORIZONTAL));
+ }
+ } else {
+ result.add(new CollidableComponent(null, ConduitGeometryUtil.instance.getBoundingBox(ConduitConnectorType.BOTH), ForgeDirection.UNKNOWN, ConduitConnectorType.BOTH));
+ }
+
+ }
+
+ private boolean containsOnlySingleVerticalConnections() {
+ return getConnectionCount(ForgeDirection.UP) < 2 && getConnectionCount(ForgeDirection.DOWN) < 2;
+ }
+
+ private boolean containsOnlySingleHorizontalConnections() {
+ return getConnectionCount(ForgeDirection.WEST) < 2 && getConnectionCount(ForgeDirection.EAST) < 2 &&
+ getConnectionCount(ForgeDirection.NORTH) < 2 && getConnectionCount(ForgeDirection.SOUTH) < 2;
+ }
+
+ private boolean allDirectionsHaveSameConnectionCount() {
+ for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) {
+ boolean hasCon = conduits.get(0).isConnectedTo(dir);
+ for (int i = 1; i < conduits.size(); i++) {
+ if (hasCon != conduits.get(i).isConnectedTo(dir)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ private boolean containsOnlyHorizontalConnections() {
+ for (IConduit con : conduits) {
+ for (ForgeDirection dir : con.getConduitConnections()) {
+ if (dir == ForgeDirection.UP || dir == ForgeDirection.DOWN) {
+ return false;
+ }
+ }
+ for (ForgeDirection dir : con.getExternalConnections()) {
+ if (dir == ForgeDirection.UP || dir == ForgeDirection.DOWN) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ private int getConnectionCount(ForgeDirection dir) {
+ if(dir == ForgeDirection.UNKNOWN) {
+ return conduits.size();
+ }
+ int result = 0;
+ for (IConduit con : conduits) {
+ if (con.containsConduitConnection(dir) || con.containsExternalConnection(dir)) {
+ result++;
+ }
+ }
+ return result;
+ }
+
+ // ------------ Power -----------------------------
+
+ @Override
+ public void doWork(PowerHandler workProvider) {
+ IPowerConduit pc = getConduit(IPowerConduit.class);
+ if (pc != null) {
+ pc.doWork(workProvider);
+ }
+ }
+
+ @Override
+ public PowerReceiver getPowerReceiver(ForgeDirection side) {
+ IPowerConduit pc = getConduit(IPowerConduit.class);
+ if (pc != null) {
+ return pc.getPowerReceiver(side);
+ }
+ return null;
+ }
+
+ @Override
+ public PowerHandler getPowerHandler() {
+ IPowerConduit pc = getConduit(IPowerConduit.class);
+ if (pc != null) {
+ return pc.getPowerHandler();
+ }
+ return null;
+ }
+
+ @Override
+ public void applyPerdition() {
+ IPowerConduit pc = getConduit(IPowerConduit.class);
+ if (pc != null) {
+ pc.applyPerdition();
+ }
+
+ }
+
+ @Override
+ public World getWorld() {
+ return worldObj;
+ }
+
+
+
+ //------- Liquids -----------------------------
+
+
+ @Override
+ public int fill(ForgeDirection from, FluidStack resource, boolean doFill) {
+ ILiquidConduit lc = getConduit(ILiquidConduit.class);
+ if (lc != null) {
+ return lc.fill(from, resource, doFill);
+ }
+ return 0;
+ }
+
+ @Override
+ public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) {
+ ILiquidConduit lc = getConduit(ILiquidConduit.class);
+ if (lc != null) {
+ return lc.drain(from, resource, doDrain);
+ }
+ return null;
+ }
+
+ @Override
+ public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) {
+ ILiquidConduit lc = getConduit(ILiquidConduit.class);
+ if (lc != null) {
+ return lc.drain(from, maxDrain, doDrain);
+ }
+ return null;
+ }
+
+ @Override
+ public boolean canFill(ForgeDirection from, Fluid fluid) {
+ ILiquidConduit lc = getConduit(ILiquidConduit.class);
+ if (lc != null) {
+ return lc.canFill(from, fluid);
+ }
+ return false;
+ }
+
+ @Override
+ public boolean canDrain(ForgeDirection from, Fluid fluid) {
+ ILiquidConduit lc = getConduit(ILiquidConduit.class);
+ if (lc != null) {
+ return lc.canDrain(from, fluid);
+ }
+ return false;
+ }
+
+ @Override
+ public FluidTankInfo[] getTankInfo(ForgeDirection from) {
+ ILiquidConduit lc = getConduit(ILiquidConduit.class);
+ if (lc != null) {
+ return lc.getTankInfo(from);
+ }
+ return null;
+ }
+
+
+}
diff --git a/common/crazypants/enderio/conduit/facade/BlockConduitFacade.java b/common/crazypants/enderio/conduit/facade/BlockConduitFacade.java
new file mode 100644
index 00000000..935dfcac
--- /dev/null
+++ b/common/crazypants/enderio/conduit/facade/BlockConduitFacade.java
@@ -0,0 +1,100 @@
+package crazypants.enderio.conduit.facade;
+
+import net.minecraft.block.Block;
+import net.minecraft.block.material.Material;
+import net.minecraft.client.renderer.texture.IconRegister;
+import net.minecraft.tileentity.TileEntity;
+import net.minecraft.util.Icon;
+import net.minecraft.world.IBlockAccess;
+import net.minecraft.world.World;
+import cpw.mods.fml.common.registry.GameRegistry;
+import cpw.mods.fml.common.registry.LanguageRegistry;
+import cpw.mods.fml.relauncher.Side;
+import cpw.mods.fml.relauncher.SideOnly;
+import crazypants.enderio.ModObject;
+import crazypants.enderio.conduit.IConduitBundle;
+
+public class BlockConduitFacade extends Block {
+
+ public static BlockConduitFacade create() {
+ BlockConduitFacade result = new BlockConduitFacade();
+ result.init();
+ return result;
+ }
+
+ private BlockConduitFacade() {
+ super(ModObject.blockConduitFacade.id, Material.rock);
+ setHardness(0.5F);
+ setStepSound(Block.soundStoneFootstep);
+ setUnlocalizedName(ModObject.blockConduitFacade.unlocalisedName);
+ setCreativeTab(null);
+ }
+
+ private void init() {
+ LanguageRegistry.addName(this, "Utility for Rendering DO NOT USE");
+ GameRegistry.registerBlock(this, ModObject.blockConduitFacade.unlocalisedName);
+ }
+
+ @Override
+ public void registerIcons(IconRegister iconRegister) {
+ blockIcon = iconRegister.registerIcon("enderio:conduitFacade");
+ }
+
+ @Override
+ @SideOnly(Side.CLIENT)
+ public Icon getBlockTexture(IBlockAccess ba, int x, int y, int z, int side) {
+ TileEntity te = ba.getBlockTileEntity(x, y, z);
+ if (!(te instanceof IConduitBundle)) {
+ return blockIcon;
+ }
+ IConduitBundle cb = (IConduitBundle) te;
+ int id = cb.getFacadeId();
+ int meta = cb.getFacadeMetadata();
+ if (id <= 0 || id == blockID) {
+ return blockIcon;
+ }
+ return Block.blocksList[id].getIcon(side, meta);
+ }
+
+
+ @Override
+ public int getDamageValue(World par1World, int x, int y, int z) {
+ Mimic m = getMimic(par1World, x, y, z);
+ if (m != null) {
+ return m.meta;
+ }
+ return 0;
+ }
+
+ private Mimic getMimic(IBlockAccess ba, int x, int y, int z) {
+ TileEntity te = ba.getBlockTileEntity(x, y, z);
+ if (!(te instanceof IConduitBundle)) {
+ // System.out.println("BlockConduitFacade.getMimic: Not a conduit bundle");
+ return null;
+ }
+ IConduitBundle cb = (IConduitBundle) te;
+ int id = cb.getFacadeId();
+ int meta = cb.getFacadeMetadata();
+
+ if(id <= 0) {
+ return null;
+ }
+
+ return new Mimic(id, meta);
+ }
+
+ class Mimic {
+ int id;
+ int meta;
+ Block block;
+
+ private Mimic(int id, int meta) {
+ super();
+ this.id = id;
+ this.meta = meta;
+ this.block = Block.blocksList[id];
+ }
+
+ }
+
+}
diff --git a/common/crazypants/enderio/conduit/facade/FacadeRenderer.java b/common/crazypants/enderio/conduit/facade/FacadeRenderer.java
new file mode 100644
index 00000000..de9333b0
--- /dev/null
+++ b/common/crazypants/enderio/conduit/facade/FacadeRenderer.java
@@ -0,0 +1,93 @@
+package crazypants.enderio.conduit.facade;
+
+import net.minecraft.block.Block;
+import net.minecraft.client.renderer.RenderBlocks;
+import net.minecraft.item.ItemStack;
+import net.minecraftforge.client.IItemRenderer;
+
+import org.lwjgl.opengl.GL11;
+
+import crazypants.enderio.EnderIO;
+import crazypants.enderio.machine.painter.PainterUtil;
+import crazypants.render.RenderUtil;
+
+
+public class FacadeRenderer implements IItemRenderer {
+
+ @Override
+ public boolean handleRenderType(ItemStack item, ItemRenderType type) {
+ return type == ItemRenderType.ENTITY || type == ItemRenderType.EQUIPPED || type == ItemRenderType.INVENTORY || type == ItemRenderType.EQUIPPED_FIRST_PERSON;
+ }
+
+ @Override
+ public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) {
+ return true;
+ }
+
+ @Override
+ public void renderItem(ItemRenderType type, ItemStack item, Object... data) {
+ if (type == ItemRenderType.INVENTORY) {
+ RenderBlocks renderBlocks = (RenderBlocks) data[0];
+ renderToInventory(item, renderBlocks);
+ } else if (type == ItemRenderType.EQUIPPED || type == ItemRenderType.EQUIPPED_FIRST_PERSON) {
+ renderEquipped(item, (RenderBlocks) data[0]);
+ } else if (type == ItemRenderType.ENTITY) {
+ renderEntity(item, (RenderBlocks) data[0]);
+ } else {
+ System.out.println("FacadeRenderer.renderItem: Unsupported render type");
+ }
+ }
+
+ private void renderEntity(ItemStack item, RenderBlocks renderBlocks) {
+ GL11.glPushMatrix();
+ GL11.glScalef(0.5f, 0.5f, 0.5f);
+ renderToInventory(item, renderBlocks);
+ GL11.glPopMatrix();
+ }
+
+ private void renderEquipped(ItemStack item, RenderBlocks renderBlocks) {
+ renderToInventory(item, renderBlocks);
+ }
+
+ private void renderToInventory(ItemStack item, RenderBlocks renderBlocks) {
+
+ Block block = PainterUtil.getSourceBlock(item);
+ if (block != null ) {
+ //Render the facade block
+
+ RenderUtil.bindBlockTexture();
+ renderBlocks.renderBlockAsItem(block, PainterUtil.getSourceBlockMetadata(item), 1.0F);
+
+ //then the 'overlay' that marks it as a facade
+ //GL11.glDepthFunc(GL11.GL_ALWAYS);
+ GL11.glDepthFunc(GL11.GL_LEQUAL);
+ GL11.glDisable(GL11.GL_LIGHTING);
+ GL11.glDepthMask(false);
+ GL11.glEnable(GL11.GL_BLEND);
+ GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
+
+ GL11.glEnable(GL11.GL_POLYGON_OFFSET_FILL);
+ GL11.glPolygonOffset(-1.0f, -1.0f);
+
+
+ RenderUtil.bindItemTexture();
+ renderBlocks.setOverrideBlockTexture(EnderIO.itemConduitFacade.getOverlayIcon());
+ renderBlocks.renderBlockAsItem(block, item.getItemDamage(), 1.0F);
+
+ GL11.glDisable(GL11.GL_POLYGON_OFFSET_FILL);
+
+ renderBlocks.clearOverrideBlockTexture();
+ GL11.glDisable(GL11.GL_BLEND);
+ GL11.glDepthMask(true);
+ GL11.glEnable(GL11.GL_LIGHTING);
+ GL11.glDepthFunc(GL11.GL_LEQUAL);
+
+ } else {
+ renderBlocks.setOverrideBlockTexture(EnderIO.itemConduitFacade.getIconFromDamage(0));
+ renderBlocks.renderBlockAsItem(Block.stone, 0, 1.0F);
+ renderBlocks.clearOverrideBlockTexture();
+ }
+
+ }
+
+}
diff --git a/common/crazypants/enderio/conduit/facade/ItemConduitFacade.java b/common/crazypants/enderio/conduit/facade/ItemConduitFacade.java
new file mode 100644
index 00000000..e3721359
--- /dev/null
+++ b/common/crazypants/enderio/conduit/facade/ItemConduitFacade.java
@@ -0,0 +1,106 @@
+package crazypants.enderio.conduit.facade;
+
+import net.minecraft.client.renderer.texture.IconRegister;
+import net.minecraft.entity.player.EntityPlayer;
+import net.minecraft.item.*;
+import net.minecraft.util.Icon;
+import net.minecraft.world.World;
+import net.minecraftforge.common.ForgeDirection;
+import cpw.mods.fml.common.registry.*;
+import cpw.mods.fml.relauncher.*;
+import crazypants.enderio.*;
+import crazypants.enderio.conduit.IConduitBundle;
+import crazypants.enderio.machine.painter.*;
+
+public class ItemConduitFacade extends Item {
+
+ public static ItemConduitFacade create() {
+ ItemConduitFacade result = new ItemConduitFacade();
+ result.init();
+ return result;
+ }
+
+ protected Icon overlayIcon;
+
+ protected ItemConduitFacade() {
+ super(ModObject.itemConduitFacade.id);
+ setCreativeTab(EnderIOTab.tabEnderIO);
+ setUnlocalizedName(ModObject.itemConduitFacade.unlocalisedName);
+ setMaxStackSize(64);
+ }
+
+ protected void init() {
+ LanguageRegistry.addName(this, ModObject.itemConduitFacade.name);
+ GameRegistry.registerItem(this, ModObject.itemConduitFacade.unlocalisedName);
+ }
+
+ @Override
+ public void registerIcons(IconRegister iconRegister) {
+ itemIcon = iconRegister.registerIcon("enderio:ConduitFacade");
+ overlayIcon = iconRegister.registerIcon("enderio:conduitFacadeOverlay");
+ }
+
+ public Icon getOverlayIcon() {
+ return overlayIcon;
+ }
+
+ @Override
+ public boolean onItemUse(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side, float par8,
+ float par9, float par10) {
+
+ if (world.isRemote) {
+ return true;
+ }
+
+ ForgeDirection dir = ForgeDirection.values()[side];
+ int placeX = x + dir.offsetX;
+ int placeY = y + dir.offsetY;
+ int placeZ = z + dir.offsetZ;
+
+ if (player.canPlayerEdit(placeX, placeY, placeZ, side, itemStack) && world.isAirBlock(placeX, placeY, placeZ)
+ && PainterUtil.getSourceBlockId(itemStack) > 0) {
+
+ world.setBlock(placeX, placeY, placeZ, EnderIO.blockConduitBundle.blockID);
+ IConduitBundle bundle = (IConduitBundle) world.getBlockTileEntity(placeX, placeY, placeZ);
+ bundle.setFacadeId(PainterUtil.getSourceBlockId(itemStack));
+ bundle.setFacadeMetadata(PainterUtil.getSourceBlockMetadata(itemStack));
+ if (!player.capabilities.isCreativeMode) {
+ itemStack.stackSize--;
+ }
+ return true;
+ }
+
+ return false;
+ }
+
+ @Override
+ @SideOnly(Side.CLIENT)
+ public boolean isFull3D() {
+ return true;
+ }
+
+ @Override
+ public void onCreated(ItemStack itemStack, World world, EntityPlayer player) {
+ if (PainterUtil.getSourceBlock(itemStack) == null) {
+ PainterUtil.setSourceBlock(itemStack, ModObject.blockConduitFacade.id, 0);
+ }
+ }
+
+ public ItemStack createItemStackForSourceBlock(int id, int itemDamage) {
+ if (id < 1) {
+ id = ModObject.blockConduitFacade.id;
+ }
+ ItemStack result = new ItemStack(itemID, 1, 0);
+ PainterUtil.setSourceBlock(result, id, itemDamage);
+ return result;
+ }
+
+ public static final class FacadePainterRecipe extends BasicPainterTemplate {
+
+ public FacadePainterRecipe() {
+ super(ModObject.itemConduitFacade.actualId);
+ }
+
+ }
+
+}
diff --git a/common/crazypants/enderio/conduit/geom/CollidableCache.java b/common/crazypants/enderio/conduit/geom/CollidableCache.java
new file mode 100644
index 00000000..54fa6638
--- /dev/null
+++ b/common/crazypants/enderio/conduit/geom/CollidableCache.java
@@ -0,0 +1,83 @@
+package crazypants.enderio.conduit.geom;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+
+import crazypants.enderio.conduit.IConduit;
+
+import net.minecraftforge.common.ForgeDirection;
+
+public class CollidableCache {
+
+ public static final CollidableCache instance = new CollidableCache();
+
+ private final Map> cache = new HashMap>();
+
+ public CacheKey createKey(Class extends IConduit> baseType, Offset offset, ForgeDirection dir, boolean isStub) {
+ return new CacheKey(baseType, offset, dir, isStub);
+ }
+
+ public Collection getCollidables(CacheKey key, IConduit conduit) {
+ Collection result = cache.get(key);
+ if(result == null) {
+ result = conduit.createCollidables(key);
+ cache.put(key, result);
+ }
+ return result;
+ }
+
+
+ public static class CacheKey {
+
+ public final Class extends IConduit> baseType;
+ public final String className; //used to generate reliable equals / hashcode
+ public final Offset offset;
+ public final ForgeDirection dir;
+ public final boolean isStub;
+
+ public CacheKey(Class extends IConduit> baseType, Offset offset, ForgeDirection dir, boolean isStub) {
+ this.baseType = baseType;
+ className = baseType.getCanonicalName();
+ this.offset = offset;
+ this.dir = dir;
+ this.isStub = isStub;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((className == null) ? 0 : className.hashCode());
+ result = prime * result + ((dir == null) ? 0 : dir.hashCode());
+ result = prime * result + (isStub ? 1231 : 1237);
+ result = prime * result + ((offset == null) ? 0 : offset.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;
+ CacheKey other = (CacheKey) obj;
+ if (className == null) {
+ if (other.className != null)
+ return false;
+ } else if (!className.equals(other.className))
+ return false;
+ if (dir != other.dir)
+ return false;
+ if (isStub != other.isStub)
+ return false;
+ if (offset != other.offset)
+ return false;
+ return true;
+ }
+
+ }
+
+}
diff --git a/common/crazypants/enderio/conduit/geom/CollidableComponent.java b/common/crazypants/enderio/conduit/geom/CollidableComponent.java
new file mode 100644
index 00000000..a97ee06a
--- /dev/null
+++ b/common/crazypants/enderio/conduit/geom/CollidableComponent.java
@@ -0,0 +1,28 @@
+package crazypants.enderio.conduit.geom;
+
+import crazypants.enderio.conduit.IConduit;
+import crazypants.render.BoundingBox;
+import net.minecraftforge.common.ForgeDirection;
+
+public class CollidableComponent {
+
+ public final Class extends IConduit> conduitType;
+ public final BoundingBox bound;
+ public final ForgeDirection dir;
+ public final Object data;
+
+ public CollidableComponent(Class extends IConduit> conduitType, BoundingBox bound, ForgeDirection id,Object data) {
+ this.conduitType = conduitType;
+ this.bound = bound;
+ this.dir = id;
+ this.data = data;
+ }
+
+ @Override
+ public String toString() {
+ return "CollidableComponent [conduitType=" + conduitType + ", bound=" + bound + ", id=" + dir + "]";
+ }
+
+
+
+}
diff --git a/common/crazypants/enderio/conduit/geom/ConduitConnectorType.java b/common/crazypants/enderio/conduit/geom/ConduitConnectorType.java
new file mode 100644
index 00000000..002c5ed4
--- /dev/null
+++ b/common/crazypants/enderio/conduit/geom/ConduitConnectorType.java
@@ -0,0 +1,9 @@
+package crazypants.enderio.conduit.geom;
+
+public enum ConduitConnectorType {
+
+ VERTICAL,
+ HORIZONTAL,
+ BOTH
+
+}
diff --git a/common/crazypants/enderio/conduit/geom/ConduitGeometryUtil.java b/common/crazypants/enderio/conduit/geom/ConduitGeometryUtil.java
new file mode 100644
index 00000000..0bf49d8b
--- /dev/null
+++ b/common/crazypants/enderio/conduit/geom/ConduitGeometryUtil.java
@@ -0,0 +1,131 @@
+package crazypants.enderio.conduit.geom;
+
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.Map;
+
+import crazypants.enderio.conduit.IConduit;
+import crazypants.render.BoundingBox;
+import crazypants.vecmath.VecmathUtil;
+import crazypants.vecmath.Vector3d;
+
+import net.minecraftforge.common.ForgeDirection;
+
+public class ConduitGeometryUtil {
+
+ public static final ConduitGeometryUtil instance = new ConduitGeometryUtil();
+
+ public static final float STUB_WIDTH = 0.2f;
+ public static final float STUB_HEIGHT = 0.2f;
+
+ public static final float WIDTH = 0.075f;
+ public static final float HEIGHT = 0.075f;
+
+ public static final float HWIDTH = WIDTH / 2;
+ public static final float HHEIGHT = HEIGHT / 2;
+
+ // All values are for a single conduit core
+ public static final Vector3d CORE_MIN = new Vector3d(0.5f - HWIDTH, 0.5 - HHEIGHT, 0.5 - HWIDTH);
+ public static final Vector3d CORE_MAX = new Vector3d(CORE_MIN.x + WIDTH, CORE_MIN.y + HEIGHT, CORE_MIN.z + WIDTH);
+ public static final BoundingBox CORE_BOUNDS = new BoundingBox(CORE_MIN, CORE_MAX);
+
+ private Map boundsCache = new HashMap();
+
+ private EnumMap connectorBounds = new EnumMap(ConduitConnectorType.class);
+
+ private ConduitGeometryUtil() {
+
+ }
+
+ public BoundingBox getBoundingBox(ConduitConnectorType type) {
+ BoundingBox result = connectorBounds.get(type);
+ if (result == null) {
+ result = createConnector(type);
+ result = result.scale(1.2f, 1.2f, 1.2f);
+ connectorBounds.put(type, result);
+ }
+ return result;
+ }
+
+ private BoundingBox createConnector(ConduitConnectorType type) {
+ float distance = WIDTH + HWIDTH;
+ switch (type) {
+ case VERTICAL:
+ return new BoundingBox(0.5 - HWIDTH, 0.5 - distance, 0.5 - HWIDTH, 0.5 + HWIDTH, 0.5 + distance, 0.5 + HWIDTH);
+ case HORIZONTAL:
+ return new BoundingBox(0.5 - distance, 0.5 - HWIDTH, 0.5 - HWIDTH, 0.5 + distance, 0.5 + HWIDTH, 0.5 + HWIDTH);
+ case BOTH:
+ return createConnector(ConduitConnectorType.VERTICAL).expandBy(createConnector(ConduitConnectorType.HORIZONTAL));
+ default:
+ return CORE_BOUNDS;
+ }
+
+ }
+
+ public BoundingBox getBoundingBox(Class extends IConduit> type, ForgeDirection dir, boolean isStub, Offset offset) {
+ GeometryKey key = new GeometryKey(dir, isStub, offset, type);
+ BoundingBox result = boundsCache.get(key);
+ if (result == null) {
+ result = createConduitBounds(type, key);
+ boundsCache.put(key, result);
+ }
+ return result;
+ }
+
+ public Vector3d getTranslation(ForgeDirection dir, Offset offset) {
+ Vector3d result = new Vector3d(offset.xOffset, offset.yOffset,0);
+ result.scale(WIDTH);
+ return result;
+ }
+
+ private BoundingBox createConduitBounds(Class extends IConduit> type, GeometryKey key) {
+ return createConduitBounds(type, key.dir, key.isStub, key.offset);
+ }
+
+ private BoundingBox createConduitBounds(Class extends IConduit> type, ForgeDirection dir, boolean isStub, Offset offset) {
+ BoundingBox bb = CORE_BOUNDS;
+// if(type == IRedstoneConduit.class) {
+// bb = bb.scale(0.5f, 0.5f, 0.5f);
+// }
+ Vector3d min = bb.getMin();
+ Vector3d max = bb.getMax();
+
+ switch (dir) {
+ case WEST:
+ min.x = isStub ? Math.max(0, bb.minX - STUB_WIDTH) : 0;
+ max.x = bb.minX;
+ break;
+ case EAST:
+ min.x = bb.maxX;
+ max.x = isStub ? Math.min(1, bb.maxX + STUB_WIDTH) : 1;
+ break;
+ case DOWN:
+ min.y = isStub ? Math.max(0, bb.minY - STUB_HEIGHT) : 0;
+ max.y = bb.minY;
+ break;
+ case UP:
+ max.y = isStub ? Math.min(1, bb.maxY + STUB_HEIGHT) : 1;
+ min.y = bb.maxY;
+ break;
+ case NORTH:
+ min.z = isStub ? Math.max(0.0F, bb.minZ - STUB_WIDTH) : 0;
+ max.z = bb.minZ;
+ break;
+ case SOUTH:
+ max.z = isStub ? Math.min(1F, bb.maxZ + STUB_WIDTH) : 1;
+ min.z = bb.maxZ;
+ break;
+ default:
+ break;
+ }
+
+ Vector3d trans = getTranslation(dir, offset);
+ min.add(trans);
+ max.add(trans);
+ bb = new BoundingBox(VecmathUtil.clamp(min,0,1), VecmathUtil.clamp(max,0,1));
+ return bb;
+ }
+
+
+
+}
diff --git a/common/crazypants/enderio/conduit/geom/GeometryKey.java b/common/crazypants/enderio/conduit/geom/GeometryKey.java
new file mode 100644
index 00000000..b3aaa151
--- /dev/null
+++ b/common/crazypants/enderio/conduit/geom/GeometryKey.java
@@ -0,0 +1,60 @@
+package crazypants.enderio.conduit.geom;
+
+import crazypants.enderio.conduit.IConduit;
+import net.minecraftforge.common.ForgeDirection;
+
+public final class GeometryKey {
+
+ public final ForgeDirection dir;
+ public final boolean isStub;
+ public final Offset offset;
+ public final String className;
+
+ public GeometryKey(ForgeDirection dir, boolean isStub, Offset offset,Class extends IConduit> type) {
+ this.dir = dir;
+ this.isStub = isStub;
+ this.offset = offset;
+ className = type != null ? type.getName() : null;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((className == null) ? 0 : className.hashCode());
+ result = prime * result + ((dir == null) ? 0 : dir.hashCode());
+ result = prime * result + (isStub ? 1231 : 1237);
+ result = prime * result + ((offset == null) ? 0 : offset.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;
+ GeometryKey other = (GeometryKey) obj;
+ if (className == null) {
+ if (other.className != null)
+ return false;
+ } else if (!className.equals(other.className))
+ return false;
+ if (dir != other.dir)
+ return false;
+ if (isStub != other.isStub)
+ return false;
+ if (offset != other.offset)
+ return false;
+ return true;
+ }
+
+
+
+
+
+
+
+}
diff --git a/common/crazypants/enderio/conduit/geom/Offset.java b/common/crazypants/enderio/conduit/geom/Offset.java
new file mode 100644
index 00000000..bc3e609c
--- /dev/null
+++ b/common/crazypants/enderio/conduit/geom/Offset.java
@@ -0,0 +1,31 @@
+package crazypants.enderio.conduit.geom;
+
+
+
+/**
+ * Offset vectors are based on Y up.
+ * @author brad
+ */
+public enum Offset {
+
+ NONE(0,0),
+ TOP(0,1),
+ BOTTOM(0,-1),
+ LEFT(-1,0),
+ RIGHT(1,0),
+ TL(-1,1),
+ TR(1,1),
+ BL(-1,-1),
+ BR(1,-1);
+
+ public final int xOffset;
+ public final int yOffset;
+
+ private Offset(int xOffset, int yOffset) {
+ this.xOffset = xOffset;
+ this.yOffset = yOffset;
+ }
+
+}
+
+
diff --git a/common/crazypants/enderio/conduit/geom/Offsets.java b/common/crazypants/enderio/conduit/geom/Offsets.java
new file mode 100644
index 00000000..735dc6ab
--- /dev/null
+++ b/common/crazypants/enderio/conduit/geom/Offsets.java
@@ -0,0 +1,84 @@
+package crazypants.enderio.conduit.geom;
+
+import java.util.*;
+
+import crazypants.enderio.conduit.IConduit;
+import crazypants.enderio.conduit.liquid.ILiquidConduit;
+import crazypants.enderio.conduit.power.IPowerConduit;
+import crazypants.enderio.conduit.redstone.IRedstoneConduit;
+
+
+public class Offsets {
+
+ private static Map OFFSETS = new HashMap();
+
+ static {
+ OFFSETS.put(key(IRedstoneConduit.class, true, false), Offset.BOTTOM);
+ OFFSETS.put(key(IPowerConduit.class, true, false), Offset.TOP);
+ OFFSETS.put(key(ILiquidConduit.class, true, false), Offset.NONE);
+
+ OFFSETS.put(key(IRedstoneConduit.class, false, true), Offset.LEFT);
+ OFFSETS.put(key(IPowerConduit.class, false, true), Offset.RIGHT);
+ OFFSETS.put(key(ILiquidConduit.class, false, true), Offset.NONE);
+
+ OFFSETS.put(key(IRedstoneConduit.class, true, true), Offset.BL);
+ OFFSETS.put(key(IPowerConduit.class, true, true), Offset.TR);
+ OFFSETS.put(key(ILiquidConduit.class, true, true), Offset.NONE);
+ }
+
+ public static Offset get(Class extends IConduit> type, boolean horizontal, boolean vertical) {
+ return OFFSETS.get(key(type,horizontal,vertical));
+ }
+
+ public static OffsetKey key(Class extends IConduit> type, boolean horizontal, boolean vertical) {
+ return new OffsetKey(type, horizontal, vertical);
+ }
+
+ public static class OffsetKey {
+
+ String typeName;
+ boolean horizontal;
+ boolean vertical;
+
+ private OffsetKey(Class extends IConduit> type, boolean horizontal, boolean vertical) {
+ this.typeName = type.getCanonicalName();
+ this.horizontal = horizontal;
+ this.vertical = vertical;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + (horizontal ? 1231 : 1237);
+ result = prime * result + ((typeName == null) ? 0 : typeName.hashCode());
+ result = prime * result + (vertical ? 1231 : 1237);
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ OffsetKey other = (OffsetKey) obj;
+ if (horizontal != other.horizontal)
+ return false;
+ if (typeName == null) {
+ if (other.typeName != null)
+ return false;
+ } else if (!typeName.equals(other.typeName))
+ return false;
+ if (vertical != other.vertical)
+ return false;
+ return true;
+ }
+
+ }
+
+
+
+}
diff --git a/common/crazypants/enderio/conduit/liquid/ConduitTank.java b/common/crazypants/enderio/conduit/liquid/ConduitTank.java
new file mode 100644
index 00000000..613ef186
--- /dev/null
+++ b/common/crazypants/enderio/conduit/liquid/ConduitTank.java
@@ -0,0 +1,183 @@
+package crazypants.enderio.conduit.liquid;
+
+import net.minecraft.nbt.NBTTagCompound;
+import net.minecraftforge.fluids.FluidRegistry;
+import net.minecraftforge.fluids.FluidStack;
+import net.minecraftforge.fluids.FluidTankInfo;
+import net.minecraftforge.fluids.IFluidTank;
+
+public class ConduitTank implements IFluidTank {
+
+ private FluidStack fluid;
+ private int capacity;
+ private int tankPressure = 0;
+
+ ConduitTank(int capacity) {
+ this.capacity = capacity;
+ }
+
+ public int getFluidAmount() {
+ return fluid == null ? 0 : fluid.amount;
+ }
+
+ public float getFilledRatio() {
+ if(getFluidAmount() <= 0) {
+ return 0;
+ }
+ if(getCapacity() <= 0) {
+ return -1;
+ }
+ return (float) getFluidAmount() / getCapacity();
+ }
+
+ public boolean isFull() {
+ return getFluidAmount() >= getCapacity();
+ }
+
+ public void setAmount(int amount) {
+ if(fluid != null) {
+ fluid.amount = amount;
+ }
+ }
+
+ public int getAvailableSpace() {
+ return getCapacity() - getFluidAmount();
+ }
+
+ public void addAmount(int amount) {
+ setAmount(getFluidAmount() + amount);
+ }
+
+ @Override
+ public FluidTankInfo getInfo() {
+ return new FluidTankInfo(this);
+ }
+
+
+ @Override
+ public FluidStack getFluid() {
+ return this.fluid;
+ }
+
+ @Override
+ public int getCapacity() {
+ return this.capacity;
+ }
+
+ public void setLiquid(FluidStack liquid) {
+ this.fluid = liquid;
+ }
+
+ public void setCapacity(int capacity) {
+ this.capacity = capacity;
+ if (getFluidAmount() > capacity) {
+ setAmount(capacity);
+ }
+ }
+
+ @Override
+ public int fill(FluidStack resource, boolean doFill) {
+ if (resource == null || resource.fluidID <= 0) {
+ return 0;
+ }
+
+ if (fluid == null || fluid.fluidID <= 0) {
+ if (resource.amount <= capacity) {
+ if (doFill) {
+ fluid = resource.copy();
+ }
+ return resource.amount;
+ } else {
+ if (doFill) {
+ fluid = resource.copy();
+ fluid.amount = capacity;
+ }
+ return capacity;
+ }
+ }
+
+ if (!fluid.isFluidEqual(resource)) {
+ return 0;
+ }
+
+ int space = capacity - fluid.amount;
+ if (resource.amount <= space) {
+ if (doFill) {
+ fluid.amount += resource.amount;
+ }
+ return resource.amount;
+ } else {
+ if (doFill) {
+ fluid.amount = capacity;
+ }
+ return space;
+ }
+
+ }
+
+ @Override
+ public FluidStack drain(int maxDrain, boolean doDrain) {
+ if (fluid == null || fluid.fluidID <= 0) {
+ return null;
+ }
+ if (fluid.amount <= 0) {
+ return null;
+ }
+
+ int used = maxDrain;
+ if (fluid.amount < used) {
+ used = fluid.amount;
+ }
+
+ if (doDrain) {
+ fluid.amount -= used;
+ }
+
+ FluidStack drained = new FluidStack(fluid.fluidID, used);
+
+ if (fluid.amount < 0) {
+ fluid.amount = 0;
+ }
+ return drained;
+ }
+
+ public void setTankPressure(int pressure) {
+ this.tankPressure = pressure;
+ }
+
+ public String getLiquidName() {
+ return fluid != null ? FluidRegistry.getFluidName(fluid) : null;
+ }
+
+ public boolean containsValidLiquid() {
+ return fluid != null && FluidRegistry.getFluidName(fluid) != null;
+ }
+
+ public NBTTagCompound writeToNBT(NBTTagCompound nbt) {
+ if (containsValidLiquid()) {
+ fluid.writeToNBT(nbt);
+ } else {
+ nbt.setString("emptyTank", "");
+ }
+ return nbt;
+ }
+
+ public IFluidTank readFromNBT(NBTTagCompound nbt) {
+ if (!nbt.hasKey("emptyTank")) {
+ FluidStack liquid = FluidStack.loadFluidStackFromNBT(nbt);
+ if (liquid != null) {
+ setLiquid(liquid);
+ }
+ }
+ return this;
+ }
+
+ public void remove(int amount) {
+ if(fluid == null) {
+ return;
+ }
+ fluid.amount -= amount;
+ fluid.amount = Math.max(0, fluid.amount);
+ }
+
+}
diff --git a/common/crazypants/enderio/conduit/liquid/ILiquidConduit.java b/common/crazypants/enderio/conduit/liquid/ILiquidConduit.java
new file mode 100644
index 00000000..edba3e0c
--- /dev/null
+++ b/common/crazypants/enderio/conduit/liquid/ILiquidConduit.java
@@ -0,0 +1,31 @@
+package crazypants.enderio.conduit.liquid;
+
+import crazypants.enderio.conduit.IConduit;
+import net.minecraftforge.common.ForgeDirection;
+import net.minecraftforge.fluids.FluidContainerRegistry;
+import net.minecraftforge.fluids.FluidStack;
+import net.minecraftforge.fluids.IFluidHandler;
+
+public interface ILiquidConduit extends IConduit, IFluidHandler {
+
+ static final int VOLUME_PER_CONNECTION = FluidContainerRegistry.BUCKET_VOLUME/4;
+
+ public static final String ICON_KEY ="enderio:liquidConduit";
+ public static final String ICON_CORE_KEY ="enderio:liquidConduitCore";
+ public static final String ICON_EXTRACT_KEY ="enderio:liquidConduitExtract";
+
+ void setFluidType(FluidStack fluidType);
+
+ FluidStack getFluidType();
+
+ ConduitTank getTank();
+
+ IFluidHandler getExternalHandler(ForgeDirection direction);
+
+ boolean canOutputToDir(ForgeDirection dir);
+
+ boolean isExtractingFromDir(ForgeDirection dir);
+
+ void setExtractingFromDir(ForgeDirection dir, boolean extracting);
+
+}
diff --git a/common/crazypants/enderio/conduit/liquid/ItemLiquidConduit.java b/common/crazypants/enderio/conduit/liquid/ItemLiquidConduit.java
new file mode 100644
index 00000000..4e4a0a30
--- /dev/null
+++ b/common/crazypants/enderio/conduit/liquid/ItemLiquidConduit.java
@@ -0,0 +1,36 @@
+package crazypants.enderio.conduit.liquid;
+
+import crazypants.enderio.ModObject;
+import crazypants.enderio.conduit.AbstractItemConduit;
+import crazypants.enderio.conduit.IConduit;
+import crazypants.enderio.conduit.ItemConduitSubtype;
+import net.minecraft.client.renderer.texture.IconRegister;
+import net.minecraft.item.ItemStack;
+
+public class ItemLiquidConduit extends AbstractItemConduit {
+
+ private static ItemConduitSubtype[] subtypes = new ItemConduitSubtype[] {
+ new ItemConduitSubtype(ModObject.itemLiquidConduit.unlocalisedName, ModObject.itemLiquidConduit.name, "enderio:ItemLiquidConduit"),
+ };
+
+ public static ItemLiquidConduit create() {
+ ItemLiquidConduit result = new ItemLiquidConduit();
+ result.init(subtypes);
+ return result;
+ }
+
+ protected ItemLiquidConduit() {
+ super(ModObject.itemLiquidConduit);
+ }
+
+ @Override
+ public Class extends IConduit> getBaseConduitType() {
+ return ILiquidConduit.class;
+ }
+
+ @Override
+ public IConduit createConduit(ItemStack stack) {
+ return new LiquidConduit();
+ }
+
+}
diff --git a/common/crazypants/enderio/conduit/liquid/LiquidConduit.java b/common/crazypants/enderio/conduit/liquid/LiquidConduit.java
new file mode 100644
index 00000000..af10dedb
--- /dev/null
+++ b/common/crazypants/enderio/conduit/liquid/LiquidConduit.java
@@ -0,0 +1,548 @@
+package crazypants.enderio.conduit.liquid;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import crazypants.enderio.ModObject;
+import crazypants.enderio.conduit.AbstractConduit;
+import crazypants.enderio.conduit.AbstractConduitNetwork;
+import crazypants.enderio.conduit.ConduitUtil;
+import crazypants.enderio.conduit.IConduit;
+import crazypants.enderio.conduit.IConduitBundle;
+import crazypants.enderio.conduit.RaytraceResult;
+import crazypants.enderio.conduit.geom.CollidableComponent;
+import crazypants.enderio.machine.reservoir.TileReservoir;
+import crazypants.render.IconUtil;
+import crazypants.util.BlockCoord;
+
+import net.minecraft.client.renderer.texture.IconRegister;
+import net.minecraft.entity.player.EntityPlayer;
+import net.minecraft.item.Item;
+import net.minecraft.item.ItemStack;
+import net.minecraft.nbt.NBTTagCompound;
+import net.minecraft.tileentity.TileEntity;
+import net.minecraft.util.ChatMessageComponent;
+import net.minecraft.util.Icon;
+import net.minecraft.world.World;
+import net.minecraftforge.common.ForgeDirection;
+import net.minecraftforge.fluids.Fluid;
+import net.minecraftforge.fluids.FluidContainerRegistry;
+import net.minecraftforge.fluids.FluidRegistry;
+import net.minecraftforge.fluids.FluidStack;
+import net.minecraftforge.fluids.FluidTankInfo;
+import net.minecraftforge.fluids.IFluidHandler;
+
+public class LiquidConduit extends AbstractConduit implements ILiquidConduit {
+
+ static final Map ICONS = new HashMap();
+
+ public static void initIcons() {
+ IconUtil.addIconProvider(new IconUtil.IIconProvider() {
+
+ @Override
+ public void registerIcons(IconRegister 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));
+ }
+
+ @Override
+ public int getTextureType() {
+ return 0;
+ }
+
+ });
+ }
+
+ private LiquidConduitNetwork network;
+
+ private ConduitTank tank = new ConduitTank(0);
+
+ private float lastSyncRatio = -99;
+
+ private boolean pushing = false;
+
+ private final Set extractDirs = new HashSet();
+
+ // -----------------------------
+
+ private long lastEmptyTick = 0;
+ private int numEmptyEvents = 0;
+
+ private boolean stateDirty = false;
+
+ private int maxDrainPerTick = 50;
+
+ @Override
+ public boolean onBlockActivated(EntityPlayer player, RaytraceResult res) {
+ if (player.getCurrentEquippedItem() == null) {
+ return false;
+ }
+ if (ConduitUtil.isToolEquipped(player)) {
+
+ if (!getBundle().getEntity().worldObj.isRemote) {
+ ForgeDirection faceHit = ForgeDirection.getOrientation(res.movingObjectPosition.sideHit);
+ if (res.component != null) {
+ ForgeDirection connDir = (ForgeDirection) res.component.dir;
+
+ if (connDir == ForgeDirection.UNKNOWN || connDir == faceHit) {
+ // Attempt to join networls
+ ILiquidConduit neighbour = getFluidConduit(faceHit);
+ if (neighbour != null && LiquidConduitNetwork.areFluidsCompatable(getFluidType(), neighbour.getFluidType())) {
+ // kill the networks so a new one is formed combining then
+ if (neighbour.getNetwork() != null) {
+ neighbour.getNetwork().destroyNetwork();
+ }
+ if (getNetwork() != null) {
+ getNetwork().destroyNetwork();
+ }
+ // and join'm'up
+ neighbour.conduitConnectionAdded(faceHit.getOpposite());
+ conduitConnectionAdded(faceHit);
+ }
+ } else if (containsExternalConnection(connDir)) {
+ // Toggle extraction mode
+ setExtractingFromDir(connDir, !isExtractingFromDir(connDir));
+ }
+ }
+
+ } else {
+ String str = player.worldObj.isRemote ? "[Client]" : "[Server]";
+ System.out.println(str +
+ " LiquidConduit.onBlockActivated: Tank volume is: " +
+ tank.getCapacity() + " tank contains: " + tank.getFluidAmount()
+ + " filled ratio is: " + tank.getFilledRatio());
+ }
+ return true;
+
+ } else if (player.getCurrentEquippedItem().itemID == Item.bucketEmpty.itemID) {
+
+ if (!getBundle().getEntity().worldObj.isRemote) {
+ long curTick = getBundle().getEntity().worldObj.getWorldTime();
+ if (curTick - lastEmptyTick < 20) {
+ numEmptyEvents++;
+ } else {
+ numEmptyEvents = 1;
+ }
+ lastEmptyTick = curTick;
+
+ if (numEmptyEvents < 2) {
+ tank.setAmount(0);
+ } else if (network != null) {
+ network.setFluidType(null);
+ numEmptyEvents = 0;
+ }
+ }
+
+ return true;
+ } else {
+
+ FluidStack fluid = FluidContainerRegistry.getFluidForFilledItem(player.getCurrentEquippedItem());
+ if (fluid != null) {
+ if (!getBundle().getEntity().worldObj.isRemote) {
+ if (network != null && (network.getFluidType() == null || network.getTotalVolume() < 500)) {
+ network.setFluidType(fluid);
+ ChatMessageComponent c = ChatMessageComponent.func_111066_d("Fluid type set to " + FluidRegistry.getFluidName(fluid));
+ player.sendChatToPlayer(c);
+ }
+ }
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ @Override
+ public void updateEntity(World world) {
+ super.updateEntity(world);
+ if (world.isRemote) {
+ return;
+ }
+ doExtract();
+ // Limit these updates to prevent spamming during flow
+ if (stateDirty || (lastSyncRatio != tank.getFilledRatio() && world.getTotalWorldTime() % 2 == 0)) {
+ lastSyncRatio = tank.getFilledRatio();
+ setActive(lastSyncRatio > 0);
+ getBundle().dirty();
+ stateDirty = false;
+ }
+ }
+
+ private void doExtract() {
+
+ BlockCoord loc = getLocation();
+ if (!getBundle().getEntity().worldObj.isBlockIndirectlyGettingPowered(loc.x, loc.y, loc.z)) {
+ return;
+ }
+
+ for (ForgeDirection dir : extractDirs) {
+ IFluidHandler extTank = getTankContainer(getLocation().getLocation(dir));
+
+ int maxPush = tank.getFluidAmount();
+ int couldPush = pushLiquid(dir, maxPush, false);
+ int targetExtract = Math.min(maxDrainPerTick, tank.getAvailableSpace() + couldPush);
+ FluidStack couldDrain = extTank.drain(dir.getOpposite(), targetExtract, false);
+ if (couldDrain != null && network != null && network.canAcceptLiquid(couldDrain)) {
+ couldDrain = extTank.drain(dir.getOpposite(), targetExtract, true);
+ if (couldDrain != null) {
+ FluidStack drained = couldDrain.copy();
+
+ int totalVolume = tank.getFluidAmount() + drained.amount;
+ int pushed = pushLiquid(dir, Math.min(drained.amount, maxPush), true);
+ // System.out.println("LiquidConduit.doExtract: Drained: " +
+ // drained.amount + " pushed = " + pushed + " contains volume " +
+ // tank.getAmount());
+ drained.amount = totalVolume - pushed;
+ tank.setLiquid(drained);
+ }
+ }
+ }
+
+ }
+
+ @Override
+ public boolean canOutputToDir(ForgeDirection dir) {
+ // TODO: In/Out control on externals
+ if (conduitConnections.contains(dir)) {
+ return true;
+ }
+ if (!externalConnections.contains(dir)) {
+ return false;
+ }
+ if (isExtractingFromDir(dir)) {
+ return false;
+ }
+ IFluidHandler 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;
+ }
+
+ @Override
+ public boolean isExtractingFromDir(ForgeDirection dir) {
+ return extractDirs.contains(dir);
+ }
+
+ @Override
+ public void setExtractingFromDir(ForgeDirection dir, boolean extracting) {
+ if (isExtractingFromDir(dir) == extracting) {
+ return;
+ }
+ if (!extracting) {
+ extractDirs.remove(dir);
+ } else {
+ extractDirs.add(dir);
+ }
+ stateDirty = true;
+ }
+
+ @Override
+ public void externalConnectionRemoved(ForgeDirection fromDirection) {
+ super.externalConnectionRemoved(fromDirection);
+ setExtractingFromDir(fromDirection, false);
+ }
+
+ @Override
+ public void setFluidType(FluidStack liquidType) {
+ if (tank.getFluid() != null && tank.getFluid().isFluidEqual(liquidType)) {
+ return;
+ }
+ if (liquidType != null) {
+ liquidType = liquidType.copy();
+ }
+ tank.setLiquid(liquidType);
+ }
+
+ @Override
+ public int fill(ForgeDirection from, FluidStack resource, boolean doFill) {
+ if (network == null) {
+ return 0;
+ }
+ if (network.canAcceptLiquid(resource)) {
+ network.setFluidType(resource);
+ } else {
+ return 0;
+ }
+ int recieveAmount = resource == null ? 0 : resource.amount;
+ if (recieveAmount <= 0) {
+ return 0;
+ }
+ // int maxPush = Math.min(recieveAmount, tank.getFluidAmount());
+ int maxPush = Math.max(0, recieveAmount + tank.getFluidAmount() - tank.getCapacity());
+
+ int pushedVolume = pushLiquid(from, maxPush, doFill);
+ if (doFill) {
+ tank.drain(pushedVolume, doFill);
+ return tank.fill(resource, doFill);
+ } else {
+ int amount = tank.getFluidAmount();
+ tank.drain(pushedVolume, true);
+ int res = tank.fill(resource, false);
+ tank.setAmount(amount);
+ return res;
+ }
+ }
+
+ private int pushLiquid(ForgeDirection from, int amount, boolean doPush) {
+ if (pushing || amount <= 0 || tank.getFluid() == null) { // avoid circular
+ // pushing
+ return 0;
+ }
+
+ pushing = true;
+ int pushed = 0;
+
+ try {
+
+ Set cons = new HashSet(getConduitConnections());
+ cons.addAll(getExternalConnections());
+ cons.remove(from);
+
+ if (cons.size() == 0) {
+ return pushed;
+ }
+
+ int numToPushTo;
+ int amountPerCon;
+ List toRemove = new ArrayList(cons.size());
+ FluidStack toPush = tank.getFluid().copy();
+ do {
+ numToPushTo = cons.size();
+ amountPerCon = amount / numToPushTo;
+ amountPerCon = Math.max(1, amountPerCon);
+ toPush.amount = amountPerCon;
+ for (ForgeDirection dir : cons) {
+ IFluidHandler con = getTankContainer(getLocation().getLocation(dir));
+ // NB: Dont push liquid into a conduit that is fuller than yourself
+ ILiquidConduit conduitCon = getFluidConduit(dir);
+ if (con == null || !canOutputToDir(dir) || (conduitCon != null && conduitCon.getTank().getFilledRatio() > tank.getFilledRatio())) {
+ toRemove.add(dir);
+ } else {
+ int filled = con.fill(dir.getOpposite(), toPush, doPush);
+ if (filled < amountPerCon) {
+ toRemove.add(dir);
+ }
+ pushed += filled;
+
+ }
+ toPush.amount = amountPerCon;
+ if (pushed >= amount) {
+ return amount;
+ }
+ }
+ for (ForgeDirection dir : toRemove) {
+ cons.remove(dir);
+ }
+
+ } while (!cons.isEmpty() && pushed < amount);
+
+ } finally {
+ pushing = false;
+ }
+
+ return pushed;
+ }
+
+ private ILiquidConduit getFluidConduit(ForgeDirection dir) {
+ TileEntity ent = getBundle().getEntity();
+ return ConduitUtil.getConduit(ent.worldObj, ent, dir, ILiquidConduit.class);
+ }
+
+ @Override
+ public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) {
+ return tank.drain(maxDrain, doDrain);
+ }
+
+ @Override
+ public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) {
+ if (resource != null && !resource.isFluidEqual(tank.getFluid())) {
+ return null;
+ }
+ return drain(from, resource.amount, doDrain);
+ }
+
+ @Override
+ public boolean canFill(ForgeDirection from, Fluid fluid) {
+ if (tank.getFluid() == null) {
+ return true;
+ }
+ if (fluid != null && fluid.getID() == tank.getFluid().fluidID) {
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public boolean canDrain(ForgeDirection from, Fluid fluid) {
+ if (tank.getFluid() == null || fluid == null) {
+ return false;
+ }
+ return tank.getFluid().getFluid().getID() == fluid.getID();
+ }
+
+ @Override
+ public FluidTankInfo[] getTankInfo(ForgeDirection from) {
+ return new FluidTankInfo[] { tank.getInfo() };
+ }
+
+ // -----------------------------
+
+ @Override
+ public void writeToNBT(NBTTagCompound nbtRoot) {
+ super.writeToNBT(nbtRoot);
+ if (tank.containsValidLiquid()) {
+ nbtRoot.setTag("tank", tank.getFluid().writeToNBT(new NBTTagCompound()));
+ }
+
+ int[] dirs = new int[extractDirs.size()];
+ Iterator cons = extractDirs.iterator();
+ for (int i = 0; i < dirs.length; i++) {
+ dirs[i] = cons.next().ordinal();
+ }
+ nbtRoot.setIntArray("extractDirs", dirs);
+ }
+
+ @Override
+ public void readFromNBT(NBTTagCompound nbtRoot) {
+ super.readFromNBT(nbtRoot);
+ updateTanksCapacity();
+ FluidStack liquid = FluidStack.loadFluidStackFromNBT(nbtRoot.getCompoundTag("tank"));
+ tank.setLiquid(liquid);
+
+ extractDirs.clear();
+ int[] dirs = nbtRoot.getIntArray("extractDirs");
+ for (int i = 0; i < dirs.length; i++) {
+ extractDirs.add(ForgeDirection.values()[dirs[i]]);
+ }
+ }
+
+ @Override
+ protected void connectionsChanged() {
+ super.connectionsChanged();
+ updateTanksCapacity();
+ }
+
+ @Override
+ public ConduitTank getTank() {
+ return tank;
+ }
+
+ @Override
+ public Class extends IConduit> getBaseConduitType() {
+ return ILiquidConduit.class;
+ }
+
+ @Override
+ public ItemStack createItem() {
+ return new ItemStack(ModObject.itemLiquidConduit.actualId, 1, 0);
+ }
+
+ @Override
+ public AbstractConduitNetwork> getNetwork() {
+ return network;
+ }
+
+ @Override
+ public boolean setNetwork(AbstractConduitNetwork> network) {
+ if (network == null) {
+ this.network = null;
+ return true;
+ }
+
+ LiquidConduitNetwork n = (LiquidConduitNetwork) network;
+ if (tank.getFluid() == null) {
+ tank.setLiquid(n.getFluidType() == null ? null : n.getFluidType().copy());
+ } else if (n.getFluidType() == null) {
+ n.setFluidType(tank.getFluid());
+ } else if (!tank.getFluid().isFluidEqual(n.getFluidType())) {
+ return false;
+ }
+ this.network = (LiquidConduitNetwork) network;
+ return true;
+ }
+
+ @Override
+ public boolean canConnectToExternal(ForgeDirection direction) {
+ return getExternalHandler(direction) != null;
+ }
+
+ @Override
+ public IFluidHandler getExternalHandler(ForgeDirection direction) {
+ IFluidHandler con = getTankContainer(getLocation().getLocation(direction));
+ return (con != null && !(con instanceof IConduitBundle)) ? con : null;
+ }
+
+ @Override
+ public boolean canConnectToConduit(ForgeDirection direction, IConduit con) {
+ if (!(con instanceof ILiquidConduit)) {
+ return false;
+ }
+ if (getFluidType() != null && ((ILiquidConduit) con).getFluidType() == null) {
+ return false;
+ }
+ return LiquidConduitNetwork.areFluidsCompatable(getFluidType(), ((ILiquidConduit) con).getFluidType());
+ }
+
+ @Override
+ public net.minecraftforge.fluids.FluidStack getFluidType() {
+ FluidStack result = null;
+ if (network != null) {
+ result = network.getFluidType();
+ }
+ if (result == null) {
+ result = tank.getFluid();
+ }
+ return result;
+ }
+
+ @Override
+ public Icon getTextureForState(CollidableComponent component) {
+ if (component.dir == ForgeDirection.UNKNOWN) {
+ return ICONS.get(ICON_CORE_KEY);
+ }
+ if (isExtractingFromDir((ForgeDirection) component.dir)) {
+ return ICONS.get(ICON_EXTRACT_KEY);
+ }
+ return ICONS.get(ICON_KEY);
+ }
+
+ @Override
+ public Icon getTransmitionTextureForState(CollidableComponent component) {
+ if (active && tank.getFluid() != null) {
+ return tank.getFluid().getFluid().getStillIcon();
+ }
+ return null;
+ }
+
+ @Override
+ public float getTransmitionGeometryScale() {
+ return tank.getFilledRatio();
+ }
+
+ private IFluidHandler getTankContainer(BlockCoord bc) {
+ return getTankContainer(bc.x, bc.y, bc.z);
+ }
+
+ private IFluidHandler getTankContainer(int x, int y, int z) {
+ TileEntity te = getBundle().getEntity().worldObj.getBlockTileEntity(x, y, z);
+ if (te instanceof IFluidHandler) {
+ return (IFluidHandler) te;
+ }
+ return null;
+ }
+
+ private void updateTanksCapacity() {
+ int totalConnections = getConduitConnections().size() + getExternalConnections().size();
+ tank.setCapacity(totalConnections * VOLUME_PER_CONNECTION);
+ }
+
+}
diff --git a/common/crazypants/enderio/conduit/liquid/LiquidConduitNetwork.java b/common/crazypants/enderio/conduit/liquid/LiquidConduitNetwork.java
new file mode 100644
index 00000000..31ab6d09
--- /dev/null
+++ b/common/crazypants/enderio/conduit/liquid/LiquidConduitNetwork.java
@@ -0,0 +1,285 @@
+package crazypants.enderio.conduit.liquid;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import crazypants.enderio.conduit.AbstractConduitNetwork;
+import crazypants.enderio.conduit.ConduitUtil;
+import crazypants.enderio.conduit.IConduit;
+import crazypants.util.BlockCoord;
+
+import net.minecraft.world.World;
+import net.minecraftforge.common.ForgeDirection;
+import net.minecraftforge.fluids.FluidStack;
+import net.minecraftforge.fluids.IFluidHandler;
+
+public class LiquidConduitNetwork extends AbstractConduitNetwork {
+
+ private FluidStack liquidType;
+ private long timeAtLastApply;
+
+ private int maxFlowsPerTick = 10;
+ private int lastFlowIndex = 0;
+
+ private boolean printFlowTiming = false;
+
+ @Override
+ public Class extends ILiquidConduit> getBaseConduitType() {
+ return ILiquidConduit.class;
+ }
+
+ public FluidStack getFluidType() {
+ return liquidType;
+ }
+
+ @Override
+ public void addConduit(ILiquidConduit con) {
+ super.addConduit(con);
+ con.setFluidType(liquidType);
+ }
+
+ public void setFluidType(FluidStack newType) {
+ if (liquidType != null && liquidType.isFluidEqual(newType)) {
+ return;
+ }
+ if (newType != null) {
+ liquidType = newType.copy();
+ liquidType.amount = 0;
+ } else {
+ liquidType = null;
+ }
+ for (ILiquidConduit conduit : conduits) {
+ conduit.setFluidType(liquidType);
+ }
+ }
+
+ public boolean canAcceptLiquid(FluidStack acceptable) {
+ return areFluidsCompatable(liquidType, acceptable);
+ }
+
+ public static boolean areFluidsCompatable(FluidStack a, FluidStack b) {
+ if (a == null || b == null) {
+ return true;
+ }
+ return a.isFluidEqual(b);
+ }
+
+ public int getTotalVolume() {
+ int totalVolume = 0;
+ for (ILiquidConduit con : conduits) {
+ totalVolume += con.getTank().getFluidAmount();
+ }
+ return totalVolume;
+ }
+
+ @Override
+ public void onUpdateEntity(IConduit conduit) {
+ World world = conduit.getBundle().getEntity().worldObj;
+ if (world == null) {
+ return;
+ }
+ if (world.isRemote || liquidType == null) {
+ return;
+ }
+
+ long curTime = world.getTotalWorldTime();
+ if (curTime != timeAtLastApply) {
+ timeAtLastApply = curTime;
+ // 1000 water, 6000 lava
+ if (liquidType != null && liquidType.getFluid() != null) {
+ int visc = liquidType.getFluid().getViscosity();
+ if (curTime % (visc / 500) == 0) {
+ long start = System.nanoTime();
+ if (doFlow() && printFlowTiming) {
+ long took = System.nanoTime() - start;
+ double secs = took / 1000000000.0;
+ System.out.println("LiquidConduitNetwork.onUpdateEntity: took " + secs + " secs, " + (secs * 1000) + " millis");
+ }
+ }
+ }
+ }
+ }
+
+ private boolean doFlow() {
+
+ // int preVol = 0;
+ // for (ILiquidConduit con : conduits) {
+ // preVol += con.getTank().getAmount();
+ // }
+
+ List actions = new ArrayList();
+ for (int i = 0; i < Math.min(maxFlowsPerTick, conduits.size()); i++) {
+
+ if (lastFlowIndex >= conduits.size()) {
+ lastFlowIndex = 0;
+ }
+ flowFrom(conduits.get(lastFlowIndex), actions);
+ ++lastFlowIndex;
+
+ }
+ for (FlowAction action : actions) {
+ action.apply();
+ }
+
+ // int postVol = 0;
+ // for (ILiquidConduit con : conduits) {
+ // postVol += con.getTank().getAmount();
+ // }
+ // if (preVol != postVol) {
+ // System.out.println("LiquidConduitNetwork.doFlow: net change of: " +
+ // (postVol - preVol));
+ // }
+
+ return !actions.isEmpty();
+ }
+
+ private void flowFrom(ILiquidConduit con, List actions) {
+
+ ConduitTank tank = con.getTank();
+ int totalAmount = tank.getFluidAmount();
+ if (totalAmount <= 0) {
+ return;
+ }
+
+ int maxFlowVolume = 20;
+
+ // First flow all we can down, then balance the rest
+ if (con.getConduitConnections().contains(ForgeDirection.DOWN)) {
+ BlockCoord loc = con.getLocation().getLocation(ForgeDirection.DOWN);
+ ILiquidConduit downCon = ConduitUtil.getConduit(con.getBundle().getEntity().worldObj, loc.x, loc.y, loc.z, ILiquidConduit.class);
+ int filled = downCon.fill(ForgeDirection.UP, tank.getFluid().copy(), false);
+ tank.addAmount(-filled);
+ downCon.getTank().addAmount(filled);
+ }
+
+ totalAmount = tank.getFluidAmount();
+ if (totalAmount <= 0) {
+ return;
+ }
+ FluidStack available = tank.getFluid();
+ int totalRequested = 0;
+ int numRequests = 0;
+ // Then to external connections
+ for (ForgeDirection dir : con.getExternalConnections()) {
+ if (con.canOutputToDir(dir)) {
+ IFluidHandler extCon = con.getExternalHandler(dir);
+ if (extCon != null) {
+ int amount = extCon.fill(dir.getOpposite(), available.copy(), false);
+ if (amount > 0) {
+ totalRequested += amount;
+ numRequests++;
+ }
+ }
+ }
+ }
+
+ if (numRequests > 0) {
+ int amountPerRequest = Math.min(totalAmount, totalRequested) / numRequests;
+
+ // -----
+ amountPerRequest = Math.min(maxFlowVolume, amountPerRequest);
+ // ----
+
+ FluidStack requestSource = available.copy();
+ requestSource.amount = amountPerRequest;
+ for (ForgeDirection dir : con.getExternalConnections()) {
+ if (con.canOutputToDir(dir)) {
+ IFluidHandler extCon = con.getExternalHandler(dir);
+ if (extCon != null) {
+ int amount = extCon.fill(dir.getOpposite(), requestSource.copy(), true);
+ if (amount > 0) {
+ tank.addAmount(-amount);
+ }
+ }
+ }
+ }
+ }
+
+ // TODO: Liquid can currently flow upwards from a down connection
+
+ totalAmount = tank.getFluidAmount();
+ if (totalAmount <= 0) {
+ return;
+ }
+ int totalCapacity = tank.getCapacity();
+
+ BlockCoord loc = con.getLocation();
+ Collection connections =
+ ConduitUtil.getConnectedConduits(con.getBundle().getEntity().worldObj,
+ loc.x, loc.y, loc.z, ILiquidConduit.class);
+ int numTargets = 0;
+ for (ILiquidConduit neighbour : connections) {
+ if (canFlowTo(con, neighbour)) { // can only flow within same network
+ totalAmount += neighbour.getTank().getFluidAmount();
+ totalCapacity += neighbour.getTank().getCapacity();
+ numTargets++;
+ }
+ }
+
+ float targetRatio = (float) totalAmount / totalCapacity;
+ int netChange = 0;
+ int flowVolume = Math.round((targetRatio - tank.getFilledRatio()) * tank.getCapacity());
+
+ // -----
+ flowVolume = Math.min(maxFlowVolume, flowVolume);
+ // ----
+
+ if (Math.abs(flowVolume) < 2) {
+ return; // dont bother with transfers of less than a thousands of a bucket
+ }
+
+ netChange += flowVolume;
+ actions.add(new FlowAction(con, flowVolume));
+ for (ILiquidConduit neigbour : connections) {
+ if (canFlowTo(con, neigbour)) { // can only flow within same network
+ flowVolume = Math.round((targetRatio - neigbour.getTank().getFilledRatio()) * neigbour.getTank().getCapacity());
+ if (flowVolume != 0) {
+ actions.add(new FlowAction(neigbour, flowVolume));
+ netChange += flowVolume;
+ }
+ }
+ }
+
+ if (netChange != 0) {
+ actions.add(new FlowAction(con, -netChange));
+ }
+ }
+
+ private boolean canFlowTo(ILiquidConduit con, ILiquidConduit neighbour) {
+ if (neighbour.getNetwork() != this) {
+ return false;
+ }
+ if (neighbour.getLocation().y > con.getLocation().y) {
+ return false;
+ }
+ float nr = neighbour.getTank().getFilledRatio();
+ if (nr >= con.getTank().getFilledRatio()) {
+ return false;
+ }
+ return true;
+ }
+
+ static class FlowAction {
+ ILiquidConduit con;
+ int amount;
+
+ FlowAction(ILiquidConduit con, int amount) {
+ this.con = con;
+ this.amount = amount;
+ }
+
+ void apply() {
+ if (amount != 0) {
+ // int preFlow = con.getTank().getAmount();
+ con.getTank().addAmount(amount);
+ // System.out.println("LiquidConduitNetwork.FlowAction.apply: Con " +
+ // con.getLocation() + " went from " + preFlow + " to " +
+ // con.getTank().getAmount()
+ // + " with transfer amount " + amount);
+ }
+ }
+
+ }
+
+}
diff --git a/common/crazypants/enderio/conduit/liquid/LiquidConduitRenderer.java b/common/crazypants/enderio/conduit/liquid/LiquidConduitRenderer.java
new file mode 100644
index 00000000..96641769
--- /dev/null
+++ b/common/crazypants/enderio/conduit/liquid/LiquidConduitRenderer.java
@@ -0,0 +1,118 @@
+package crazypants.enderio.conduit.liquid;
+
+import static crazypants.render.CubeRenderer.setupVertices;
+import crazypants.enderio.conduit.*;
+import crazypants.enderio.conduit.geom.CollidableComponent;
+import crazypants.enderio.conduit.render.*;
+import crazypants.render.BoundingBox;
+import crazypants.vecmath.Vector3d;
+
+import net.minecraft.util.Icon;
+import net.minecraftforge.common.ForgeDirection;
+
+public class LiquidConduitRenderer extends DefaultConduitRenderer {
+
+ private float downRatio;
+
+ private float flatRatio;
+
+ private float upRatio;
+
+ @Override
+ public boolean isRendererForConduit(IConduit conduit) {
+ if (conduit instanceof ILiquidConduit) {
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public void renderEntity(ConduitBundleRenderer conduitBundleRenderer, IConduitBundle te, IConduit conduit, double x, double y, double z, float partialTick,
+ float worldLight) {
+ calculateRatios((ILiquidConduit) conduit);
+ super.renderEntity(conduitBundleRenderer, te, conduit, x, y, z, partialTick, worldLight);
+ }
+
+ protected void renderConduit(Icon tex, CollidableComponent component) {
+ if (isNSEWUP(component.dir)) {
+ BoundingBox[] cubes = toCubes(component.bound);
+ for (BoundingBox cube : cubes) {
+ drawSection(cube, tex.getMinU(), tex.getMaxU(), tex.getMinV(), tex.getMaxV(), component.dir, false);
+ }
+ } else {
+ drawSection(component.bound, tex.getMinU(), tex.getMaxU(), tex.getMinV(), tex.getMaxV(), component.dir, true);
+ }
+ }
+
+ protected void renderTransmission(Icon tex, CollidableComponent component) {
+ BoundingBox[] cubes = toCubes(component.bound);
+ for (BoundingBox cube : cubes) {
+ drawSection(cube, tex.getMinU(), tex.getMaxU(), tex.getMinV(), tex.getMaxV(), component.dir, true);
+ }
+ }
+
+ @Override
+ protected void setVerticesForTransmission(BoundingBox bound, ForgeDirection id) {
+
+ float yScale = getRatioForConnection(id);
+
+ float xs = ((ForgeDirection) id).offsetX == 0 ? 0.9f : 1;
+ float ys = ((ForgeDirection) id).offsetY == 0 ? Math.min(yScale, 0.9f) : yScale;
+ float zs = ((ForgeDirection) id).offsetZ == 0 ? 0.9f : 1;
+
+ float sizeY = bound.sizeY();
+ bound = bound.scale(xs, ys, zs);
+ float transY = (bound.sizeY() - sizeY) / 2;
+
+ Vector3d translation = new Vector3d(0, transY, 0);
+ setupVertices(bound.translate(translation));
+ }
+
+ private void calculateRatios(ILiquidConduit conduit) {
+ ConduitTank tank = conduit.getTank();
+ int totalAmount = tank.getFluidAmount();
+
+ int upCapacity = 0;
+ if (conduit.containsConduitConnection(ForgeDirection.UP) || conduit.containsExternalConnection(ForgeDirection.UP)) {
+ upCapacity = ILiquidConduit.VOLUME_PER_CONNECTION;
+ }
+ int downCapacity = 0;
+ if (conduit.containsConduitConnection(ForgeDirection.DOWN) || conduit.containsExternalConnection(ForgeDirection.DOWN)) {
+ downCapacity = ILiquidConduit.VOLUME_PER_CONNECTION;
+ }
+
+ int flatCapacity = tank.getCapacity() - upCapacity - downCapacity;
+
+ int usedCapacity = 0;
+ if (downCapacity > 0) {
+ int inDown = Math.min(totalAmount, downCapacity);
+ usedCapacity += inDown;
+ downRatio = (float) inDown / downCapacity;
+ }
+ if (flatCapacity > 0 && usedCapacity < totalAmount) {
+ int inFlat = Math.min(flatCapacity, totalAmount - usedCapacity);
+ usedCapacity += inFlat;
+ flatRatio = (float) inFlat / flatCapacity;
+ } else {
+ flatRatio = 0;
+ }
+ if (upCapacity > 0 && usedCapacity < totalAmount) {
+ int inUp = Math.min(upCapacity, totalAmount - usedCapacity);
+ upRatio = (float) inUp / upCapacity;
+ } else {
+ upRatio = 0;
+ }
+
+ }
+
+ private float getRatioForConnection(ForgeDirection id) {
+ if (id == ForgeDirection.UP) {
+ return upRatio;
+ }
+ if (id == ForgeDirection.DOWN) {
+ return downRatio;
+ }
+ return flatRatio;
+ }
+
+}
diff --git a/common/crazypants/enderio/conduit/power/IPowerConduit.java b/common/crazypants/enderio/conduit/power/IPowerConduit.java
new file mode 100644
index 00000000..7c65d48a
--- /dev/null
+++ b/common/crazypants/enderio/conduit/power/IPowerConduit.java
@@ -0,0 +1,23 @@
+package crazypants.enderio.conduit.power;
+
+import crazypants.enderio.conduit.IConduit;
+import crazypants.enderio.power.ICapacitor;
+import crazypants.enderio.power.IInternalPowerReceptor;
+import net.minecraftforge.common.ForgeDirection;
+import buildcraft.api.power.IPowerReceptor;
+
+public interface IPowerConduit extends IConduit, IInternalPowerReceptor {
+
+ public static final String ICON_KEY ="enderio:powerConduit";
+ public static final String ICON_CORE_KEY ="enderio:powerConduitCore";
+ public static final String ICON_TRANSMISSION_KEY = "enderio:powerConduitTransmission";
+
+ IPowerReceptor getExternalPowerReceptor(ForgeDirection direction);
+
+ ICapacitor getCapacitor();
+
+ float getEnergyStored();
+
+ void setEnergyStored(float energyStored);
+
+}
diff --git a/common/crazypants/enderio/conduit/power/ItemPowerConduit.java b/common/crazypants/enderio/conduit/power/ItemPowerConduit.java
new file mode 100644
index 00000000..0fd02d5c
--- /dev/null
+++ b/common/crazypants/enderio/conduit/power/ItemPowerConduit.java
@@ -0,0 +1,53 @@
+package crazypants.enderio.conduit.power;
+
+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.power.ICapacitor;
+
+public class ItemPowerConduit extends AbstractItemConduit {
+
+ static ItemConduitSubtype[] subtypes = new ItemConduitSubtype[] {
+ new ItemConduitSubtype(ModObject.itemPowerConduit.unlocalisedName, ModObject.itemPowerConduit.name, "enderio:itemPowerConduit"),
+ new ItemConduitSubtype(ModObject.itemPowerConduit.unlocalisedName + "Enhanced", "Enhanced " + ModObject.itemPowerConduit.name, "enderio:itemPowerConduitEnhanced"),
+ new ItemConduitSubtype(ModObject.itemPowerConduit.unlocalisedName + "Ender", "Ender " + ModObject.itemPowerConduit.name, "enderio:itemPowerConduitEnder")
+ };
+
+ public static ItemPowerConduit create() {
+ ItemPowerConduit result = new ItemPowerConduit();
+ result.init(subtypes);
+ return result;
+ }
+
+ protected ItemPowerConduit() {
+ super(ModObject.itemPowerConduit);
+ }
+
+ @Override
+ public Class extends IConduit> getBaseConduitType() {
+ return IPowerConduit.class;
+ }
+
+ @Override
+ public IConduit createConduit(ItemStack stack) {
+ return new PowerConduit(stack.getItemDamage());
+ }
+
+ @Override
+ @SideOnly(Side.CLIENT)
+ public void addInformation(ItemStack itemStack, EntityPlayer par2EntityPlayer, List list, boolean par4) {
+ super.addInformation(itemStack, par2EntityPlayer, list, par4);
+ ICapacitor cap = PowerConduit.CAPACITORS[itemStack.getItemDamage()];
+ list.add(String.format("I/O %d MJ/t", cap.getMaxEnergyExtracted()));
+ list.add(String.format("Storage %d MJ", cap.getMaxEnergyStored()));
+ }
+
+
+}
diff --git a/common/crazypants/enderio/conduit/power/NetworkPowerManager.java b/common/crazypants/enderio/conduit/power/NetworkPowerManager.java
new file mode 100644
index 00000000..eea92f16
--- /dev/null
+++ b/common/crazypants/enderio/conduit/power/NetworkPowerManager.java
@@ -0,0 +1,251 @@
+package crazypants.enderio.conduit.power;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.Map;
+
+import crazypants.enderio.conduit.power.PowerConduitNetwork.ReceptorEntry;
+import crazypants.enderio.power.IInternalPowerReceptor;
+import crazypants.enderio.power.PowerHandlerUtil;
+import crazypants.util.BlockCoord;
+
+import net.minecraft.nbt.NBTTagCompound;
+import net.minecraft.world.World;
+import net.minecraftforge.common.ForgeDirection;
+import buildcraft.api.power.IPowerReceptor;
+import buildcraft.api.power.PowerHandler;
+import buildcraft.api.power.PowerHandler.PowerReceiver;
+import buildcraft.api.power.PowerHandler.Type;
+
+public class NetworkPowerManager {
+
+ private PowerConduitNetwork network;
+
+ private int maxEnergyStored;
+ private float energyStored;
+ private float reserved;
+
+ private int updateRenderTicks = 10;
+ private int inactiveTicks = 100;
+
+ private final List receptors = new ArrayList();
+ private ListIterator receptorIterator = receptors.listIterator();
+
+ private boolean lastActiveValue = false;
+ private int ticksWithNoPower = 0;
+
+ private final Map starveBuffers = new HashMap();
+
+ public NetworkPowerManager(PowerConduitNetwork netowrk, World world) {
+ this.network = netowrk;
+ maxEnergyStored = 64;
+ }
+
+
+ public float addEnergy(float quantity) {
+ float used = quantity;
+ energyStored += quantity;
+ if (energyStored > maxEnergyStored) {
+ used -= energyStored - maxEnergyStored;
+ energyStored = maxEnergyStored;
+ } else if (energyStored < 0) {
+ used -= energyStored;
+ energyStored = 0;
+ }
+ updateConduitStorage();
+ return used;
+ }
+
+ public void applyRecievedPower() {
+
+ updateStorage();
+
+ float extracted = extractRecievedEnergy();
+ addEnergy(extracted);
+ checkReserves();
+ float quantity = energyStored;
+ boolean active;
+ if (quantity > 0) {
+ ticksWithNoPower = 0;
+ active = true;
+ } else {
+ ticksWithNoPower++;
+ active = false;
+ }
+
+ boolean doRender = active != lastActiveValue && (active || (!active && ticksWithNoPower > updateRenderTicks));
+
+ if (doRender) {
+ lastActiveValue = active;
+ for (IPowerConduit con : network.getConduits()) {
+ con.setActive(active);
+ }
+ }
+
+ if (quantity <= 0 || receptors.isEmpty()) {
+ return;
+ }
+
+
+ int appliedCount = 0;
+ int numReceptors = receptors.size();
+ int numEngines = 0;
+ while (quantity > 0 && appliedCount < numReceptors) {
+
+ if (!receptors.isEmpty() && !receptorIterator.hasNext()) {
+ receptorIterator = receptors.listIterator();
+ }
+
+ ReceptorEntry r = receptorIterator.next();
+ float reservedForEntry = removeReservedEnergy(r);
+
+ for (ForgeDirection dir : r.directions) {
+
+ PowerReceiver pp = r.powerReceptor.getPowerReceiver(dir);
+ if(pp != null) {
+ if(pp.getType() != Type.ENGINE) {
+
+ float used = 0;
+ float nonReservedPower = quantity - reserved;
+ float available = nonReservedPower + reservedForEntry;
+ float canOffer = Math.min(r.emmiter.getCapacitor().getMaxEnergyExtracted(),available);
+ float requested = pp.powerRequest();
+
+ //If it is possible to supply the minimum amount of energy
+ if(pp.getMinEnergyReceived() <= r.emmiter.getCapacitor().getMaxEnergyExtracted()) {
+ //Buffer energy if we can't meet it now
+ if(pp.getMinEnergyReceived() > canOffer && requested > 0) {
+ reserveEnergy(r, canOffer);
+ used += canOffer;
+ } else if (r.powerReceptor instanceof IInternalPowerReceptor) {
+ used = PowerHandlerUtil.transmitInternal((IInternalPowerReceptor) r.powerReceptor, pp, canOffer, Type.PIPE, dir);
+ } else {
+ used = pp.receiveEnergy(Type.PIPE, Math.min(requested, canOffer), dir);
+ }
+
+ }
+ quantity -= used;
+
+ } else if(pp.getType() == Type.ENGINE && !(r.powerReceptor instanceof IInternalPowerReceptor)) {
+ numEngines++;
+ }
+
+ if(quantity <= 0) {
+ break;
+ }
+
+ }
+ }
+ appliedCount++;
+ }
+ float leaveForBlowingUpEngines = numEngines * 8;
+ if(leaveForBlowingUpEngines > maxEnergyStored) {
+ leaveForBlowingUpEngines = maxEnergyStored;
+ }
+ energyStored = Math.min(quantity, maxEnergyStored - leaveForBlowingUpEngines);
+ updateConduitStorage();
+ }
+
+ private float removeReservedEnergy(ReceptorEntry r) {
+ StarveBuffer starveBuf = starveBuffers.remove(r.coord);
+ if(starveBuf == null) {
+ return 0;
+ }
+ float result = starveBuf.stored;
+ reserved -= result;
+ return result;
+ }
+
+ private void reserveEnergy(ReceptorEntry r, float amount) {
+ starveBuffers.put(r.coord, new StarveBuffer(amount));
+ reserved += amount;
+ }
+
+ private void checkReserves() {
+ if(reserved > maxEnergyStored * 0.9) {
+ starveBuffers.clear();
+ reserved = 0;
+ }
+ }
+
+
+ private void updateConduitStorage() {
+ float energyLeft = energyStored;
+ for(IPowerConduit con : network.getConduits()) {
+ float give = con.getCapacitor().getMaxEnergyStored();
+ if(give > energyLeft) {
+ give = energyLeft;
+ }
+ con.setEnergyStored(give);
+ energyLeft -= give;
+ }
+ }
+
+
+ boolean isActive() {
+ return energyStored > 0;
+ }
+
+ private void updateStorage() {
+ maxEnergyStored = 0;
+ energyStored = 0;
+ for(IPowerConduit con : network.getConduits()) {
+ maxEnergyStored += con.getCapacitor().getMaxEnergyStored();
+ energyStored += con.getEnergyStored();
+ }
+ if(energyStored > maxEnergyStored) {
+ energyStored = maxEnergyStored;
+ }
+
+ }
+
+ private float extractRecievedEnergy() {
+ float extracted = 0;
+ for(IPowerConduit conduit : network.getConduits()) {
+ PowerHandler ph = conduit.getPowerHandler();
+ extracted += ph.getEnergyStored();
+ ph.update();
+ ph.setEnergy(0);
+ }
+ return extracted;
+ }
+
+ public void receptorsChanged() {
+ receptors.clear();
+ receptors.addAll(network.getPowerReceptors());
+ receptorIterator = receptors.listIterator();
+ }
+
+
+ void onNetworkDestroyed() {
+ //Pass out all the stored energy to the conduits
+ for(IPowerConduit con : network.getConduits()) {
+ PowerHandler ph = con.getPowerHandler();
+ float give = ph.getMaxEnergyStored() - ph.getEnergyStored();
+ give = Math.min(give, energyStored);
+ ph.setEnergy(ph.getEnergyStored() + give);
+ energyStored -= give;
+ if(energyStored <= 0) {
+ return;
+ }
+ }
+
+ }
+
+ private static class StarveBuffer {
+
+ float stored;
+
+ public StarveBuffer(float stored) {
+ this.stored = stored;
+ }
+
+ void addToStore(float val) {
+ stored += val;
+ }
+
+ }
+
+}
diff --git a/common/crazypants/enderio/conduit/power/PowerConduit.java b/common/crazypants/enderio/conduit/power/PowerConduit.java
new file mode 100644
index 00000000..e299bdf5
--- /dev/null
+++ b/common/crazypants/enderio/conduit/power/PowerConduit.java
@@ -0,0 +1,234 @@
+package crazypants.enderio.conduit.power;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import crazypants.enderio.ModObject;
+import crazypants.enderio.conduit.AbstractConduit;
+import crazypants.enderio.conduit.AbstractConduitNetwork;
+import crazypants.enderio.conduit.IConduit;
+import crazypants.enderio.conduit.IConduitBundle;
+import crazypants.enderio.conduit.geom.CollidableComponent;
+import crazypants.enderio.power.BasicCapacitor;
+import crazypants.enderio.power.ICapacitor;
+import crazypants.enderio.power.PowerHandlerUtil;
+import crazypants.render.BoundingBox;
+import crazypants.render.IconUtil;
+import crazypants.vecmath.Vector3d;
+
+import net.minecraft.client.renderer.texture.IconRegister;
+import net.minecraft.item.ItemStack;
+import net.minecraft.nbt.NBTTagCompound;
+import net.minecraft.tileentity.TileEntity;
+import net.minecraft.util.Icon;
+import net.minecraft.world.World;
+import net.minecraftforge.common.ForgeDirection;
+import buildcraft.api.power.IPowerEmitter;
+import buildcraft.api.power.IPowerReceptor;
+import buildcraft.api.power.PowerHandler;
+import buildcraft.api.power.PowerHandler.PowerReceiver;
+import buildcraft.api.power.PowerHandler.Type;
+
+public class PowerConduit extends AbstractConduit implements IPowerConduit {
+
+ static final Map ICONS = new HashMap();
+
+ static final ICapacitor[] CAPACITORS = new BasicCapacitor[] {
+ new BasicCapacitor(0, 64, 64, 0, 0, 0, 64),
+ new BasicCapacitor(0, 128, 128, 0, 0, 0, 128),
+ new BasicCapacitor(0, 1024, 1024, 0, 0, 0, 1024)
+ };
+
+ static final String[] POSTFIX = new String[] { "", "Enhanced", "Ender" };
+
+ static ItemStack createItemStackForSubtype(int subtype) {
+ ItemStack result = new ItemStack(ModObject.itemPowerConduit.actualId, 1, subtype);
+ return result;
+
+ }
+
+ public static void initIcons() {
+ IconUtil.addIconProvider(new IconUtil.IIconProvider() {
+
+ @Override
+ public void registerIcons(IconRegister register) {
+ for (String pf : POSTFIX) {
+ ICONS.put(ICON_KEY + pf, register.registerIcon(ICON_KEY + pf));
+ ICONS.put(ICON_CORE_KEY + pf, register.registerIcon(ICON_CORE_KEY + pf));
+ }
+ ICONS.put(ICON_TRANSMISSION_KEY, register.registerIcon(ICON_TRANSMISSION_KEY));
+ }
+
+ @Override
+ public int getTextureType() {
+ return 0;
+ }
+
+ });
+ }
+
+ public static final float WIDTH = 0.075f;
+ public static final float HEIGHT = 0.075f;
+
+ public static final Vector3d MIN = new Vector3d(0.5f - WIDTH, 0.5 - HEIGHT, 0.5 - WIDTH);
+ public static final Vector3d MAX = new Vector3d(MIN.x + WIDTH, MIN.y + HEIGHT, MIN.z + WIDTH);
+
+ public static final BoundingBox BOUNDS = new BoundingBox(MIN, MAX);
+
+ protected PowerConduitNetwork network;
+ private PowerHandler powerHandler;
+
+ private int subtype;
+
+ private float energyStored;
+
+ public PowerConduit() {
+ }
+
+ public PowerConduit(int meta) {
+ this.subtype = meta;
+ powerHandler = createPowerHandlerForType();
+ }
+
+ @Override
+ public ICapacitor getCapacitor() {
+ return CAPACITORS[subtype];
+ }
+
+ private PowerHandler createPowerHandlerForType() {
+ return PowerHandlerUtil.createHandler(CAPACITORS[subtype], this, Type.PIPE);
+ }
+
+ public float getEnergyStored() {
+ return energyStored;
+ }
+
+ public void setEnergyStored(float energyStored) {
+ this.energyStored = energyStored;
+ }
+
+ @Override
+ public void writeToNBT(NBTTagCompound nbtRoot) {
+ super.writeToNBT(nbtRoot);
+ nbtRoot.setShort("subtype", (short) subtype);
+ nbtRoot.setFloat("energyStored", energyStored);
+ }
+
+ @Override
+ public void readFromNBT(NBTTagCompound nbtRoot) {
+ super.readFromNBT(nbtRoot);
+ subtype = nbtRoot.getShort("subtype");
+ if (powerHandler == null) {
+ powerHandler = createPowerHandlerForType();
+ }
+ energyStored = nbtRoot.getFloat("energyStored");
+ if(energyStored < 0) {
+ energyStored = 0;
+ }
+ }
+
+ @Override
+ public PowerReceiver getPowerReceiver(ForgeDirection side) {
+ return powerHandler.getPowerReceiver();
+ }
+
+ @Override
+ public PowerHandler getPowerHandler() {
+ return powerHandler;
+ }
+
+ @Override
+ public void applyPerdition() {
+ }
+
+ @Override
+ public void doWork(PowerHandler workProvider) {
+ }
+
+ @Override
+ public World getWorld() {
+ return getBundle().getEntity().worldObj;
+ }
+
+ @Override
+ public AbstractConduitNetwork> getNetwork() {
+ return network;
+ }
+
+ @Override
+ public boolean setNetwork(AbstractConduitNetwork> network) {
+ this.network = (PowerConduitNetwork) network;
+ return true;
+ }
+
+ @Override
+ public boolean canConnectToExternal(ForgeDirection direction) {
+ IPowerReceptor rec = getExternalPowerReceptor(direction);
+ if(rec instanceof IPowerEmitter) {
+ return ((IPowerEmitter)rec).canEmitPowerFrom(direction.getOpposite());
+ }
+ return rec != null;
+ }
+
+ @Override
+ public void externalConnectionAdded(ForgeDirection direction) {
+ super.externalConnectionAdded(direction);
+ if (network != null) {
+ TileEntity te = bundle.getEntity();
+ network.powerReceptorAdded(this, direction, te.xCoord + direction.offsetX, te.yCoord + direction.offsetY, te.zCoord + direction.offsetZ,
+ getExternalPowerReceptor(direction));
+ }
+ }
+
+ @Override
+ public void externalConnectionRemoved(ForgeDirection direction) {
+ super.externalConnectionRemoved(direction);
+ if (network != null) {
+ TileEntity te = bundle.getEntity();
+ network.powerReceptorRemoved(te.xCoord + direction.offsetX, te.yCoord + direction.offsetY, te.zCoord + direction.offsetZ);
+ }
+ }
+
+ @Override
+ public IPowerReceptor getExternalPowerReceptor(ForgeDirection direction) {
+ TileEntity te = bundle.getEntity();
+ World world = te.worldObj;
+ if (world == null) {
+ return null;
+ }
+ TileEntity test = world.getBlockTileEntity(te.xCoord + direction.offsetX, te.yCoord + direction.offsetY, te.zCoord + direction.offsetZ);
+ if (test instanceof IConduitBundle) {
+ return null;
+ }
+ if (test instanceof IPowerReceptor) {
+ return (IPowerReceptor) test;
+ }
+ return null;
+ }
+
+ @Override
+ public ItemStack createItem() {
+ return createItemStackForSubtype(subtype);
+ }
+
+ @Override
+ public Class extends IConduit> getBaseConduitType() {
+ return IPowerConduit.class;
+ }
+
+ // Rendering
+ @Override
+ public Icon getTextureForState(CollidableComponent component) {
+ if (component.dir == ForgeDirection.UNKNOWN) {
+ return ICONS.get(ICON_CORE_KEY + POSTFIX[subtype]);
+ }
+ return ICONS.get(ICON_KEY + POSTFIX[subtype]);
+ }
+
+ @Override
+ public Icon getTransmitionTextureForState(CollidableComponent component) {
+ //return ICONS.get(ICON_TRANSMISSION_KEY);
+ return null;
+ }
+
+}
diff --git a/common/crazypants/enderio/conduit/power/PowerConduitNetwork.java b/common/crazypants/enderio/conduit/power/PowerConduitNetwork.java
new file mode 100644
index 00000000..3e53478b
--- /dev/null
+++ b/common/crazypants/enderio/conduit/power/PowerConduitNetwork.java
@@ -0,0 +1,136 @@
+package crazypants.enderio.conduit.power;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import crazypants.enderio.conduit.AbstractConduitNetwork;
+import crazypants.enderio.conduit.IConduit;
+import crazypants.enderio.conduit.IConduitBundle;
+import crazypants.util.BlockCoord;
+
+import net.minecraft.tileentity.TileEntity;
+import net.minecraft.world.World;
+import net.minecraftforge.common.ForgeDirection;
+import buildcraft.api.power.IPowerReceptor;
+import buildcraft.api.power.PowerHandler;
+import buildcraft.api.power.PowerHandler.PowerReceiver;
+import buildcraft.api.power.PowerHandler.Type;
+
+public class PowerConduitNetwork extends AbstractConduitNetwork {
+
+ // ----------------------------------------------------------------------
+
+ NetworkPowerManager powerManager;
+
+
+ private Map powerReceptors = new HashMap();
+
+ private long timeAtLastApply = -1;
+
+ public PowerConduitNetwork() {
+ }
+
+ @Override
+ public void init(IConduitBundle tile, Collection connections, World world) {
+ super.init(tile, connections, world);
+ powerManager = new NetworkPowerManager(this, world);
+ powerManager.receptorsChanged();
+ }
+
+ @Override
+ public void destroyNetwork() {
+ for (IPowerConduit con : conduits) {
+ con.setActive(false);
+ }
+ powerManager.onNetworkDestroyed();
+ super.destroyNetwork();
+ }
+
+ public NetworkPowerManager getPowerManager() {
+ return powerManager;
+ }
+
+ @Override
+ public void addConduit(IPowerConduit con) {
+ super.addConduit(con);
+ Set externalDirs = con.getExternalConnections();
+ for (ForgeDirection dir : externalDirs) {
+ IPowerReceptor pr = con.getExternalPowerReceptor(dir);
+ if (pr != null) {
+ TileEntity te = con.getBundle().getEntity();
+ powerReceptorAdded(con, dir, te.xCoord + dir.offsetX, te.yCoord + dir.offsetY, te.zCoord + dir.offsetZ, pr);
+ }
+ }
+ if(powerManager != null) {
+ con.setActive(powerManager.isActive());
+ }
+ }
+
+ @Override
+ public Class extends IPowerConduit> getBaseConduitType() {
+ return IPowerConduit.class;
+ }
+
+ public void powerReceptorAdded(IPowerConduit powerConduit, ForgeDirection direction, int x, int y, int z, IPowerReceptor powerReceptor) {
+ if(powerReceptor == null) {
+ return;
+ }
+ BlockCoord key = new BlockCoord(x, y, z);
+ ReceptorEntry re = powerReceptors.get(key);
+ if(re == null) {
+ re = new ReceptorEntry(powerReceptor, key, powerConduit);
+ powerReceptors.put(key, re);
+ }
+ re.directions.add(direction);
+ if(powerManager != null) {
+ powerManager.receptorsChanged();
+ }
+ }
+
+ public void powerReceptorRemoved(int x, int y, int z) {
+ powerReceptors.remove(new BlockCoord(x, y, z));
+ powerManager.receptorsChanged();
+ }
+
+ public Collection getPowerReceptors() {
+ return powerReceptors.values();
+ }
+
+ @Override
+ public void onUpdateEntity(IConduit conduit) {
+ World world = conduit.getBundle().getEntity().worldObj;
+ if(world == null) {
+ return;
+ }
+ if(world.isRemote) {
+ return;
+ }
+ long curTime = world.getTotalWorldTime();
+ if(curTime != timeAtLastApply) {
+ timeAtLastApply = curTime;
+ powerManager.applyRecievedPower();
+ }
+ }
+
+
+ public static class ReceptorEntry {
+
+ IPowerConduit emmiter;
+ IPowerReceptor powerReceptor;
+ BlockCoord coord;
+ //The different directions that we connect to the sucker
+ Set directions = new HashSet();
+
+ public ReceptorEntry(IPowerReceptor powerReceptor, BlockCoord coord,IPowerConduit emmiter) {
+ this.powerReceptor = powerReceptor;
+ this.coord = coord;
+ this.emmiter = emmiter;
+ }
+
+ }
+
+
+}
diff --git a/common/crazypants/enderio/conduit/redstone/IRedstoneConduit.java b/common/crazypants/enderio/conduit/redstone/IRedstoneConduit.java
new file mode 100644
index 00000000..1cc11cac
--- /dev/null
+++ b/common/crazypants/enderio/conduit/redstone/IRedstoneConduit.java
@@ -0,0 +1,39 @@
+package crazypants.enderio.conduit.redstone;
+
+import java.util.Set;
+
+import crazypants.enderio.conduit.IConduit;
+
+import net.minecraftforge.common.ForgeDirection;
+
+public interface IRedstoneConduit extends IConduit {
+
+ public static final String KEY_CONDUIT_ICON ="enderio:redstoneConduit";
+ public static final String KEY_TRANSMISSION_ICON ="enderio:redstoneConduitTransmission";
+ public static final String KEY_CORE_OFF_ICON ="enderio:redstoneConduitCoreOff";
+ public static final String KEY_CORE_ON_ICON ="enderio:redstoneConduitCoreOn";
+
+ enum SignalColor {
+ RED
+ }
+
+ //External redstone interface
+
+ int isProvidingStrongPower(ForgeDirection toDirection);
+
+ int isProvidingWeakPower(ForgeDirection toDirection);
+
+ //signals
+
+ //--- Server Side Only
+ Set getNetworkInputs();
+
+ Set getNetworkOutputs(ForgeDirection side);
+
+ //--- Set on server side, used on client side for rendering
+
+
+ boolean isReplaceableByControl(Class extends IRedstoneConduit> replacenebtType);
+
+
+}
diff --git a/common/crazypants/enderio/conduit/redstone/ItemRedstoneConduit.java b/common/crazypants/enderio/conduit/redstone/ItemRedstoneConduit.java
new file mode 100644
index 00000000..10697f17
--- /dev/null
+++ b/common/crazypants/enderio/conduit/redstone/ItemRedstoneConduit.java
@@ -0,0 +1,41 @@
+package crazypants.enderio.conduit.redstone;
+
+import crazypants.enderio.ModObject;
+import crazypants.enderio.conduit.*;
+import crazypants.enderio.conduit.facade.ItemConduitFacade;
+import net.minecraft.client.renderer.texture.IconRegister;
+import net.minecraft.item.ItemStack;
+
+public class ItemRedstoneConduit extends AbstractItemConduit {
+
+ private static ItemConduitSubtype[] subtypes = new ItemConduitSubtype[] {
+ new ItemConduitSubtype(ModObject.itemRedstoneConduit.unlocalisedName, ModObject.itemRedstoneConduit.name, "enderio:itemRedstoneConduit"),
+ new ItemConduitSubtype(ModObject.itemRedstoneConduit.unlocalisedName + "switch", "Conduit Switch", "enderio:itemRedstoneSwitch")
+
+ };
+
+ public static ItemRedstoneConduit create() {
+ ItemRedstoneConduit result = new ItemRedstoneConduit();
+ result.init(subtypes);
+ return result;
+ }
+
+ protected ItemRedstoneConduit() {
+ super(ModObject.itemRedstoneConduit);
+ }
+
+ @Override
+ public Class extends IConduit> getBaseConduitType() {
+ return IRedstoneConduit.class;
+ }
+
+ @Override
+ public IConduit createConduit(ItemStack stack) {
+ if(stack.getItemDamage() == 1) {
+ return new RedstoneSwitch();
+ } else {
+ return new RedstoneConduit();
+ }
+ }
+
+}
diff --git a/common/crazypants/enderio/conduit/redstone/RedstoneConduit.java b/common/crazypants/enderio/conduit/redstone/RedstoneConduit.java
new file mode 100644
index 00000000..337d0b20
--- /dev/null
+++ b/common/crazypants/enderio/conduit/redstone/RedstoneConduit.java
@@ -0,0 +1,221 @@
+package crazypants.enderio.conduit.redstone;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import crazypants.enderio.EnderIO;
+import crazypants.enderio.ModObject;
+import crazypants.enderio.conduit.AbstractConduit;
+import crazypants.enderio.conduit.AbstractConduitNetwork;
+import crazypants.enderio.conduit.IConduit;
+import crazypants.enderio.conduit.geom.CollidableComponent;
+import crazypants.render.IconUtil;
+import crazypants.util.BlockCoord;
+
+import net.minecraft.block.Block;
+import net.minecraft.client.renderer.texture.IconRegister;
+import net.minecraft.item.ItemStack;
+import net.minecraft.tileentity.TileEntity;
+import net.minecraft.util.Icon;
+import net.minecraft.world.World;
+import net.minecraftforge.common.ForgeDirection;
+
+public class RedstoneConduit extends AbstractConduit implements IRedstoneConduit {
+
+
+ static final Map ICONS = new HashMap();
+
+
+ public static void initIcons() {
+ IconUtil.addIconProvider(new IconUtil.IIconProvider() {
+
+ @Override
+ public void registerIcons(IconRegister register) {
+ ICONS.put(KEY_CORE_OFF_ICON, register.registerIcon(KEY_CORE_OFF_ICON));
+ ICONS.put(KEY_CORE_ON_ICON, register.registerIcon(KEY_CORE_ON_ICON));
+ ICONS.put(KEY_CONDUIT_ICON, register.registerIcon(KEY_CONDUIT_ICON));
+ ICONS.put(KEY_TRANSMISSION_ICON, register.registerIcon(KEY_TRANSMISSION_ICON));
+ }
+
+ @Override
+ public int getTextureType() {
+ return 0;
+ }
+
+ });
+ }
+
+ protected RedstoneConduitNetwork network;
+
+ protected final Set externalSignals = new HashSet();
+
+ public RedstoneConduit() {
+ }
+
+ @Override
+ public boolean isReplaceableByControl(Class extends IRedstoneConduit> replacenebtType) {
+ return true;
+ }
+
+ @Override
+ public ItemStack createItem() {
+ return new ItemStack(ModObject.itemRedstoneConduit.actualId,1,0);
+ }
+
+ @Override
+ public Class extends IConduit> getBaseConduitType() {
+ return IRedstoneConduit.class;
+ }
+
+ @Override
+ public AbstractConduitNetwork getNetwork() {
+ return network;
+ }
+
+ @Override
+ public boolean setNetwork(AbstractConduitNetwork> network) {
+ this.network = (RedstoneConduitNetwork) network;
+ return true;
+ }
+
+ @Override
+ public boolean canConnectToExternal(ForgeDirection direction) {
+ TileEntity te = bundle.getEntity();
+ World world = te.worldObj;
+ if (world == null) {
+ return false;
+ }
+ int id = world.getBlockId(te.xCoord + direction.offsetX, te.yCoord + direction.offsetY, te.zCoord + direction.offsetZ);
+ if (id > 0 && id != EnderIO.blockConduitBundle.blockID) {
+
+ //We can connect to a block if it can provide power or it is receiving a string signal (not emitted by us)
+
+ BlockCoord loc = getLocation().getLocation(direction);
+
+ boolean toggleNetwork = network != null && network.isNetworkEnabled();
+ if(toggleNetwork ) {
+ network.setNetworkEnabled(false);
+ }
+ boolean gettingStrongPower = world.getBlockPowerInput(loc.x, loc.y, loc.z) == 15;
+ if(toggleNetwork) {
+ network.setNetworkEnabled(true);
+ }
+
+
+ //We can get an input from the block when:
+ return
+ Block.blocksList[id].canProvidePower() || //The block can provide power
+ //Or its getting a strong signal that we are not providing
+ gettingStrongPower;
+ //( world.getBlockPowerInput(loc.x, loc.y, loc.z) == 15 && isProvidingStrongPower(direction) != 15 );
+ }
+ return false;
+ }
+
+ @Override
+ public Set getNetworkInputs() {
+ Set res = new HashSet();
+ for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) {
+ if (canConnectToExternal(dir)) {
+ int input = getExternalPowerLevel(dir);
+ if (input > 1) { //need to degrade external signals by one as they enter
+ BlockCoord loc = getLocation().getLocation(dir);
+ Signal signal = new Signal(loc.x, loc.y, loc.z, input - 1, SignalColor.RED);
+ res.add(signal);
+ }
+ }
+ }
+ return res;
+ }
+
+ @Override
+ public Set getNetworkOutputs(ForgeDirection side) {
+ if (network == null) {
+ return Collections.emptySet();
+ }
+ return network.getSignals();
+ }
+
+ @Override
+ public boolean onNeighborBlockChange(int blockId) {
+ World world = getBundle().getEntity().worldObj;
+ if (world.isRemote) {
+ return false;
+ }
+ if (blockId == EnderIO.blockConduitBundle.blockID) {
+ return false;
+ }
+ boolean res = super.onNeighborBlockChange(blockId);
+
+ if (network == null || network.updatingNetwork) {
+ return false;
+ }
+
+ if(blockId > 0 && Block.blocksList[blockId].canProvidePower() && network != null) {
+ //TODO: Just recalculate the signals, no need for a full rebuild
+ network.destroyNetwork();
+ return false;
+ }
+ return res;
+ }
+
+ private int getExternalPowerLevel(ForgeDirection dir) {
+ if (network != null) {
+ network.setNetworkEnabled(false);
+ }
+ World world = getBundle().getEntity().worldObj;
+ BlockCoord loc = getLocation();
+ int result = world.getStrongestIndirectPower(loc.x, loc.y, loc.z);
+
+ if (network != null) {
+ network.setNetworkEnabled(true);
+ }
+ return result;
+
+ }
+
+ @Override
+ public int isProvidingStrongPower(ForgeDirection toDirection) {
+ return 0;
+ }
+
+ @Override
+ public int isProvidingWeakPower(ForgeDirection toDirection) {
+ if (network == null || !network.isNetworkEnabled()) {
+ return 0;
+ }
+ int result = 0;
+ for (Signal signal : network.getSignals()) {
+ result = Math.max(result, signal.strength);
+ }
+ return result;
+ }
+
+ @Override
+ public Icon getTextureForState(CollidableComponent component) {
+ if (component.dir == ForgeDirection.UNKNOWN) {
+ return isActive() ? ICONS.get(KEY_CORE_ON_ICON) : ICONS.get(KEY_CORE_OFF_ICON);
+ }
+ //return ICONS.get(KEY_CONDUIT_ICON);
+ return isActive() ? ICONS.get(KEY_TRANSMISSION_ICON) : ICONS.get(KEY_CONDUIT_ICON);
+ }
+
+ @Override
+ public Icon getTransmitionTextureForState(CollidableComponent component) {
+// if (component.id == ForgeDirection.UNKNOWN) {
+// return null;
+// }
+// return isActive() ? ICONS.get(KEY_TRANSMISSION_ICON) : null;
+ return null;
+
+ }
+
+ @Override
+ public String toString() {
+ return "RedstoneConduit [network=" + network + " connections=" + conduitConnections + " active=" + active + "]";
+ }
+
+}
diff --git a/common/crazypants/enderio/conduit/redstone/RedstoneConduitNetwork.java b/common/crazypants/enderio/conduit/redstone/RedstoneConduitNetwork.java
new file mode 100644
index 00000000..3321a150
--- /dev/null
+++ b/common/crazypants/enderio/conduit/redstone/RedstoneConduitNetwork.java
@@ -0,0 +1,185 @@
+package crazypants.enderio.conduit.redstone;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import crazypants.enderio.conduit.AbstractConduitNetwork;
+import crazypants.enderio.conduit.IConduitBundle;
+
+import net.minecraft.tileentity.TileEntity;
+import net.minecraft.world.World;
+
+public class RedstoneConduitNetwork extends AbstractConduitNetwork {
+
+ private final Set signals = new HashSet();
+
+ boolean updatingNetwork = false;
+
+ private boolean networkEnabled = true;
+
+ public RedstoneConduitNetwork() {
+ }
+
+ @Override
+ public Class extends IRedstoneConduit> getBaseConduitType() {
+ return IRedstoneConduit.class;
+ }
+
+ @Override
+ public void init(IConduitBundle tile, Collection connections, World world) {
+ super.init(tile, connections, world);
+ updatingNetwork = true;
+ notifyNeigborsOfSignals();
+ updatingNetwork = false;
+ }
+
+ @Override
+ public void destroyNetwork() {
+ updatingNetwork = true;
+ for (IRedstoneConduit con : conduits) {
+ con.setActive(false);
+ }
+ //Notify neighbours that all signals have been lost
+ List copy = new ArrayList(signals);
+ signals.clear();
+ for(Signal s : copy) {
+ notifyNeigborsOfSignalUpdate(s);
+ }
+ updatingNetwork = false;
+ super.destroyNetwork();
+ }
+
+ @Override
+ public void addConduit(IRedstoneConduit con) {
+ updatingNetwork = true;
+ super.addConduit(con);
+ Set newInputs = con.getNetworkInputs();
+ signals.addAll(newInputs);
+ //Notify existing nodes of new signals
+ for (Signal signal : newInputs) {
+ notifyNeigborsOfSignalUpdate(signal);
+ }
+ //and new nodes neighbours of all signals
+ for (Signal signal : signals) {
+ notifyConduitNeighbours(con, signal);
+ }
+ updatingNetwork = false;
+ }
+
+ public Set getSignals() {
+ if(networkEnabled) {
+ return signals;
+ } else {
+ return Collections.emptySet();
+ }
+ }
+
+ //Need to disable the network when determining the strength of external signals
+ //to avoid feed back looops
+ void setNetworkEnabled(boolean enabled) {
+ networkEnabled = enabled;
+ }
+
+ public boolean isNetworkEnabled() {
+ return networkEnabled;
+ }
+
+ public void addSignal(Signal signal) {
+ updatingNetwork = true;
+ signals.add(signal);
+ notifyNetworkOfUpdate();
+ notifyNeigborsOfSignalUpdate(signal);
+ updatingNetwork = false;
+
+ }
+
+ public void removeSignal(Signal signal) {
+ updatingNetwork = true;
+ signals.remove(signal);
+ notifyNetworkOfUpdate();
+ notifyNeigborsOfSignalUpdate(signal);
+ updatingNetwork = false;
+ }
+
+ public void replaceSignal(Signal oldSig, Signal newSig) {
+ updatingNetwork = true;
+ signals.remove(oldSig);
+ signals.add(newSig);
+ notifyNetworkOfUpdate();
+ notifyNeigborsOfSignalUpdate(newSig);
+ updatingNetwork = false;
+ }
+
+ @Override
+ public void notifyNetworkOfUpdate() {
+ for (IRedstoneConduit con : conduits) {
+ con.setActive(!getSignals().isEmpty());
+ }
+ super.notifyNetworkOfUpdate();
+ }
+
+ @Override
+ public String toString() {
+ return "RedstoneConduitNetwork [signals=" + signalsString() + ", conduits=" + conduitsString() + "]";
+ }
+
+ private String conduitsString() {
+ StringBuilder sb = new StringBuilder();
+ for (IRedstoneConduit con : conduits) {
+ TileEntity te = con.getBundle().getEntity();
+ sb.append("<");
+ sb.append(te.xCoord + "," + te.yCoord + "," + te.zCoord);
+ sb.append(">");
+ }
+ return sb.toString();
+ }
+
+ String signalsString() {
+ StringBuilder sb = new StringBuilder();
+ for (Signal s : signals) {
+ sb.append("<");
+ sb.append(s);
+ sb.append(">");
+
+ }
+ return sb.toString();
+ }
+
+ private void notifyNeigborsOfSignals() {
+ for(Signal signal : signals) {
+ notifyNeigborsOfSignalUpdate(signal);
+ }
+ }
+
+ private void notifyNeigborsOfSignalUpdate(Signal signal) {
+ for (IRedstoneConduit con : conduits) {
+ notifyConduitNeighbours(con, signal);
+ }
+ }
+
+ private void notifyConduitNeighbours(IRedstoneConduit con, Signal signal) {
+ if (con.getBundle() == null) {
+ System.out.println("RedstoneConduitNetwork.notifyNeigborsOfSignalUpdate: NULL BUNDLE!!!!");
+ return;
+ }
+ TileEntity te = con.getBundle().getEntity();
+
+ te.worldObj.notifyBlocksOfNeighborChange(te.xCoord, te.yCoord, te.zCoord, te.worldObj.getBlockId(te.xCoord, te.yCoord, te.zCoord));
+ // Need to notify neighbours neighbours for changes to string signals
+ if (signal != null && signal.strength >= 15 && signal.x == te.xCoord && signal.y == te.yCoord && signal.z == te.zCoord) {
+
+ te.worldObj.notifyBlocksOfNeighborChange(te.xCoord + 1, te.yCoord, te.zCoord, te.worldObj.getBlockId(te.xCoord + 1, te.yCoord, te.zCoord));
+ te.worldObj.notifyBlocksOfNeighborChange(te.xCoord - 1, te.yCoord, te.zCoord, te.worldObj.getBlockId(te.xCoord - 1, te.yCoord, te.zCoord));
+ te.worldObj.notifyBlocksOfNeighborChange(te.xCoord, te.yCoord + 1, te.zCoord, te.worldObj.getBlockId(te.xCoord, te.yCoord + 1, te.zCoord));
+ te.worldObj.notifyBlocksOfNeighborChange(te.xCoord, te.yCoord - 1, te.zCoord, te.worldObj.getBlockId(te.xCoord, te.yCoord - 1, te.zCoord));
+ te.worldObj.notifyBlocksOfNeighborChange(te.xCoord, te.yCoord, te.zCoord + 1, te.worldObj.getBlockId(te.xCoord, te.yCoord, te.zCoord + 1));
+ te.worldObj.notifyBlocksOfNeighborChange(te.xCoord, te.yCoord, te.zCoord - 1, te.worldObj.getBlockId(te.xCoord, te.yCoord, te.zCoord - 1));
+
+ }
+ }
+
+}
diff --git a/common/crazypants/enderio/conduit/redstone/RedstoneSwitch.java b/common/crazypants/enderio/conduit/redstone/RedstoneSwitch.java
new file mode 100644
index 00000000..82d0c830
--- /dev/null
+++ b/common/crazypants/enderio/conduit/redstone/RedstoneSwitch.java
@@ -0,0 +1,145 @@
+package crazypants.enderio.conduit.redstone;
+
+import java.util.List;
+import java.util.Set;
+
+import crazypants.enderio.ModObject;
+import crazypants.enderio.conduit.RaytraceResult;
+import crazypants.enderio.conduit.geom.CollidableComponent;
+import crazypants.enderio.conduit.geom.ConduitGeometryUtil;
+import crazypants.enderio.conduit.geom.Offset;
+import crazypants.render.BoundingBox;
+import crazypants.render.IconUtil;
+import crazypants.util.BlockCoord;
+import crazypants.vecmath.Vector3d;
+
+import net.minecraft.client.renderer.texture.IconRegister;
+import net.minecraft.entity.player.EntityPlayer;
+import net.minecraft.item.ItemStack;
+import net.minecraft.nbt.NBTTagCompound;
+import net.minecraft.tileentity.TileEntity;
+import net.minecraft.util.Icon;
+import net.minecraftforge.common.ForgeDirection;
+
+public class RedstoneSwitch extends RedstoneConduit {
+
+ static final String SWITCH_TAG = "switch";
+ public static final String SWITHC_ICON_OFF_KEY = "enderio:redstoneConduitSwitchOff";
+ public static final String SWITCH_ICON_ON_KEY = "enderio:redstoneConduitSwitchOn";
+
+ private boolean isOn;
+
+ public static void initIcons() {
+ IconUtil.addIconProvider(new IconUtil.IIconProvider() {
+
+ @Override
+ public void registerIcons(IconRegister register) {
+ ICONS.put(RedstoneSwitch.SWITHC_ICON_OFF_KEY, register.registerIcon(SWITHC_ICON_OFF_KEY));
+ ICONS.put(RedstoneSwitch.SWITCH_ICON_ON_KEY, register.registerIcon(SWITCH_ICON_ON_KEY));
+ }
+
+ @Override
+ public int getTextureType() {
+ return 0;
+ }
+
+ });
+ }
+
+ @Override
+ public boolean isReplaceableByControl(Class extends IRedstoneConduit> replacenebtType) {
+ return false;
+ }
+
+ @Override
+ public ItemStack createItem() {
+ return new ItemStack(ModObject.itemRedstoneConduit.actualId,1,1);
+ }
+
+ @Override
+ public int isProvidingStrongPower(ForgeDirection toDirection) {
+ if (network == null || !network.isNetworkEnabled()) {
+ return 0;
+ }
+ return isOn ? 15 : 0;
+ }
+
+ @Override
+ public void writeToNBT(NBTTagCompound nbtRoot) {
+ super.writeToNBT(nbtRoot);
+ nbtRoot.setBoolean("switchOn", isOn);
+ }
+
+ @Override
+ public void readFromNBT(NBTTagCompound nbtRoot) {
+ super.readFromNBT(nbtRoot);
+ isOn = nbtRoot.getBoolean("switchOn");
+ }
+
+ Icon getSwitchIcon() {
+ return isOn ? ICONS.get(SWITCH_ICON_ON_KEY) : ICONS.get(SWITHC_ICON_OFF_KEY);
+ }
+
+ @Override
+ public Icon getTextureForState(CollidableComponent component) {
+ if (SWITCH_TAG.equals(component.data)) {
+ return isOn ? ICONS.get(SWITCH_ICON_ON_KEY) : ICONS.get(SWITHC_ICON_OFF_KEY);
+ }
+ return super.getTextureForState(component);
+ }
+
+
+ @Override
+ public List getCollidableComponents() {
+ if (collidables != null && !collidablesDirty) {
+ return collidables;
+ }
+
+ Offset o = getBundle().getOffset(getBaseConduitType(), ForgeDirection.UNKNOWN);
+ Vector3d trans = ConduitGeometryUtil.instance.getTranslation(ForgeDirection.UNKNOWN, o);
+
+ List result = super.getCollidableComponents();
+ BoundingBox[] aabb = RedstoneSwitchRenderer.instance.getAABB();
+
+ for (BoundingBox bb : aabb) {
+ result.add(new CollidableComponent(IRedstoneConduit.class, bb.translate(trans), ForgeDirection.UNKNOWN, SWITCH_TAG));
+ }
+
+ return result;
+ }
+
+ @Override
+ public boolean onBlockActivated(EntityPlayer player, RaytraceResult res) {
+ if (res.component.data != null && res.component.data.equals(SWITCH_TAG)) {
+ toggleSwitch();
+ return true;
+ }
+ return false;
+ }
+
+ private void toggleSwitch() {
+ isOn = !isOn;
+ if (network == null) {
+ return;
+ }
+ TileEntity te = bundle.getEntity();
+ Signal signal = new Signal(te.xCoord, te.yCoord, te.zCoord, 15, SignalColor.RED);
+ if (isOn) {
+ network.addSignal(signal);
+ } else {
+ network.removeSignal(signal);
+ }
+ }
+
+ @Override
+ public Set getNetworkInputs() {
+ Set res = super.getNetworkInputs();
+ if (isOn) {
+ BlockCoord loc = getLocation();
+ Signal signal = new Signal(loc.x, loc.y, loc.z, 15, SignalColor.RED);
+ res.add(signal);
+ }
+ return res;
+ }
+
+}
diff --git a/common/crazypants/enderio/conduit/redstone/RedstoneSwitchRenderer.java b/common/crazypants/enderio/conduit/redstone/RedstoneSwitchRenderer.java
new file mode 100644
index 00000000..adcf4f36
--- /dev/null
+++ b/common/crazypants/enderio/conduit/redstone/RedstoneSwitchRenderer.java
@@ -0,0 +1,112 @@
+package crazypants.enderio.conduit.redstone;
+
+import crazypants.enderio.EnderIO;
+import crazypants.enderio.conduit.IConduit;
+import crazypants.enderio.conduit.IConduitBundle;
+import crazypants.enderio.conduit.geom.CollidableComponent;
+import crazypants.enderio.conduit.geom.ConduitGeometryUtil;
+import crazypants.enderio.conduit.render.ConduitBundleRenderer;
+import crazypants.enderio.conduit.render.DefaultConduitRenderer;
+import crazypants.render.BoundingBox;
+import crazypants.render.CubeRenderer;
+import crazypants.render.VertexRotation;
+import crazypants.render.VertexTransform;
+import crazypants.vecmath.Vector3d;
+import net.minecraft.client.renderer.Tessellator;
+import net.minecraft.util.Icon;
+import net.minecraftforge.common.ForgeDirection;
+
+public class RedstoneSwitchRenderer extends DefaultConduitRenderer {
+
+ public static RedstoneSwitchRenderer instance = new RedstoneSwitchRenderer();
+
+ private static final float SIZE = 0.2f;
+ private static final float HW = SIZE/3;
+ private static final float HH = SIZE/2;
+ private static final float DEPTH = 0.05f;
+ private static final float HD = DEPTH/2;
+
+ private static final float DIST = 0.25f;
+
+ private static final float CON_HW = 0.015f;
+
+
+ private final VertexTransform[] xForms;
+ private final BoundingBox switchBounds;
+ private final BoundingBox connectorBounds;
+
+ private final BoundingBox[] aabb;
+
+ private RedstoneSwitchRenderer() {
+ BoundingBox bb = new BoundingBox(0.5- HW, 0.5- HH, 0.5- HD, 0.5+ HW, 0.5+ HH, 0.5 + HD);
+ switchBounds = bb.translate(0, 0, DIST);
+
+ connectorBounds = new BoundingBox(0.5- CON_HW, 0.5- CON_HW, 0.5- CON_HW, 0.5+ CON_HW, 0.5+ CON_HW, 0.5 + DIST);
+
+ Vector3d axis = new Vector3d(0,1,0);
+ Vector3d p = new Vector3d(0.5,0.5,0.5);
+ xForms = new VertexTransform[4];
+ double angle = Math.toRadians(45);
+ for(int i=0; i < xForms.length; i++) {
+ //TODO
+ //xForms[i] = new Rotation(angle, axis, p);
+ xForms[i] = new VertexRotation(angle, axis, p);
+ angle += Math.toRadians(90);
+ }
+
+ aabb = new BoundingBox[xForms.length];
+ for(int i=0; i < xForms.length; i++) {
+ aabb[i] = switchBounds.transform(xForms[i]);
+ }
+
+ }
+
+ public BoundingBox[] getAABB() {
+ return aabb;
+ }
+
+ @Override
+ public boolean isRendererForConduit(IConduit conduit) {
+ return conduit.getClass() == RedstoneSwitch.class;
+ }
+
+ @Override
+ public void renderEntity(ConduitBundleRenderer conduitBundleRenderer, IConduitBundle bundle, IConduit conduit, double x, double y, double z, float partialTick,
+ float worldLight) {
+
+ super.renderEntity(conduitBundleRenderer, bundle, conduit, x, y, z, partialTick, worldLight);
+
+ RedstoneSwitch sw = (RedstoneSwitch)conduit;
+
+ Tessellator tessellator = Tessellator.instance;
+ float selfIllum = Math.max(worldLight, conduit.getSelfIlluminationForState(null));
+ tessellator.setColorOpaque_F(selfIllum, selfIllum, selfIllum);
+
+ Icon[] icons = new Icon[6];
+ for(int i=0;i sources) {
+ // Each source is 5 ints
+ int[] result = new int[sources.size() * 5];
+ int i = 0;
+ for (SignalSource ss : sources) {
+ result[i] = ss.signal.x;
+ i++;
+ result[i] = ss.signal.y;
+ i++;
+ result[i] = ss.signal.z;
+ i++;
+ result[i] = ss.signal.strength;
+ i++;
+ result[i] = ss.signal.color.ordinal();
+ i++;
+ result[i] = ss.fromDirection.ordinal();
+ i++;
+ }
+ return result;
+ }
+
+ public static Set fromIntArray(int[] enc) {
+ Set result = new HashSet();
+ for(int i=0; i < enc.length; i+=5) {
+ Signal sig = new Signal(enc[i], enc[i+1], enc[i+2], enc[i+3], SignalColor.values()[enc[i+4]]);
+ result.add(new SignalSource(sig, ForgeDirection.values()[enc[i+4]]));
+ }
+ return result;
+ }
+
+}
diff --git a/common/crazypants/enderio/conduit/render/ConduitBundleRenderer.java b/common/crazypants/enderio/conduit/render/ConduitBundleRenderer.java
new file mode 100644
index 00000000..2015ebf3
--- /dev/null
+++ b/common/crazypants/enderio/conduit/render/ConduitBundleRenderer.java
@@ -0,0 +1,212 @@
+package crazypants.enderio.conduit.render;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import net.minecraft.block.Block;
+import net.minecraft.client.Minecraft;
+import net.minecraft.client.entity.EntityClientPlayerMP;
+import net.minecraft.client.renderer.RenderBlocks;
+import net.minecraft.client.renderer.Tessellator;
+import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
+import net.minecraft.tileentity.TileEntity;
+import net.minecraft.util.Icon;
+import net.minecraft.world.IBlockAccess;
+import net.minecraftforge.common.ForgeDirection;
+
+import org.lwjgl.opengl.GL11;
+import org.lwjgl.opengl.GL12;
+
+import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
+import crazypants.enderio.EnderIO;
+import crazypants.enderio.ModObject;
+import crazypants.enderio.conduit.BlockConduitBundle;
+import crazypants.enderio.conduit.ConduitUtil;
+import crazypants.enderio.conduit.IConduit;
+import crazypants.enderio.conduit.IConduitBundle;
+import crazypants.enderio.conduit.facade.BlockConduitFacade;
+import crazypants.enderio.conduit.geom.CollidableComponent;
+import crazypants.render.BoundingBox;
+import crazypants.render.CubeRenderer;
+import crazypants.render.RenderUtil;
+
+public class ConduitBundleRenderer extends TileEntitySpecialRenderer implements ISimpleBlockRenderingHandler {
+
+ private static final float CONNECTOR_DEPTH = 0.05f;
+ private static final float CONNECTOR_WIDTH = 0.3f;
+
+ private Map connectorBounds = new HashMap();
+
+ public ConduitBundleRenderer() {
+ for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) {
+ connectorBounds.put(dir, createConnector(dir));
+ }
+ }
+
+ @Override
+ public void renderTileEntityAt(TileEntity te, double x, double y, double z, float partialTick) {
+ IConduitBundle bundle = (IConduitBundle) te;
+ EntityClientPlayerMP player = Minecraft.getMinecraft().thePlayer;
+ if (ConduitUtil.renderFacade(bundle, player)) {
+ return;
+ }
+
+ // Lighting calcuations to allow for self illumination
+ float val = RenderUtil.claculateTotalBrightnessForLocation(te.worldObj, te.xCoord, te.yCoord, te.zCoord);
+ renderTileEntityAt(bundle, x, y, z, partialTick, val);
+ }
+
+
+ public void renderTileEntityAt(IConduitBundle bundle, double x, double y, double z, float partialTick, float brightness) {
+
+ RenderUtil.bindBlockTexture();
+ Minecraft.getMinecraft().entityRenderer.disableLightmap(0);
+
+ GL11.glPushAttrib(GL11.GL_ENABLE_BIT);
+ GL11.glPushAttrib(GL11.GL_LIGHTING_BIT);
+ //GL11.glPushAttrib(GL11.GL_POLYGON_BIT);
+ GL11.glEnable(GL12.GL_RESCALE_NORMAL);
+ GL11.glEnable(GL11.GL_BLEND);
+ GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
+ GL11.glShadeModel(GL11.GL_SMOOTH);
+ //GL11.glDisable (GL11.GL_CULL_FACE);
+
+ GL11.glPushMatrix();
+ GL11.glTranslated(x, y, z);
+
+ Tessellator tessellator = Tessellator.instance;
+ tessellator.startDrawingQuads();
+
+ // Conduits
+ Set externals = new HashSet();
+ for (IConduit con : bundle.getConduits()) {
+ ConduitRenderer renderer = EnderIO.proxy.getRendererForConduit(con);
+ renderer.renderEntity(this, bundle, con, x, y, z, partialTick, brightness);
+ externals.addAll(con.getExternalConnections());
+ }
+
+ // Internal conectors between conduits
+ List connectors = bundle.getConnectors();
+ for (CollidableComponent component : connectors) {
+ if (component.conduitType != null) {
+ IConduit con = bundle.getConduit(component.conduitType);
+ float selfIllum = Math.max(brightness, con.getSelfIlluminationForState(component));
+ tessellator.setColorRGBA_F(selfIllum, selfIllum, selfIllum, 1);
+ CubeRenderer.render(component.bound, con.getTextureForState(component));
+ } else {
+ Icon tex = EnderIO.blockConduitBundle.getConnectorIcon();
+ CubeRenderer.render(component.bound, tex);
+ }
+ }
+
+ // External connection terminations
+ for (ForgeDirection dir : externals) {
+ renderExternalConnection(dir);
+ }
+
+ tessellator.draw();
+ GL11.glPopMatrix();
+ GL11.glPopAttrib();
+ GL11.glPopAttrib();
+ //GL11.glPopAttrib();
+
+ }
+
+ private void renderExternalConnection(ForgeDirection dir) {
+ Icon tex = EnderIO.blockConduitBundle.getConnectorIcon();
+ BoundingBox[] bbs = connectorBounds.get(dir);
+ for (BoundingBox bb : bbs) {
+ CubeRenderer.render(bb, tex);
+ }
+ }
+
+ private static BoundingBox[] createConnector(ForgeDirection dir) {
+
+ BoundingBox[] res = new BoundingBox[2];
+
+ float cMin = 0.5f - CONNECTOR_WIDTH / 2;
+ float cMax = 0.5f + CONNECTOR_WIDTH / 2;
+ float dMin = 1 - CONNECTOR_DEPTH / 2;
+ float dMax = 1;
+
+ res[0] = createConnectorComponent(dir, cMin, cMax, dMin, dMax);
+
+ cMin = 0.5f - CONNECTOR_WIDTH / 3;
+ cMax = 0.5f + CONNECTOR_WIDTH / 3;
+ dMin = 1 - CONNECTOR_DEPTH;
+ dMax = 1 - CONNECTOR_DEPTH / 2;
+
+ res[1] = createConnectorComponent(dir, cMin, cMax, dMin, dMax);
+
+ return res;
+ }
+
+ private static BoundingBox createConnectorComponent(ForgeDirection dir, float cornerMin, float cornerMax, float depthMin, float depthMax) {
+ float minX = (1 - Math.abs(dir.offsetX)) * cornerMin + dir.offsetX * depthMin;
+ float minY = (1 - Math.abs(dir.offsetY)) * cornerMin + dir.offsetY * depthMin;
+ float minZ = (1 - Math.abs(dir.offsetZ)) * cornerMin + dir.offsetZ * depthMin;
+
+ float maxX = (1 - Math.abs(dir.offsetX)) * cornerMax + (dir.offsetX * depthMax);
+ float maxY = (1 - Math.abs(dir.offsetY)) * cornerMax + (dir.offsetY * depthMax);
+ float maxZ = (1 - Math.abs(dir.offsetZ)) * cornerMax + (dir.offsetZ * depthMax);
+
+ minX = fix(minX);
+ minY = fix(minY);
+ minZ = fix(minZ);
+ maxX = fix(maxX);
+ maxY = fix(maxY);
+ maxZ = fix(maxZ);
+
+ BoundingBox bb = new BoundingBox(minX, minY, minZ, maxX, maxY, maxZ);
+ bb = bb.fixMinMax();
+
+ return bb;
+ }
+
+ private static float fix(float val) {
+ return val < 0 ? 1 + val : val;
+ }
+
+ @Override
+ public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks rb) {
+
+ IConduitBundle bundle = (IConduitBundle) world.getBlockTileEntity(x, y, z);
+ EntityClientPlayerMP player = Minecraft.getMinecraft().thePlayer;
+
+ if (bundle.hasFacade()) {
+
+ int facadeId = bundle.getFacadeId();
+ if (ConduitUtil.isFacadeHidden(bundle, player)) {
+ bundle.setFacadeId(0);
+ }
+
+ BlockConduitFacade facb = (BlockConduitFacade) Block.blocksList[ModObject.blockConduitFacade.actualId];
+ facb.setBlockBounds(0, 0, 0, 1, 1, 1);
+ rb.setRenderBoundsFromBlock(facb);
+ rb.renderStandardBlock(facb, x, y, z);
+
+ bundle.setFacadeId(facadeId);
+
+ }
+
+ return true;
+ }
+
+ @Override
+ public boolean shouldRender3DInInventory() {
+ return false;
+ }
+
+ @Override
+ public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer) {
+ }
+
+ @Override
+ public int getRenderId() {
+ return BlockConduitBundle.rendererId;
+ }
+
+}
diff --git a/common/crazypants/enderio/conduit/render/ConduitRenderer.java b/common/crazypants/enderio/conduit/render/ConduitRenderer.java
new file mode 100644
index 00000000..4e1a4665
--- /dev/null
+++ b/common/crazypants/enderio/conduit/render/ConduitRenderer.java
@@ -0,0 +1,12 @@
+package crazypants.enderio.conduit.render;
+
+import crazypants.enderio.conduit.IConduit;
+import crazypants.enderio.conduit.IConduitBundle;
+
+public interface ConduitRenderer {
+
+ boolean isRendererForConduit(IConduit conduit);
+
+ void renderEntity(ConduitBundleRenderer conduitBundleRenderer, IConduitBundle te, IConduit con, double x, double y, double z, float partialTick, float worldLight);
+
+}
diff --git a/common/crazypants/enderio/conduit/render/DefaultConduitRenderer.java b/common/crazypants/enderio/conduit/render/DefaultConduitRenderer.java
new file mode 100644
index 00000000..ca58ac0a
--- /dev/null
+++ b/common/crazypants/enderio/conduit/render/DefaultConduitRenderer.java
@@ -0,0 +1,296 @@
+package crazypants.enderio.conduit.render;
+
+import static crazypants.render.CubeRenderer.*;
+import static net.minecraftforge.common.ForgeDirection.*;
+
+import java.util.Collection;
+
+import crazypants.enderio.conduit.*;
+import crazypants.enderio.conduit.geom.CollidableComponent;
+import crazypants.render.BoundingBox;
+
+import net.minecraft.client.renderer.Tessellator;
+import net.minecraft.util.Icon;
+import net.minecraftforge.common.ForgeDirection;
+
+public class DefaultConduitRenderer implements ConduitRenderer {
+
+ protected float transmissionScaleFactor;
+
+ @Override
+ public boolean isRendererForConduit(IConduit conduit) {
+ return true;
+ }
+
+ @Override
+ public void renderEntity(ConduitBundleRenderer conduitBundleRenderer, IConduitBundle te, IConduit conduit, double x, double y, double z, float partialTick,
+ float worldLight) {
+
+ Collection components = conduit.getCollidableComponents();
+ Tessellator tessellator = Tessellator.instance;
+
+ transmissionScaleFactor = conduit.getTransmitionGeometryScale();
+
+ Icon tex;
+ boolean active = conduit.isActive();
+ for (CollidableComponent component : components) {
+ if (renderComponent(component)) {
+ float selfIllum = Math.max(worldLight, conduit.getSelfIlluminationForState(component));
+ if (active && isNSEWUP(component.dir) &&
+ conduit.getTransmitionTextureForState(component) != null) {
+ tessellator.setColorRGBA_F(selfIllum + 0.1f, selfIllum + 0.1f,
+ selfIllum + 0.1f, 0.75f);
+ tex = conduit.getTransmitionTextureForState(component);
+ renderTransmission(tex, component);
+ }
+
+ tex = conduit.getTextureForState(component);
+ tessellator.setColorOpaque_F(selfIllum, selfIllum, selfIllum);
+ renderConduit(tex, component);
+ }
+
+ }
+
+ }
+
+ protected void renderConduit(Icon tex, CollidableComponent component) {
+ if (isNSEWUP(component.dir)) {
+ RoundedSegmentRenderer.renderSegment(component.dir, component.bound, tex.getMinU(), tex.getMaxU(), tex.getMinV(), tex.getMaxV());
+ } else {
+ drawSection(component.bound, tex.getMinU(), tex.getMaxU(), tex.getMinV(), tex.getMaxV(), component.dir, true);
+ }
+ }
+
+ protected void renderTransmission(Icon tex, CollidableComponent component) {
+ RoundedSegmentRenderer.renderSegment(component.dir, component.bound, tex.getMinU(), tex.getMaxU(), tex.getMinV(), tex.getMaxV());
+ }
+
+ // @Override
+ public void renderEntity2(ConduitBundleRenderer conduitBundleRenderer, IConduitBundle te, IConduit conduit, double x, double y, double z, float partialTick,
+ float worldLight) {
+
+ Collection components = conduit.getCollidableComponents();
+ Tessellator tessellator = Tessellator.instance;
+
+ transmissionScaleFactor = conduit.getTransmitionGeometryScale();
+
+ Icon tex;
+ boolean active = conduit.isActive();
+ for (CollidableComponent component : components) {
+ if (renderComponent(component)) {
+ float selfIllum = Math.max(worldLight, conduit.getSelfIlluminationForState(component));
+ if (active && isNSEWUP(component.dir) && conduit.getTransmitionTextureForState(component) != null) {
+ tessellator.setColorRGBA_F(selfIllum + 0.1f, selfIllum + 0.1f, selfIllum + 0.1f, 0.75f);
+ tex = conduit.getTransmitionTextureForState(component);
+ drawSection(component.bound, tex.getMinU(), tex.getMaxU(), tex.getMinV(), tex.getMaxV(), component.dir, true);
+ }
+
+ tex = conduit.getTextureForState(component);
+ tessellator.setColorOpaque_F(selfIllum, selfIllum, selfIllum);
+ BoundingBox[] cubes = toCubes(component.bound);
+ for (BoundingBox cube : cubes) {
+ drawSection(cube, tex.getMinU(), tex.getMaxU(), tex.getMinV(), tex.getMaxV(), component.dir, false);
+ }
+ }
+
+ }
+
+ }
+
+ protected boolean renderComponent(CollidableComponent component) {
+ return true;
+ }
+
+ protected boolean isNSEWUP(ForgeDirection dir) {
+ return dir == NORTH || dir == SOUTH || dir == EAST || dir == WEST || dir == UP || dir == DOWN;
+ }
+
+ protected void drawSection(BoundingBox bound, float minU, float maxU, float minV, float maxV, ForgeDirection dir, boolean isTransmission) {
+
+ setupVertices(bound);
+
+ Tessellator tessellator = Tessellator.instance;
+
+ if (isTransmission) {
+ setVerticesForTransmission(bound, dir);
+ }
+
+ if (dir == NORTH || dir == UP || dir == EAST) { // maintain consistent texture
+ // dir relative to the cneter
+ // of the conduit
+ float tmp = minU;
+ minU = maxU;
+ maxU = tmp;
+ }
+
+ boolean rotateSides = dir == UP || dir == DOWN;
+ boolean rotateTopBottom = dir == NORTH || dir == SOUTH;
+
+ if (dir != NORTH && dir != SOUTH) {
+ tessellator.setNormal(0, 0, -1);
+ if (rotateSides) {
+ addVecWithUV(verts[1], maxU, maxV);
+ addVecWithUV(verts[0], maxU, minV);
+ addVecWithUV(verts[3], minU, minV);
+ addVecWithUV(verts[2], minU, maxV);
+ } else {
+ addVecWithUV(verts[1], minU, minV);
+ addVecWithUV(verts[0], maxU, minV);
+ addVecWithUV(verts[3], maxU, maxV);
+ addVecWithUV(verts[2], minU, maxV);
+ }
+ if (dir == WEST || dir == EAST) {
+ float tmp = minU;
+ minU = maxU;
+ maxU = tmp;
+ }
+ tessellator.setNormal(0, 0, 1);
+ if (rotateSides) {
+ addVecWithUV(verts[4], maxU, maxV);
+ addVecWithUV(verts[5], maxU, minV);
+ addVecWithUV(verts[6], minU, minV);
+ addVecWithUV(verts[7], minU, maxV);
+ } else {
+ addVecWithUV(verts[4], minU, minV);
+ addVecWithUV(verts[5], maxU, minV);
+ addVecWithUV(verts[6], maxU, maxV);
+ addVecWithUV(verts[7], minU, maxV);
+ }
+ if (dir == WEST || dir == EAST) {
+ float tmp = minU;
+ minU = maxU;
+ maxU = tmp;
+ }
+ }
+
+ if (dir != UP && dir != DOWN) {
+
+ tessellator.setNormal(0, 1, 0);
+ if (rotateTopBottom) {
+ addVecWithUV(verts[6], maxU, maxV);
+ addVecWithUV(verts[2], minU, maxV);
+ addVecWithUV(verts[3], minU, minV);
+ addVecWithUV(verts[7], maxU, minV);
+ } else {
+ addVecWithUV(verts[6], minU, minV);
+ addVecWithUV(verts[2], minU, maxV);
+ addVecWithUV(verts[3], maxU, maxV);
+ addVecWithUV(verts[7], maxU, minV);
+ }
+
+ tessellator.setNormal(0, -1, 0);
+ if (rotateTopBottom) {
+ addVecWithUV(verts[0], minU, minV);
+ addVecWithUV(verts[1], minU, maxV);
+ addVecWithUV(verts[5], maxU, maxV);
+ addVecWithUV(verts[4], maxU, minV);
+ } else {
+ addVecWithUV(verts[0], maxU, maxV);
+ addVecWithUV(verts[1], minU, maxV);
+ addVecWithUV(verts[5], minU, minV);
+ addVecWithUV(verts[4], maxU, minV);
+ }
+ }
+
+ if (dir != EAST && dir != WEST) {
+
+ // if(id == NORTH) {
+ // float tmp = minU;
+ // minU = maxU;
+ // maxU = tmp;
+ // }
+
+ tessellator.setNormal(1, 0, 0);
+ if (rotateSides) {
+ addVecWithUV(verts[2], minU, maxV);
+ addVecWithUV(verts[6], minU, minV);
+ addVecWithUV(verts[5], maxU, minV);
+ addVecWithUV(verts[1], maxU, maxV);
+ } else {
+ addVecWithUV(verts[2], minU, maxV);
+ addVecWithUV(verts[6], maxU, maxV);
+ addVecWithUV(verts[5], maxU, minV);
+ addVecWithUV(verts[1], minU, minV);
+ }
+
+ tessellator.setNormal(-1, 0, 0);
+ if (rotateSides) {
+ addVecWithUV(verts[0], maxU, maxV);
+ addVecWithUV(verts[4], maxU, minV);
+ addVecWithUV(verts[7], minU, minV);
+ addVecWithUV(verts[3], minU, maxV);
+ } else {
+ addVecWithUV(verts[0], minU, minV);
+ addVecWithUV(verts[4], maxU, minV);
+ addVecWithUV(verts[7], maxU, maxV);
+ addVecWithUV(verts[3], minU, maxV);
+ }
+ }
+ }
+
+ protected void setVerticesForTransmission(BoundingBox bound, ForgeDirection dir) {
+ float xs = dir.offsetX == 0 ? transmissionScaleFactor : 1;
+ float ys = dir.offsetY == 0 ? transmissionScaleFactor : 1;
+ float zs = dir.offsetZ == 0 ? transmissionScaleFactor : 1;
+ setupVertices(bound.scale(xs, ys, zs));
+ }
+
+ // TODO: This is a really hacky, imprecise and slow way to do this
+ public BoundingBox[] toCubes(BoundingBox bb) {
+
+ // NB This on handles the really simple conduit case!
+
+ float width = bb.maxX - bb.minX;
+ float height = bb.maxY - bb.minY;
+ float depth = bb.maxZ - bb.minZ;
+
+ if (width > 0 && height > 0 && depth > 0) {
+ if (width / depth > 1.5f || depth / width > 1.5f) {
+ // split horizontally
+ if (width > depth) {
+ int numSplits = Math.round(width / depth);
+ float newWidth = width / numSplits;
+ BoundingBox[] result = new BoundingBox[numSplits];
+ float lastMax = bb.minX;
+ for (int i = 0; i < numSplits; i++) {
+ float max = lastMax + newWidth;
+ result[i] = new BoundingBox(lastMax, bb.minY, bb.minZ, max, bb.maxY, bb.maxZ);
+ lastMax = max;
+ }
+ return result;
+
+ } else {
+
+ int numSplits = Math.round(depth / width);
+ float newWidth = depth / numSplits;
+ BoundingBox[] result = new BoundingBox[numSplits];
+ float lastMax = bb.minZ;
+ for (int i = 0; i < numSplits; i++) {
+ float max = lastMax + newWidth;
+ result[i] = new BoundingBox(bb.minX, bb.minY, lastMax, bb.maxX, bb.maxY, max);
+ lastMax = max;
+ }
+ return result;
+
+ }
+
+ } else if (height / width > 1.5) {
+
+ int numSplits = Math.round(height / width);
+ float newWidth = height / numSplits;
+ BoundingBox[] result = new BoundingBox[numSplits];
+ float lastMax = bb.minY;
+ for (int i = 0; i < numSplits; i++) {
+ float max = lastMax + newWidth;
+ result[i] = new BoundingBox(bb.minX, lastMax, bb.minZ, bb.maxX, max, bb.maxZ);
+ lastMax = max;
+ }
+ return result;
+
+ }
+ }
+
+ return new BoundingBox[] { bb };
+ }
+
+}
diff --git a/common/crazypants/enderio/conduit/render/ItemConduitRenderer.java b/common/crazypants/enderio/conduit/render/ItemConduitRenderer.java
new file mode 100644
index 00000000..d935006c
--- /dev/null
+++ b/common/crazypants/enderio/conduit/render/ItemConduitRenderer.java
@@ -0,0 +1,68 @@
+package crazypants.enderio.conduit.render;
+
+import net.minecraft.client.renderer.RenderBlocks;
+import net.minecraft.client.renderer.Tessellator;
+import net.minecraft.item.ItemStack;
+import net.minecraftforge.client.IItemRenderer;
+
+import org.lwjgl.opengl.GL11;
+
+import crazypants.render.BoundingBox;
+import crazypants.render.CubeRenderer;
+
+
+public class ItemConduitRenderer implements IItemRenderer {
+
+ private final BoundingBox bb;
+
+ public ItemConduitRenderer() {
+ float scale = 0.8f;
+ bb = BoundingBox.UNIT_CUBE.scale(scale,scale,scale);
+ }
+
+
+
+ @Override
+ public boolean handleRenderType(ItemStack item, ItemRenderType type) {
+ return type == ItemRenderType.ENTITY || type == ItemRenderType.EQUIPPED || type == ItemRenderType.INVENTORY || type == ItemRenderType.EQUIPPED_FIRST_PERSON;
+ }
+
+ @Override
+ public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) {
+ return true;
+ }
+
+ @Override
+ public void renderItem(ItemRenderType type, ItemStack item, Object... data) {
+ RenderBlocks renderBlocks = (RenderBlocks) data[0];
+ if (type == ItemRenderType.INVENTORY) {
+ renderToInventory(item, renderBlocks);
+ } else if (type == ItemRenderType.EQUIPPED) {
+ renderEquipped(item, renderBlocks);
+ } else if (type == ItemRenderType.ENTITY) {
+ renderEntity(item, renderBlocks);
+ } else if (type == ItemRenderType.EQUIPPED_FIRST_PERSON) {
+ renderEntity(item, renderBlocks);
+ } else {
+ System.out.println("FacadeRenderer.renderItem: Unsupported render type");
+ }
+ }
+
+ private void renderEntity(ItemStack item, RenderBlocks renderBlocks) {
+ GL11.glPushMatrix();
+ GL11.glScalef(0.5f, 0.5f, 0.5f);
+ renderToInventory(item, renderBlocks);
+ GL11.glPopMatrix();
+ }
+
+ private void renderEquipped(ItemStack item, RenderBlocks renderBlocks) {
+ renderToInventory(item, renderBlocks);
+ }
+
+ private void renderToInventory(ItemStack item, RenderBlocks renderBlocks) {
+ Tessellator.instance.startDrawingQuads();
+ CubeRenderer.render(bb, item.getItem().getIconFromDamage(item.getItemDamage()));
+ Tessellator.instance.draw();
+ }
+
+}
diff --git a/common/crazypants/enderio/conduit/render/RoundedSegmentRenderer.java b/common/crazypants/enderio/conduit/render/RoundedSegmentRenderer.java
new file mode 100644
index 00000000..86a583b4
--- /dev/null
+++ b/common/crazypants/enderio/conduit/render/RoundedSegmentRenderer.java
@@ -0,0 +1,186 @@
+package crazypants.enderio.conduit.render;
+
+import static crazypants.util.ForgeDirectionOffsets.offsetScaled;
+import static net.minecraftforge.common.ForgeDirection.SOUTH;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import crazypants.enderio.conduit.geom.ConduitGeometryUtil;
+import crazypants.render.BoundingBox;
+import crazypants.util.ForgeDirectionOffsets;
+import crazypants.vecmath.Matrix4d;
+import crazypants.vecmath.Vector2d;
+import crazypants.vecmath.Vector3d;
+import crazypants.vecmath.Vector3f;
+
+
+import net.minecraft.client.renderer.Tessellator;
+import net.minecraftforge.common.ForgeDirection;
+
+public class RoundedSegmentRenderer {
+
+ private static Coord[][] DIR_COORDS = new Coord[ForgeDirection.VALID_DIRECTIONS.length][];
+
+ private static final Vector3d REF_TRANS = new Vector3d(0.5, 0.5, 0.5);
+
+ static {
+ double circ = ConduitGeometryUtil.WIDTH * 0.7;
+
+ Coord[] refCoords = createUnitSectionQuads(16, -0.25, 0.25);
+
+ for (Coord coord : refCoords) {
+ coord.xyz.x = coord.xyz.x * circ;
+ coord.xyz.y = coord.xyz.y * circ;
+ }
+ Matrix4d rotMat = new Matrix4d();
+ rotMat.setIdentity();
+ rotMat.setTranslation(REF_TRANS);
+
+ DIR_COORDS[SOUTH.ordinal()] = xformCoords(refCoords, rotMat, offsetScaled(ForgeDirection.SOUTH, 0.25));
+
+ rotMat.makeRotationY(Math.PI);
+ rotMat.setTranslation(REF_TRANS);
+ DIR_COORDS[ForgeDirection.NORTH.ordinal()] = xformCoords(refCoords, rotMat, offsetScaled(ForgeDirection.NORTH, 0.25));
+
+ rotMat.makeRotationY(Math.PI / 2);
+ rotMat.setTranslation(REF_TRANS);
+ DIR_COORDS[ForgeDirection.EAST.ordinal()] = xformCoords(refCoords, rotMat, offsetScaled(ForgeDirection.EAST, 0.25));
+
+ rotMat.makeRotationY(-Math.PI / 2);
+ rotMat.setTranslation(REF_TRANS);
+ DIR_COORDS[ForgeDirection.WEST.ordinal()] = xformCoords(refCoords, rotMat, offsetScaled(ForgeDirection.WEST, 0.25));
+
+ rotMat.makeRotationX(-Math.PI / 2);
+ rotMat.setTranslation(REF_TRANS);
+ DIR_COORDS[ForgeDirection.UP.ordinal()] = xformCoords(refCoords, rotMat, offsetScaled(ForgeDirection.UP, 0.25));
+
+ rotMat.makeRotationX(Math.PI / 2);
+ rotMat.setTranslation(REF_TRANS);
+ DIR_COORDS[ForgeDirection.DOWN.ordinal()] = xformCoords(refCoords, rotMat, offsetScaled(ForgeDirection.DOWN, 0.25));
+
+ }
+
+
+ private static Coord[] xformCoords(Coord[] refCoords, Matrix4d rotMat, Vector3d trans) {
+ Coord[] res = new Coord[refCoords.length];
+ for (int i = 0; i < res.length; i++) {
+ res[i] = new Coord(refCoords[i]);
+ rotMat.transform(res[i].xyz);
+ rotMat.transformNormal(res[i].normal);
+ res[i].xyz.add(trans);
+ }
+ return res;
+ }
+
+ private static Coord[] xformCoords(List refCoords, Matrix4d rotMat, Vector3d trans) {
+ Coord[] res = new Coord[refCoords.size()];
+ for (int i = 0; i < res.length; i++) {
+ res[i] = new Coord(refCoords.get(i));
+ rotMat.transform(res[i].xyz);
+ rotMat.transformNormal(res[i].normal);
+ res[i].xyz.add(trans);
+ }
+ return res;
+ }
+
+ public static Coord[] createUnitCrossSection(double xOffset, double yOffset, double zOffset, int numCoords, int u) {
+
+ Coord[] crossSection = new Coord[numCoords];
+
+ double angle = 0;
+ double inc = (Math.PI * 2) / (crossSection.length - 1);
+ for (int i = 0; i < crossSection.length; i++) {
+ double x = Math.cos(angle) * 0.5;
+ double y = Math.sin(angle) * 0.5;
+ angle += inc;
+ crossSection[i] = new Coord();
+ crossSection[i].setXYZ(xOffset + x, yOffset + y, zOffset);
+ crossSection[i].setNormal(x, y, 0);
+ crossSection[i].setUV(u, y + 0.5);
+ }
+ return crossSection;
+
+ }
+
+ public static void renderSegment(ForgeDirection dir, BoundingBox bounds, float minU, float maxU, float minV, float maxV) {
+ float uScale = maxU - minU;
+ float vScale = maxV - minV;
+
+ Vector3d offset = calcOffset(dir, bounds);
+
+ Tessellator tes = Tessellator.instance;
+ Coord[] coords = DIR_COORDS[dir.ordinal()];
+ for (Coord coord : coords) {
+ double u = minU + (coord.uv.x * uScale);
+ double v = minV + (coord.uv.y * vScale);
+ tes.setNormal(coord.normal.x, coord.normal.y, coord.normal.z);
+ tes.addVertexWithUV(offset.x + coord.xyz.x, offset.y + coord.xyz.y, offset.z + coord.xyz.z, u, v);
+ }
+ }
+
+
+ private static Vector3d calcOffset(ForgeDirection dir, BoundingBox bounds) {
+ Vector3d res = new Vector3d();
+ Vector3d center = bounds.getCenter();
+ if(dir != ForgeDirection.UP && dir != ForgeDirection.DOWN) {
+ res.set(0, center.y - REF_TRANS.y,0);
+ } else {
+ res.set(center.x - REF_TRANS.x, 0,0);
+ }
+ return res;
+ }
+
+ public static Coord[] createUnitSectionQuads(int numCoords, double minZ, double maxZ) {
+
+ Coord[] z0 = createUnitCrossSection(0, 0, minZ, numCoords + 1, 0);
+ Coord[] z1 = createUnitCrossSection(0, 0, maxZ, numCoords + 1, 1);
+
+ Coord[] result = new Coord[numCoords * 4];
+ for (int i = 0; i < numCoords; i++) {
+ int index = i * 4;
+ result[index] = new Coord(z0[i]);
+ result[index + 1] = new Coord(z0[i + 1]);
+ result[index + 2] = new Coord(z1[i + 1]);
+ result[index + 3] = new Coord(z1[i]);
+ }
+ return result;
+
+ }
+
+ public static class Coord {
+
+ Vector3d xyz = new Vector3d();
+ Vector2d uv = new Vector2d();
+ Vector3f normal = new Vector3f();
+
+ Coord() {
+ }
+
+ Coord(Coord other) {
+ xyz.set(other.xyz);
+ uv.set(other.uv);
+ normal.set(other.normal);
+ }
+
+ void setXYZ(double x, double y, double z) {
+ xyz.set(x, y, z);
+ }
+
+ void setUV(double u, double v) {
+ uv.set(u, v);
+ }
+
+ void setNormal(double x, double y, double z) {
+ normal.set((float)x,(float)y,(float)z);
+ normal.normalize();
+ }
+
+ @Override
+ public String toString() {
+ return "Coord [xyz=" + xyz + ", uv=" + uv + "]";
+ }
+
+ }
+
+}
diff --git a/common/crazypants/enderio/enderface/BlockEnderIO.java b/common/crazypants/enderio/enderface/BlockEnderIO.java
new file mode 100644
index 00000000..8fa7d2ea
--- /dev/null
+++ b/common/crazypants/enderio/enderface/BlockEnderIO.java
@@ -0,0 +1,113 @@
+package crazypants.enderio.enderface;
+
+import net.minecraft.block.Block;
+import net.minecraft.block.ITileEntityProvider;
+import net.minecraft.block.material.Material;
+import net.minecraft.client.renderer.texture.IconRegister;
+import net.minecraft.entity.player.EntityPlayer;
+import net.minecraft.item.Item;
+import net.minecraft.item.ItemStack;
+import net.minecraft.nbt.NBTTagCompound;
+import net.minecraft.tileentity.TileEntity;
+import net.minecraft.util.ChatMessageComponent;
+import net.minecraft.util.Icon;
+import net.minecraft.world.IBlockAccess;
+import net.minecraft.world.World;
+import cpw.mods.fml.common.registry.GameRegistry;
+import cpw.mods.fml.common.registry.LanguageRegistry;
+import crazypants.enderio.EnderIO;
+import crazypants.enderio.EnderIOTab;
+import crazypants.enderio.ModObject;
+
+public class BlockEnderIO extends Block implements ITileEntityProvider {
+
+ public static BlockEnderIO create() {
+ BlockEnderIO result = new BlockEnderIO();
+ result.init();
+ return result;
+ }
+
+ Icon frameIcon;
+
+ private BlockEnderIO() {
+ super(ModObject.blockEnderIo.id, Material.rock);
+ setHardness(0.5F);
+ setStepSound(Block.soundStoneFootstep);
+ setUnlocalizedName(ModObject.blockEnderIo.unlocalisedName);
+ setCreativeTab(EnderIOTab.tabEnderIO);
+ }
+
+ private void init() {
+ LanguageRegistry.addName(this, ModObject.blockEnderIo.name);
+ GameRegistry.registerBlock(this, ModObject.blockEnderIo.unlocalisedName);
+ GameRegistry.registerTileEntity(TileEnderIO.class, ModObject.blockEnderIo.unlocalisedName + "TileEntity");
+ GameRegistry.addRecipe(new ItemStack(this), "zxz", "xyx", "zxz", 'x', new ItemStack(Item.eyeOfEnder), 'y', new ItemStack(Block.enderChest), 'z',
+ new ItemStack(Item.diamond));
+ }
+
+ @Override
+ public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer entityPlayer, int par6, float par7, float par8, float par9) {
+ if (entityPlayer.isSneaking()) {
+ return false;
+ }
+ if (entityPlayer.getCurrentEquippedItem() != null && entityPlayer.getCurrentEquippedItem().itemID == EnderIO.itemEnderface.itemID) {
+ ItemStack enderFaceStack = entityPlayer.getCurrentEquippedItem();
+ NBTTagCompound nbttagcompound = enderFaceStack.getTagCompound();
+ if (nbttagcompound == null) {
+ nbttagcompound = new NBTTagCompound();
+ }
+ nbttagcompound.setBoolean(ItemEnderface.KEY_IO_SET, true);
+ nbttagcompound.setInteger(ItemEnderface.KEY_IO_X, x);
+ nbttagcompound.setInteger(ItemEnderface.KEY_IO_Y, y);
+ nbttagcompound.setInteger(ItemEnderface.KEY_IO_Z, z);
+ nbttagcompound.setInteger(ItemEnderface.KEY_DIMENSION, world.provider.dimensionId);
+ enderFaceStack.setTagCompound(nbttagcompound);
+
+ entityPlayer.setCurrentItemOrArmor(0, enderFaceStack);
+
+ if (world.isRemote) {
+ ChatMessageComponent c = ChatMessageComponent.func_111066_d("EnderIO Interface Selected");
+ entityPlayer.sendChatToPlayer(c);
+ }
+
+ }
+ return true;
+ }
+
+ @Override
+ public boolean renderAsNormalBlock() {
+ return false;
+ }
+
+ @Override
+ public boolean isOpaqueCube() {
+ return false;
+ }
+
+ @Override
+ public int getRenderType() {
+ return -1;
+ }
+
+ @Override
+ public int getLightValue(IBlockAccess world, int x, int y, int z) {
+ return 13;
+ }
+
+ @Override
+ public int getLightOpacity(World world, int x, int y, int z) {
+ return 100;
+ }
+
+ @Override
+ public void registerIcons(IconRegister iconRegister) {
+ blockIcon = iconRegister.registerIcon("enderio:enderIO");
+ frameIcon = iconRegister.registerIcon("enderio:enderIOFrame");
+ }
+
+ @Override
+ public TileEntity createNewTileEntity(World world) {
+ return new TileEnderIO();
+ }
+
+}
diff --git a/common/crazypants/enderio/enderface/ContainerWrapper.java b/common/crazypants/enderio/enderface/ContainerWrapper.java
new file mode 100644
index 00000000..e0d3238b
--- /dev/null
+++ b/common/crazypants/enderio/enderface/ContainerWrapper.java
@@ -0,0 +1,114 @@
+package crazypants.enderio.enderface;
+
+import net.minecraft.entity.player.EntityPlayer;
+import net.minecraft.inventory.Slot;
+import net.minecraft.item.ItemStack;
+
+public class ContainerWrapper extends net.minecraft.inventory.Container {
+
+ public net.minecraft.inventory.Container wrapped;
+
+ public ContainerWrapper(net.minecraft.inventory.Container wrapped) {
+ this.wrapped = wrapped;
+ this.inventoryItemStacks = wrapped.inventoryItemStacks;
+ this.inventorySlots = wrapped.inventorySlots;
+ this.windowId = wrapped.windowId;
+ }
+
+ @Override
+ public boolean canDragIntoSlot(Slot par1Slot) {
+ return wrapped.canDragIntoSlot(par1Slot);
+ }
+
+ @Override
+ public boolean canInteractWith(net.minecraft.entity.player.EntityPlayer arg0) {
+ return true;
+ }
+
+ @Override
+ public net.minecraft.inventory.Slot getSlot(int arg0) {
+ return wrapped.getSlot(arg0);
+ }
+
+ @SuppressWarnings("rawtypes")
+ @Override
+ public java.util.List getInventory() {
+ return wrapped.getInventory();
+ }
+
+ @Override
+ public boolean enchantItem(net.minecraft.entity.player.EntityPlayer arg0, int arg1) {
+ return wrapped.enchantItem(arg0, arg1);
+ }
+
+ @Override
+ public net.minecraft.item.ItemStack slotClick(int arg0, int arg1, int arg2, net.minecraft.entity.player.EntityPlayer arg3) {
+ return wrapped.slotClick(arg0, arg1, arg2, arg3);
+ }
+
+ @Override
+ public boolean func_94530_a(net.minecraft.item.ItemStack arg0, net.minecraft.inventory.Slot arg1) {
+ return wrapped.func_94530_a(arg0, arg1);
+ }
+
+ @Override
+ public void addCraftingToCrafters(net.minecraft.inventory.ICrafting arg0) {
+ wrapped.addCraftingToCrafters(arg0);
+ }
+
+ @Override
+ public void detectAndSendChanges() {
+ wrapped.detectAndSendChanges();
+ }
+
+ @Override
+ public void removeCraftingFromCrafters(net.minecraft.inventory.ICrafting arg0) {
+ wrapped.removeCraftingFromCrafters(arg0);
+ }
+
+ @Override
+ public net.minecraft.inventory.Slot getSlotFromInventory(net.minecraft.inventory.IInventory arg0, int arg1) {
+ return wrapped.getSlotFromInventory(arg0, arg1);
+ }
+
+ @Override
+ public net.minecraft.item.ItemStack transferStackInSlot(net.minecraft.entity.player.EntityPlayer arg0, int arg1) {
+ return wrapped.transferStackInSlot(arg0, arg1);
+ }
+
+ @Override
+ public void onCraftMatrixChanged(net.minecraft.inventory.IInventory arg0) {
+ wrapped.onCraftMatrixChanged(arg0);
+ }
+
+ @Override
+ public void putStackInSlot(int arg0, net.minecraft.item.ItemStack arg1) {
+ wrapped.putStackInSlot(arg0, arg1);
+ }
+
+ @Override
+ public void putStacksInSlots(net.minecraft.item.ItemStack[] arg0) {
+ wrapped.putStacksInSlots(arg0);
+ }
+
+ @Override
+ public void updateProgressBar(int arg0, int arg1) {
+ wrapped.updateProgressBar(arg0, arg1);
+ }
+
+ @Override
+ public short getNextTransactionID(net.minecraft.entity.player.InventoryPlayer arg0) {
+ return wrapped.getNextTransactionID(arg0);
+ }
+
+ @Override
+ public boolean isPlayerNotUsingContainer(net.minecraft.entity.player.EntityPlayer arg0) {
+ return wrapped.isPlayerNotUsingContainer(arg0);
+ }
+
+ @Override
+ public void setPlayerIsPresent(net.minecraft.entity.player.EntityPlayer arg0, boolean arg1) {
+ wrapped.setPlayerIsPresent(arg0, arg1);
+ }
+
+}
diff --git a/common/crazypants/enderio/enderface/EnderIoRenderer.java b/common/crazypants/enderio/enderface/EnderIoRenderer.java
new file mode 100644
index 00000000..0e830940
--- /dev/null
+++ b/common/crazypants/enderio/enderface/EnderIoRenderer.java
@@ -0,0 +1,157 @@
+package crazypants.enderio.enderface;
+
+import net.minecraft.client.Minecraft;
+import net.minecraft.client.renderer.Tessellator;
+import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
+import net.minecraft.entity.EntityLivingBase;
+import net.minecraft.item.Item;
+import net.minecraft.item.ItemStack;
+import net.minecraft.tileentity.TileEntity;
+import net.minecraft.util.Icon;
+import net.minecraftforge.client.IItemRenderer;
+
+import org.lwjgl.opengl.GL11;
+
+import crazypants.enderio.EnderIO;
+import crazypants.render.BoundingBox;
+import crazypants.render.CubeRenderer;
+import crazypants.render.RenderUtil;
+import crazypants.vecmath.Matrix4d;
+import crazypants.vecmath.VecmathUtil;
+import crazypants.vecmath.Vector3d;
+
+
+public class EnderIoRenderer extends TileEntitySpecialRenderer implements IItemRenderer {
+
+ @Override
+ public void renderTileEntityAt(TileEntity te, double x, double y, double z, float f) {
+ EntityLivingBase entityPlayer = tileEntityRenderer.entityLivingPlayer;
+
+ Vector3d playerEye = new Vector3d(entityPlayer.posX, entityPlayer.posY + 1.62 - entityPlayer.yOffset, entityPlayer.posZ);
+ Vector3d blockOrigin = new Vector3d(te.xCoord + 0.5, te.yCoord + 0.5, te.zCoord + 0.5);
+ Matrix4d lookMat = VecmathUtil.createMatrixAsLookAt(blockOrigin, playerEye, RenderUtil.UP_V);
+ lookMat.setTranslation(new Vector3d());
+ lookMat.invert();
+
+ int brightness = RenderUtil.setTesselatorBrightness(tileEntityRenderer.worldObj, te.xCoord, te.yCoord, te.zCoord);
+ render(x, y, z, lookMat, brightness);
+ }
+
+ public void render(double x, double y, double z, Matrix4d lookMat, int brightness) {
+
+
+ GL11.glPushMatrix();
+ GL11.glTranslated(x + 0.5, y + 0.5, z + 0.5);
+
+ Icon tex = Item.eyeOfEnder.getIconFromDamage(0);
+ RenderUtil.bindItemTexture();
+ float minU = tex.getMinU();
+ float maxU = tex.getMaxU();
+ float minV = tex.getMinV();
+ float maxV = tex.getMaxV();
+
+ GL11.glDisable(GL11.GL_CULL_FACE);
+ GL11.glColor3f(1, 1, 1);
+ renderBillboard(lookMat, minU, maxU, minV, maxV, 0.8, brightness);
+
+ // Glint
+ float maxUV = 32;
+ GL11.glDepthFunc(GL11.GL_EQUAL);
+ GL11.glDisable(GL11.GL_LIGHTING);
+ RenderUtil.bindGlintTexture();
+ GL11.glEnable(GL11.GL_BLEND);
+ GL11.glBlendFunc(GL11.GL_SRC_COLOR, GL11.GL_ONE);
+ float blendFactor = 1F;
+ GL11.glColor4f(0.5F * blendFactor, 0.25F * blendFactor, 0.8F * blendFactor, 1.0F);
+
+ GL11.glMatrixMode(GL11.GL_TEXTURE);
+ GL11.glPushMatrix();
+ float scale = 0.125F;
+ GL11.glScalef(scale, scale, scale);
+ float tans = Minecraft.getSystemTime() % 3000L / 3000.0F * 8.0F;
+ GL11.glTranslatef(tans, 0.0F, 0.0F);
+ GL11.glRotatef(-50.0F, 0.0F, 0.0F, 1.0F);
+ renderBillboard(lookMat, 0, maxUV, 0, maxUV, 0.8, brightness);
+ GL11.glPopMatrix();
+
+ GL11.glPushMatrix();
+ GL11.glScalef(scale, scale, scale);
+ tans = Minecraft.getSystemTime() % 4873L / 4873.0F * 8.0F;
+ GL11.glTranslatef(-tans, 0.0F, 0.0F);
+ GL11.glRotatef(10.0F, 0.0F, 0.0F, 1.0F);
+ renderBillboard(lookMat, 0, maxUV, 0, maxUV, 0.8,brightness);
+ GL11.glPopMatrix();
+
+ GL11.glMatrixMode(GL11.GL_MODELVIEW);
+ GL11.glDisable(GL11.GL_BLEND);
+ GL11.glEnable(GL11.GL_LIGHTING);
+ GL11.glDepthFunc(GL11.GL_LEQUAL);
+
+
+
+ GL11.glColor4f(1, 1, 1, 1.0F);
+ GL11.glPopMatrix();
+
+ GL11.glPushMatrix();
+ GL11.glTranslated(x, y, z);
+
+
+ RenderUtil.bindBlockTexture();
+ Tessellator.instance.startDrawingQuads();
+ Tessellator.instance.setBrightness(brightness);
+
+ GL11.glEnable(GL11.GL_BLEND);
+ GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
+ CubeRenderer.render(BoundingBox.UNIT_CUBE, EnderIO.blockEnderIo.frameIcon);
+ Tessellator.instance.draw();
+ GL11.glPopMatrix();
+
+ GL11.glDisable(GL11.GL_BLEND);
+
+ }
+
+ private void renderBillboard(Matrix4d lookMat, float minU, float maxU, float minV, float maxV, double size, int brightness) {
+
+ Tessellator tes = Tessellator.instance;
+ tes.startDrawingQuads();
+ tes.setBrightness(brightness);
+
+ double s = size / 2;
+ Vector3d v = new Vector3d();
+ v.set(-s, s, 0);
+ lookMat.transform(v);
+ tes.addVertexWithUV(v.x, v.y, v.z, minU, maxV);
+ v.set(s, s, 0);
+ lookMat.transform(v);
+ tes.addVertexWithUV(v.x, v.y, v.z, maxU, maxV);
+ v.set(s, -s, 0);
+ lookMat.transform(v);
+ tes.addVertexWithUV(v.x, v.y, v.z, maxU, minV);
+ v.set(-s, -s, 0);
+ lookMat.transform(v);
+ tes.addVertexWithUV(v.x, v.y, v.z, minU, minV);
+ tes.draw();
+ }
+
+ @Override
+ public boolean handleRenderType(ItemStack item, ItemRenderType type) {
+ return true;
+ }
+
+ @Override
+ public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) {
+ return true;
+ }
+
+ @Override
+ public void renderItem(ItemRenderType type, ItemStack item, Object... data) {
+ Matrix4d lookMat = new Matrix4d();
+ lookMat.setIdentity();
+
+ lookMat = VecmathUtil.createMatrixAsLookAt(RenderUtil.ZERO_V, new Vector3d(1, 0, 0), RenderUtil.UP_V);
+
+ render(0, 0, 0, lookMat, 0xF000F0);
+
+ }
+
+}
diff --git a/common/crazypants/enderio/enderface/GuiEnderface.java b/common/crazypants/enderio/enderface/GuiEnderface.java
new file mode 100644
index 00000000..6d5be227
--- /dev/null
+++ b/common/crazypants/enderio/enderface/GuiEnderface.java
@@ -0,0 +1,507 @@
+package crazypants.enderio.enderface;
+
+import java.awt.Rectangle;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import net.minecraft.block.Block;
+import net.minecraft.client.gui.GuiScreen;
+import net.minecraft.client.gui.ScaledResolution;
+import net.minecraft.client.renderer.RenderBlocks;
+import net.minecraft.client.renderer.RenderHelper;
+import net.minecraft.client.renderer.Tessellator;
+import net.minecraft.client.renderer.tileentity.TileEntityRenderer;
+import net.minecraft.entity.player.EntityPlayer;
+import net.minecraft.network.packet.Packet250CustomPayload;
+import net.minecraft.tileentity.TileEntity;
+import net.minecraft.util.Icon;
+import net.minecraft.util.MovingObjectPosition;
+import net.minecraft.util.Vec3;
+import net.minecraft.world.World;
+import net.minecraft.world.chunk.Chunk;
+
+import org.lwjgl.input.Mouse;
+import org.lwjgl.opengl.GL11;
+import org.lwjgl.opengl.GL12;
+
+import cpw.mods.fml.common.network.PacketDispatcher;
+import crazypants.enderio.ModObject;
+import crazypants.enderio.PacketHandler;
+import crazypants.render.RenderUtil;
+import crazypants.util.BlockCoord;
+import crazypants.vecmath.Camera;
+import crazypants.vecmath.Matrix4d;
+import crazypants.vecmath.VecmathUtil;
+import crazypants.vecmath.Vector3d;
+
+public class GuiEnderface extends GuiScreen {
+
+ protected static final RenderBlocks RB = new RenderBlocks();
+
+ private float pitch = -45;
+ private float yaw = 45;
+
+ private final EntityPlayer player;
+ private final World world;
+ private final int ioX;
+ private final int ioY;
+ private final int ioZ;
+ private boolean chunkLoaded;
+
+ private List blocks = new ArrayList();
+
+ private int gw;
+ private int gh;
+ private int guiLeft;
+ private int guiTop;
+ private int finalGw;
+ private int finalGh;
+ // private boolean animateInX = true;
+ private boolean animateInX = false;
+ private boolean animateInY = false;
+ // private boolean animating = true;
+ float animationDuration = 180;
+
+ private final Vector3d origin = new Vector3d();
+ private final Vector3d eye = new Vector3d();
+ private final Camera camera = new Camera();
+ private final Matrix4d pitchRot = new Matrix4d();
+ private final Matrix4d yawRot = new Matrix4d();
+
+ private float scaleAnimX;
+
+ private int range;
+
+ boolean dragging = false;
+
+ private double distance;
+
+ private long initTime;
+
+ public GuiEnderface(EntityPlayer player, World world, int ioX, int ioY, int ioZ) {
+ this.player = player;
+ this.world = world;
+ this.ioX = ioX;
+ this.ioY = ioY;
+ this.ioZ = ioZ;
+
+ distance = 10 + (range * 2);
+
+ origin.set(ioX + 0.5, ioY + 0.5, ioZ + 0.5);
+ pitchRot.setIdentity();
+ yawRot.setIdentity();
+
+ Chunk c = world.getChunkFromBlockCoords(ioX, ioZ);
+ chunkLoaded = c != null && c.isChunkLoaded;
+ RB.blockAccess = world;
+
+ blocks.add(new ViewableBlocks(ioX, ioY, ioZ, ModObject.blockEnderIo.id));
+ range = 3;
+ for (int x = ioX - range; x <= ioX + range; x++) {
+ for (int y = ioY - range; y <= ioY + range; y++) {
+ for (int z = ioZ - range; z <= ioZ + range; z++) {
+ int blockId = world.getBlockId(x, y, z);
+ if (blockId > 0 && blockId < Block.blocksList.length) {
+ blocks.add(new ViewableBlocks(x, y, z, blockId));
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Adds the buttons (and other controls) to the screen in question.
+ */
+ @Override
+ public void initGui() {
+
+ finalGw = width * 1;
+ finalGh = height * 1;
+ // gw = finalGw - 1;
+ // gh = finalGh - 1;
+ gw = finalGw;
+ gh = finalGh;
+ // gw = 0;
+ // gh = 0;
+ guiLeft = (width - gw) / 2;
+ guiTop = (height - gh) / 2;
+
+ initTime = world.getTotalWorldTime();
+ }
+
+ @Override
+ public boolean doesGuiPauseGame() {
+ return false;
+ }
+
+ /**
+ * Handles mouse input.
+ */
+ @Override
+ public void handleMouseInput() {
+ super.handleMouseInput();
+
+ if (Mouse.getEventButton() == 0) {
+ dragging = Mouse.getEventButtonState();
+ }
+
+ if (dragging) {
+ yaw -= (Mouse.getEventDX() / (double) mc.displayWidth) * 180;
+ pitch += (Mouse.getEventDY() / (double) mc.displayHeight) * 180;
+ pitch = (float) VecmathUtil.clamp(pitch, -80, 80);
+ }
+
+ distance -= Mouse.getDWheel() * 0.01;
+ distance = VecmathUtil.clamp(distance, 0.1, 20);
+
+ long elapsed = world.getTotalWorldTime() - initTime;
+
+ if (Mouse.getEventButton() == 1 && !Mouse.getEventButtonState() && camera.isValid() && elapsed > 10) {
+
+ int x = Mouse.getEventX();
+ int y = Mouse.getEventY();
+ Vector3d start = new Vector3d();
+ Vector3d end = new Vector3d();
+ if (camera.getRayForPixel(x, y, start, end)) {
+ end.scale(distance * 2);
+ end.add(start);
+ doSelection(start, end);
+ }
+
+ }
+
+ }
+
+ private void doSelection(Vector3d start, Vector3d end) {
+ start.add(origin);
+ end.add(origin);
+ List hits = new ArrayList();
+ for (ViewableBlocks ug : blocks) {
+ if (!ug.bc.equals(new BlockCoord(ioX, ioY, ioZ))) {
+ MovingObjectPosition res = Block.blocksList[ug.blockId].collisionRayTrace(world, ug.bc.x, ug.bc.y, ug.bc.z,
+ Vec3.createVectorHelper(start.x, start.y, start.z), Vec3.createVectorHelper(end.x, end.y, end.z));
+ if (res != null) {
+ hits.add(res);
+ }
+ }
+ }
+ MovingObjectPosition hit = getClosestHit(Vec3.createVectorHelper(start.x, start.y, start.z), hits);
+ if (hit != null) {
+ int id = world.getBlockId(hit.blockX, hit.blockY, hit.blockZ);
+ openInterface(hit.blockX, hit.blockY, hit.blockZ);
+ }
+
+ }
+
+ public static MovingObjectPosition getClosestHit(Vec3 origin, Collection candidates) {
+ double minLengthSquared = Double.POSITIVE_INFINITY;
+ MovingObjectPosition closest = null;
+
+ for (MovingObjectPosition hit : candidates) {
+ if (hit != null) {
+ double lengthSquared = hit.hitVec.squareDistanceTo(origin);
+ if (lengthSquared < minLengthSquared) {
+ minLengthSquared = lengthSquared;
+ closest = hit;
+ }
+ }
+ }
+ return closest;
+ }
+
+ /**
+ * Draws the screen and all the components in it.
+ */
+ @Override
+ public void drawScreen(int par1, int par2, float partialTick) {
+
+ animateBackground(partialTick);
+ drawDefaultBackground();
+
+ RenderHelper.disableStandardItemLighting();
+ RenderHelper.enableGUIStandardItemLighting();
+ drawEnderfaceBackground();
+
+ if (!updateCamera(partialTick)) {
+ return;
+ }
+ applyCamera(partialTick);
+
+ if (!animateInX && !animateInY) {
+
+ if (chunkLoaded) {
+
+ GL11.glEnable(GL11.GL_CULL_FACE);
+ GL11.glEnable(GL12.GL_RESCALE_NORMAL);
+
+ RenderHelper.disableStandardItemLighting();
+ mc.entityRenderer.enableLightmap(0);
+ RenderUtil.bindBlockTexture();
+
+ Vector3d trans = new Vector3d((-origin.x) + eye.x, (-origin.y) + eye.y, (-origin.z) + eye.z);
+ Tessellator.instance.startDrawingQuads();
+ Tessellator.instance.setTranslation(trans.x, trans.y, trans.z);
+ for (ViewableBlocks ug : blocks) {
+ RB.setRenderBounds(0, 0, 0, 1, 1, 1);
+ RB.renderBlockByRenderType(Block.blocksList[ug.blockId], ug.bc.x, ug.bc.y, ug.bc.z);
+ }
+ Tessellator.instance.draw();
+ Tessellator.instance.setTranslation(0, 0, 0);
+
+ RenderHelper.enableStandardItemLighting();
+ TileEntityRenderer.instance.playerX = origin.x - eye.x;
+ TileEntityRenderer.instance.playerY = origin.y - eye.y;
+ TileEntityRenderer.instance.playerZ = origin.z - eye.z;
+ TileEntityRenderer.staticPlayerX = origin.x - eye.x;
+ TileEntityRenderer.staticPlayerY = origin.y - eye.y;
+ TileEntityRenderer.staticPlayerZ = origin.z - eye.z;
+ for (ViewableBlocks ug : blocks) {
+ TileEntity tile = world.getBlockTileEntity(ug.bc.x, ug.bc.y, ug.bc.z);
+ if (tile != null) {
+ TileEntityRenderer.instance.renderTileEntity(tile, partialTick);
+ }
+ }
+
+ // mc.entityRenderer.disableLightmap(0);
+ } else {
+ drawCenteredString(fontRenderer, "EnderIO chunk not loaded.", width / 2, height / 2 - 32, 0xFFFFFFFF);
+ }
+ }
+ drawEffectOverlay(partialTick);
+ }
+
+ private boolean updateCamera(float partialTick) {
+ ScaledResolution scaledresolution = new ScaledResolution(mc.gameSettings, mc.displayWidth, mc.displayHeight);
+ int vpx = guiLeft * scaledresolution.getScaleFactor();
+ int vpy = guiTop * scaledresolution.getScaleFactor();
+ int vpw = (int) ((float) gw / width * mc.displayWidth);
+ int vph = (int) ((float) gh / height * mc.displayHeight);
+ if (vpw <= 0 || vph <= 0) {
+ return false;
+ }
+
+ camera.setViewport(vpx, vpy, vpw, vph);
+ camera.setProjectionMatrixAsPerspective(30, 0.05, 50, vpw, vph);
+
+ eye.set(0, 0, distance);
+ pitchRot.makeRotationX(Math.toRadians(pitch));
+ yawRot.makeRotationY(Math.toRadians(yaw));
+ pitchRot.transform(eye);
+ yawRot.transform(eye);
+ camera.setViewMatrixAsLookAt(eye, RenderUtil.ZERO_V, RenderUtil.UP_V);
+ return camera.isValid();
+ }
+
+ private void applyCamera(float partialTick) {
+ Rectangle vp = camera.getViewport();
+ GL11.glViewport(vp.x, vp.y, vp.width, vp.height);
+ GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT);
+ GL11.glMatrixMode(GL11.GL_PROJECTION);
+ RenderUtil.loadMatrix(camera.getTransposeProjectionMatrix());
+ GL11.glMatrixMode(GL11.GL_MODELVIEW);
+ RenderUtil.loadMatrix(camera.getTransposeViewMatrix());
+
+ scaleAnimX += (partialTick * 0.25);
+ float v = 0.4f;
+ float sf = 1.0F * (1 + v / 32);
+ GL11.glRotatef((scaleAnimX + partialTick) * 7, 0.0F, 1.0F, 1.0F);
+ GL11.glScalef(sf, 1.0F, 1.0f);
+ GL11.glRotatef(-(scaleAnimX + partialTick) * 7, 0.0F, 1.0F, 1.0F);
+
+ GL11.glTranslatef(-(float) eye.x, -(float) eye.y, -(float) eye.z);
+ }
+
+ private float portalFade = 1;
+
+ private void drawEffectOverlay(float partialTick) {
+ ScaledResolution scaledresolution = new ScaledResolution(this.mc.gameSettings, this.mc.displayWidth, this.mc.displayHeight);
+ GL11.glMatrixMode(GL11.GL_PROJECTION);
+ GL11.glLoadIdentity();
+ GL11.glOrtho(0.0D, scaledresolution.getScaledWidth_double(), scaledresolution.getScaledHeight_double(), 0.0D, 1000.0D, 3000.0D);
+ GL11.glMatrixMode(GL11.GL_MODELVIEW);
+ GL11.glLoadIdentity();
+ GL11.glTranslatef(0.0F, 0.0F, -2000.0F);
+ GL11.glEnable(GL11.GL_BLEND);
+ GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
+ GL11.glDisable(GL11.GL_DEPTH_TEST);
+ GL11.glDisable(GL11.GL_ALPHA_TEST);
+ GL11.glDepthMask(false);
+
+ RenderHelper.disableStandardItemLighting();
+ RenderHelper.enableGUIStandardItemLighting();
+
+ GL11.glDisable(GL11.GL_LIGHTING);
+ mc.entityRenderer.disableLightmap(0);
+
+ portalFade -= (partialTick * (1f / animationDuration));
+ portalFade = Math.max(0, portalFade);
+ if (portalFade >= 0) {
+ drawRect(scaledresolution.getScaledWidth(), scaledresolution.getScaledHeight(), 0, 0.3f, 0.16f, Math.max(0.3f, portalFade));
+ }
+
+ GL11.glEnable(GL11.GL_LIGHTING);
+ mc.entityRenderer.enableLightmap(0);
+
+ renderPortalOverlay(0.9f - (0.1f * (1 - portalFade)), scaledresolution.getScaledWidth(), scaledresolution.getScaledHeight());
+
+ GL11.glDepthMask(true);
+ GL11.glEnable(GL11.GL_DEPTH_TEST);
+ GL11.glEnable(GL11.GL_ALPHA_TEST);
+ GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
+
+ }
+
+ /**
+ * Renders the portal overlay. Args: portalStrength, width, height
+ */
+ protected void renderPortalOverlay(float par1, int par2, int par3) {
+ if (par1 < 1.0F) {
+ par1 *= par1;
+ par1 *= par1;
+ par1 = par1 * 0.8F + 0.2F;
+ }
+ GL11.glColor4f(1.0F, 1.0F, 1.0F, par1);
+ RenderUtil.bindBlockTexture();
+ Icon icon = Block.portal.getBlockTextureFromSide(1);
+ float f1 = icon.getMinU();
+ float f2 = icon.getMinV();
+ float f3 = icon.getMaxU();
+ float f4 = icon.getMaxV();
+ Tessellator tessellator = Tessellator.instance;
+ tessellator.startDrawingQuads();
+ tessellator.addVertexWithUV(0.0D, par3, -90.0D, f1, f4);
+ tessellator.addVertexWithUV(par2, par3, -90.0D, f3, f4);
+ tessellator.addVertexWithUV(par2, 0.0D, -90.0D, f3, f2);
+ tessellator.addVertexWithUV(0.0D, 0.0D, -90.0D, f1, f2);
+ tessellator.draw();
+ }
+
+ private boolean animating() {
+ return gw < finalGw || gh < finalGh;
+ }
+
+ private void drawRect(int width, int height, float r, float g,
+ float b, float a) {
+ Tessellator tessellator = Tessellator.instance;
+ GL11.glDisable(GL11.GL_TEXTURE_2D);
+ GL11.glColor4f(r, g, b, a);
+ tessellator.startDrawingQuads();
+ tessellator.addVertex(0.0D, height, 0.0D);
+ tessellator.addVertex(width, height, 0.0D);
+ tessellator.addVertex(width, 0.0D, 0.0D);
+ tessellator.addVertex(0.0D, 0.0D, 0.0D);
+ tessellator.draw();
+ GL11.glEnable(GL11.GL_TEXTURE_2D);
+ }
+
+ private void animateBackground(float partialTick) {
+
+ if (!animating()) {
+ return;
+ }
+
+ // if (animateInX) {
+ // animationDuration *= 0.8;
+ // }
+ int mag = (int) ((width / (animationDuration * 0.5f)) * partialTick);
+ int mag2 = mag * 2;
+
+ int ymag = (int) ((height / (animationDuration * 0.5f)) * partialTick);
+ // int ymag = mag;
+ int ymag2 = ymag * 2;
+
+ if (animateInX) {
+ gw -= mag2;
+ guiLeft += mag;
+ if (gw <= 0) {
+ animateInX = false;
+ // animateInY = false;
+ }
+ } else {
+ gw += mag2;
+ guiLeft -= mag;
+ }
+
+ if (animateInY) {
+ gh -= ymag2;
+ guiTop += ymag;
+ if (gh <= 0) {
+ animateInY = false;
+ // animateInX= false;
+ }
+ } else {
+ gh += ymag2;
+ guiTop -= ymag;
+ }
+
+ gw = Math.min(gw, finalGw);
+ gh = Math.min(gh, finalGh);
+ guiLeft = Math.max((width - finalGw) / 2, guiLeft);
+ guiTop = Math.max((height - finalGh) / 2, guiTop);
+
+ }
+
+ private void drawEnderfaceBackground() {
+
+ int w = this.gw;
+ int h = this.gh;
+ int left = this.guiLeft;
+ int top = this.guiTop;
+ int cx = left + w / 2;
+ int cy = top + h / 2;
+
+ // black outline
+ drawRect(left, top, left + w, top + h, 0xFF000000);
+ left += 1;
+ top += 1;
+ w -= 2;
+ h -= 2;
+
+ // border
+ int topH = 0xFFFFFFFF;
+ int botH = 0xFF555555;
+ int rightH = 0xFF555555;
+ int leftH = 0xFFFFFFFF;
+ if (animateInX) {
+ leftH = 0xFF555555;
+ rightH = 0xFFFFFFFF;
+ }
+ if (animateInY) {
+ topH = 0xFF555555;
+ botH = 0xFFFFFFFF;
+ }
+
+ // drawRect(left, top, left + w, top + 1, topH);
+ // drawRect(left, top, left + 1, top + h, leftH);
+ // drawRect(left + w - 1, top + 1, left + w, top + h, rightH);
+ // drawRect(left + 1, top + h - 1, left + w, top + h, botH);
+
+ left += 1;
+ top += 1;
+ w -= 2;
+ h -= 2;
+ // green background
+ // drawRect(left, top, left + w, top + h, 0xFF004C2A);
+ drawRect(left, top, left + w, top + h, 0xFF00331C);
+
+ }
+
+ void openInterface(int targetX, int targetY, int targetZ) {
+ Packet250CustomPayload pkt = PacketHandler.getPacketEnderface(targetX, targetY, targetZ);
+ PacketDispatcher.sendPacketToServer(pkt);
+ }
+
+ static class ViewableBlocks {
+ BlockCoord bc;
+ int blockId;
+
+ private ViewableBlocks(int x, int y, int z, int blockId) {
+ super();
+ this.bc = new BlockCoord(x, y, z);
+ this.blockId = blockId;
+ }
+
+ }
+
+}
diff --git a/common/crazypants/enderio/enderface/ItemEnderface.java b/common/crazypants/enderio/enderface/ItemEnderface.java
new file mode 100644
index 00000000..63c12741
--- /dev/null
+++ b/common/crazypants/enderio/enderface/ItemEnderface.java
@@ -0,0 +1,122 @@
+package crazypants.enderio.enderface;
+
+import net.minecraft.client.renderer.texture.IconRegister;
+import net.minecraft.entity.player.EntityPlayer;
+import net.minecraft.item.Item;
+import net.minecraft.item.ItemStack;
+import net.minecraft.nbt.NBTTagCompound;
+import net.minecraft.util.ChatMessageComponent;
+import net.minecraft.world.World;
+import net.minecraft.world.chunk.Chunk;
+import cpw.mods.fml.common.network.IGuiHandler;
+import cpw.mods.fml.common.registry.GameRegistry;
+import cpw.mods.fml.common.registry.LanguageRegistry;
+import crazypants.enderio.EnderIO;
+import crazypants.enderio.EnderIOTab;
+import crazypants.enderio.GuiHandler;
+import crazypants.enderio.ModObject;
+
+public class ItemEnderface extends Item implements IGuiHandler {
+
+ public static final String KEY_IO_SET = "enderFaceIoSet";
+ public static final String KEY_IO_X = "enderFaceIoX";
+ public static final String KEY_IO_Y = "enderFaceIoY";
+ public static final String KEY_IO_Z = "enderFaceIoZ";
+ public static final String KEY_DIMENSION = "enderFaceDimension";
+
+ public static ItemEnderface create() {
+ ItemEnderface result = new ItemEnderface();
+ result.init();
+ return result;
+ }
+
+ protected ItemEnderface() {
+ super(ModObject.itemEnderface.id);
+ setCreativeTab(EnderIOTab.tabEnderIO);
+ setUnlocalizedName(ModObject.itemEnderface.unlocalisedName);
+ setMaxStackSize(1);
+ }
+
+ protected void init() {
+ LanguageRegistry.addName(this, ModObject.itemEnderface.name);
+ GameRegistry.addRecipe(new ItemStack(this), " x ", "xyx", " x ", 'x', new ItemStack(Item.diamond), 'y', new ItemStack(Item.eyeOfEnder));
+ GameRegistry.registerItem(this, ModObject.itemEnderface.unlocalisedName);
+ EnderIO.guiHandler.registerGuiHandler(GuiHandler.GUI_ID_ENDERFACE, this);
+ }
+
+ @Override
+ public void registerIcons(IconRegister iconRegister) {
+ itemIcon = iconRegister.registerIcon("enderio:enderface");
+ }
+
+ @Override
+ public boolean hasEffect(ItemStack par1ItemStack, int pass) {
+ return true;
+ }
+
+ @Override
+ public void onCreated(ItemStack itemStack, World world, EntityPlayer entityPlayer) {
+ super.onCreated(itemStack, world, entityPlayer);
+ NBTTagCompound nbttagcompound = new NBTTagCompound();
+ nbttagcompound.setBoolean(KEY_IO_SET, false);
+ nbttagcompound.setInteger(KEY_IO_X, -1);
+ nbttagcompound.setInteger(KEY_IO_Y, -1);
+ nbttagcompound.setInteger(KEY_IO_Z, -1);
+ nbttagcompound.setInteger(KEY_DIMENSION, -1);
+ itemStack.setTagCompound(nbttagcompound);
+ }
+
+ @Override
+ public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
+ return null;
+ }
+
+ @Override
+ public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
+ return new GuiEnderface(player, world, x, y, z);
+ }
+
+ @Override
+ public ItemStack onItemRightClick(ItemStack itemStack, World world, final EntityPlayer entityPlayer) {
+
+ if (!world.isRemote) {
+ return itemStack;
+ }
+
+ NBTTagCompound tag = itemStack.getTagCompound();
+ boolean tagsSet = tag != null && tag.getBoolean(KEY_IO_SET);
+
+ if (tag != null && tag.getBoolean(KEY_IO_SET)) {
+
+ int x = tag.getInteger(KEY_IO_X);
+ int y = tag.getInteger(KEY_IO_Y);
+ int z = tag.getInteger(KEY_IO_Z);
+ int dimension = tag.getInteger(KEY_DIMENSION);
+
+ if(world.provider.dimensionId != dimension) {
+ ChatMessageComponent c = ChatMessageComponent.func_111066_d("EnderIO block is in a different dimension.");
+ entityPlayer.sendChatToPlayer(c);
+ return itemStack;
+ }
+
+ Chunk c = world.getChunkFromBlockCoords(x, z);
+ if(c == null || !c.isChunkLoaded) {
+ ChatMessageComponent cm = ChatMessageComponent.func_111066_d("EnderIO block's chunk is not loaded.");
+ entityPlayer.sendChatToPlayer(cm);
+ return itemStack;
+ }
+ int blockId = world.getBlockId(x, y, z);
+ if (blockId != EnderIO.blockEnderIo.blockID) {
+ ChatMessageComponent cm = ChatMessageComponent.func_111066_d("EnderIO block has been destroyed.");
+ entityPlayer.sendChatToPlayer(cm);
+ return itemStack;
+ }
+ entityPlayer.openGui(EnderIO.instance, GuiHandler.GUI_ID_ENDERFACE, world, x, y, z);
+ return itemStack;
+ }
+ ChatMessageComponent cm = ChatMessageComponent.func_111066_d(" Enderface not synchronized with EnderIO.");
+ entityPlayer.sendChatToPlayer(cm);
+ return itemStack;
+ }
+
+}
diff --git a/common/crazypants/enderio/enderface/TileEnderIO.java b/common/crazypants/enderio/enderface/TileEnderIO.java
new file mode 100644
index 00000000..68d314f0
--- /dev/null
+++ b/common/crazypants/enderio/enderface/TileEnderIO.java
@@ -0,0 +1,7 @@
+package crazypants.enderio.enderface;
+
+import net.minecraft.tileentity.TileEntity;
+
+public class TileEnderIO extends TileEntity {
+
+}
diff --git a/common/crazypants/enderio/machine/AbstractMachineBlock.java b/common/crazypants/enderio/machine/AbstractMachineBlock.java
new file mode 100644
index 00000000..79fab59e
--- /dev/null
+++ b/common/crazypants/enderio/machine/AbstractMachineBlock.java
@@ -0,0 +1,246 @@
+package crazypants.enderio.machine;
+
+import java.util.Random;
+
+import net.minecraft.block.BlockContainer;
+import net.minecraft.block.material.MapColor;
+import net.minecraft.block.material.Material;
+import net.minecraft.client.renderer.texture.IconRegister;
+import net.minecraft.entity.EntityLivingBase;
+import net.minecraft.entity.item.EntityItem;
+import net.minecraft.entity.player.EntityPlayer;
+import net.minecraft.item.ItemStack;
+import net.minecraft.nbt.NBTTagCompound;
+import net.minecraft.tileentity.TileEntity;
+import net.minecraft.util.Icon;
+import net.minecraft.util.MathHelper;
+import net.minecraft.world.IBlockAccess;
+import net.minecraft.world.World;
+import cpw.mods.fml.common.FMLCommonHandler;
+import cpw.mods.fml.common.network.IGuiHandler;
+import cpw.mods.fml.common.registry.GameRegistry;
+import cpw.mods.fml.common.registry.LanguageRegistry;
+import cpw.mods.fml.relauncher.Side;
+import cpw.mods.fml.relauncher.SideOnly;
+import crazypants.enderio.ClientProxy;
+import crazypants.enderio.EnderIO;
+import crazypants.enderio.EnderIOTab;
+import crazypants.enderio.ModObject;
+import crazypants.render.IconUtil;
+
+public abstract class AbstractMachineBlock extends BlockContainer implements IGuiHandler {
+
+ public static final Icon[] REDSTONE_CONTROL_ICONS = new Icon[RedstoneControlMode.values().length];
+
+ static {
+ IconUtil.addIconProvider(new IconUtil.IIconProvider() {
+
+ @Override
+ public void registerIcons(IconRegister iconRegister) {
+ REDSTONE_CONTROL_ICONS[RedstoneControlMode.IGNORE.ordinal()] = iconRegister.registerIcon("enderio:iconRedstoneIgnore");
+ REDSTONE_CONTROL_ICONS[RedstoneControlMode.ON.ordinal()] = iconRegister.registerIcon("enderio:iconRedstoneOn");
+ REDSTONE_CONTROL_ICONS[RedstoneControlMode.OFF.ordinal()] = iconRegister.registerIcon("enderio:iconRedstoneOff");
+ }
+
+ @Override
+ public int getTextureType() {
+ return 0;
+ }
+
+ });
+ }
+
+ @SideOnly(Side.CLIENT)
+ public static Icon getRedstoneControlIcon(RedstoneControlMode mode) {
+ return REDSTONE_CONTROL_ICONS[mode.ordinal()];
+ }
+
+ @SideOnly(Side.CLIENT)
+ protected Icon[][] iconBuffer;
+
+ protected final Random random;
+
+ protected final ModObject modObject;
+
+ protected final Class teClass;
+
+ protected AbstractMachineBlock(ModObject mo, Class teClass) {
+ super(mo.id, new Material(MapColor.ironColor));
+ modObject = mo;
+ this.teClass = teClass;
+ setHardness(2.0F);
+ setStepSound(soundMetalFootstep);
+ setUnlocalizedName(mo.unlocalisedName);
+ setCreativeTab(EnderIOTab.tabEnderIO);
+ random = new Random();
+
+ }
+
+ protected void init() {
+ LanguageRegistry.addName(this, modObject.name);
+ GameRegistry.registerBlock(this, modObject.unlocalisedName);
+ GameRegistry.registerTileEntity(teClass, modObject.unlocalisedName + "TileEntity");
+ EnderIO.guiHandler.registerGuiHandler(getGuiId(), this);
+ }
+
+ @Override
+ public TileEntity createNewTileEntity(World world) {
+ return null;
+ }
+
+ @Override
+ public TileEntity createTileEntity(World world, int metadata) {
+ try {
+ return teClass.newInstance();
+ } catch (Exception e) {
+ FMLCommonHandler.instance().raiseException(e, "Could not create tile entity from class " + teClass, true);
+ return null;
+ }
+ }
+
+ @Override
+ public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer entityPlayer, int par6, float par7, float par8, float par9) {
+ if (entityPlayer.isSneaking()) {
+ return false;
+ }
+ entityPlayer.openGui(EnderIO.instance, getGuiId(), world, x, y, z);
+ return true;
+ }
+
+ @Override
+ public void registerIcons(IconRegister iconRegister) {
+
+ iconBuffer = new Icon[1][12];
+ // first the 6 sides in OFF state
+ iconBuffer[0][0] = iconRegister.registerIcon("enderio:machineSide");
+ iconBuffer[0][1] = iconRegister.registerIcon("enderio:machineSide");
+ iconBuffer[0][2] = iconRegister.registerIcon("enderio:machineSide");
+ iconBuffer[0][3] = iconRegister.registerIcon(getMachineFrontIconKey(false));
+ iconBuffer[0][4] = iconRegister.registerIcon("enderio:machineSide");
+ iconBuffer[0][5] = iconRegister.registerIcon("enderio:machineSide");
+
+ iconBuffer[0][6] = iconRegister.registerIcon("enderio:machineSide");
+ iconBuffer[0][7] = iconRegister.registerIcon("enderio:machineSide");
+ iconBuffer[0][8] = iconRegister.registerIcon("enderio:machineSide");
+ iconBuffer[0][9] = iconRegister.registerIcon(getMachineFrontIconKey(true));
+ iconBuffer[0][10] = iconRegister.registerIcon("enderio:machineSide");
+ iconBuffer[0][11] = iconRegister.registerIcon("enderio:machineSide");
+
+ }
+
+ @Override
+ public Icon getBlockTexture(IBlockAccess world, int x, int y, int z, int blockSide) {
+ // used to render the block in the world
+ TileEntity te = world.getBlockTileEntity(x, y, z);
+ int facing = 0;
+ if (te instanceof AbstractMachineEntity) {
+ AbstractMachineEntity me = (AbstractMachineEntity) te;
+ facing = me.facing;
+ }
+ if (isActive(world, x, y, z)) {
+ return iconBuffer[0][ClientProxy.sideAndFacingToSpriteOffset[blockSide][facing] + 6];
+ } else {
+ return iconBuffer[0][ClientProxy.sideAndFacingToSpriteOffset[blockSide][facing]];
+ }
+ }
+
+ @Override
+ public Icon getIcon(int blockSide, int blockMeta) {
+ // This is used to render the block as an item
+ return iconBuffer[0][blockSide];
+ }
+
+ @Override
+ public void breakBlock(World world, int x, int y, int z, int par5, int par6) {
+ @SuppressWarnings("unchecked")
+ T te = (T) world.getBlockTileEntity(x, y, z);
+ if (te != null) {
+ dropContent(0, te, world, te.xCoord, te.yCoord, te.zCoord);
+ }
+ super.breakBlock(world, x, y, z, par5, par6);
+ }
+
+ public void dropContent(int newSize, T inventory, World world, int xCoord, int yCoord, int zCoord) {
+ for (int i = newSize; i < inventory.getSizeInventory(); i++) {
+ ItemStack itemstack = inventory.getStackInSlot(i);
+ if (itemstack == null) {
+ continue;
+ }
+ float f = random.nextFloat() * 0.8F + 0.1F;
+ float f1 = random.nextFloat() * 0.8F + 0.1F;
+ float f2 = random.nextFloat() * 0.8F + 0.1F;
+
+ EntityItem entityitem = new EntityItem(world, xCoord + f, (float) yCoord + (newSize > 0 ? 1 : 0) + f1, zCoord + f2, new ItemStack(
+ itemstack.itemID, itemstack.stackSize, itemstack.getItemDamage()));
+ float f3 = 0.05F;
+ entityitem.motionX = (float) random.nextGaussian() * f3;
+ entityitem.motionY = (float) random.nextGaussian() * f3 + 0.2F;
+ entityitem.motionZ = (float) random.nextGaussian() * f3;
+ if (itemstack.hasTagCompound()) {
+ entityitem.getEntityItem().setTagCompound((NBTTagCompound) itemstack.getTagCompound().copy());
+ }
+ world.spawnEntityInWorld(entityitem);
+ }
+ }
+
+ @Override
+ public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase player, ItemStack stack) {
+ super.onBlockPlacedBy(world, x, y, z, player, stack);
+ int heading = MathHelper.floor_double(player.rotationYaw * 4.0F / 360.0F + 0.5D) & 3;
+ AbstractMachineEntity te = (AbstractMachineEntity) world.getBlockTileEntity(x, y, z);
+ switch (heading) {
+ case 0:
+ te.setFacing((short) 2);
+ break;
+ case 1:
+ te.setFacing((short) 5);
+ break;
+ case 2:
+ te.setFacing((short) 3);
+ break;
+ case 3:
+ te.setFacing((short) 4);
+ break;
+ default:
+ break;
+ }
+ world.markBlockForUpdate(x, y, z);
+ }
+
+ @Override
+ public void onBlockAdded(World world, int x, int y, int z) {
+ super.onBlockAdded(world, x, y, z);
+ world.markBlockForUpdate(x, y, z);
+ }
+
+ @Override
+ public void onNeighborBlockChange(World world, int x, int y, int z, int blockId) {
+ AbstractMachineEntity te = (AbstractMachineEntity) world.getBlockTileEntity(x, y, z);
+ te.onNeighborBlockChange(blockId);
+ }
+
+ @Override
+ public void randomDisplayTick(World world, int x, int y, int z, Random rand) {
+ // If active, randomly throw some smoke around
+ if (isActive(world, x, y, z)) {
+ float startX = x + 1.0F;
+ float startY = y + 1.0F;
+ float startZ = z + 1.0F;
+ for (int i = 0; i < 4; i++) {
+ float xOffset = -0.2F - rand.nextFloat() * 0.6F;
+ float yOffset = -0.1F + rand.nextFloat() * 0.2F;
+ float zOffset = -0.2F - rand.nextFloat() * 0.6F;
+ world.spawnParticle("smoke", startX + xOffset, startY + yOffset, startZ + zOffset, 0.0D, 0.0D, 0.0D);
+ }
+ }
+ }
+
+ protected abstract int getGuiId();
+
+ protected abstract String getMachineFrontIconKey(boolean active);
+
+ private boolean isActive(IBlockAccess blockAccess, int x, int y, int z) {
+ return ((AbstractMachineEntity) blockAccess.getBlockTileEntity(x, y, z)).isActive();
+ }
+
+}
diff --git a/common/crazypants/enderio/machine/AbstractMachineEntity.java b/common/crazypants/enderio/machine/AbstractMachineEntity.java
new file mode 100644
index 00000000..e969c257
--- /dev/null
+++ b/common/crazypants/enderio/machine/AbstractMachineEntity.java
@@ -0,0 +1,353 @@
+package crazypants.enderio.machine;
+
+import cpw.mods.fml.relauncher.Side;
+import cpw.mods.fml.relauncher.SideOnly;
+import crazypants.enderio.PacketHandler;
+import crazypants.enderio.power.*;
+import net.minecraft.client.Minecraft;
+import net.minecraft.entity.player.EntityPlayer;
+import net.minecraft.inventory.IInventory;
+import net.minecraft.item.ItemStack;
+import net.minecraft.nbt.*;
+import net.minecraft.network.packet.Packet;
+import net.minecraft.tileentity.TileEntity;
+import net.minecraft.world.World;
+import net.minecraftforge.common.ForgeDirection;
+import buildcraft.api.power.*;
+import buildcraft.api.power.PowerHandler.PowerReceiver;
+import buildcraft.api.power.PowerHandler.Type;
+
+public abstract class AbstractMachineEntity extends TileEntity implements IInventory, IInternalPowerReceptor, IMachine {
+
+ public short facing;
+
+ // Client sync monitoring
+ protected int ticksSinceSync = -1;
+ protected boolean firstUpdate = true;
+ protected boolean lastActive;
+ protected float lastSyncPowerStored = -1;
+
+ // Power
+ protected ICapacitor capacitor;
+
+ // Used on the client as the power provided isn't sinked
+ private float storedEnergy;
+
+
+ protected ItemStack[] inventory;
+ protected final int inventorySize;
+
+ protected PowerHandler powerHandler;
+
+ protected RedstoneControlMode redstoneControlMode;
+
+ protected boolean redstoneCheckPassed;
+
+ public AbstractMachineEntity(int inventorySize, Type powerType) {
+ this.inventorySize = inventorySize;
+ facing = 3;
+ capacitor = new BasicCapacitor();
+ powerHandler = PowerHandlerUtil.createHandler(capacitor, this, powerType);
+
+ inventory = new ItemStack[inventorySize];
+
+ redstoneControlMode = RedstoneControlMode.IGNORE;
+ }
+
+ public AbstractMachineEntity(int inventorySize) {
+ this(inventorySize, Type.MACHINE);
+ }
+
+ public RedstoneControlMode getRedstoneControlMode() {
+ return redstoneControlMode;
+ }
+
+ public void setRedstoneControlMode(RedstoneControlMode redstoneControlMode) {
+ this.redstoneControlMode = redstoneControlMode;
+ }
+
+ @Override
+ public PowerHandler getPowerHandler() {
+ return powerHandler;
+ }
+
+ @Override
+ public void applyPerdition() {
+ // TODO Apply values derived capcitor
+
+ }
+
+ public short getFacing() {
+ return facing;
+ }
+
+ public void setFacing(short facing) {
+ this.facing = facing;
+ }
+
+ public abstract boolean isActive();
+
+ public abstract float getProgress();
+
+ public int getProgressScaled(int scale) {
+ int result = (int) (getProgress() * scale);
+ return result;
+ }
+
+ // --- Power
+ // --------------------------------------------------------------------------------------
+
+ public boolean hasPower() {
+ boolean hasPower = powerHandler.getEnergyStored() > 0;
+ return hasPower;
+ }
+
+ public ICapacitor getCapacitor() {
+ return capacitor;
+ }
+
+ public int getEnergyStoredScaled(int scale) {
+ // NB: called on the client so can't use the power provider
+ return (int) (scale * (storedEnergy / capacitor.getMaxEnergyStored()));
+ }
+
+ public float getEnergyStored() {
+ return storedEnergy;
+ }
+
+ // Needs NBT support for this
+ // public void setCapacitor(ICapacitor capacitor) {
+ // this.capacitor = capacitor;
+ // powerProvider.setCapacitor(capacitor);
+ // }
+
+ @Override
+ public void doWork(PowerHandler workProvider) {
+ }
+
+ @Override
+ public PowerReceiver getPowerReceiver(ForgeDirection side) {
+ return powerHandler.getPowerReceiver();
+ }
+
+ @Override
+ public World getWorld() {
+ return worldObj;
+ }
+
+ protected float getPowerUsePerTick() {
+ return capacitor.getMaxEnergyExtracted();
+ }
+
+ // --- Process Loop
+ // --------------------------------------------------------------------------
+
+ @Override
+ public void updateEntity() {
+
+ if (worldObj == null) { // sanity check
+ return;
+ }
+
+ if (worldObj.isRemote) {
+ // check if the block on the client needs to update its texture
+ if (isActive() != lastActive) {
+ worldObj.markBlockForRenderUpdate(xCoord, yCoord, zCoord);
+ }
+ lastActive = isActive();
+ return;
+
+ } // else is server, do all logic only on the server
+
+ float stored = powerHandler.getEnergyStored();
+ powerHandler.update();
+ powerHandler.setEnergy(stored);
+
+ boolean requiresClientSync = false;
+ if (firstUpdate) {
+ // First update, send state to client
+ firstUpdate = false;
+ requiresClientSync = true;
+ }
+
+ redstoneCheckPassed = true;
+ if(redstoneControlMode == RedstoneControlMode.ON) {
+ int powerLevel = worldObj.getStrongestIndirectPower(xCoord, yCoord, zCoord);
+ if(powerLevel < 1) {
+ redstoneCheckPassed = false;
+ }
+ } else if(redstoneControlMode == RedstoneControlMode.OFF) {
+ int powerLevel = worldObj.getStrongestIndirectPower(xCoord, yCoord, zCoord);
+ if(powerLevel > 0) {
+ redstoneCheckPassed = false;
+ }
+ }
+
+
+ requiresClientSync |= processTasks(redstoneCheckPassed);
+
+
+ // Update if our power has changed by more than 1%
+ requiresClientSync |= Math.abs(lastSyncPowerStored - powerHandler.getEnergyStored()) > powerHandler.getMaxEnergyStored() / 100;
+
+ if (requiresClientSync) {
+ lastSyncPowerStored = powerHandler.getEnergyStored();
+ // this will cause 'getPacketDescription()' to be called and its result
+ // will be sent to the PacketHandler on the other end of
+ // client/server connection
+ worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
+ // And this will make sure our current tile entity state is saved
+ worldObj.updateTileEntityChunkAndDoNothing(xCoord, yCoord, zCoord, this);
+ }
+
+ }
+
+ protected abstract boolean processTasks(boolean redstoneCheckPassed);
+
+
+ // ---- Tile Entity
+ // ------------------------------------------------------------------------------
+
+
+
+ @Override
+ public Packet getDescriptionPacket() {
+ return PacketHandler.getPacket(this);
+ }
+
+ @Override
+ public void readFromNBT(NBTTagCompound nbtRoot) {
+ super.readFromNBT(nbtRoot);
+
+ facing = nbtRoot.getShort("facing");
+
+ float storedEnergy = nbtRoot.getFloat("storedEnergy");
+ powerHandler.setEnergy(storedEnergy);
+ // For the client as provider is not saved to NBT
+ this.storedEnergy = storedEnergy;
+
+ // read in the inventories contents
+ inventory = new ItemStack[inventorySize];
+ NBTTagList itemList = nbtRoot.getTagList("Items");
+
+ for (int i = 0; i < itemList.tagCount(); i++) {
+ NBTTagCompound itemStack = (NBTTagCompound) itemList.tagAt(i);
+ byte slot = itemStack.getByte("Slot");
+ if (slot >= 0 && slot < inventory.length) {
+ inventory[slot] = ItemStack.loadItemStackFromNBT(itemStack);
+ }
+ }
+
+ int rsContr = nbtRoot.getInteger("redstoneControlMode");
+ if(rsContr < 0 || rsContr >= RedstoneControlMode.values().length) {
+ rsContr = 0;
+ }
+ redstoneControlMode = RedstoneControlMode.values()[rsContr];
+
+ }
+
+ @Override
+ public void writeToNBT(NBTTagCompound nbtRoot) {
+ super.writeToNBT(nbtRoot);
+ nbtRoot.setShort("facing", facing);
+ nbtRoot.setFloat("storedEnergy", powerHandler.getEnergyStored());
+
+ // write inventory list
+ NBTTagList itemList = new NBTTagList();
+ for (int i = 0; i < inventory.length; i++) {
+ if (inventory[i] != null) {
+ NBTTagCompound itemStackNBT = new NBTTagCompound();
+ itemStackNBT.setByte("Slot", (byte) i);
+ inventory[i].writeToNBT(itemStackNBT);
+ itemList.appendTag(itemStackNBT);
+ }
+ }
+ nbtRoot.setTag("Items", itemList);
+
+ nbtRoot.setInteger("redstoneControlMode", redstoneControlMode.ordinal());
+ }
+
+ // ---- Inventory
+ // ------------------------------------------------------------------------------
+
+ @Override
+ public boolean isInvNameLocalized() {
+ return false;
+ }
+
+ @Override
+ public boolean isUseableByPlayer(EntityPlayer player) {
+ if (worldObj == null) {
+ return true;
+ }
+ if (worldObj.getBlockTileEntity(xCoord, yCoord, zCoord) != this) {
+ return false;
+ }
+ return player.getDistanceSq(xCoord + 0.5D, yCoord + 0.5D, zCoord + 0.5D) <= 64D;
+ }
+
+ @Override
+ public int getSizeInventory() {
+ return inventorySize;
+ }
+
+ @Override
+ public int getInventoryStackLimit() {
+ return 64;
+ }
+
+ @Override
+ public ItemStack getStackInSlot(int slot) {
+ return inventory[slot];
+ }
+
+ @Override
+ public ItemStack decrStackSize(int fromSlot, int amount) {
+ ItemStack fromStack = inventory[fromSlot];
+ if (fromStack == null) {
+ return null;
+ }
+ if (fromStack.stackSize <= amount) {
+ inventory[fromSlot] = null;
+ return fromStack;
+ }
+ ItemStack result = new ItemStack(fromStack.itemID, amount, fromStack.getItemDamage());
+ if (fromStack.stackTagCompound != null) {
+ result.stackTagCompound = (NBTTagCompound) fromStack.stackTagCompound.copy();
+ }
+ fromStack.stackSize -= amount;
+ return result;
+ }
+
+ @Override
+ public void setInventorySlotContents(int slot, ItemStack contents) {
+ if (contents == null) {
+ inventory[slot] = contents;
+ } else {
+ inventory[slot] = contents.copy();
+ }
+
+ if (contents != null && contents.stackSize > getInventoryStackLimit()) {
+ contents.stackSize = getInventoryStackLimit();
+ }
+ }
+
+ @Override
+ public ItemStack getStackInSlotOnClosing(int i) {
+ return null;
+ }
+
+ @Override
+ public void openChest() {
+ }
+
+ @Override
+ public void closeChest() {
+ }
+
+ public void onNeighborBlockChange(int blockId) {
+ }
+
+
+
+}
diff --git a/common/crazypants/enderio/machine/AbstractPoweredTaskEntity.java b/common/crazypants/enderio/machine/AbstractPoweredTaskEntity.java
new file mode 100644
index 00000000..2158b289
--- /dev/null
+++ b/common/crazypants/enderio/machine/AbstractPoweredTaskEntity.java
@@ -0,0 +1,189 @@
+package crazypants.enderio.machine;
+
+import net.minecraft.inventory.ISidedInventory;
+import net.minecraft.item.ItemStack;
+import net.minecraft.nbt.NBTTagCompound;
+
+public abstract class AbstractPoweredTaskEntity extends AbstractMachineEntity implements ISidedInventory {
+
+ protected PoweredTask currentTask = null;
+
+ public AbstractPoweredTaskEntity(int inventorySize) {
+ super(inventorySize);
+ }
+
+ @Override
+ public int[] getAccessibleSlotsFromSide(int var1) {
+ int[] res = new int[inventory.length];
+ for(int i=0;i maxInputIndex) {
+ return false;
+ }
+ if (!isItemValidForSlot(i, itemstack)) {
+ return false;
+ }
+ if (inventory[i] == null) {
+ return true;
+ }
+ if (inventory[i].stackSize + itemstack.stackSize > inventory[i].getMaxStackSize()) {
+ return false;
+ }
+ return inventory[i].isItemEqual(itemstack);
+ }
+
+ @Override
+ public boolean canExtractItem(int i, ItemStack itemstack, int j) {
+ int outputIndex = inventory.length - 1;
+ if (outputIndex != 2) {
+ return false;
+ }
+ if (inventory[outputIndex] == null || inventory[outputIndex].stackSize < itemstack.stackSize) {
+ return false;
+ }
+ return itemstack.itemID == inventory[outputIndex].itemID;
+ }
+
+ @Override
+ public boolean isActive() {
+ return currentTask == null ? false : currentTask.getProgress() > 0 && hasPower() && redstoneCheckPassed;
+ }
+
+ @Override
+ public float getProgress() {
+ return currentTask == null ? 0 : currentTask.getProgress();
+ }
+
+ @Override
+ protected boolean processTasks(boolean redstoneChecksPassed) {
+
+ if(!redstoneChecksPassed) {
+ return false;
+ }
+
+ boolean requiresClientSync = false;
+ // Process any current items
+ requiresClientSync |= checkProgress();
+
+ // Then see if we need to start a new one
+ IMachineRecipe nextRecipe = canStartNextTask();
+ if (nextRecipe != null) {
+ requiresClientSync |= startNextTask(nextRecipe);
+ }
+ return requiresClientSync;
+ }
+
+ protected boolean checkProgress() {
+ if (currentTask == null || !hasPower()) {
+ return false;
+ }
+ float used = powerHandler.useEnergy(0, getPowerUsePerTick(), true);
+ currentTask.update(used);
+ // then check if we are done
+ if (currentTask.isComplete()) {
+ taskComplete();
+ }
+ return true;
+ }
+
+ protected void taskComplete() {
+ int outputIndex = inventory.length - 1;
+ if (currentTask != null) {
+ ItemStack result = currentTask.getCompletedResult()[0];
+ if (inventory[outputIndex] == null) {
+ inventory[outputIndex] = result.copy();
+ } else {
+ int newStackSize = inventory[outputIndex].stackSize += result.stackSize;
+ inventory[outputIndex] = result.copy();
+ inventory[outputIndex].stackSize = newStackSize;
+ }
+ }
+ currentTask = null;
+ }
+
+ protected RecipeInput[] getInputs() {
+ RecipeInput[] res = new RecipeInput[inventorySize - 1];
+ for(int i=0;i < res.length;i++) {
+ res[i] = new RecipeInput(i, inventory[i]);
+ }
+ return res;
+ }
+
+ protected IMachineRecipe canStartNextTask() {
+ if (currentTask != null) {
+ return null; // already cooking something
+ }
+ if (!hasPower()) {
+ return null; // no heat to cook
+ }
+
+ IMachineRecipe nextRecipe = MachineRecipeRegistry.instance.getRecipeForInputs(getMachineName(), getInputs());
+ if (nextRecipe == null) {
+ return null; // no template
+ }
+
+ int outputIndex = inventory.length - 1;
+ // make sure we can merge the recipe output with our result
+ if (inventory[outputIndex] == null) {
+ return nextRecipe;
+ }
+ ItemStack nextResult = nextRecipe.getCompletedResult(getInputs())[0];
+ if (inventory[outputIndex].stackSize + nextResult.stackSize > inventory[outputIndex].getMaxStackSize()) {
+ return null; // no room for output
+ }
+
+ if(!canMergeWithCurrentOuput(nextResult)) {
+ return null;
+ }
+
+ return nextRecipe;
+ }
+
+ protected boolean canMergeWithCurrentOuput(ItemStack nextResult) {
+ if (!nextResult.isItemEqual(inventory[inventory.length - 1])) {
+ // next result is a different item type
+ return false;
+ }
+ return true;
+ }
+
+ protected boolean startNextTask(IMachineRecipe nextRecipe) {
+ if (hasPower() && nextRecipe.isRecipe(getInputs())) {
+ // then get our recipe and take away the source items
+ currentTask = new PoweredTask(nextRecipe, getInputs());
+ for(RecipeInput input : getInputs()) {
+ int consumed = nextRecipe.getQuantityConsumed(input);
+ decrStackSize(input.slotNumber, consumed);
+ }
+ return true;
+ }
+ return false;
+ }
+
+
+ @Override
+ public void readFromNBT(NBTTagCompound nbtRoot) {
+ super.readFromNBT(nbtRoot);
+ currentTask = PoweredTask.readFromNBT(nbtRoot.getCompoundTag("currentTask"));
+ }
+
+ @Override
+ public void writeToNBT(NBTTagCompound nbtRoot) {
+ super.writeToNBT(nbtRoot);
+ if (currentTask != null) {
+ NBTTagCompound currentTaskNBT = new NBTTagCompound();
+ currentTask.writeToNBT(currentTaskNBT);
+ nbtRoot.setCompoundTag("currentTask", currentTaskNBT);
+ }
+ }
+
+
+
+}
diff --git a/common/crazypants/enderio/machine/BlockElectricLight.java b/common/crazypants/enderio/machine/BlockElectricLight.java
new file mode 100644
index 00000000..79f75c15
--- /dev/null
+++ b/common/crazypants/enderio/machine/BlockElectricLight.java
@@ -0,0 +1,95 @@
+package crazypants.enderio.machine;
+
+import net.minecraft.block.Block;
+import net.minecraft.block.material.Material;
+import net.minecraft.client.renderer.texture.IconRegister;
+import net.minecraft.util.Icon;
+import net.minecraft.world.*;
+import net.minecraftforge.common.ForgeDirection;
+import cpw.mods.fml.common.registry.*;
+import cpw.mods.fml.relauncher.*;
+import crazypants.enderio.ModObject;
+
+public class BlockElectricLight extends Block {
+
+
+ public static BlockElectricLight create() {
+ BlockElectricLight result = new BlockElectricLight();
+ result.init();
+ return result;
+ }
+
+ public BlockElectricLight() {
+ super(ModObject.blockElectricLight.id, Material.rock);
+ setHardness(2.0F);
+ setStepSound(soundGlassFootstep);
+ setUnlocalizedName(ModObject.blockElectricLight.unlocalisedName);
+ //setCreativeTab(EnderIOTab.tabEnderIO);
+ setLightOpacity(0);
+ setLightValue(1);
+ }
+
+
+ private void init() {
+ LanguageRegistry.addName(this, ModObject.blockElectricLight.name);
+ GameRegistry.registerBlock(this, ModObject.blockElectricLight.unlocalisedName);
+ //GameRegistry.addRecipe(new ItemStack(this), "zxz", "xyx", "zxz", 'x', new ItemStack(Item.eyeOfEnder), 'y', new ItemStack(Block.enderChest),'z', new ItemStack(Item.diamond));
+ }
+
+ @Override
+ public void registerIcons(IconRegister iconRegister) {
+ blockIcon = iconRegister.registerIcon("enderio:blockElectricLightFace");
+ }
+
+ @Override
+ public boolean renderAsNormalBlock() {
+ return false;
+ }
+
+ @Override
+ @SideOnly(Side.CLIENT)
+ public Icon getBlockTexture(IBlockAccess par1iBlockAccess, int par2, int par3, int par4, int par5) {
+ // TODO Auto-generated method stub
+ return super.getBlockTexture(par1iBlockAccess, par2, par3, par4, par5);
+ }
+
+ @Override
+ @SideOnly(Side.CLIENT)
+ public Icon getIcon(int par1, int par2) {
+ // TODO Auto-generated method stub
+ return super.getIcon(par1, par2);
+ }
+
+ @Override
+ public boolean isOpaqueCube() {
+ return false;
+ }
+
+ @Override
+ public void onNeighborBlockChange(World par1World, int par2, int par3, int par4, int par5) {
+ super.onNeighborBlockChange(par1World, par2, par3, par4, par5);
+ }
+
+ @Override
+ public boolean canPlaceBlockOnSide(World par1World, int x, int y, int z, int side) {
+ ForgeDirection dir = ForgeDirection.getOrientation(side);
+ ForgeDirection op = dir.getOpposite();
+ return par1World.isBlockSolidOnSide(x + op.offsetX, y + op.offsetY, z + op.offsetZ, dir);
+// ForgeDirection dir = ForgeDirection.getOrientation(side);
+// return (dir == DOWN && par1World.isBlockSolidOnSide(x, y + 1, z, DOWN )) ||
+// (dir == UP && par1World.isBlockSolidOnSide(x, y - 1, z, UP )) ||
+// (dir == NORTH && par1World.isBlockSolidOnSide(x, y, z + 1, NORTH)) ||
+// (dir == SOUTH && par1World.isBlockSolidOnSide(x, y, z - 1, SOUTH)) ||
+// (dir == WEST && par1World.isBlockSolidOnSide(x + 1, y, z, WEST )) ||
+// (dir == EAST && par1World.isBlockSolidOnSide(x - 1, y, z, EAST ));
+ }
+
+
+ @Override
+ public boolean canPlaceTorchOnTop(World world, int x, int y, int z) {
+ return false;
+ }
+
+
+
+}
diff --git a/common/crazypants/enderio/machine/GuiMachineBase.java b/common/crazypants/enderio/machine/GuiMachineBase.java
new file mode 100644
index 00000000..18b7c9bf
--- /dev/null
+++ b/common/crazypants/enderio/machine/GuiMachineBase.java
@@ -0,0 +1,129 @@
+package crazypants.enderio.machine;
+
+import java.awt.Rectangle;
+import java.util.Iterator;
+
+import org.lwjgl.opengl.GL11;
+
+import cpw.mods.fml.common.network.PacketDispatcher;
+import crazypants.enderio.PacketHandler;
+import crazypants.enderio.machine.painter.PainterContainer;
+import crazypants.render.GuiContainerBase;
+import crazypants.render.GuiToolTip;
+import crazypants.render.IconButton;
+import crazypants.render.ItemButton;
+import crazypants.render.RenderUtil;
+
+import net.minecraft.block.Block;
+import net.minecraft.client.gui.GuiButton;
+import net.minecraft.entity.player.InventoryPlayer;
+import net.minecraft.inventory.Container;
+import net.minecraft.item.Item;
+import net.minecraft.network.packet.Packet;
+
+public abstract class GuiMachineBase extends GuiContainerBase {
+
+
+ protected static final int POWER_Y = 13;
+ protected final int POWER_X = 15;
+ protected static final int POWER_WIDTH = 11;
+ protected static final int POWER_HEIGHT = 53;
+ protected static final int BOTTOM_POWER_Y = POWER_Y + POWER_HEIGHT;
+
+ protected static final int BUTTON_SIZE = 16;
+ protected static final int REDSTONE_BUTTON_ID = 99;
+
+
+ private AbstractMachineEntity tileEntity;
+
+ private IconButton redstoneButton;
+
+ public GuiMachineBase(AbstractMachineEntity machine, Container container) {
+ super(container);
+ tileEntity = machine;
+ addToolTip(new GuiToolTip(new Rectangle(POWER_X, POWER_Y, POWER_WIDTH, POWER_HEIGHT),"") {
+
+ @Override
+ protected void updateText() {
+ text.clear();
+ text.add(Math.round(tileEntity.getEnergyStored()) + "/" + tileEntity.getCapacitor().getMaxEnergyStored() + " MJ");
+ }
+
+ });
+ addToolTip(new GuiToolTip(new Rectangle(0, 0, 0, 0),"") {
+
+ @Override
+ protected void updateText() {
+ text.clear();
+ switch(tileEntity.getRedstoneControlMode()) {
+ case ON:
+ text.add("Active when");
+ text.add("recieving a");
+ text.add("redstone signal.");
+ break;
+ case OFF:
+ text.add("Active when not");
+ text.add("recieving a");
+ text.add("redstone signal.");
+ break;
+ case IGNORE:
+ default:
+ text.add("Allways active.");
+ }
+
+ }
+
+ @Override
+ public void onTick(int mouseX, int mouseY) {
+ bounds.setBounds(xSize - 5 - BUTTON_SIZE, 5, BUTTON_SIZE, BUTTON_SIZE);
+ super.onTick(mouseX, mouseY);
+ }
+
+ });
+
+ }
+
+ @Override
+ protected void actionPerformed(GuiButton par1GuiButton) {
+ if(par1GuiButton.id == REDSTONE_BUTTON_ID) {
+ int ordinal = tileEntity.getRedstoneControlMode().ordinal();
+ ordinal++;
+ if(ordinal >= RedstoneControlMode.values().length) {
+ ordinal = 0;
+ }
+ tileEntity.setRedstoneControlMode(RedstoneControlMode.values()[ordinal]);
+ redstoneButton.setIcon(AbstractMachineBlock.getRedstoneControlIcon(tileEntity.getRedstoneControlMode()));
+ Packet pkt = PacketHandler.getRedstoneControlPacket(tileEntity);
+ PacketDispatcher.sendPacketToServer(pkt);
+ }
+ }
+
+ @Override
+ public void initGui() {
+ super.initGui();
+ int x = guiLeft + xSize - 5 - BUTTON_SIZE;
+ int y = guiTop + 5;
+
+ redstoneButton = new IconButton(fontRenderer, REDSTONE_BUTTON_ID, x, y, AbstractMachineBlock.getRedstoneControlIcon(tileEntity.getRedstoneControlMode()), RenderUtil.BLOCK_TEX);
+ redstoneButton.setSize(BUTTON_SIZE, BUTTON_SIZE);
+
+ buttonList.add(redstoneButton);
+ }
+
+
+
+ protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3) {
+ GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
+ int k = (width - xSize) / 2;
+ int l = (height - ySize) / 2;
+ int i1 = tileEntity.getEnergyStoredScaled(POWER_HEIGHT);
+ drawTexturedModalRect(k + POWER_X, l + BOTTOM_POWER_Y - i1, 176, 31, 11, i1);
+
+ for (int i = 0; i < buttonList.size(); ++i) {
+ GuiButton guibutton = (GuiButton)this.buttonList.get(i);
+ guibutton.drawButton(this.mc, 0, 0);
+ }
+
+ }
+
+}
diff --git a/common/crazypants/enderio/machine/IMachine.java b/common/crazypants/enderio/machine/IMachine.java
new file mode 100644
index 00000000..7be23d52
--- /dev/null
+++ b/common/crazypants/enderio/machine/IMachine.java
@@ -0,0 +1,8 @@
+package crazypants.enderio.machine;
+
+public interface IMachine {
+
+
+ String getMachineName();
+
+}
diff --git a/common/crazypants/enderio/machine/IMachineRecipe.java b/common/crazypants/enderio/machine/IMachineRecipe.java
new file mode 100644
index 00000000..fbc7a90a
--- /dev/null
+++ b/common/crazypants/enderio/machine/IMachineRecipe.java
@@ -0,0 +1,21 @@
+package crazypants.enderio.machine;
+
+import net.minecraft.item.ItemStack;
+
+public interface IMachineRecipe {
+
+ String getUid();
+
+ float getEnergyRequired(RecipeInput... inputs);
+
+ public boolean isRecipe(RecipeInput... inputs);
+
+ ItemStack[] getCompletedResult(RecipeInput... inputs);
+
+ boolean isValidInput(int slotNumber, ItemStack item);
+
+ String getMachineName();
+
+ int getQuantityConsumed(RecipeInput input);
+
+}
diff --git a/common/crazypants/enderio/machine/MachineRecipeRegistry.java b/common/crazypants/enderio/machine/MachineRecipeRegistry.java
new file mode 100644
index 00000000..f463521f
--- /dev/null
+++ b/common/crazypants/enderio/machine/MachineRecipeRegistry.java
@@ -0,0 +1,62 @@
+package crazypants.enderio.machine;
+
+import java.util.*;
+
+public class MachineRecipeRegistry {
+
+ public static final MachineRecipeRegistry instance = new MachineRecipeRegistry();
+
+ private final Map> machineRecipes = new HashMap>();
+
+ public void registerRecipe(String machine, IMachineRecipe recipe) {
+ getRecipesForMachine(machine).put(recipe.getUid(), recipe);
+ }
+
+ public Map getRecipesForMachine(String machineName) {
+ Map res = machineRecipes.get(machineName);
+ if(res == null) {
+ res = new HashMap();
+ machineRecipes.put(machineName, res);
+ }
+ return res;
+ }
+
+ public IMachineRecipe getRecipeForUid(String uid) {
+ for(Map recipes : machineRecipes.values()) {
+ for(IMachineRecipe recipe : recipes.values()) {
+ if(uid.equals(recipe.getUid())) {
+ return recipe;
+ }
+ }
+ }
+ return null;
+ }
+
+ public IMachineRecipe getRecipeForInputs(String machineName, RecipeInput... inputs) {
+ Map recipes = getRecipesForMachine(machineName);
+ if(recipes == null) {
+ return null;
+ }
+ for(IMachineRecipe recipe : recipes.values()) {
+ if(recipe.isRecipe(inputs)) {
+ return recipe;
+ }
+ }
+ return null;
+ }
+
+ public List getRecipesForInput(String machineName, RecipeInput input) {
+ if(input == null) {
+ return Collections.emptyList();
+ }
+ List