diff --git a/bin/minecraft/textures/PlatinumCable.png b/bin/minecraft/textures/PlatinumCable.png new file mode 100644 index 000000000..f6691059f Binary files /dev/null and b/bin/minecraft/textures/PlatinumCable.png differ diff --git a/bin/minecraft/textures/items.png b/bin/minecraft/textures/items.png index 04e9bc49d..999cfb6d5 100644 Binary files a/bin/minecraft/textures/items.png and b/bin/minecraft/textures/items.png differ diff --git a/src/common/ic2/api/IEnergyStorage.java b/src/common/ic2/api/IEnergyStorage.java index a89bd7dcd..f67b7afb0 100644 --- a/src/common/ic2/api/IEnergyStorage.java +++ b/src/common/ic2/api/IEnergyStorage.java @@ -23,5 +23,5 @@ public interface IEnergyStorage { * * @return Energy output in EU/t */ - public int getOutput(); + public int getRate(); } diff --git a/src/common/net/uberkat/obsidian/common/ContainerAdvancedElectricMachine.java b/src/common/net/uberkat/obsidian/common/ContainerAdvancedElectricMachine.java index 8d6a4750f..12083c2e1 100644 --- a/src/common/net/uberkat/obsidian/common/ContainerAdvancedElectricMachine.java +++ b/src/common/net/uberkat/obsidian/common/ContainerAdvancedElectricMachine.java @@ -165,7 +165,7 @@ public class ContainerAdvancedElectricMachine extends Container return null; } - currentSlot.onPickupFromSlot(slotStack); + currentSlot.putStack(slotStack); } return stack; diff --git a/src/common/net/uberkat/obsidian/common/ContainerElectricMachine.java b/src/common/net/uberkat/obsidian/common/ContainerElectricMachine.java index ad125dbd9..d4add4114 100644 --- a/src/common/net/uberkat/obsidian/common/ContainerElectricMachine.java +++ b/src/common/net/uberkat/obsidian/common/ContainerElectricMachine.java @@ -122,7 +122,7 @@ public class ContainerElectricMachine extends Container return null; } - currentSlot.onPickupFromSlot(slotStack); + currentSlot.putStack(slotStack); } return stack; diff --git a/src/common/net/uberkat/obsidian/common/ContainerPowerUnit.java b/src/common/net/uberkat/obsidian/common/ContainerPowerUnit.java index 5faadd971..71844d6f2 100644 --- a/src/common/net/uberkat/obsidian/common/ContainerPowerUnit.java +++ b/src/common/net/uberkat/obsidian/common/ContainerPowerUnit.java @@ -91,7 +91,7 @@ public class ContainerPowerUnit extends Container return null; } - currentSlot.onPickupFromSlot(slotStack); + currentSlot.putStack(slotStack); } return stack; diff --git a/src/common/net/uberkat/obsidian/common/EntityObsidianTNT.java b/src/common/net/uberkat/obsidian/common/EntityObsidianTNT.java index e8cc183ac..38d980bb8 100644 --- a/src/common/net/uberkat/obsidian/common/EntityObsidianTNT.java +++ b/src/common/net/uberkat/obsidian/common/EntityObsidianTNT.java @@ -97,7 +97,7 @@ public class EntityObsidianTNT extends Entity private void explode() { - worldObj.createExplosion((Entity)null, posX, posY, posZ, ObsidianIngots.ObsidianTNTBlastRadius); + worldObj.createExplosion((Entity)null, posX, posY, posZ, ObsidianIngots.ObsidianTNTBlastRadius, true); hasExploded = true; } diff --git a/src/common/net/uberkat/obsidian/common/ItemEnergized.java b/src/common/net/uberkat/obsidian/common/ItemEnergized.java index 028194135..d76b9e49f 100644 --- a/src/common/net/uberkat/obsidian/common/ItemEnergized.java +++ b/src/common/net/uberkat/obsidian/common/ItemEnergized.java @@ -4,7 +4,7 @@ import java.util.List; import obsidian.api.IEnergizedItem; -import universalelectricity.UniversalElectricity; +import universalelectricity.core.UniversalElectricity; import universalelectricity.electricity.ElectricInfo; import universalelectricity.implement.IItemElectric; @@ -28,7 +28,7 @@ public class ItemEnergized extends ItemObsidian implements IEnergizedItem, IItem setCreativeTab(CreativeTabs.tabRedstone); } - public void addInformation(ItemStack itemstack, List list) + public void addInformation(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag) { int energy = getEnergy(itemstack); diff --git a/src/common/net/uberkat/obsidian/common/ItemMachineUpgrade.java b/src/common/net/uberkat/obsidian/common/ItemMachineUpgrade.java index 4068a8c7b..c0fd22d38 100644 --- a/src/common/net/uberkat/obsidian/common/ItemMachineUpgrade.java +++ b/src/common/net/uberkat/obsidian/common/ItemMachineUpgrade.java @@ -2,6 +2,7 @@ package net.uberkat.obsidian.common; import java.util.List; +import net.minecraft.src.CreativeTabs; import net.minecraft.src.ItemStack; import obsidian.api.IMachineUpgrade; @@ -11,5 +12,6 @@ public class ItemMachineUpgrade extends ItemObsidian implements IMachineUpgrade { super(i); setMaxStackSize(1); + setCreativeTab(CreativeTabs.tabRedstone); } } diff --git a/src/common/net/uberkat/obsidian/common/ItemObsidianBow.java b/src/common/net/uberkat/obsidian/common/ItemObsidianBow.java index 2e868f0e2..f32d541a8 100644 --- a/src/common/net/uberkat/obsidian/common/ItemObsidianBow.java +++ b/src/common/net/uberkat/obsidian/common/ItemObsidianBow.java @@ -65,7 +65,7 @@ public class ItemObsidianBow extends ItemObsidian if (f == 1.0F) { - entityarrow.func_70243_d(true); + entityarrow.setIsCritical(true); } int j = EnchantmentHelper.getEnchantmentLevel(Enchantment.power.effectId, itemstack); diff --git a/src/common/net/uberkat/obsidian/common/ItemObsidianHoe.java b/src/common/net/uberkat/obsidian/common/ItemObsidianHoe.java index d90509a79..eff9e1739 100644 --- a/src/common/net/uberkat/obsidian/common/ItemObsidianHoe.java +++ b/src/common/net/uberkat/obsidian/common/ItemObsidianHoe.java @@ -16,9 +16,9 @@ public class ItemObsidianHoe extends ItemObsidian * Callback for item usage. If the item does something special on right clicking, he will have one of those. Return * True if something happen and false if it don't. This is for ITEMS, not BLOCKS ! */ - public boolean onItemUse(ItemStack par1ItemStack, EntityPlayer par2EntityPlayer, World par3World, int par4, int par5, int par6, int par7) + public boolean onItemUse(ItemStack par1ItemStack, EntityPlayer par2EntityPlayer, World par3World, int par4, int par5, int par6, int par7, float par8, float par9, float par10) { - if (!par2EntityPlayer.canPlayerEdit(par4, par5, par6)) + if (!par2EntityPlayer.func_82247_a(par4, par5, par6, par7, par1ItemStack)) { return false; } diff --git a/src/common/net/uberkat/obsidian/common/ObsidianIngots.java b/src/common/net/uberkat/obsidian/common/ObsidianIngots.java index f6f07f6b2..dbc0e0306 100644 --- a/src/common/net/uberkat/obsidian/common/ObsidianIngots.java +++ b/src/common/net/uberkat/obsidian/common/ObsidianIngots.java @@ -503,6 +503,15 @@ public class ObsidianIngots GameRegistry.addRecipe(new ItemStack(MachineBlock, 1, 3), new Object[] { "***", "*L*", "***", Character.valueOf('*'), PlatinumIngot, Character.valueOf('L'), Item.bucketLava }); + GameRegistry.addRecipe(new ItemStack(SpeedUpgrade), new Object[] { + "PAP", "ARA", "PAP", Character.valueOf('P'), PlatinumDust, Character.valueOf('A'), EnrichedAlloy, Character.valueOf('E'), Item.emerald + }); + GameRegistry.addRecipe(new ItemStack(EnergyUpgrade), new Object[] { + "RAR", "AEA", "RAR", Character.valueOf('R'), Item.redstone, Character.valueOf('A'), EnrichedAlloy, Character.valueOf('E'), Item.emerald + }); + GameRegistry.addRecipe(new ItemStack(UltimateUpgrade), new Object[] { + "ERA", "RDR", "ARS", Character.valueOf('E'), EnergyUpgrade, Character.valueOf('R'), Item.redstone, Character.valueOf('A'), EnrichedAlloy, Character.valueOf('D'), Item.diamond, Character.valueOf('S'), SpeedUpgrade + }); if(extrasEnabled) { diff --git a/src/common/net/uberkat/obsidian/common/PacketHandler.java b/src/common/net/uberkat/obsidian/common/PacketHandler.java index f5f9ff880..b61e2d82c 100644 --- a/src/common/net/uberkat/obsidian/common/PacketHandler.java +++ b/src/common/net/uberkat/obsidian/common/PacketHandler.java @@ -13,7 +13,7 @@ import com.google.common.io.ByteStreams; import net.minecraft.src.EntityPlayer; import net.minecraft.src.ModLoader; -import net.minecraft.src.NetworkManager; +import net.minecraft.src.INetworkManager; import net.minecraft.src.Packet; import net.minecraft.src.Packet250CustomPayload; import net.minecraft.src.TileEntity; @@ -32,7 +32,7 @@ import cpw.mods.fml.server.FMLServerHandler; */ public class PacketHandler implements IPacketHandler { - public void onPacketData(NetworkManager manager, Packet250CustomPayload packet, Player player) + public void onPacketData(INetworkManager manager, Packet250CustomPayload packet, Player player) { ByteArrayDataInput dataStream = ByteStreams.newDataInput(packet.data); EntityPlayer entityplayer = (EntityPlayer)player; diff --git a/src/common/net/uberkat/obsidian/common/TileEntityAdvancedElectricMachine.java b/src/common/net/uberkat/obsidian/common/TileEntityAdvancedElectricMachine.java index b96858c89..c367b9d98 100644 --- a/src/common/net/uberkat/obsidian/common/TileEntityAdvancedElectricMachine.java +++ b/src/common/net/uberkat/obsidian/common/TileEntityAdvancedElectricMachine.java @@ -7,7 +7,7 @@ import java.util.List; import obsidian.api.IEnergizedItem; -import universalelectricity.UniversalElectricity; +import universalelectricity.core.UniversalElectricity; import universalelectricity.electricity.ElectricInfo; import universalelectricity.implement.IItemElectric; @@ -93,7 +93,7 @@ public abstract class TileEntityAdvancedElectricMachine extends TileEntityBasicM } else if(inventory[3].getItem() instanceof IItemElectric) { - IItemElectric electricItem = (IItemElectric) inventory[3].getItem(); + IItemElectric electricItem = (IItemElectric)inventory[3].getItem(); if (electricItem.canProduceElectricity()) { @@ -327,7 +327,7 @@ public abstract class TileEntityAdvancedElectricMachine extends TileEntityBasicM PacketHandler.sendAdvancedElectricMachinePacketWithRange(this, 50); } - public void handlePacketData(NetworkManager network, Packet250CustomPayload packet, EntityPlayer player, ByteArrayDataInput dataStream) + public void handlePacketData(INetworkManager network, Packet250CustomPayload packet, EntityPlayer player, ByteArrayDataInput dataStream) { try { facing = dataStream.readInt(); @@ -421,7 +421,7 @@ public abstract class TileEntityAdvancedElectricMachine extends TileEntityBasicM public String[] getMethodNames() { - return new String[] {"getStored", "getSecondaryStored", "getProgress", "isActive", "facing", "canOperate"}; + return new String[] {"getStored", "getSecondaryStored", "getProgress", "isActive", "facing", "canOperate", "getMaxEnergy", "getEnergyNeeded"}; } public Object[] callMethod(IComputerAccess computer, int method, Object[] arguments) throws Exception @@ -440,9 +440,13 @@ public abstract class TileEntityAdvancedElectricMachine extends TileEntityBasicM return new Object[] {facing}; case 5: return new Object[] {canOperate()}; + case 6: + return new Object[] {currentMaxEnergy}; + case 7: + return new Object[] {(currentMaxEnergy-energyStored)}; default: System.err.println("[ObsidianIngots] Attempted to call unknown method with computer ID " + computer.getID()); - return null; + return new Object[] {"Unknown command."}; } } } diff --git a/src/common/net/uberkat/obsidian/common/TileEntityBasicMachine.java b/src/common/net/uberkat/obsidian/common/TileEntityBasicMachine.java index 65d879892..28efb28b0 100644 --- a/src/common/net/uberkat/obsidian/common/TileEntityBasicMachine.java +++ b/src/common/net/uberkat/obsidian/common/TileEntityBasicMachine.java @@ -1,7 +1,7 @@ package net.uberkat.obsidian.common; import obsidian.api.IElectricMachine; -import universalelectricity.UniversalElectricity; +import universalelectricity.core.UniversalElectricity; import universalelectricity.electricity.ElectricInfo; import universalelectricity.electricity.ElectricityManager; import universalelectricity.prefab.TileEntityDisableable; @@ -92,10 +92,6 @@ public abstract class TileEntityBasicMachine extends TileEntityDisableable imple */ public TileEntityBasicMachine(String soundPath, String name, String path, int perTick, int ticksRequired, int maxEnergy) { - if(ObsidianIngots.hooks.UELoaded) - { - ElectricityManager.instance.registerElectricUnit(this); - } ENERGY_PER_TICK = perTick; TICKS_REQUIRED = currentTicksRequired = ticksRequired; MAX_ENERGY = currentMaxEnergy = maxEnergy; @@ -445,5 +441,26 @@ public abstract class TileEntityBasicMachine extends TileEntityDisableable imple par2ItemStack.stackSize = getInventoryStackLimit(); } } - + + public int transferToAcceptor(int amount) + { + int rejects = 0; + int neededEnergy = currentMaxEnergy-energyStored; + if(amount <= neededEnergy) + { + energyStored += amount; + } + else if(amount > neededEnergy) + { + energyStored += neededEnergy; + rejects = amount-neededEnergy; + } + + return rejects; + } + + public boolean canReceive(ForgeDirection side) + { + return true; + } } diff --git a/src/common/net/uberkat/obsidian/common/TileEntityElectricMachine.java b/src/common/net/uberkat/obsidian/common/TileEntityElectricMachine.java index 1671d1d46..d82fb3e4e 100644 --- a/src/common/net/uberkat/obsidian/common/TileEntityElectricMachine.java +++ b/src/common/net/uberkat/obsidian/common/TileEntityElectricMachine.java @@ -7,7 +7,7 @@ import java.util.List; import obsidian.api.IEnergizedItem; -import universalelectricity.UniversalElectricity; +import universalelectricity.core.UniversalElectricity; import universalelectricity.electricity.ElectricInfo; import universalelectricity.implement.IItemElectric; @@ -266,7 +266,7 @@ public abstract class TileEntityElectricMachine extends TileEntityBasicMachine PacketHandler.sendElectricMachinePacketWithRange(this, 50); } - public void handlePacketData(NetworkManager network, Packet250CustomPayload packet, EntityPlayer player, ByteArrayDataInput dataStream) + public void handlePacketData(INetworkManager network, Packet250CustomPayload packet, EntityPlayer player, ByteArrayDataInput dataStream) { try { facing = dataStream.readInt(); @@ -343,7 +343,7 @@ public abstract class TileEntityElectricMachine extends TileEntityBasicMachine public String[] getMethodNames() { - return new String[] {"getStored", "getProgress", "isActive", "facing", "canOperate"}; + return new String[] {"getStored", "getProgress", "isActive", "facing", "canOperate", "getMaxEnergy", "getEnergyNeeded"}; } public Object[] callMethod(IComputerAccess computer, int method, Object[] arguments) throws Exception @@ -360,9 +360,13 @@ public abstract class TileEntityElectricMachine extends TileEntityBasicMachine return new Object[] {facing}; case 4: return new Object[] {canOperate()}; + case 5: + return new Object[] {currentMaxEnergy}; + case 6: + return new Object[] {(currentMaxEnergy-energyStored)}; default: System.err.println("[ObsidianIngots] Attempted to call unknown method with computer ID " + computer.getID()); - return null; + return new Object[] {"Unknown command."}; } } } diff --git a/src/common/net/uberkat/obsidian/common/TileEntityPowerUnit.java b/src/common/net/uberkat/obsidian/common/TileEntityPowerUnit.java index c2edb32e0..4a3f7a9eb 100644 --- a/src/common/net/uberkat/obsidian/common/TileEntityPowerUnit.java +++ b/src/common/net/uberkat/obsidian/common/TileEntityPowerUnit.java @@ -6,20 +6,18 @@ import java.io.IOException; import obsidian.api.IEnergizedItem; import obsidian.api.ITileNetwork; +import obsidian.api.IEnergyAcceptor; -import universalelectricity.UniversalElectricity; +import universalelectricity.core.UniversalElectricity; +import universalelectricity.core.Vector3; import universalelectricity.electricity.ElectricInfo; import universalelectricity.electricity.ElectricityManager; import universalelectricity.implement.IConductor; import universalelectricity.implement.IElectricityReceiver; import universalelectricity.implement.IItemElectric; import universalelectricity.implement.IJouleStorage; -import universalelectricity.network.ConnectionHandler; -import universalelectricity.network.ConnectionHandler.ConnectionType; -import universalelectricity.network.ISimpleConnectionHandler; import universalelectricity.prefab.TileEntityConductor; import universalelectricity.prefab.TileEntityDisableable; -import universalelectricity.prefab.Vector3; import buildcraft.api.power.IPowerProvider; import buildcraft.api.power.IPowerReceptor; @@ -44,7 +42,7 @@ import net.minecraft.src.*; import net.minecraftforge.common.ForgeDirection; import net.minecraftforge.common.ISidedInventory; -public class TileEntityPowerUnit extends TileEntityDisableable implements IInventory, ISidedInventory, ITileNetwork, IWrenchable, IEnergySink, IEnergySource, IEnergyStorage, IPowerReceptor, IJouleStorage, IElectricityReceiver, IPeripheral +public class TileEntityPowerUnit extends TileEntityDisableable implements IInventory, ISidedInventory, ITileNetwork, IWrenchable, IEnergySink, IEnergySource, IEnergyStorage, IPowerReceptor, IJouleStorage, IElectricityReceiver, IEnergyAcceptor, IPeripheral { /** The inventory slot itemstacks used by this power unit. */ public ItemStack[] inventory = new ItemStack[2]; @@ -85,10 +83,6 @@ public class TileEntityPowerUnit extends TileEntityDisableable implements IInven */ public TileEntityPowerUnit(int energy, int i) { - if(ObsidianIngots.hooks.UELoaded) - { - ElectricityManager.instance.registerElectricUnit(this); - } maxEnergy = energy; output = i; if(PowerFramework.currentFramework != null) @@ -199,26 +193,45 @@ public class TileEntityPowerUnit extends TileEntityDisableable implements IInven } } - if(isPowerReceptor(tileEntity)) + if(tileEntity != null) { - IPowerReceptor receptor = (IPowerReceptor)tileEntity; - int energyNeeded = Math.min(receptor.getPowerProvider().getMinEnergyReceived(), receptor.getPowerProvider().getMaxEnergyReceived())*10; - float transferEnergy = Math.max(Math.min(Math.min(energyNeeded, energyStored), 54000), 0); - receptor.getPowerProvider().receiveEnergy((float)(transferEnergy/10), Orientations.dirs()[ForgeDirection.getOrientation(facing).getOpposite().ordinal()]); - setEnergy(energyStored - (int)transferEnergy); - } - - TileEntity connector = Vector3.getConnectorFromSide(worldObj, Vector3.get(this), ForgeDirection.getOrientation(facing)); - - if(connector != null && connector instanceof TileEntityConductor) - { - double joulesNeeded = ElectricityManager.instance.getElectricityRequired(((IConductor) connector).getConnectionID()); - double transferAmps = Math.max(Math.min(Math.min(ElectricInfo.getAmps(joulesNeeded, getVoltage()), ElectricInfo.getAmps(energyStored*UniversalElectricity.IC2_RATIO, getVoltage())), 80), 0); - if (!worldObj.isRemote) + if(isPowerReceptor(tileEntity)) { - ElectricityManager.instance.produceElectricity(this, (IConductor) connector, transferAmps, getVoltage()); + IPowerReceptor receptor = (IPowerReceptor)tileEntity; + int energyNeeded = Math.min(receptor.getPowerProvider().getMinEnergyReceived(), receptor.getPowerProvider().getMaxEnergyReceived())*10; + float transferEnergy = Math.max(Math.min(Math.min(energyNeeded, energyStored), 54000), 0); + receptor.getPowerProvider().receiveEnergy((float)(transferEnergy/10), Orientations.dirs()[ForgeDirection.getOrientation(facing).getOpposite().ordinal()]); + setEnergy(energyStored - (int)transferEnergy); + } + else if(tileEntity instanceof TileEntityConductor) + { + double joulesNeeded = ElectricityManager.instance.getElectricityRequired(((IConductor) tileEntity).getNetwork()); + double transferAmps = Math.max(Math.min(Math.min(ElectricInfo.getAmps(joulesNeeded, getVoltage()), ElectricInfo.getAmps(energyStored*UniversalElectricity.IC2_RATIO, getVoltage())), 80), 0); + if (!worldObj.isRemote) + { + ElectricityManager.instance.produceElectricity(this, (IConductor)tileEntity, transferAmps, getVoltage()); + } + setEnergy(energyStored - (int)(ElectricInfo.getJoules(transferAmps, getVoltage())*UniversalElectricity.TO_IC2_RATIO)); + } + else if(tileEntity instanceof IEnergyAcceptor) + { + if(((IEnergyAcceptor)tileEntity).canReceive(ForgeDirection.getOrientation(facing).getOpposite())) + { + int sendingEnergy = 0; + if(energyStored >= output) + { + sendingEnergy = output; + } + else if(energyStored < output) + { + sendingEnergy = energyStored; + } + + int rejects = ((IEnergyAcceptor)tileEntity).transferToAcceptor(output); + + setEnergy(energyStored - (sendingEnergy - rejects)); + } } - setEnergy(energyStored - (int)(ElectricInfo.getJoules(transferAmps, getVoltage())*UniversalElectricity.TO_IC2_RATIO)); } } @@ -375,7 +388,7 @@ public class TileEntityPowerUnit extends TileEntityDisableable implements IInven nbtTags.setTag("Items", tagList); } - public void handlePacketData(NetworkManager network, Packet250CustomPayload packet, EntityPlayer player, ByteArrayDataInput dataStream) + public void handlePacketData(INetworkManager network, Packet250CustomPayload packet, EntityPlayer player, ByteArrayDataInput dataStream) { try { facing = dataStream.readInt(); @@ -448,7 +461,7 @@ public class TileEntityPowerUnit extends TileEntityDisableable implements IInven return maxEnergy; } - public int getOutput() + public int getRate() { return output; } @@ -570,7 +583,7 @@ public class TileEntityPowerUnit extends TileEntityDisableable implements IInven public String[] getMethodNames() { - return new String[] {"getStored", "getOutput"}; + return new String[] {"getStored", "getOutput", "getMaxEnergy", "getEnergyNeeded"}; } public Object[] callMethod(IComputerAccess computer, int method, Object[] arguments) throws Exception @@ -581,6 +594,10 @@ public class TileEntityPowerUnit extends TileEntityDisableable implements IInven return new Object[] {energyStored}; case 1: return new Object[] {output}; + case 2: + return new Object[] {maxEnergy}; + case 3: + return new Object[] {(maxEnergy-energyStored)}; default: System.err.println("[ObsidianIngots] Attempted to call unknown method with computer ID " + computer.getID()); return null; @@ -595,4 +612,26 @@ public class TileEntityPowerUnit extends TileEntityDisableable implements IInven public void attach(IComputerAccess computer, String computerSide) {} public void detach(IComputerAccess computer) {} + + public int transferToAcceptor(int amount) + { + int rejects = 0; + int neededEnergy = maxEnergy-energyStored; + if(amount <= neededEnergy) + { + energyStored += amount; + } + else if(amount > neededEnergy) + { + energyStored += neededEnergy; + rejects = amount-neededEnergy; + } + + return rejects; + } + + public boolean canReceive(ForgeDirection side) + { + return side != ForgeDirection.getOrientation(facing); + } } diff --git a/src/common/obsidian/api/IElectricMachine.java b/src/common/obsidian/api/IElectricMachine.java index 5a11e2495..9c02d10a7 100644 --- a/src/common/obsidian/api/IElectricMachine.java +++ b/src/common/obsidian/api/IElectricMachine.java @@ -19,7 +19,7 @@ import net.minecraftforge.common.ISidedInventory; * @author AidanBrady * */ -public interface IElectricMachine extends IInventory, ISidedInventory, IWrenchable, ITileNetwork, IPowerReceptor, IEnergySink, IJouleStorage, IElectricityReceiver, IPeripheral +public interface IElectricMachine extends IInventory, ISidedInventory, IWrenchable, ITileNetwork, IPowerReceptor, IEnergySink, IJouleStorage, IElectricityReceiver, IEnergyAcceptor, IPeripheral { /** * Update call for machines. Use instead of updateEntity() - it's called every tick. diff --git a/src/common/obsidian/api/IEnergyAcceptor.java b/src/common/obsidian/api/IEnergyAcceptor.java new file mode 100644 index 000000000..744a0ff61 --- /dev/null +++ b/src/common/obsidian/api/IEnergyAcceptor.java @@ -0,0 +1,10 @@ +package obsidian.api; + +import net.minecraftforge.common.ForgeDirection; + +public interface IEnergyAcceptor +{ + public int transferToAcceptor(int amount); + + public boolean canReceive(ForgeDirection side); +} diff --git a/src/common/obsidian/api/ITileNetwork.java b/src/common/obsidian/api/ITileNetwork.java index b58ccfeb3..c3fe09009 100644 --- a/src/common/obsidian/api/ITileNetwork.java +++ b/src/common/obsidian/api/ITileNetwork.java @@ -1,7 +1,7 @@ package obsidian.api; import net.minecraft.src.EntityPlayer; -import net.minecraft.src.NetworkManager; +import net.minecraft.src.INetworkManager; import net.minecraft.src.Packet250CustomPayload; import com.google.common.io.ByteArrayDataInput; @@ -20,5 +20,5 @@ public interface ITileNetwork * @param player * @param dataStream */ - public void handlePacketData(NetworkManager network, Packet250CustomPayload packet, EntityPlayer player, ByteArrayDataInput dataStream); + public void handlePacketData(INetworkManager network, Packet250CustomPayload packet, EntityPlayer player, ByteArrayDataInput dataStream); } diff --git a/src/common/railcraft/common/api/carts/CartBase.java b/src/common/railcraft/common/api/carts/CartBase.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/carts/CartTools.java b/src/common/railcraft/common/api/carts/CartTools.java old mode 100644 new mode 100755 index 4fa0e650d..c889872dd --- a/src/common/railcraft/common/api/carts/CartTools.java +++ b/src/common/railcraft/common/api/carts/CartTools.java @@ -17,6 +17,7 @@ public abstract class CartTools { public static ILinkageManager serverLinkageManager; + /** * Registers a subclass of EntityMinecart with the game engine. * @@ -29,8 +30,7 @@ public abstract class CartTools * @param tag The String identifier * @param internalId The mods internal entity id */ - public static void registerMinecart(Object mod, Class type, String tag, int internalId) - { + public static void registerMinecart(Object mod, Class type, String tag, int internalId) { EntityRegistry.registerModEntity(type, tag, internalId, mod, 80, 3, true); } @@ -42,8 +42,7 @@ public abstract class CartTools * @param world The World, may be required in the future * @return an instance of ILinkageManager */ - public static ILinkageManager getLinkageManager(World world) - { + public static ILinkageManager getLinkageManager(World world) { return serverLinkageManager; } @@ -54,8 +53,7 @@ public abstract class CartTools * * @param owner */ - public static void setCartOwner(EntityMinecart cart, EntityPlayer owner) - { + public static void setCartOwner(EntityMinecart cart, EntityPlayer owner) { cart.getEntityData().setString("owner", owner.username); } @@ -66,8 +64,7 @@ public abstract class CartTools * * @param owner */ - public static void setCartOwner(EntityMinecart cart, String owner) - { + public static void setCartOwner(EntityMinecart cart, String owner) { cart.getEntityData().setString("owner", owner); } @@ -78,8 +75,7 @@ public abstract class CartTools * * @param owner */ - public static String getCartOwner(EntityMinecart cart) - { + public static String getCartOwner(EntityMinecart cart) { return cart.getEntityData().getString("owner"); } @@ -91,8 +87,7 @@ public abstract class CartTools * @return true if the item matches the cart * @see IMinecart */ - public static boolean doesCartMatchFilter(ItemStack stack, EntityMinecart cart) - { + public static boolean doesCartMatchFilter(ItemStack stack, EntityMinecart cart) { if(stack == null) { return false; } @@ -100,7 +95,26 @@ public abstract class CartTools return ((IMinecart)cart).doesCartMatchFilter(stack, cart); } ItemStack cartItem = cart.getCartItem(); - return cartItem != null && stack.isItemEqual(cartItem); + return cartItem != null && isItemEqual(stack, cartItem); + } + + private static boolean isItemEqual(ItemStack a, ItemStack b) { + if(a == null || b == null) { + return false; + } + if(a.itemID != b.itemID) { + return false; + } + if(a.stackTagCompound != null && !a.stackTagCompound.equals(b.stackTagCompound)) { + return false; + } + if(a.getHasSubtypes() && (a.getItemDamage() == -1 || b.getItemDamage() == -1)) { + return true; + } + if(a.getHasSubtypes() && a.getItemDamage() != b.getItemDamage()) { + return false; + } + return true; } /** @@ -120,8 +134,7 @@ public abstract class CartTools * @return the cart placed or null if failed * @see IMinecartItem, ItemMinecart */ - public static EntityMinecart placeCart(String owner, ItemStack cart, World world, int i, int j, int k) - { + public static EntityMinecart placeCart(String owner, ItemStack cart, World world, int i, int j, int k) { if(cart == null) { return null; } @@ -131,7 +144,7 @@ public abstract class CartTools return mi.placeCart(owner, cart, world, i, j, k); } else if(cart.getItem() instanceof ItemMinecart) { try { - boolean placed = cart.getItem().onItemUseFirst(cart, null, world, i, j, k, 0, 0, 0, 0); + boolean placed = cart.getItem().onItemUse(cart, null, world, i, j, k, 0, 0, 0, 0); if(placed) { List carts = getMinecartsAt(world, i, j, k, 0.3f); if(carts.size() > 0) { @@ -152,8 +165,7 @@ public abstract class CartTools * @param cart * @param stack */ - public static void offerOrDropItem(EntityMinecart cart, ItemStack stack) - { + public static void offerOrDropItem(EntityMinecart cart, ItemStack stack) { EntityMinecart link_A = getLinkageManager(cart.worldObj).getLinkedCartA(cart); EntityMinecart link_B = getLinkageManager(cart.worldObj).getLinkedCartB(cart); @@ -169,26 +181,22 @@ public abstract class CartTools } } - public static boolean isMinecartOnRailAt(World world, int i, int j, int k, float sensitivity) - { + public static boolean isMinecartOnRailAt(World world, int i, int j, int k, float sensitivity) { return isMinecartOnRailAt(world, i, j, k, sensitivity, null, true); } - public static boolean isMinecartOnRailAt(World world, int i, int j, int k, float sensitivity, Class type, boolean subclass) - { + public static boolean isMinecartOnRailAt(World world, int i, int j, int k, float sensitivity, Class type, boolean subclass) { if(BlockRail.isRailBlockAt(world, i, j, k)) { return isMinecartAt(world, i, j, k, sensitivity, type, subclass); } return false; } - public static boolean isMinecartOnAnySide(World world, int i, int j, int k, float sensitivity) - { + public static boolean isMinecartOnAnySide(World world, int i, int j, int k, float sensitivity) { return isMinecartOnAnySide(world, i, j, k, sensitivity, null, true); } - public static boolean isMinecartOnAnySide(World world, int i, int j, int k, float sensitivity, Class type, boolean subclass) - { + public static boolean isMinecartOnAnySide(World world, int i, int j, int k, float sensitivity, Class type, boolean subclass) { List list = new ArrayList(); for(int side = 0; side < 6; side++) { list.addAll(getMinecartsOnSide(world, i, j, k, sensitivity, ForgeDirection.getOrientation(side))); @@ -206,13 +214,11 @@ public abstract class CartTools return false; } - public static boolean isMinecartAt(World world, int i, int j, int k, float sensitivity) - { + public static boolean isMinecartAt(World world, int i, int j, int k, float sensitivity) { return isMinecartAt(world, i, j, k, sensitivity, null, true); } - public static boolean isMinecartAt(World world, int i, int j, int k, float sensitivity, Class type, boolean subclass) - { + public static boolean isMinecartAt(World world, int i, int j, int k, float sensitivity, Class type, boolean subclass) { List list = getMinecartsAt(world, i, j, k, sensitivity); if(type == null) { @@ -227,8 +233,7 @@ public abstract class CartTools return false; } - public static List getMinecartsOnAllSides(World world, int i, int j, int k, float sensitivity) - { + public static List getMinecartsOnAllSides(World world, int i, int j, int k, float sensitivity) { List carts = new ArrayList(); for(int side = 0; side < 6; side++) { carts.addAll(getMinecartsOnSide(world, i, j, k, sensitivity, ForgeDirection.getOrientation(side))); @@ -237,8 +242,7 @@ public abstract class CartTools return carts; } - public static List getMinecartsOnAllSides(World world, int i, int j, int k, float sensitivity, Class type, boolean subclass) - { + public static List getMinecartsOnAllSides(World world, int i, int j, int k, float sensitivity, Class type, boolean subclass) { List list = new ArrayList(); List carts = new ArrayList(); for(int side = 0; side < 6; side++) { @@ -253,8 +257,7 @@ public abstract class CartTools return carts; } - private static int getYOnSide(int y, ForgeDirection side) - { + private static int getYOnSide(int y, ForgeDirection side) { switch (side) { case UP: return y + 1; @@ -265,8 +268,7 @@ public abstract class CartTools } } - private static int getXOnSide(int x, ForgeDirection side) - { + private static int getXOnSide(int x, ForgeDirection side) { switch (side) { case EAST: return x + 1; @@ -277,8 +279,7 @@ public abstract class CartTools } } - private static int getZOnSide(int z, ForgeDirection side) - { + private static int getZOnSide(int z, ForgeDirection side) { switch (side) { case NORTH: return z - 1; @@ -289,31 +290,26 @@ public abstract class CartTools } } - public static List getMinecartsOnSide(World world, int i, int j, int k, float sensitivity, ForgeDirection side) - { + public static List getMinecartsOnSide(World world, int i, int j, int k, float sensitivity, ForgeDirection side) { return getMinecartsAt(world, getXOnSide(i, side), getYOnSide(j, side), getZOnSide(k, side), sensitivity); } - public static boolean isMinecartOnSide(World world, int i, int j, int k, float sensitivity, ForgeDirection side) - { + public static boolean isMinecartOnSide(World world, int i, int j, int k, float sensitivity, ForgeDirection side) { return getMinecartOnSide(world, i, j, k, sensitivity, side) != null; } - public static EntityMinecart getMinecartOnSide(World world, int i, int j, int k, float sensitivity, ForgeDirection side) - { + public static EntityMinecart getMinecartOnSide(World world, int i, int j, int k, float sensitivity, ForgeDirection side) { for(EntityMinecart cart : getMinecartsOnSide(world, i, j, k, sensitivity, side)) { return cart; } return null; } - public static boolean isMinecartOnSide(World world, int i, int j, int k, float sensitivity, ForgeDirection side, Class type, boolean subclass) - { + public static boolean isMinecartOnSide(World world, int i, int j, int k, float sensitivity, ForgeDirection side, Class type, boolean subclass) { return getMinecartOnSide(world, i, j, k, sensitivity, side, type, subclass) != null; } - public static EntityMinecart getMinecartOnSide(World world, int i, int j, int k, float sensitivity, ForgeDirection side, Class type, boolean subclass) - { + public static EntityMinecart getMinecartOnSide(World world, int i, int j, int k, float sensitivity, ForgeDirection side, Class type, boolean subclass) { for(EntityMinecart cart : getMinecartsOnSide(world, i, j, k, sensitivity, side)) { if(type == null || (subclass && type.isInstance(cart)) || cart.getClass() == type) { return cart; @@ -331,8 +327,7 @@ public abstract class CartTools * @param sensitivity Controls the size of the search box, ranges from (-inf, 0.49]. * @return */ - public static List getMinecartsAt(World world, int i, int j, int k, float sensitivity) - { + public static List getMinecartsAt(World world, int i, int j, int k, float sensitivity) { sensitivity = Math.min(sensitivity, 0.49f); List entities = world.getEntitiesWithinAABB(net.minecraft.src.EntityMinecart.class, AxisAlignedBB.getAABBPool().addOrModifyAABBInPool(i + sensitivity, j + sensitivity, k + sensitivity, i + 1 - sensitivity, j + 1 - sensitivity, k + 1 - sensitivity)); List carts = new ArrayList(); @@ -342,8 +337,7 @@ public abstract class CartTools return carts; } - public static List getMinecartsIn(World world, int i1, int j1, int k1, int i2, int j2, int k2) - { + public static List getMinecartsIn(World world, int i1, int j1, int k1, int i2, int j2, int k2) { List entities = world.getEntitiesWithinAABB(net.minecraft.src.EntityMinecart.class, AxisAlignedBB.getAABBPool().addOrModifyAABBInPool(i1, j1, k1, i2, j2, k2)); List carts = new ArrayList(); for(Object o : entities) { @@ -360,13 +354,11 @@ public abstract class CartTools * @param cart * @return speed */ - public static double getCartSpeedUncapped(EntityMinecart cart) - { + public static double getCartSpeedUncapped(EntityMinecart cart) { return Math.sqrt(cart.motionX * cart.motionX + cart.motionZ * cart.motionZ); } - public static boolean cartVelocityIsLessThan(EntityMinecart cart, float vel) - { + public static boolean cartVelocityIsLessThan(EntityMinecart cart, float vel) { return Math.abs(cart.motionX) < vel && Math.abs(cart.motionZ) < vel; } } diff --git a/src/common/railcraft/common/api/carts/ICartRenderInterface.java b/src/common/railcraft/common/api/carts/ICartRenderInterface.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/carts/IEnergyTransfer.java b/src/common/railcraft/common/api/carts/IEnergyTransfer.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/carts/IExplosiveCart.java b/src/common/railcraft/common/api/carts/IExplosiveCart.java new file mode 100755 index 000000000..c9f860222 --- /dev/null +++ b/src/common/railcraft/common/api/carts/IExplosiveCart.java @@ -0,0 +1,56 @@ +package railcraft.common.api.carts; + +public interface IExplosiveCart +{ + + /** + * If set to true the cart should explode after + * whatever fuse duration is set. + * + * @param primed + */ + public void setPrimed(boolean primed); + + /** + * Returns whether the cart is primed to explode. + * + * @return primed + */ + public boolean isPrimed(); + + /** + * Returns the length of the current fuse. + * + * @return fuse length in ticks + */ + public int getFuse(); + + /** + * Optional function to allow setting the fuse duration. + * + * Used by the Priming Track. + * + * @param fuse in ticks + */ + public void setFuse(int fuse); + + /** + * Returns the blast radius, but I don't think anything currently uses this. + * + * @return blast radius + */ + public float getBlastRadius(); + + /** + * Optional function to allow setting the blast radius. + * + * @param radius + */ + public void setBlastRadius(float radius); + + /** + * Causes the cart to explode immediately. + * + */ + public void explode(); +} diff --git a/src/common/railcraft/common/api/carts/IItemTransfer.java b/src/common/railcraft/common/api/carts/IItemTransfer.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/carts/ILinkableCart.java b/src/common/railcraft/common/api/carts/ILinkableCart.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/carts/ILinkageManager.java b/src/common/railcraft/common/api/carts/ILinkageManager.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/carts/ILiquidTransfer.java b/src/common/railcraft/common/api/carts/ILiquidTransfer.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/carts/IMinecart.java b/src/common/railcraft/common/api/carts/IMinecart.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/carts/TransferCartBase.java b/src/common/railcraft/common/api/carts/TransferCartBase.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/carts/bore/IBoreHead.java b/src/common/railcraft/common/api/carts/bore/IBoreHead.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/carts/bore/IMineable.java b/src/common/railcraft/common/api/carts/bore/IMineable.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/core/INetworkedObject.java b/src/common/railcraft/common/api/core/INetworkedObject.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/core/IPostConnection.java b/src/common/railcraft/common/api/core/IPostConnection.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/core/WorldCoordinate.java b/src/common/railcraft/common/api/core/WorldCoordinate.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/core/items/BallastRegistry.java b/src/common/railcraft/common/api/core/items/BallastRegistry.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/core/items/EnumItemType.java b/src/common/railcraft/common/api/core/items/EnumItemType.java old mode 100644 new mode 100755 index 850ff8230..00a7a2aca --- a/src/common/railcraft/common/api/core/items/EnumItemType.java +++ b/src/common/railcraft/common/api/core/items/EnumItemType.java @@ -31,7 +31,7 @@ public enum EnumItemType } switch (this) { case FUEL: - return TileEntityFurnace.getItemBurnTime(stack) > 0; + return TileEntityFurnace.isItemFuel(stack); case RAIL: return stack.getItem() instanceof ITrackItem || (stack.getItem() instanceof ItemBlock && BlockRail.isRailBlock(stack.itemID)); case MINECART: diff --git a/src/common/railcraft/common/api/core/items/ICrowbar.java b/src/common/railcraft/common/api/core/items/ICrowbar.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/core/items/IMinecartItem.java b/src/common/railcraft/common/api/core/items/IMinecartItem.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/core/items/ITrackItem.java b/src/common/railcraft/common/api/core/items/ITrackItem.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/core/items/ItemRegistry.java b/src/common/railcraft/common/api/core/items/ItemRegistry.java old mode 100644 new mode 100755 index 3760fad30..20303394e --- a/src/common/railcraft/common/api/core/items/ItemRegistry.java +++ b/src/common/railcraft/common/api/core/items/ItemRegistry.java @@ -62,6 +62,7 @@ public final class ItemRegistry */ public static void registerItem(String tag, ItemStack item) { + tag = tag.replace("rc.", ""); registry.put(tag, item); } diff --git a/src/common/railcraft/common/api/crafting/IBlastFurnaceCraftingManager.java b/src/common/railcraft/common/api/crafting/IBlastFurnaceCraftingManager.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/crafting/IBlastFurnaceRecipe.java b/src/common/railcraft/common/api/crafting/IBlastFurnaceRecipe.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/crafting/ICokeOvenCraftingManager.java b/src/common/railcraft/common/api/crafting/ICokeOvenCraftingManager.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/crafting/ICokeOvenRecipe.java b/src/common/railcraft/common/api/crafting/ICokeOvenRecipe.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/crafting/IRockCrusherCraftingManager.java b/src/common/railcraft/common/api/crafting/IRockCrusherCraftingManager.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/crafting/IRockCrusherRecipe.java b/src/common/railcraft/common/api/crafting/IRockCrusherRecipe.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/crafting/IRollingMachineCraftingManager.java b/src/common/railcraft/common/api/crafting/IRollingMachineCraftingManager.java old mode 100644 new mode 100755 index 6b9ee7f66..e9275efb5 --- a/src/common/railcraft/common/api/crafting/IRollingMachineCraftingManager.java +++ b/src/common/railcraft/common/api/crafting/IRollingMachineCraftingManager.java @@ -4,6 +4,7 @@ import java.util.List; import net.minecraft.src.IRecipe; import net.minecraft.src.InventoryCrafting; import net.minecraft.src.ItemStack; +import net.minecraft.src.World; /** * @@ -16,7 +17,7 @@ public interface IRollingMachineCraftingManager void addShapelessRecipe(ItemStack output, Object[] compenents); - ItemStack findMatchingRecipe(InventoryCrafting inventorycrafting); + ItemStack findMatchingRecipe(InventoryCrafting inventorycrafting, World world); List getRecipeList(); diff --git a/src/common/railcraft/common/api/crafting/RailcraftCraftingManager.java b/src/common/railcraft/common/api/crafting/RailcraftCraftingManager.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/signals/EnumSignalAspect.java b/src/common/railcraft/common/api/signals/EnumSignalAspect.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/signals/IBlockSignal.java b/src/common/railcraft/common/api/signals/IBlockSignal.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/signals/ISignalController.java b/src/common/railcraft/common/api/signals/ISignalController.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/signals/ISignalReceiver.java b/src/common/railcraft/common/api/signals/ISignalReceiver.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/signals/SignalTools.java b/src/common/railcraft/common/api/signals/SignalTools.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/tracks/ITrackCustomPlaced.java b/src/common/railcraft/common/api/tracks/ITrackCustomPlaced.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/tracks/ITrackCustomShape.java b/src/common/railcraft/common/api/tracks/ITrackCustomShape.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/tracks/ITrackEmitter.java b/src/common/railcraft/common/api/tracks/ITrackEmitter.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/tracks/ITrackInstance.java b/src/common/railcraft/common/api/tracks/ITrackInstance.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/tracks/ITrackLockdown.java b/src/common/railcraft/common/api/tracks/ITrackLockdown.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/tracks/ITrackPowered.java b/src/common/railcraft/common/api/tracks/ITrackPowered.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/tracks/ITrackReversable.java b/src/common/railcraft/common/api/tracks/ITrackReversable.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/tracks/ITrackSwitch.java b/src/common/railcraft/common/api/tracks/ITrackSwitch.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/tracks/ITrackTile.java b/src/common/railcraft/common/api/tracks/ITrackTile.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/tracks/RailTools.java b/src/common/railcraft/common/api/tracks/RailTools.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/tracks/TrackInstanceBase.java b/src/common/railcraft/common/api/tracks/TrackInstanceBase.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/tracks/TrackRegistry.java b/src/common/railcraft/common/api/tracks/TrackRegistry.java old mode 100644 new mode 100755 diff --git a/src/common/railcraft/common/api/tracks/TrackSpec.java b/src/common/railcraft/common/api/tracks/TrackSpec.java old mode 100644 new mode 100755 diff --git a/src/common/universalelectricity/BasicComponents.java b/src/common/universalelectricity/BasicComponents.java deleted file mode 100644 index 0d1a32c5e..000000000 --- a/src/common/universalelectricity/BasicComponents.java +++ /dev/null @@ -1,61 +0,0 @@ -package universalelectricity; - -import net.minecraft.src.Block; -import net.minecraft.src.Item; -import net.minecraft.src.ItemStack; -import universalelectricity.ore.OreGenBase; -import universalelectricity.prefab.ItemElectric; - -/** - * The main class for managing Basic Component items and blocks. Reference objects from this class to add them to your - * recipes and such. - * @author Calclavia - */ - -public class BasicComponents -{ - public static final String FILE_PATH = "/basiccomponents/textures/"; - public static final String BLOCK_TEXTURE_FILE = FILE_PATH + "blocks.png"; - public static final String ITEM_TEXTURE_FILE = FILE_PATH + "items.png"; - - /** - * Try not reference to these variable in pre-initialization as they might be null! - */ - public static int BLOCK_ID_PREFIX = 3970; - - //Metadata ore block that contains copper - public static Block blockBasicOre; - public static Block blockCopperWire; - public static Block oilMoving; - public static Block oilStill; - public static Block blockMachine; - public static Block blockMulti; - - public static final int ITEM_ID_PREFIX = 13970; - public static ItemElectric itemBattery; - public static Item itemWrench; - public static Item itemCopperIngot; - public static Item itemTinIngot; - public static Item itemSteelIngot; - public static Item itemSteelDust; - public static Item itemCircuit; - public static Item itemBronzeIngot; - public static Item itemBronzeDust; - public static Item itemSteelPlate; - public static Item itemBronzePlate; - public static Item itemMotor; - public static Item itemOilBucket; - public static Item itemCopperPlate; - public static Item itemTinPlate; - - /** - * Some neat references to help you out. - */ - public static ItemStack coalGenerator; - public static ItemStack batteryBox; - public static ItemStack electricFurnace; - - - public static OreGenBase copperOreGeneration; - public static OreGenBase tinOreGeneration; -} diff --git a/src/common/universalelectricity/UEConfig.java b/src/common/universalelectricity/UEConfig.java deleted file mode 100644 index 3d57a2a1a..000000000 --- a/src/common/universalelectricity/UEConfig.java +++ /dev/null @@ -1,56 +0,0 @@ -package universalelectricity; - -import net.minecraftforge.common.Configuration; - -public class UEConfig -{ - public static int getConfigData(Configuration configuration, String name, int defaultInt) - { - configuration.load(); - int returnInt = defaultInt; - returnInt = Integer.parseInt(configuration.get(name, Configuration.CATEGORY_GENERAL, defaultInt).value); - configuration.save(); - return returnInt; - } - - public static boolean getConfigData(Configuration configuration, String name, boolean defaultBoolean) - { - configuration.load(); - boolean returnBoolean = defaultBoolean; - returnBoolean = Boolean.parseBoolean(configuration.get(name, Configuration.CATEGORY_GENERAL, defaultBoolean).value); - configuration.save(); - return returnBoolean; - } - - public static int getBlockConfigID(Configuration configuration, String name, int defaultID) - { - configuration.load(); - int id = defaultID; - - id = Integer.parseInt(configuration.getBlock(name, defaultID).value); - - if (id <= 136) - { - return defaultID; - } - - configuration.save(); - return id; - } - - public static int getItemConfigID(Configuration configuration, String name, int defaultID) - { - configuration.load(); - int id = defaultID; - - id = Integer.parseInt(configuration.getItem(name, Configuration.CATEGORY_ITEM, defaultID).value); - - if (id < 256) - { - return defaultID; - } - - configuration.save(); - return id; - } -} diff --git a/src/common/universalelectricity/UniversalElectricity.java b/src/common/universalelectricity/UniversalElectricity.java deleted file mode 100644 index 240aef12c..000000000 --- a/src/common/universalelectricity/UniversalElectricity.java +++ /dev/null @@ -1,90 +0,0 @@ -package universalelectricity; - -import java.io.File; - -import net.minecraft.src.MapColor; -import net.minecraft.src.Material; -import net.minecraftforge.common.Configuration; -import net.minecraftforge.common.ForgeVersion; -import cpw.mods.fml.common.Loader; - -public class UniversalElectricity -{ - public static final int MAJOR_VERSION = 0; - public static final int MINOR_VERSION = 9; - public static final int REVISION_VERSION = 3; - - public static final String VERSION = MAJOR_VERSION+"."+MINOR_VERSION+"."+REVISION_VERSION; - - public static final Configuration CONFIGURATION = new Configuration(new File(Loader.instance().getConfigDir(), "UniversalElectricity/UniversalElectricity.cfg")); - - //EU to Watts ratio - public static final float IC2_RATIO = (float)UEConfig.getConfigData(CONFIGURATION, "IndustrialCraft Conversion Ratio", 7); - - //MJ to Watts ratio. - public static final float BC3_RATIO = (float)UEConfig.getConfigData(CONFIGURATION, "BuildCraft Conversion Ratio", 85);; - - public static final float TO_IC2_RATIO = 1/IC2_RATIO; - - public static final float TO_BC_RATIO = 1/BC3_RATIO; - - /** - * Use this material for all your machine blocks. It can be breakable by hand. - */ - public static final Material machine = new Material(MapColor.ironColor); - - public static void versionLock(int major, int minor, int revision, boolean strict) - { - if(MAJOR_VERSION != major) - { - throw new RuntimeException("Universal Electricity wrong version! Require v"+major+"."+minor+"."+revision); - } - - if(MINOR_VERSION < minor) - { - throw new RuntimeException("Universal Electricity minor version is too old! Require v"+major+"."+minor+"."+revision); - } - - if(REVISION_VERSION < revision) - { - if(strict) - { - throw new RuntimeException("Universal Electricity is too old! Require v"+major+"."+minor+"."+revision); - } - else - { - System.out.println("Universal Electricity is not the specified version. Odd things might happen. Require "+major+"."+minor+"."+revision); - } - } - } - - public static void forgeLock(int major, int minor, int revision, boolean strict) - { - if(ForgeVersion.getMajorVersion() != major) - { - throw new RuntimeException("Universal Electricity: Wrong Minecraft Forge version! Require "+major+"."+minor+"."+revision); - } - - if(ForgeVersion.getMinorVersion() < minor) - { - throw new RuntimeException("Universal Electricity: Minecraft Forge minor version is too old! Require "+major+"."+minor+"."+revision); - } - - if(ForgeVersion.getRevisionVersion() < revision) - { - if(strict) - { - throw new RuntimeException("Universal Electricity: Minecraft Forge revision version is too old! Require "+major+"."+minor+"."+revision); - } - else - { - System.out.println("Universal Electricity Warning: Minecraft Forge is not the specified version. Odd things might happen. Require "+major+"."+minor+"."+revision); - } - } - } - - public static void forgeLock(int major, int minor, int revision) - { - forgeLock(major, minor, revision, false); - } -} diff --git a/src/common/universalelectricity/core/UEConfig.java b/src/common/universalelectricity/core/UEConfig.java new file mode 100755 index 000000000..4be1e4d17 --- /dev/null +++ b/src/common/universalelectricity/core/UEConfig.java @@ -0,0 +1,50 @@ +package universalelectricity.core; + +import net.minecraftforge.common.Configuration; + +public class UEConfig +{ + public static int getConfigData(Configuration configuration, String name, int defaultInt) + { + configuration.load(); + int returnInt = defaultInt; + returnInt = Integer.parseInt(configuration.get(name, Configuration.CATEGORY_GENERAL, defaultInt).value); + configuration.save(); + return returnInt; + } + + public static boolean getConfigData(Configuration configuration, String name, boolean defaultBoolean) + { + configuration.load(); + boolean returnBoolean = defaultBoolean; + returnBoolean = Boolean.parseBoolean(configuration.get(name, Configuration.CATEGORY_GENERAL, defaultBoolean).value); + configuration.save(); + return returnBoolean; + } + + public static int getBlockConfigID(Configuration configuration, String name, int defaultID) + { + configuration.load(); + int id = defaultID; + + id = Integer.parseInt(configuration.getBlock(name, defaultID).value); + + if (id <= 136) { return defaultID; } + + configuration.save(); + return id; + } + + public static int getItemConfigID(Configuration configuration, String name, int defaultID) + { + configuration.load(); + int id = defaultID; + + id = Integer.parseInt(configuration.getItem(name, Configuration.CATEGORY_ITEM, defaultID).value); + + if (id < 256) { return defaultID; } + + configuration.save(); + return id; + } +} diff --git a/src/common/universalelectricity/core/UELoader.java b/src/common/universalelectricity/core/UELoader.java new file mode 100755 index 000000000..e0dbde41f --- /dev/null +++ b/src/common/universalelectricity/core/UELoader.java @@ -0,0 +1,68 @@ +package universalelectricity.core; + +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.ForgeSubscribe; +import net.minecraftforge.event.world.WorldEvent.Load; +import net.minecraftforge.event.world.WorldEvent.Unload; +import universalelectricity.electricity.ElectricityManager; +import universalelectricity.electricity.ElectricityManagerTicker; +import cpw.mods.fml.common.FMLLog; +import cpw.mods.fml.common.Loader; +import cpw.mods.fml.common.Side; +import cpw.mods.fml.common.registry.TickRegistry; + +/** + * A class used to load Universal Electricity and make it work. + * @author Calclavia + * + */ +public class UELoader +{ + public static final UELoader INSTANCE = new UELoader(); + + public static boolean isInitialized = false; + + public void initiate() + { + if (!isInitialized) + { + TickRegistry.registerTickHandler(new ElectricityManagerTicker(), Side.SERVER); + ElectricityManager.instance = new ElectricityManager(); + MinecraftForge.EVENT_BUS.register(this); + + if (UniversalElectricity.BC3_RATIO <= 0 || !Loader.isModLoaded("BuildCraft|Core")) + { + FMLLog.fine("Disabled Buildcraft electricity conversion!"); + } + else + { + FMLLog.fine("Buildcraft conversion ratio: " + UniversalElectricity.BC3_RATIO); + } + + if (UniversalElectricity.IC2_RATIO <= 0 || !Loader.isModLoaded("IC2")) + { + FMLLog.fine("Disabled Industrialcraft electricity conversion!"); + } + else + { + FMLLog.fine("IC2 conversion ratio: " + UniversalElectricity.IC2_RATIO); + } + + FMLLog.finest("Universal Electricity v" + UniversalElectricity.VERSION + " successfully loaded!"); + + isInitialized = true; + } + } + + @ForgeSubscribe + public void onWorldLoad(Load event) + { + ElectricityManagerTicker.inGameTicks = 0; + } + + @ForgeSubscribe + public void onWorldUnload(Unload event) + { + ElectricityManager.instance = new ElectricityManager(); + } +} diff --git a/src/common/universalelectricity/core/UniversalElectricity.java b/src/common/universalelectricity/core/UniversalElectricity.java new file mode 100755 index 000000000..abc082bd2 --- /dev/null +++ b/src/common/universalelectricity/core/UniversalElectricity.java @@ -0,0 +1,119 @@ +package universalelectricity.core; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.src.MapColor; +import net.minecraft.src.Material; +import net.minecraftforge.common.Configuration; +import net.minecraftforge.common.ForgeVersion; +import cpw.mods.fml.common.FMLLog; +import cpw.mods.fml.common.Loader; + +/** + * Instructions for using the Universal Electricity API. + * + * The less you include of the API, the more compatible your + * mod will be for future releases of Universal Electricity. + * + * REQUIRED PACKAGES: + * "universalelectricity" + * "universalelectricity.electricity" + * "universalelectricity.implements" - Some interfaces can be removed if not needed. + * + * The rest of the classes should be removed if you are not going to use them. + * + * @author Calclavia + * + */ +public class UniversalElectricity +{ + /** + * The version of the Universal Electricity API. + */ + public static final int MAJOR_VERSION = 1; + public static final int MINOR_VERSION = 0; + public static final int REVISION_VERSION = 0; + public static final String VERSION = MAJOR_VERSION + "." + MINOR_VERSION + "." + REVISION_VERSION; + + /** + * The Universal Electricity configuration file. + */ + public static final Configuration CONFIGURATION = new Configuration(new File(Loader.instance().getConfigDir(), "UniversalElectricity/UniversalElectricity.cfg")); + + /** + * Conversion ratios between Buildcraft and Industrialcraft energy. + */ + // EU to Watts ratio + public static final float IC2_RATIO = (float) UEConfig.getConfigData(CONFIGURATION, "IndustrialCraft Conversion Ratio", 7); + // MJ to Watts ratio. + public static final float BC3_RATIO = (float) UEConfig.getConfigData(CONFIGURATION, "BuildCraft Conversion Ratio", 85);; + public static final float TO_IC2_RATIO = 1 / IC2_RATIO; + public static final float TO_BC_RATIO = 1 / BC3_RATIO; + + /** + * Use this material for all your machine blocks. It can be breakable by + * hand. + */ + public static final Material machine = new Material(MapColor.ironColor); + + public static final List mods = new ArrayList(); + + /** + * You must register your mod with Universal Electricity. Call this in your + * mod's pre-initialization stage. + */ + public static void register(Object mod, int major, int minor, int revision, boolean strict) + { + if (MAJOR_VERSION != major) { throw new RuntimeException("Universal Electricity wrong version! Require v" + major + "." + minor + "." + revision); } + + if (MINOR_VERSION < minor) { throw new RuntimeException("Universal Electricity minor version is too old! Require v" + major + "." + minor + "." + revision); } + + if (REVISION_VERSION < revision) + { + if (strict) + { + throw new RuntimeException("Universal Electricity is too old! Require v" + major + "." + minor + "." + revision); + } + else + { + FMLLog.warning("Universal Electricity is not the specified version. Odd things might happen. Recommend to have v" + major + "." + minor + "." + revision); + } + } + + mods.add(mod); + + FMLLog.fine(mod.getClass().getSimpleName()+" has been registered to Universal Electricity."); + + UELoader.INSTANCE.initiate(); + } + + /** + * A function that allows you to lock your mod to a specific version of + * Forge. + */ + public static void forgeLock(int major, int minor, int revision, boolean strict) + { + if (ForgeVersion.getMajorVersion() != major) { throw new RuntimeException("Universal Electricity: Wrong Minecraft Forge version! Require " + major + "." + minor + "." + revision); } + + if (ForgeVersion.getMinorVersion() < minor) { throw new RuntimeException("Universal Electricity: Minecraft Forge minor version is too old! Require " + major + "." + minor + "." + revision); } + + if (ForgeVersion.getRevisionVersion() < revision) + { + if (strict) + { + throw new RuntimeException("Universal Electricity: Minecraft Forge revision version is too old! Require " + major + "." + minor + "." + revision); + } + else + { + System.out.println("Universal Electricity Warning: Minecraft Forge is not the specified version. Odd things might happen. Require " + major + "." + minor + "." + revision); + } + } + } + + public static void forgeLock(int major, int minor, int revision) + { + forgeLock(major, minor, revision, false); + } +} diff --git a/src/common/universalelectricity/core/Vector2.java b/src/common/universalelectricity/core/Vector2.java new file mode 100755 index 000000000..079c99827 --- /dev/null +++ b/src/common/universalelectricity/core/Vector2.java @@ -0,0 +1,106 @@ +package universalelectricity.core; + +import net.minecraft.src.MathHelper; + +/** + * Vector2 Class is used for defining objects in a 2D space. Vector2 makes it + * easier to handle the coordinates of objects. Instead of fumbling with x and y + * variables, all x and y variables are stored in one class. Vector3.x, + * Vector3.y. + * + * @author Calclavia + */ + +public class Vector2 implements Cloneable +{ + public double x; + public double y; + + public Vector2() + { + this(0, 0); + } + + public Vector2(int x, int y) + { + this.x = x; + this.y = y; + } + + public Vector2(double x, double y) + { + this.x = x; + this.y = y; + } + + // Returns the values as an int + public int intX() + { + return (int) Math.floor(this.x); + } + + public int intY() + { + return (int) Math.floor(this.y); + } + + /** + * Makes a new copy of this Vector. Prevents variable referencing problems. + */ + @Override + public Vector2 clone() + { + return new Vector2(this.x, this.y); + } + + public static boolean isPointInRegion(Vector2 point, Vector2 minPoint, Vector2 maxPoint) + { + return (point.x > minPoint.x && point.x < maxPoint.x) && (point.y > minPoint.y && point.y < maxPoint.y); + } + + public static double distance(Vector2 par1, Vector2 par2) + { + double var2 = par1.x - par2.x; + double var4 = par1.y - par2.y; + return MathHelper.sqrt_double(var2 * var2 + var4 * var4); + } + + public static double slope(Vector2 par1, Vector2 par2) + { + double var2 = par1.x - par2.x; + double var4 = par1.y - par2.y; + return var4 / var2; + } + + public void add(Vector2 par1) + { + this.x += par1.x; + this.y += par1.y; + } + + public void add(double par1) + { + this.x += par1; + this.y += par1; + } + + public Vector2 round() + { + return new Vector2(Math.round(this.x), Math.round(this.y)); + } + + public Vector2 floor() + { + return new Vector2(Math.floor(this.x), Math.floor(this.y)); + } + + public String output() + { + return "Vector2: " + this.x + "," + this.y; + } + + public void printVector() + { + System.out.println(output()); + } +} \ No newline at end of file diff --git a/src/common/universalelectricity/core/Vector3.java b/src/common/universalelectricity/core/Vector3.java new file mode 100755 index 000000000..480f9f860 --- /dev/null +++ b/src/common/universalelectricity/core/Vector3.java @@ -0,0 +1,448 @@ +package universalelectricity.core; + +import net.minecraft.src.ChunkCoordinates; +import net.minecraft.src.Entity; +import net.minecraft.src.MathHelper; +import net.minecraft.src.MovingObjectPosition; +import net.minecraft.src.NBTTagCompound; +import net.minecraft.src.TileEntity; +import net.minecraft.src.Vec3; +import net.minecraft.src.World; +import net.minecraftforge.common.ForgeDirection; +import universalelectricity.implement.IConnector; + +/** + * Vector3 Class is used for defining objects in a 3D space. Vector3 makes it + * easier to handle the coordinates of objects. Instead of fumbling with x, y + * and z variables, all x, y and z variables are stored in one class. Vector3.x, + * Vector3.y, Vector3.z. + * + * @author Calclavia + */ + +public class Vector3 extends Vector2 implements Cloneable +{ + public double z; + + public Vector3() + { + this(0, 0, 0); + } + + public Vector3(int x, int y, int z) + { + this.x = x; + this.y = y; + this.z = z; + } + + public Vector3(double x, double y, double z) + { + this.x = x; + this.y = y; + this.z = z; + } + + /** + * Returns the coordinates as integers + */ + public int intX() + { + return (int) Math.floor(this.x); + } + + public int intY() + { + return (int) Math.floor(this.y); + } + + public int intZ() + { + return (int) Math.floor(this.z); + } + + /** + * Makes a new copy of this Vector. Prevents variable referencing problems. + */ + @Override + public Vector3 clone() + { + return new Vector3(this.x, this.y, this.z); + } + + /** + * Converts a TileEntity's position into Vector3 + */ + public static Vector3 get(Entity par1) + { + return new Vector3(par1.posX, par1.posY, par1.posZ); + } + + /** + * Converts an entity's position into Vector3 + */ + public static Vector3 get(TileEntity par1) + { + return new Vector3(par1.xCoord, par1.yCoord, par1.zCoord); + } + + /** + * Converts from Vec3 into a Vector3 + */ + public static Vector3 get(Vec3 par1) + { + return new Vector3(par1.xCoord, par1.yCoord, par1.zCoord); + } + + /** + * Converts a MovingObjectPosition to Vector3 + */ + public static Vector3 get(MovingObjectPosition par1) + { + return new Vector3(par1.blockX, par1.blockY, par1.blockZ); + } + + /** + * Converts a MovingObjectPosition to Vector3 + */ + public static Vector3 get(ChunkCoordinates par1) + { + return new Vector3(par1.posX, par1.posY, par1.posZ); + } + + public int getBlockID(World world) + { + return world.getBlockId(this.intX(), this.intY(), this.intZ()); + } + + public int getBlockMetadata(World world) + { + return world.getBlockMetadata(this.intX(), this.intY(), this.intZ()); + } + + public TileEntity getTileEntity(World world) + { + return world.getBlockTileEntity(this.intX(), this.intY(), this.intZ()); + } + + public void setBlock(World world, int id, int metadata) + { + world.setBlockAndMetadata(this.intX(), this.intY(), this.intZ(), id, metadata); + } + + public void setBlock(World world, int id) + { + world.setBlock(this.intX(), this.intY(), this.intZ(), id); + } + + public void setBlockWithNotify(World world, int id, int metadata) + { + world.setBlockAndMetadataWithNotify(this.intX(), this.intY(), this.intZ(), id, metadata); + } + + public void setBlockWithNotify(World world, int id) + { + world.setBlockWithNotify(this.intX(), this.intY(), this.intZ(), id); + } + + /** + * Converts this Vector3 into a Vector2 by dropping the Y axis. + */ + public Vector2 toVector2() + { + return new Vector2(this.x, this.z); + } + + /** + * Converts this vector three into a Minecraft Vec3 object + */ + public Vec3 toVec3() + { + return Vec3.createVectorHelper(this.x, this.y, this.z); + } + + /** + * Checks if a Vector3 point is located inside a region + */ + public static boolean isPointInRegion(Vector3 point, Vector3 minPoint, Vector3 maxPoint) + { + return (point.x > minPoint.x && point.x < maxPoint.x) && (point.y > minPoint.y && point.y < maxPoint.y) && (point.z > minPoint.z && point.z < maxPoint.z); + } + + /** + * Compares two vectors and see if they are equal. True if so. + */ + public boolean isEqual(Vector3 vector3) + { + return (this.x == vector3.x && this.y == vector3.y && this.z == vector3.z); + } + + /** + * Gets the distance between two vectors + * + * @return The distance + */ + public static double distance(Vector3 par1, Vector3 par2) + { + double var2 = par1.x - par2.x; + double var4 = par1.y - par2.y; + double var6 = par1.z - par2.z; + return MathHelper.sqrt_double(var2 * var2 + var4 * var4 + var6 * var6); + } + + public double distanceTo(Vector3 vector3) + { + double var2 = vector3.x - this.x; + double var4 = vector3.y - this.y; + double var6 = vector3.z - this.z; + return MathHelper.sqrt_double(var2 * var2 + var4 * var4 + var6 * var6); + } + + public static Vector3 subtract(Vector3 par1, Vector3 par2) + { + return new Vector3(par1.x - par2.x, par1.y - par2.y, par1.z - par2.z); + } + + public static Vector3 add(Vector3 par1, Vector3 par2) + { + return new Vector3(par1.x + par2.x, par1.y + par2.y, par1.z + par2.z); + } + + public static Vector3 add(Vector3 par1, double par2) + { + return new Vector3(par1.x + par2, par1.y + par2, par1.z + par2); + } + + public void add(Vector3 par1) + { + this.x += par1.x; + this.y += par1.y; + this.z += par1.z; + } + + @Override + public void add(double par1) + { + this.x += par1; + this.y += par1; + this.z += par1; + } + + public static Vector3 multiply(Vector3 par1, Vector3 par2) + { + return new Vector3(par1.x * par2.x, par1.y * par2.y, par1.z * par2.z); + } + + public static Vector3 multiply(Vector3 par1, double par2) + { + return new Vector3(par1.x * par2, par1.y * par2, par1.z * par2); + } + + public static Vector3 readFromNBT(String prefix, NBTTagCompound par1NBTTagCompound) + { + Vector3 tempVector = new Vector3(); + tempVector.x = par1NBTTagCompound.getDouble(prefix + "X"); + tempVector.y = par1NBTTagCompound.getDouble(prefix + "Y"); + tempVector.z = par1NBTTagCompound.getDouble(prefix + "Z"); + return tempVector; + } + + /** + * Saves this Vector3 to disk + * + * @param prefix + * - The prefix of this save. Use some unique string. + * @param par1NBTTagCompound + * - The NBT compound object to save the data in + */ + public void writeToNBT(String prefix, NBTTagCompound par1NBTTagCompound) + { + par1NBTTagCompound.setDouble(prefix + "X", this.x); + par1NBTTagCompound.setDouble(prefix + "Y", this.y); + par1NBTTagCompound.setDouble(prefix + "Z", this.z); + } + + @Override + public Vector3 round() + { + return new Vector3(Math.round(this.x), Math.round(this.y), Math.round(this.z)); + } + + @Override + public Vector3 floor() + { + return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z)); + } + + @Override + public String output() + { + return "Vector3: " + this.x + "," + this.y + "," + this.z; + } + + /** + * Gets a position relative to another position's side + * + * @param position + * - The position + * @param side + * - The side. 0-5 + * @return The position relative to the original position's side + */ + public void modifyPositionFromSide(ForgeDirection side) + { + switch (side.ordinal()) + { + case 0: + this.y -= 1; + break; + case 1: + this.y += 1; + break; + case 2: + this.z -= 1; + break; + case 3: + this.z += 1; + break; + case 4: + this.x -= 1; + break; + case 5: + this.x += 1; + break; + } + } + + public static TileEntity getTileEntityFromSide(World world, Vector3 position, ForgeDirection side) + { + position.modifyPositionFromSide(side); + return world.getBlockTileEntity(position.intX(), position.intY(), position.intZ()); + } + + /** + * Gets a connector unit based on the given side. + */ + public static TileEntity getConnectorFromSide(World world, Vector3 position, ForgeDirection side) + { + TileEntity tileEntity = getTileEntityFromSide(world, position, side); + + if (tileEntity instanceof IConnector) + { + if (((IConnector) tileEntity).canConnect(getOrientationFromSide(side, ForgeDirection.NORTH))) { return tileEntity; } + } + + return null; + } + + /** + * Finds the side of a block depending on it's facing direction from the + * given side. The side numbers are compatible with the + * function"getBlockTextureFromSideAndMetadata". + * + * Bottom: 0; Top: 1; Back: 2; Front: 3; Left: 4; Right: 5; + * + * @param front + * - The direction in which this block is facing/front. Use a + * number between 0 and 5. Default is 3. + * @param side + * - The side you are trying to find. A number between 0 and 5. + * @return The side relative to the facing direction. + */ + + public static ForgeDirection getOrientationFromSide(ForgeDirection front, ForgeDirection side) + { + switch (front.ordinal()) + { + case 0: + switch (side.ordinal()) + { + case 0: + return ForgeDirection.getOrientation(3); + case 1: + return ForgeDirection.getOrientation(2); + case 2: + return ForgeDirection.getOrientation(1); + case 3: + return ForgeDirection.getOrientation(0); + case 4: + return ForgeDirection.getOrientation(5); + case 5: + return ForgeDirection.getOrientation(4); + } + + case 1: + switch (side.ordinal()) + { + case 0: + return ForgeDirection.getOrientation(4); + case 1: + return ForgeDirection.getOrientation(5); + case 2: + return ForgeDirection.getOrientation(0); + case 3: + return ForgeDirection.getOrientation(1); + case 4: + return ForgeDirection.getOrientation(2); + case 5: + return ForgeDirection.getOrientation(3); + } + + case 2: + switch (side.ordinal()) + { + case 0: + return ForgeDirection.getOrientation(0); + case 1: + return ForgeDirection.getOrientation(1); + case 2: + return ForgeDirection.getOrientation(3); + case 3: + return ForgeDirection.getOrientation(2); + case 4: + return ForgeDirection.getOrientation(5); + case 5: + return ForgeDirection.getOrientation(4); + } + + case 3: + return side; + + case 4: + switch (side.ordinal()) + { + case 0: + return ForgeDirection.getOrientation(0); + case 1: + return ForgeDirection.getOrientation(1); + case 2: + return ForgeDirection.getOrientation(5); + case 3: + return ForgeDirection.getOrientation(4); + case 4: + return ForgeDirection.getOrientation(3); + case 5: + return ForgeDirection.getOrientation(2); + } + + case 5: + switch (side.ordinal()) + { + case 0: + return ForgeDirection.getOrientation(0); + case 1: + return ForgeDirection.getOrientation(1); + case 2: + return ForgeDirection.getOrientation(4); + case 3: + return ForgeDirection.getOrientation(5); + case 4: + return ForgeDirection.getOrientation(2); + case 5: + return ForgeDirection.getOrientation(3); + } + } + + return ForgeDirection.UNKNOWN; + } +} \ No newline at end of file diff --git a/src/common/universalelectricity/electricity/ElectricInfo.java b/src/common/universalelectricity/electricity/ElectricInfo.java old mode 100644 new mode 100755 index dde38c589..55722bf9e --- a/src/common/universalelectricity/electricity/ElectricInfo.java +++ b/src/common/universalelectricity/electricity/ElectricInfo.java @@ -1,8 +1,8 @@ package universalelectricity.electricity; - /** - * A better way to storage information on electricity + * An easy way to display information on electricity. + * * @author Calclavia */ @@ -10,51 +10,41 @@ public class ElectricInfo { public static enum ElectricUnit { - AMPERE("Amp", "I"), - AMP_HOUR("Amp Hour", "Ah"), - VOLTAGE("Volt", "V"), - WATT("Watt", "W"), - WATT_HOUR("Watt Hour", "Wh"), - RESISTANCE("Ohm", "R"), - CONDUCTANCE("Siemen", "S"), - JOULES("Joule", "J"); - + AMPERE("Amp", "I"), AMP_HOUR("Amp Hour", "Ah"), VOLTAGE("Volt", "V"), WATT("Watt", "W"), WATT_HOUR("Watt Hour", "Wh"), RESISTANCE("Ohm", "R"), CONDUCTANCE("Siemen", "S"), JOULES("Joule", "J"); + public String name; public String symbol; - + private ElectricUnit(String name, String symbol) { this.name = name; this.symbol = symbol; } - + public String getPlural() { - return this.name+"s"; + return this.name + "s"; } } - + public static enum MeasurementUnit { - MICRO("Micro", "mi", 0.000001), - MILLI("Milli", "m", 0.001), - KILO("Kilo", "k", 1000), - MEGA("Mega", "M", 1000000); - + MICRO("Micro", "mi", 0.000001), MILLI("Milli", "m", 0.001), KILO("Kilo", "k", 1000), MEGA("Mega", "M", 1000000); + public String name; public String symbol; public double process; - + private MeasurementUnit(String name, String symbol, double process) { this.name = name; this.symbol = symbol; this.process = process; } - + public String getName(boolean isSymbol) { - if(isSymbol) + if (isSymbol) { return symbol; } @@ -63,169 +53,149 @@ public class ElectricInfo return name; } } - + public double process(double value) { - return value/this.process; + return value / this.process; } } - + public static double getJoules(double watts, double seconds) { - return watts*seconds; + return watts * seconds; } - + public static double getJoules(double amps, double voltage, double seconds) { - return amps*voltage*seconds; + return amps * voltage * seconds; } - + public static double getWattsFromJoules(double joules, double seconds) { - return joules/seconds; + return joules / seconds; } - + public static double getAmps(double watts, double voltage) { - return watts/voltage; + return watts / voltage; } - + public static double getAmps(double ampHours) { - return ampHours*3600; + return ampHours * 3600; } - + public static double getAmpsFromWattHours(double wattHours, double voltage) { - return getWatts(wattHours)/voltage; + return getWatts(wattHours) / voltage; } - + public static double getWattHoursFromAmpHours(double ampHours, double voltage) { - return ampHours*voltage; + return ampHours * voltage; } - + public static double getAmpHours(double amps) { - return amps/3600; + return amps / 3600; } - + public static double getWatts(double amps, double voltage) { - return amps*voltage; + return amps * voltage; } - + public static double getWatts(double wattHours) { - return wattHours*3600; + return wattHours * 3600; } - + public static double getWattHours(double watts) { - return watts/3600; + return watts / 3600; } - + public static double getWattHours(double amps, double voltage) { return getWattHours(getWatts(amps, voltage)); } - + public static double getResistance(double amps, double voltage) { - return voltage/amps; + return voltage / amps; } - + public static double getConductance(double amps, double voltage) { - return amps/voltage; + return amps / voltage; } - + /** * Displays the unit as text. Works only for positive numbers. */ public static String getDisplay(double value, ElectricUnit unit, int significantFigures, boolean isShort) { String unitName = unit.name; - - if(isShort) + + if (isShort) { unitName = unit.symbol; } - else if(value > 1) + else if (value > 1) { unitName = unit.getPlural(); } - - if(value == 0) - { - return value + " " + unitName; - } - - if(value <= MeasurementUnit.MILLI.process) - { - return roundDecimals(MeasurementUnit.MICRO.process(value), significantFigures) + " " + MeasurementUnit.MICRO.getName(isShort)+unitName; - } - - if(value < 1) - { - return roundDecimals(MeasurementUnit.MILLI.process(value), significantFigures) + " " + MeasurementUnit.MILLI.getName(isShort)+unitName; - } - - if(value > MeasurementUnit.KILO.process) - { - return roundDecimals(MeasurementUnit.KILO.process(value), significantFigures) + " " + MeasurementUnit.KILO.getName(isShort)+unitName; - } - - if(value > MeasurementUnit.MEGA.process) - { - return roundDecimals(MeasurementUnit.MEGA.process(value), significantFigures) + " " + MeasurementUnit.MEGA.getName(isShort)+unitName; - } - - return roundDecimals(value, significantFigures) + " " + unitName; + + if (value == 0) { return value + " " + unitName; } + + if (value <= MeasurementUnit.MILLI.process) { return roundDecimals(MeasurementUnit.MICRO.process(value), significantFigures) + " " + MeasurementUnit.MICRO.getName(isShort) + unitName; } + + if (value < 1) { return roundDecimals(MeasurementUnit.MILLI.process(value), significantFigures) + " " + MeasurementUnit.MILLI.getName(isShort) + unitName; } + + if (value > MeasurementUnit.KILO.process) { return roundDecimals(MeasurementUnit.KILO.process(value), significantFigures) + " " + MeasurementUnit.KILO.getName(isShort) + unitName; } + + if (value > MeasurementUnit.MEGA.process) { return roundDecimals(MeasurementUnit.MEGA.process(value), significantFigures) + " " + MeasurementUnit.MEGA.getName(isShort) + unitName; } + + return roundDecimals(value, significantFigures) + " " + unitName; } - + public static String getDisplayShort(double value, ElectricUnit unit) { return getDisplay(value, unit, 2, true); } - + public static String getDisplay(double value, ElectricUnit unit) { return getDisplay(value, unit, 2, false); } - + public static String getDisplaySimple(double value, ElectricUnit unit, int significantFigures) { - if(value > 1) + if (value > 1) { - if(significantFigures < 1) - { - return (int)value + " " + unit.getPlural(); - } - - return roundDecimals(value, significantFigures) + " " + unit.getPlural(); + if (significantFigures < 1) { return (int) value + " " + unit.getPlural(); } + + return roundDecimals(value, significantFigures) + " " + unit.getPlural(); } - - if(significantFigures < 1) - { - return (int)value + " " + unit.name; - } - - return roundDecimals(value, significantFigures) + " " + unit.name; + + if (significantFigures < 1) { return (int) value + " " + unit.name; } + + return roundDecimals(value, significantFigures) + " " + unit.name; } - - + /** * Rounds a number to a specific number place places - * @param The number + * + * @param The + * number * @return The rounded number */ public static double roundDecimals(double d, int significantFigures) { - int j = (int)(d * Math.pow(10, significantFigures)); - return j / (double)Math.pow(10, significantFigures); + int j = (int) (d * Math.pow(10, significantFigures)); + return j / (double) Math.pow(10, significantFigures); } - + public static double roundDecimals(double d) { return roundDecimals(d, 2); diff --git a/src/common/universalelectricity/electricity/ElectricityManager.java b/src/common/universalelectricity/electricity/ElectricityManager.java old mode 100644 new mode 100755 index ce31a1d9a..6807e4971 --- a/src/common/universalelectricity/electricity/ElectricityManager.java +++ b/src/common/universalelectricity/electricity/ElectricityManager.java @@ -9,427 +9,402 @@ import java.util.Map; import net.minecraft.src.TileEntity; import net.minecraftforge.common.ForgeDirection; -import universalelectricity.Ticker; +import universalelectricity.core.Vector3; import universalelectricity.implement.IConductor; import universalelectricity.implement.IElectricityReceiver; -import universalelectricity.prefab.Vector3; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.TickType; /** - * This class is used to manage electricity transferring and flow. It is also used to call updates on UE tile entities. + * This class is used to manage electricity + * transferring and flow. It is also used to call + * updates on UE tile entities. + * * @author Calclavia - * + * */ public class ElectricityManager { /** - * ElectricityManager exists on both client and server side. - * Rely on the server side one as it is more accurate! Client side only simulates. + * ElectricityManager exists on both client + * and server side. Rely on the server side + * one as it is more accurate! Client side + * only simulates. */ public static ElectricityManager instance; - - private List electricityReceivers = new ArrayList(); - private List electricConductors = new ArrayList(); - private List electricityTransferQueue = new ArrayList(); - private List electricityNetworks = new ArrayList(); - private int maxConnectionID = 0; - - public ElectricityManager() - { - System.out.println("Universal Electricity's Electricity Manager Initiated."); - } - - /** - * Registers an electricity consumer for it to receive electricity. - * Call it in your consumer's tile entity constructor like this: - * ElectricityManager.registerConsumer(this); - * @param newUnit - The consumer to be registered. - */ - public void registerElectricUnit(IElectricityReceiver newUnit) - { - if (!this.electricityReceivers.contains(newUnit)) - { - this.electricityReceivers.add(newUnit); - } - } + private List electricityTransferQueue = new ArrayList(); + private List electricityNetworks = new ArrayList(); - /** - * Registers a UE conductor - * @param conductor - The conductor tile entity - * @return - The ID of the connection line that is assigned to this conductor - */ - public void registerConductor(IConductor newConductor) - { - cleanUpConnections(); - this.electricityNetworks.add(new ElectricityNetwork(getMaxConnectionID(), newConductor)); + public ElectricityManager() + { + System.out.println("Universal Electricity's Electricity Manager Initiated."); + } - if (!this.electricConductors.contains(newConductor)) - { - this.electricConductors.add(newConductor); - } - } + /** + * Registers a the conductor into the UE + * electricity net. + * + * @param conductor + * - The IConductor tile entity. + */ + public void registerConductor(IConductor newConductor) + { + cleanUpConnections(); + this.electricityNetworks.add(new ElectricityNetwork(newConductor)); + } - /** - * Merges two connection lines together into one. - * @param ID1 - ID of connection line - * @param ID2 - ID of connection line - */ - public void mergeConnection(int ID1, int ID2) - { - if(ID1 != ID2) - { - ElectricityNetwork connection1 = getConnectionByID(ID1); - ElectricityNetwork connection2 = getConnectionByID(ID2); - - if(connection1 != null && connection2 != null) - { - connection1.conductors.addAll(connection2.conductors); - connection1.setID(ID1); - this.electricityNetworks.remove(connection2); - } - else - { - System.err.println("Failed to merge Universal Electricity wire connections!"); - } - } - } - - /** - * Separate one connection line into two different ones between two conductors. - * This function does this by resetting all wires in the connection line and - * making them each reconnect. - * @param conductorA - existing conductor - * @param conductorB - broken/invalid conductor - */ - public void splitConnection(IConductor conductorA, IConductor conductorB) - { - ElectricityNetwork connection = getConnectionByID(conductorA.getConnectionID()); - connection.cleanUpArray(); - - for(IConductor conductor : connection.conductors) - { - conductor.reset(); - } - - for(IConductor conductor : connection.conductors) - { - for (byte i = 0; i < 6; i++) - { - conductor.updateConnectionWithoutSplit(Vector3.getConnectorFromSide(conductor.getWorld(), new Vector3(((TileEntity)conductor).xCoord, ((TileEntity)conductor).yCoord, ((TileEntity)conductor).zCoord), ForgeDirection.getOrientation(i)), ForgeDirection.getOrientation(i)); - } - } - } - - /** - * Gets a electricity wire connection line by it's connection ID - * @param ID - * @return - */ - public ElectricityNetwork getConnectionByID(int ID) - { - cleanUpConnections(); - - for (int i = 0; i < this.electricityNetworks.size(); i++) - { - if (this.electricityNetworks.get(i).getID() == ID) - { - return this.electricityNetworks.get(i); - } - } - - return null; - } - - /** - * Clean up and remove useless connections - */ - public void cleanUpConnections() - { - try - { - for (int i = 0; i < this.electricityNetworks.size(); i++) - { - this.electricityNetworks.get(i).cleanUpArray(); - - if (this.electricityNetworks.get(i).conductors.size() == 0) - { - this.electricityNetworks.remove(i); - } - } - } - catch(Exception e) - { - FMLLog.severe("Failed to clean up wire connections!"); - } - } - - /** - * Get the highest connection ID. Use this to assign new wire connection lines - * @return - */ - public int getMaxConnectionID() - { - this.maxConnectionID ++; - - if(this.maxConnectionID >= Integer.MAX_VALUE) - { - this.maxConnectionID = 0; - } - - return this.maxConnectionID; - } - - /** - * Produces electricity into a specific wire which will be distributed across the electricity network. - * @param sender - The machine sending the electricity. - * @param targetConductor - The conductor receiving the electricity (or connected to the machine). - * @param amps - The amount of amps this machine is sending. - * @param voltage 0 The amount of volts this machine is sending. - */ - public void produceElectricity(TileEntity sender, IConductor targetConductor, double amps, double voltage) - { - if(targetConductor != null && amps > 0 && voltage > 0) - { - //Find a path between this conductor and all connected units and try to send the electricity to them directly - ElectricityNetwork electricityNetwork = this.getConnectionByID(targetConductor.getConnectionID()); - - if(electricityNetwork != null) - { - List allElectricUnitsInLine = electricityNetwork.getConnectedReceivers(); - double leftOverAmps = amps; - - for (IConductor conductor : electricityNetwork.conductors) - { - for (byte i = 0; i < conductor.getConnectedBlocks().length; i++) - { - TileEntity tileEntity = conductor.getConnectedBlocks()[i]; - - if (tileEntity != null) - { - if (tileEntity instanceof IElectricityReceiver) - { - IElectricityReceiver receiver = (IElectricityReceiver)tileEntity; - - if (this.getActualWattRequest(receiver) > 0 && receiver.canReceiveFromSide(ForgeDirection.getOrientation(i).getOpposite())) - { - double transferAmps = Math.max(0, Math.min(leftOverAmps, Math.min(amps / allElectricUnitsInLine.size(), ElectricInfo.getAmps(this.getActualWattRequest(receiver), receiver.getVoltage())))); - leftOverAmps -= transferAmps; - - //Calculate electricity loss - double distance = Vector3.distance(Vector3.get(sender), Vector3.get((TileEntity)receiver)); - double ampsReceived = transferAmps - (transferAmps * transferAmps * targetConductor.getResistance() * distance)/voltage; - double voltsReceived = voltage - (transferAmps * targetConductor.getResistance() * distance); - - this.electricityTransferQueue.add(new ElectricityTransferData(sender, receiver, electricityNetwork, ForgeDirection.getOrientation(i).getOpposite(), ampsReceived, voltsReceived)); - } - } - } - } - } - } - } - } - - /** - * Gets the actual watt request of an electric receiver accounting all current electricity packets qued up for it. - * @return - The amount of watts requested. - */ - public double getActualWattRequest(IElectricityReceiver receiver) - { - double wattsRequest = receiver.wattRequest(); - - try - { - for (int i = 0; i < electricityTransferQueue.size(); i ++) - { - if(electricityTransferQueue.get(i) != null) - { - if(electricityTransferQueue.get(i).isValid()) - { - if(electricityTransferQueue.get(i).receiver == receiver) - { - wattsRequest -= electricityTransferQueue.get(i).amps*electricityTransferQueue.get(i).voltage; - } - } - } - } - } - catch(Exception e) - { - FMLLog.severe("Failed to get watt request!"); - } - - return Math.max(Math.min(wattsRequest, receiver.wattRequest()), 0); - } - - /** - * Checks if the current connection line needs electricity - * @return - The amount of joules this connection line needs - */ - public double getElectricityRequired(int ID) - { - ElectricityNetwork connection = this.getConnectionByID(ID); - double need = 0; - - if (connection != null) - { - for (IConductor conductor : connection.conductors) - { - for (byte i = 0; i < conductor.getConnectedBlocks().length; i++) - { - TileEntity tileEntity = conductor.getConnectedBlocks()[i]; - - if (tileEntity != null) - { - if (tileEntity instanceof IElectricityReceiver) - { - IElectricityReceiver electricUnit = (IElectricityReceiver)tileEntity; - - if (electricUnit.canReceiveFromSide(ForgeDirection.getOrientation(i).getOpposite())) - { - need += electricUnit.wattRequest(); - } - } - } - } - } - } - - return need; - } - - public double getActualElectricityRequired(int ID) - { - ElectricityNetwork connection = this.getConnectionByID(ID); - double need = 0; - - if (connection != null) - { - for (IConductor conductor : connection.conductors) - { - for (byte i = 0; i < conductor.getConnectedBlocks().length; i++) - { - TileEntity tileEntity = conductor.getConnectedBlocks()[i]; - - if (tileEntity != null) - { - if (tileEntity instanceof IElectricityReceiver) - { - IElectricityReceiver electricUnit = (IElectricityReceiver)tileEntity; - - if (electricUnit.canReceiveFromSide(ForgeDirection.getOrientation(i).getOpposite())) - { - need += this.getActualWattRequest(electricUnit); - } - } - } - } - } - } - - return need; - } - - /** - * This function is called to refresh all conductors in UE - */ - public void refreshConductors() - { - for(int j = 0; j < this.electricConductors.size(); j ++) - { - IConductor conductor = this.electricConductors.get(j); - conductor.refreshConnectedBlocks(); - } - } - - /** - * Clean up and remove useless connections - */ - public void cleanUpElectricityReceivers() - { - try - { - for (int i = 0; i < this.electricityReceivers.size(); i++) - { - IElectricityReceiver electricUnit = electricityReceivers.get(i); - - //Cleanup useless units - if (electricUnit == null) - { - electricityReceivers.remove(electricUnit); - } - else if (((TileEntity)electricUnit).isInvalid()) - { - electricityReceivers.remove(electricUnit); - } - } - } - catch(Exception e) + /** + * Merges two connection lines together into + * one. + * + * @param networkA + * - The network to be merged into. + * This network will be kept. + * @param networkB + * - The network to be merged. This + * network will be deleted. + */ + public void mergeConnection(ElectricityNetwork networkA, ElectricityNetwork networkB) + { + if (networkA != networkB) { - System.err.println("Failed to clean up electricity receivers."); - e.printStackTrace(); + if (networkA != null && networkB != null) + { + networkA.conductors.addAll(networkB.conductors); + networkA.setNetwork(); + this.electricityNetworks.remove(networkB); + networkB = null; + } + else + { + System.err.println("Failed to merge Universal Electricity wire connections!"); + } } - } + } + + /** + * Separate one connection line into two + * different ones between two conductors. This + * function does this by resetting all wires + * in the connection line and making them each + * reconnect. + * + * @param conductorA + * - existing conductor + * @param conductorB + * - broken/invalid conductor + */ + public void splitConnection(IConductor conductorA, IConductor conductorB) + { + ElectricityNetwork connection = conductorA.getNetwork(); + + if (connection != null) + { + connection.cleanUpArray(); + + for (IConductor conductor : connection.conductors) + { + conductor.reset(); + } + + for (IConductor conductor : connection.conductors) + { + for (byte i = 0; i < 6; i++) + { + conductor.updateConnectionWithoutSplit(Vector3.getConnectorFromSide(conductor.getWorld(), new Vector3(((TileEntity) conductor).xCoord, ((TileEntity) conductor).yCoord, ((TileEntity) conductor).zCoord), ForgeDirection.getOrientation(i)), ForgeDirection.getOrientation(i)); + } + } + } + else + { + FMLLog.severe("Conductor invalid network while splitting connection!"); + } + } + + /** + * Clean up and remove all useless and invalid + * connections. + */ + public void cleanUpConnections() + { + try + { + for (int i = 0; i < this.electricityNetworks.size(); i++) + { + this.electricityNetworks.get(i).cleanUpArray(); + + if (this.electricityNetworks.get(i).conductors.size() == 0) + { + this.electricityNetworks.remove(i); + } + } + } + catch (Exception e) + { + FMLLog.severe("Failed to clean up wire connections!"); + } + } + + /** + * Produces electricity into a specific wire + * which will be distributed across the + * electricity network. + * + * @param sender + * The machine sending the + * electricity. + * @param targetConductor + * The conductor receiving the + * electricity (or connected to the + * machine). + * @param amps + * The amount of amps this machine + * is sending. + * @param voltage + * The amount of volts this machine + * is sending. + */ + public void produceElectricity(TileEntity sender, IConductor targetConductor, double amps, double voltage) + { + if (targetConductor != null && amps > 0 && voltage > 0) + { + // Find a path between this conductor + // and all connected units and + // try to send the electricity to them + // directly + ElectricityNetwork electricityNetwork = targetConductor.getNetwork(); + + if (electricityNetwork != null) + { + List allElectricUnitsInLine = electricityNetwork.getConnectedReceivers(); + double leftOverAmps = amps; + + for (IConductor conductor : electricityNetwork.conductors) + { + for (byte i = 0; i < conductor.getConnectedBlocks().length; i++) + { + TileEntity tileEntity = conductor.getConnectedBlocks()[i]; + + if (tileEntity != null) + { + if (tileEntity instanceof IElectricityReceiver) + { + IElectricityReceiver receiver = (IElectricityReceiver) tileEntity; + + if (this.getActualWattRequest(receiver) > 0 && receiver.canReceiveFromSide(ForgeDirection.getOrientation(i).getOpposite())) + { + double transferAmps = Math.max(0, Math.min(leftOverAmps, Math.min(amps / allElectricUnitsInLine.size(), ElectricInfo.getAmps(this.getActualWattRequest(receiver), receiver.getVoltage())))); + leftOverAmps -= transferAmps; + + // Calculate + // electricity + // loss + double distance = Vector3.distance(Vector3.get(sender), Vector3.get((TileEntity) receiver)); + double ampsReceived = transferAmps - (transferAmps * transferAmps * targetConductor.getResistance() * distance) / voltage; + double voltsReceived = voltage - (transferAmps * targetConductor.getResistance() * distance); + + this.electricityTransferQueue.add(new ElectricityTransferData(sender, receiver, electricityNetwork, ForgeDirection.getOrientation(i).getOpposite(), ampsReceived, voltsReceived)); + } + } + } + } + } + } + else + { + FMLLog.severe("Conductor not registered to a network!"); + } + } + } + + /** + * Gets the actual watt request of an electric + * receiver accounting all current electricity + * packets qued up for it. + * + * @return - The amount of watts requested. + */ + public double getActualWattRequest(IElectricityReceiver receiver) + { + double wattsRequest = receiver.wattRequest(); + + try + { + for (int i = 0; i < electricityTransferQueue.size(); i++) + { + if (electricityTransferQueue.get(i) != null) + { + if (electricityTransferQueue.get(i).isValid()) + { + if (electricityTransferQueue.get(i).receiver == receiver) + { + wattsRequest -= electricityTransferQueue.get(i).amps * electricityTransferQueue.get(i).voltage; + } + } + } + } + } + catch (Exception e) + { + FMLLog.severe("Failed to get watt request!"); + } + + return Math.max(Math.min(wattsRequest, receiver.wattRequest()), 0); + } + + /** + * Checks if the current connection line needs + * electricity + * + * @return - The amount of joules this + * connection line needs + */ + public double getElectricityRequired(ElectricityNetwork network) + { + double need = 0; + + if (network != null) + { + for (IConductor conductor : network.conductors) + { + for (byte i = 0; i < conductor.getConnectedBlocks().length; i++) + { + TileEntity tileEntity = conductor.getConnectedBlocks()[i]; + + if (tileEntity != null) + { + if (tileEntity instanceof IElectricityReceiver) + { + IElectricityReceiver electricUnit = (IElectricityReceiver) tileEntity; + + if (electricUnit.canReceiveFromSide(ForgeDirection.getOrientation(i).getOpposite())) + { + need += electricUnit.wattRequest(); + } + } + } + } + } + } + + return need; + } + + public double getActualElectricityRequired(ElectricityNetwork network) + { + double need = 0; + + if (network != null) + { + for (IConductor conductor : network.conductors) + { + for (byte i = 0; i < conductor.getConnectedBlocks().length; i++) + { + TileEntity tileEntity = conductor.getConnectedBlocks()[i]; + + if (tileEntity != null) + { + if (tileEntity instanceof IElectricityReceiver) + { + IElectricityReceiver electricUnit = (IElectricityReceiver) tileEntity; + + if (electricUnit.canReceiveFromSide(ForgeDirection.getOrientation(i).getOpposite())) + { + need += this.getActualWattRequest(electricUnit); + } + } + } + } + } + } + + return need; + } + + /** + * This function is called to refresh all + * conductors in the world. + */ + public void refreshConductors() + { + try + { + Iterator it = electricityNetworks.iterator(); + + while (it.hasNext()) + { + ((ElectricityNetwork) it.next()).refreshConductors(); + } + } + catch (Exception e) + { + FMLLog.fine("Failed to refresh conductors."); + } + } public void onTick(EnumSet type, Object... tickData) { - if((type.contains(TickType.CLIENT) || type.contains(TickType.WORLD)) && !type.contains(TickType.WORLDLOAD)) + if (type.contains(TickType.WORLD) && !type.contains(TickType.WORLDLOAD)) { + if (ElectricityManagerTicker.inGameTicks % 40 == 0) + { + this.refreshConductors(); + } + try { HashMap conductorAmpData = new HashMap(); - - for (int i = 0; i < electricityTransferQueue.size(); i ++) - { - if(electricityTransferQueue.get(i) != null) - { - if(electricityTransferQueue.get(i).isValid()) - { - double amps = electricityTransferQueue.get(i).amps; - - if(conductorAmpData.containsKey(electricityTransferQueue.get(i).network)) - { - amps += (Double)conductorAmpData.get(electricityTransferQueue.get(i).network); - } - - conductorAmpData.put(electricityTransferQueue.get(i).network, amps); - electricityTransferQueue.get(i).receiver.onReceive(electricityTransferQueue.get(i).sender, electricityTransferQueue.get(i).amps, electricityTransferQueue.get(i).voltage, electricityTransferQueue.get(i).side); - } - } - - electricityTransferQueue.remove(i); - } - + + for (int i = 0; i < electricityTransferQueue.size(); i++) + { + if (electricityTransferQueue.get(i) != null) + { + if (electricityTransferQueue.get(i).isValid()) + { + double amps = electricityTransferQueue.get(i).amps; + + if (conductorAmpData.containsKey(electricityTransferQueue.get(i).network)) + { + amps += (Double) conductorAmpData.get(electricityTransferQueue.get(i).network); + } + + conductorAmpData.put(electricityTransferQueue.get(i).network, amps); + electricityTransferQueue.get(i).receiver.onReceive(electricityTransferQueue.get(i).sender, electricityTransferQueue.get(i).amps, electricityTransferQueue.get(i).voltage, electricityTransferQueue.get(i).side); + } + } + + electricityTransferQueue.remove(i); + } + Iterator it = conductorAmpData.entrySet().iterator(); - - while (it.hasNext()) - { - Map.Entry pairs = (Map.Entry)it.next(); - - if(pairs.getKey() != null && pairs.getValue() != null) - { - if(pairs.getKey() instanceof ElectricityNetwork && pairs.getValue() instanceof Double) - { - if(((Double)pairs.getValue()) > ((ElectricityNetwork)pairs.getKey()).getLowestAmpConductor()) - { - ((ElectricityNetwork)pairs.getKey()).meltDown(); - } - } - } - - it.remove(); - } + + while (it.hasNext()) + { + Map.Entry pairs = (Map.Entry) it.next(); + + if (pairs.getKey() != null && pairs.getValue() != null) + { + if (pairs.getKey() instanceof ElectricityNetwork && pairs.getValue() instanceof Double) + { + if (((Double) pairs.getValue()) > ((ElectricityNetwork) pairs.getKey()).getLowestAmpConductor()) + { + ((ElectricityNetwork) pairs.getKey()).onOverCharge(); + } + } + } + + it.remove(); + } } - catch(Exception e) + catch (Exception e) { System.err.println("Failed to transfer electricity to receivers."); e.printStackTrace(); } } - - if(Ticker.inGameTicks == 0) + + if (ElectricityManagerTicker.inGameTicks == 0) { this.refreshConductors(); } diff --git a/src/common/universalelectricity/Ticker.java b/src/common/universalelectricity/electricity/ElectricityManagerTicker.java old mode 100644 new mode 100755 similarity index 61% rename from src/common/universalelectricity/Ticker.java rename to src/common/universalelectricity/electricity/ElectricityManagerTicker.java index 2c3e053ce..a00634b29 --- a/src/common/universalelectricity/Ticker.java +++ b/src/common/universalelectricity/electricity/ElectricityManagerTicker.java @@ -1,41 +1,40 @@ -package universalelectricity; +package universalelectricity.electricity; import java.util.EnumSet; -import universalelectricity.electricity.ElectricityManager; import cpw.mods.fml.common.ITickHandler; import cpw.mods.fml.common.TickType; -public class Ticker implements ITickHandler +public class ElectricityManagerTicker implements ITickHandler { public static long inGameTicks = 0; @Override public void tickStart(EnumSet type, Object... tickData) { + if (ElectricityManager.instance != null) + { + ElectricityManager.instance.onTick(type, tickData); + } + inGameTicks++; + + if (inGameTicks >= Long.MAX_VALUE) + { + inGameTicks = 0; + } } @Override public void tickEnd(EnumSet type, Object... tickData) { - if(ElectricityManager.instance != null) - { - ElectricityManager.instance.onTick(type, tickData); - } - inGameTicks ++; - - if(inGameTicks >= Long.MAX_VALUE) - { - inGameTicks = 0; - } } @Override public EnumSet ticks() { - return EnumSet.of(TickType.WORLD, TickType.WORLDLOAD, TickType.CLIENT, TickType.SERVER); + return EnumSet.of(TickType.WORLD, TickType.WORLDLOAD, TickType.SERVER); } @Override diff --git a/src/common/universalelectricity/electricity/ElectricityNetwork.java b/src/common/universalelectricity/electricity/ElectricityNetwork.java old mode 100644 new mode 100755 index 440510aa4..0d4bed0c3 --- a/src/common/universalelectricity/electricity/ElectricityNetwork.java +++ b/src/common/universalelectricity/electricity/ElectricityNetwork.java @@ -10,109 +10,114 @@ import universalelectricity.implement.IElectricityReceiver; public class ElectricityNetwork { - private int ID; - public List conductors = new ArrayList(); + public List conductors = new ArrayList(); - public ElectricityNetwork(int ID, IConductor conductor) - { - this.ID = ID; - this.addConductor(conductor); - } + public ElectricityNetwork(IConductor conductor) + { + this.addConductor(conductor); + } - public void addConductor(IConductor newConductor) - { - this.cleanUpArray(); - - if (!conductors.contains(newConductor)) - { - conductors.add(newConductor); - newConductor.setConnectionID(this.ID); - } - } - - /** - * Get only the electric units that can receive electricity from the given side. - */ - public List getConnectedReceivers() - { - this.cleanUpArray(); - List returnArray = new ArrayList(); - - for (IConductor conductor : conductors) - { - for (byte i = 0; i < conductor.getConnectedBlocks().length; i++) - { - TileEntity tileEntity = conductor.getConnectedBlocks()[i]; - - if (tileEntity != null) - { - if (tileEntity instanceof IElectricityReceiver) - { - if (!returnArray.contains((IElectricityReceiver)tileEntity) && ((IElectricityReceiver)tileEntity).canReceiveFromSide(ForgeDirection.getOrientation(i).getOpposite())) - { - returnArray.add((IElectricityReceiver)tileEntity); - } - } - } - } - } - - return returnArray; - } - - public void cleanUpArray() - { - for (int i = 0; i < conductors.size(); i++) - { - if (conductors.get(i) == null) - { - conductors.remove(i); - } - else if (((TileEntity)conductors.get(i)).isInvalid()) - { - conductors.remove(i); - } - } - } - - public void setID(int ID) - { - this.ID = ID; - this.cleanUpArray(); - - for (IConductor conductor : this.conductors) - { - conductor.setConnectionID(this.ID); - } - } - - public int getID() - { - return this.ID; - } - - public void meltDown() + public void addConductor(IConductor newConductor) { this.cleanUpArray(); - - for (int i = 0; i < conductors.size(); i++) - { - conductors.get(i).onConductorMelt(); - } + + if (!conductors.contains(newConductor)) + { + conductors.add(newConductor); + newConductor.setNetwork(this); + } } - + + /** + * Get only the electric units that can receive electricity from the given + * side. + */ + public List getConnectedReceivers() + { + this.cleanUpArray(); + List returnArray = new ArrayList(); + + for (IConductor conductor : conductors) + { + for (byte i = 0; i < conductor.getConnectedBlocks().length; i++) + { + TileEntity tileEntity = conductor.getConnectedBlocks()[i]; + + if (tileEntity != null) + { + if (tileEntity instanceof IElectricityReceiver) + { + if (!returnArray.contains((IElectricityReceiver) tileEntity) && ((IElectricityReceiver) tileEntity).canReceiveFromSide(ForgeDirection.getOrientation(i).getOpposite())) + { + returnArray.add((IElectricityReceiver) tileEntity); + } + } + } + } + } + + return returnArray; + } + + public void cleanUpArray() + { + for (int i = 0; i < conductors.size(); i++) + { + if (conductors.get(i) == null) + { + conductors.remove(i); + } + else if (((TileEntity) conductors.get(i)).isInvalid()) + { + conductors.remove(i); + } + } + } + + public void setNetwork() + { + this.cleanUpArray(); + + for (IConductor conductor : this.conductors) + { + conductor.setNetwork(this); + } + } + + public void onOverCharge() + { + this.cleanUpArray(); + + for (int i = 0; i < conductors.size(); i++) + { + conductors.get(i).onOverCharge(); + } + } + public double getLowestAmpConductor() { double lowestAmp = 0; - - for(IConductor conductor : conductors) + + for (IConductor conductor : conductors) { - if(lowestAmp == 0 || conductor.getMaxAmps() < lowestAmp) + if (lowestAmp == 0 || conductor.getMaxAmps() < lowestAmp) { lowestAmp = conductor.getMaxAmps(); } } - + return lowestAmp; } + + /** + * This function is called to refresh all conductors in this network + */ + public void refreshConductors() + { + for (int j = 0; j < this.conductors.size(); j++) + { + IConductor conductor = this.conductors.get(j); + conductor.refreshConnectedBlocks(); + } + } } diff --git a/src/common/universalelectricity/electricity/ElectricityTransferData.java b/src/common/universalelectricity/electricity/ElectricityTransferData.java old mode 100644 new mode 100755 index c512ee3ef..5ab909959 --- a/src/common/universalelectricity/electricity/ElectricityTransferData.java +++ b/src/common/universalelectricity/electricity/ElectricityTransferData.java @@ -9,34 +9,34 @@ public class ElectricityTransferData public TileEntity sender; public IElectricityReceiver receiver; public ElectricityNetwork network; - public double amps; - public double voltage; - public ForgeDirection side; + public double amps; + public double voltage; + public ForgeDirection side; - /** - * @param sender - Tile that's sending electricity. - * @param receiver - Receiver that's receiving electricity - * @param conductor - Conductor that is conducting the electricity - * @param side - - * @param amps - * @param voltage - */ - public ElectricityTransferData(TileEntity sender, IElectricityReceiver receiver, ElectricityNetwork network, ForgeDirection side, double amps, double voltage) - { - this.sender = sender; - this.receiver = receiver; - this.network = network; - this.side = side; - this.amps = amps; - this.voltage = voltage; - } - - public boolean isValid() - { - return this.sender != null && - this.receiver != null && - this.network != null && - this.amps > 0 && - this.voltage > 0; - } + /** + * @param sender + * - Tile that's sending electricity. + * @param receiver + * - Receiver that's receiving electricity + * @param conductor + * - Conductor that is conducting the electricity + * @param side + * - + * @param amps + * @param voltage + */ + public ElectricityTransferData(TileEntity sender, IElectricityReceiver receiver, ElectricityNetwork network, ForgeDirection side, double amps, double voltage) + { + this.sender = sender; + this.receiver = receiver; + this.network = network; + this.side = side; + this.amps = amps; + this.voltage = voltage; + } + + public boolean isValid() + { + return this.sender != null && this.receiver != null && this.network != null && this.amps > 0 && this.voltage > 0; + } } diff --git a/src/common/universalelectricity/implement/IConductor.java b/src/common/universalelectricity/implement/IConductor.java old mode 100644 new mode 100755 index 5b3a7bf63..5c495cbb7 --- a/src/common/universalelectricity/implement/IConductor.java +++ b/src/common/universalelectricity/implement/IConductor.java @@ -3,54 +3,67 @@ package universalelectricity.implement; import net.minecraft.src.TileEntity; import net.minecraft.src.World; import net.minecraftforge.common.ForgeDirection; +import universalelectricity.electricity.ElectricityNetwork; /** * Must be applied to all tile entities that are conductors. + * * @author Calclavia - * + * */ public interface IConductor extends IConnector { /** - * The ID of the connection this conductor is in. + * The electrical network this conductor is on. */ - public int getConnectionID(); - - public void setConnectionID(int ID); - + public ElectricityNetwork getNetwork(); + + public void setNetwork(ElectricityNetwork network); + /** * The UE tile entities that this conductor is connected to. + * * @return */ - public TileEntity[] getConnectedBlocks(); - + public TileEntity[] getConnectedBlocks(); + /** - * Gets the resistance of the conductor. Used to calculate energy loss. - * A higher resistance means a higher energy loss. - * @return The amount of Ohm's of resistance. - */ - public double getResistance(); - - /** - * The maximum amount of amps this conductor can handle before melting down. This is calculating - * PER TICK! - * @return The amount of amps in volts - */ - public double getMaxAmps(); - - /** - * Called when the electricity passing through exceeds the maximum voltage. - */ - public void onConductorMelt(); - - /** - * Resets the conductor and recalculate connection IDs again - */ - public void reset(); - - public World getWorld(); - - public void updateConnection(TileEntity tileEntity, ForgeDirection side); + * Gets the resistance of the conductor. Used to calculate energy loss. A + * higher resistance means a higher energy loss. + * + * @return The amount of Ohm's of resistance. + */ + public double getResistance(); + + /** + * The maximum amount of amps this conductor can handle before melting down. + * This is calculating PER TICK! + * + * @return The amount of amps in volts + */ + public double getMaxAmps(); + + /** + * Called when the electricity passing through exceeds the maximum voltage. + */ + public void onOverCharge(); + + /** + * Resets the conductor and recalculate connection IDs again + */ + public void reset(); + + public World getWorld(); + + /** + * Adds a connection between this conductor and a UE unit + * + * @param tileEntity + * - Must be either a producer, consumer or a conductor + * @param side + * - side in which the connection is coming from + */ + public void updateConnection(TileEntity tileEntity, ForgeDirection side); public void updateConnectionWithoutSplit(TileEntity connectorFromSide, ForgeDirection orientation); diff --git a/src/common/universalelectricity/implement/IConnector.java b/src/common/universalelectricity/implement/IConnector.java old mode 100644 new mode 100755 index fc8fac629..ddc2cb126 --- a/src/common/universalelectricity/implement/IConnector.java +++ b/src/common/universalelectricity/implement/IConnector.java @@ -3,16 +3,19 @@ package universalelectricity.implement; import net.minecraftforge.common.ForgeDirection; /** - * Applied to tile entities that can connect to UE wires. + * Applied to TileEntities that can connect to UE wires. + * * @author Calclavia - * + * */ public interface IConnector { - /** - * Can this tile entity visually connect to a wire on this specific side? - * @param side. 0-5 byte - * @return - True if so. - */ - public boolean canConnect(ForgeDirection side); + /** + * Can this tile entity visually connect to a wire on this specific side? + * + * @param side + * - The side in which the connection is coming from. + * @return - True if so. + */ + public boolean canConnect(ForgeDirection side); } diff --git a/src/common/universalelectricity/implement/IDisableable.java b/src/common/universalelectricity/implement/IDisableable.java old mode 100644 new mode 100755 index 16bc71610..30597cc25 --- a/src/common/universalelectricity/implement/IDisableable.java +++ b/src/common/universalelectricity/implement/IDisableable.java @@ -1,21 +1,26 @@ package universalelectricity.implement; /** - * This class should be applied to all tile entities (mainly machines) that can be disabled (by things like EMP, short circuit etc.). + * This class should be applied to all tile entities (mainly machines) that can + * be disabled (by things like EMP, short circuit etc.). + * * @author Calclavia - * + * */ public interface IDisableable { - /** - * This is called when the tile entity is to be disabled. - * @param duration - The duration of the disable in ticks. - */ - public void onDisable(int duration); + /** + * This is called when the tile entity is to be disabled. + * + * @param duration + * - The duration of the disable in ticks. + */ + public void onDisable(int duration); - /** - * Called to see if this tile entity is disabled. - * @return True if the tile entity is disabled. - */ - public boolean isDisabled(); + /** + * Called to see if this tile entity is disabled. + * + * @return True if the tile entity is disabled. + */ + public boolean isDisabled(); } diff --git a/src/common/universalelectricity/implement/IElectricityProducer.java b/src/common/universalelectricity/implement/IElectricityProducer.java old mode 100644 new mode 100755 index 71c16bedd..65a7b2be9 --- a/src/common/universalelectricity/implement/IElectricityProducer.java +++ b/src/common/universalelectricity/implement/IElectricityProducer.java @@ -4,14 +4,17 @@ import net.minecraftforge.common.ForgeDirection; /** * Applied to tile entities that can produce electricity + * * @author Calclavia */ public interface IElectricityProducer extends IConnector, IDisableable, IVoltage { - /** - * Can this machine visually connect to a wire on this specific side? - * @param side. 0-5 byte - * @return - True if so. - */ - public boolean canConnect(ForgeDirection side); + /** + * Can this machine visually connect to a wire on this specific side? + * + * @param side + * . 0-5 byte + * @return - True if so. + */ + public boolean canConnect(ForgeDirection side); } diff --git a/src/common/universalelectricity/implement/IElectricityReceiver.java b/src/common/universalelectricity/implement/IElectricityReceiver.java old mode 100644 new mode 100755 index 11bd4db99..9e9b81ed5 --- a/src/common/universalelectricity/implement/IElectricityReceiver.java +++ b/src/common/universalelectricity/implement/IElectricityReceiver.java @@ -3,33 +3,39 @@ package universalelectricity.implement; import net.minecraft.src.TileEntity; import net.minecraftforge.common.ForgeDirection; - /** - * The IElectricityReceiver interface is an interface that must be applied to all tile entities that can input or output electricity. + * The IElectricityReceiver interface is an interface that must be applied to + * all tile entities that can input or output electricity. + * * @author Calclavia - * + * */ public interface IElectricityReceiver extends IDisableable, IConnector, IVoltage { - /** - * Called every tick on this machine. - * - * @param amps - Amount of amps this electric unit is receiving. - * @param voltage - The voltage of the electricity sent. If more than one - * packet is being sent to you in this update, the highest voltage will - * override. - * @param side - The side of the block in which the electricity is coming from. - */ - public void onReceive(TileEntity sender, double amps, double voltage, ForgeDirection side); + /** + * Called every tick on this machine. + * + * @param amps + * - Amount of amps this electric unit is receiving. + * @param voltage + * - The voltage of the electricity sent. If more than one packet + * is being sent to you in this update, the highest voltage will + * override. + * @param side + * - The side of the block in which the electricity is coming + * from. + */ + public void onReceive(TileEntity sender, double amps, double voltage, ForgeDirection side); - /** - * How many watts does this electrical unit need this tick? - * Recommended for you to return the max electricity storage of this machine (if there is one). - */ - public double wattRequest(); + /** + * How many watts does this electrical unit need this tick? Recommended for + * you to return the max electricity storage of this machine (if there is + * one). + */ + public double wattRequest(); - /** - * Can this unit receive electricity from this specific side? - */ - public boolean canReceiveFromSide(ForgeDirection side); + /** + * Can this unit receive electricity from this specific side? + */ + public boolean canReceiveFromSide(ForgeDirection side); } \ No newline at end of file diff --git a/src/common/universalelectricity/implement/IItemElectric.java b/src/common/universalelectricity/implement/IItemElectric.java old mode 100644 new mode 100755 index 0efdab9b4..3d312a2ce --- a/src/common/universalelectricity/implement/IItemElectric.java +++ b/src/common/universalelectricity/implement/IItemElectric.java @@ -7,23 +7,27 @@ public interface IItemElectric extends IJouleStorage, IVoltage /** * Called when this item receives electricity. */ - public double onReceive(double amps, double voltage, ItemStack itemStack); - - /** - * Called when something requests electricity from this item. - * @return - The amount of given joules - */ - public double onUse(double joulesNeeded, ItemStack itemStack); - - /** - * @return Returns true or false if this consumer can receive electricity at this given tick or moment. - */ - public boolean canReceiveElectricity(); - - /** - * Can this item give out electricity when placed in an tile entity? Electric items like batteries - * should be able to produce electricity (if they are rechargeable). - * @return - True or False. - */ - public boolean canProduceElectricity(); + public double onReceive(double amps, double voltage, ItemStack itemStack); + + /** + * Called when something requests electricity from this item. + * + * @return - The amount of given joules + */ + public double onUse(double joulesNeeded, ItemStack itemStack); + + /** + * @return Returns true or false if this consumer can receive electricity at + * this given tick or moment. + */ + public boolean canReceiveElectricity(); + + /** + * Can this item give out electricity when placed in an tile entity? + * Electric items like batteries should be able to produce electricity (if + * they are rechargeable). + * + * @return - True or False. + */ + public boolean canProduceElectricity(); } diff --git a/src/common/universalelectricity/implement/IJouleStorage.java b/src/common/universalelectricity/implement/IJouleStorage.java old mode 100644 new mode 100755 index 6f83e17d9..ebb89ebb3 --- a/src/common/universalelectricity/implement/IJouleStorage.java +++ b/src/common/universalelectricity/implement/IJouleStorage.java @@ -1,7 +1,9 @@ package universalelectricity.implement; /** - * This interface is to be applied to all tile entities which stores energy within them. + * This interface is to be applied to all tile entities which stores energy + * within them. + * * @author Calclavia */ public interface IJouleStorage @@ -10,12 +12,12 @@ public interface IJouleStorage * Returns the amount of joules this unit has stored. */ public double getJoules(Object... data); - + /** * Sets the amount of joules this unit has stored. */ public void setJoules(double wattHours, Object... data); - + /** * Gets the maximum amount of joules this unit can store. */ diff --git a/src/common/universalelectricity/implement/IRedstoneProvider.java b/src/common/universalelectricity/implement/IRedstoneProvider.java old mode 100644 new mode 100755 index 9a272d2a2..ac9108ceb --- a/src/common/universalelectricity/implement/IRedstoneProvider.java +++ b/src/common/universalelectricity/implement/IRedstoneProvider.java @@ -2,12 +2,13 @@ package universalelectricity.implement; /** * This should be applied on tile entities that can provide redstone power + * * @author Henry - * + * */ public interface IRedstoneProvider { - public boolean isPoweringTo(byte side); + public boolean isPoweringTo(byte side); - public boolean isIndirectlyPoweringTo(byte side); + public boolean isIndirectlyPoweringTo(byte side); } diff --git a/src/common/universalelectricity/implement/IRedstoneReceptor.java b/src/common/universalelectricity/implement/IRedstoneReceptor.java old mode 100644 new mode 100755 index 425546ad2..053fd8ff8 --- a/src/common/universalelectricity/implement/IRedstoneReceptor.java +++ b/src/common/universalelectricity/implement/IRedstoneReceptor.java @@ -1,21 +1,21 @@ package universalelectricity.implement; /** - * OPTIONAL - * This interface should be applied onto all tile entities that needs to receive redstone power. - * Look at TileEntityBatteryBox for reference. + * OPTIONAL This interface should be applied onto all tile entities that needs + * to receive redstone power. Look at TileEntityBatteryBox for reference. + * * @author Calclavia - * + * */ public interface IRedstoneReceptor { - /** - * Called when the block is powered on by redstone - */ - public void onPowerOn(); + /** + * Called when the block is powered on by redstone + */ + public void onPowerOn(); - /** - * Called when the block is powered off by redstone - */ - public void onPowerOff(); + /** + * Called when the block is powered off by redstone + */ + public void onPowerOff(); } diff --git a/src/common/universalelectricity/implement/IRotatable.java b/src/common/universalelectricity/implement/IRotatable.java old mode 100644 new mode 100755 index ab42dd413..feb1fc301 --- a/src/common/universalelectricity/implement/IRotatable.java +++ b/src/common/universalelectricity/implement/IRotatable.java @@ -3,26 +3,31 @@ package universalelectricity.implement; import net.minecraftforge.common.ForgeDirection; /** - * OPTIONAL - * This interface should be applied onto all tile entities that are rotatable. This interface however is optional - * and you do not need it for your add-on to function. It just makes things easier for you to code. + * This interface should be applied onto all tile entities that are + * rotatable. This interface however is optional and you do not need it for your + * add-on to function. It just makes things easier for you to code. + * * @author Calclavia - * + * */ public interface IRotatable { - /** - * Gets the facing direction of the tile entity. Always returns the front side of the tile entity. - * @return The facing side from 0-5 The full list of which side the number represents - * is in the UniversalElectricity class. - */ - public ForgeDirection getDirection(); + /** + * Gets the facing direction of the tile entity. Always returns the front + * side of the tile entity. + * + * @return The facing side from 0-5 The full list of which side the number + * represents is in the UniversalElectricity class. + */ + public ForgeDirection getDirection(); - /** - * Sets the facing direction of the tile entity. - * @param facingDirection - A direction from 0-5. The full list of which side the number represents - * is in the UniversalElectricity class. - */ - public void setDirection(ForgeDirection facingDirection); + /** + * Sets the facing direction of the tile entity. + * + * @param facingDirection + * - A direction from 0-5. The full list of which side the number + * represents is in the UniversalElectricity class. + */ + public void setDirection(ForgeDirection facingDirection); } diff --git a/src/common/universalelectricity/implement/ITier.java b/src/common/universalelectricity/implement/ITier.java old mode 100644 new mode 100755 index ab5487eaa..5030f2c0b --- a/src/common/universalelectricity/implement/ITier.java +++ b/src/common/universalelectricity/implement/ITier.java @@ -1,21 +1,25 @@ package universalelectricity.implement; /** - * This interface should be applied to all things that has a tier/level + * This interface should be applied to all things that has a tier/level. + * * @author Calclavia - * + * */ public interface ITier { - /** - * Gets the tier of this object - * @return - The tier - */ - public int getTier(); + /** + * Gets the tier of this object + * + * @return - The tier + */ + public int getTier(); - /** - * Sets the tier of the object - * @param tier - The tier to be set - */ - public void setTier(int tier); + /** + * Sets the tier of the object + * + * @param tier + * - The tier to be set + */ + public void setTier(int tier); } diff --git a/src/common/universalelectricity/implement/IVoltage.java b/src/common/universalelectricity/implement/IVoltage.java old mode 100644 new mode 100755 index 53f9fa469..d4c6b9879 --- a/src/common/universalelectricity/implement/IVoltage.java +++ b/src/common/universalelectricity/implement/IVoltage.java @@ -1,10 +1,15 @@ package universalelectricity.implement; +/** + * Applies to all objects that has a voltage. + * @author Calclavia + * + */ public interface IVoltage { - /** - * Gets the voltage of this object. - * @return The amount of volts. E.g 120v or 240v - */ - public double getVoltage(); + /** + * Gets the voltage of this object. + * @return The amount of volts. E.g 120v or 240v + */ + public double getVoltage(); } diff --git a/src/common/universalelectricity/implement/UEDamageSource.java b/src/common/universalelectricity/implement/UEDamageSource.java old mode 100644 new mode 100755 index f3c583b05..ac17957b7 --- a/src/common/universalelectricity/implement/UEDamageSource.java +++ b/src/common/universalelectricity/implement/UEDamageSource.java @@ -9,21 +9,21 @@ import cpw.mods.fml.common.registry.LanguageRegistry; public class UEDamageSource extends DamageSource { public static final List damageSources = new ArrayList(); - + /** - * Use this damage source for all types of electrical attacks. - */ - public static final UEDamageSource electrocution = (UEDamageSource)new UEDamageSource("electrocution", "%1$s got electrocuted!").setDamageBypassesArmor(); - - public String deathMessage; - - public UEDamageSource(String damageType) + * Use this damage source for all types of electrical attacks. + */ + public static final UEDamageSource electrocution = (UEDamageSource) new UEDamageSource("electrocution", "%1$s got electrocuted!").setDamageBypassesArmor(); + + public String deathMessage; + + public UEDamageSource(String damageType) { super(damageType); damageSources.add(this); } - - public UEDamageSource(String damageType, String deathMessage) + + public UEDamageSource(String damageType, String deathMessage) { this(damageType); this.setDeathMessage(deathMessage); @@ -34,32 +34,24 @@ public class UEDamageSource extends DamageSource this.deathMessage = deathMessage; return this; } - - public static void registerDeathMesages() - { - for(UEDamageSource damageSource : damageSources) - { - damageSource.registerDeathMessage(); - } - } - + public DamageSource setDamageBypassesArmor() - { + { return super.setDamageBypassesArmor(); - } - + } + public DamageSource setDamageAllowedInCreativeMode() - { + { return super.setDamageAllowedInCreativeMode(); - } - + } + public DamageSource setFireDamage() - { + { return super.setFireDamage(); - } - + } + public void registerDeathMessage() { - LanguageRegistry.instance().addStringLocalization("death."+this.damageType, this.deathMessage); + LanguageRegistry.instance().addStringLocalization("death." + this.damageType, this.deathMessage); } } diff --git a/src/common/universalelectricity/network/IPacketReceiver.java b/src/common/universalelectricity/network/IPacketReceiver.java deleted file mode 100644 index 6a8564a3c..000000000 --- a/src/common/universalelectricity/network/IPacketReceiver.java +++ /dev/null @@ -1,15 +0,0 @@ -package universalelectricity.network; - -import net.minecraft.src.EntityPlayer; -import net.minecraft.src.NetworkManager; -import net.minecraft.src.Packet250CustomPayload; - -import com.google.common.io.ByteArrayDataInput; - -public interface IPacketReceiver -{ - /** - * Sends some data to the tile entity. - */ - public void handlePacketData(NetworkManager network, int packetType, Packet250CustomPayload packet, EntityPlayer player, ByteArrayDataInput dataStream); -} diff --git a/src/common/universalelectricity/network/ISimpleConnectionHandler.java b/src/common/universalelectricity/network/ISimpleConnectionHandler.java deleted file mode 100644 index 28586ed6c..000000000 --- a/src/common/universalelectricity/network/ISimpleConnectionHandler.java +++ /dev/null @@ -1,12 +0,0 @@ -package universalelectricity.network; - -import universalelectricity.network.ConnectionHandler.ConnectionType; - -public interface ISimpleConnectionHandler -{ - /** - * Called when a player logs in. Use this to reset some tile entities variables if you need to. - * @param player - */ - public void handelConnection(ConnectionType type, Object... data); -} diff --git a/src/common/universalelectricity/network/PacketManager.java b/src/common/universalelectricity/network/PacketManager.java deleted file mode 100644 index e7cee2651..000000000 --- a/src/common/universalelectricity/network/PacketManager.java +++ /dev/null @@ -1,264 +0,0 @@ -package universalelectricity.network; - -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import net.minecraft.src.EntityPlayer; -import net.minecraft.src.NetworkManager; -import net.minecraft.src.Packet; -import net.minecraft.src.Packet250CustomPayload; -import net.minecraft.src.TileEntity; -import net.minecraft.src.World; -import universalelectricity.prefab.Vector3; - -import com.google.common.io.ByteArrayDataInput; -import com.google.common.io.ByteStreams; - -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.network.IPacketHandler; -import cpw.mods.fml.common.network.PacketDispatcher; -import cpw.mods.fml.common.network.Player; - -/** - * This class is used for sending and receiving packets between the server - * and the client. You can directly use this by registering this packet manager - * with NetworkMod. Example: - * @NetworkMod(channels = { "BasicComponents" }, clientSideRequired = true, serverSideRequired = false, packetHandler = PacketManager.class) - * - * Check out {@link #BasicComponents} for better reference. - * - * @author Calclavia - */ -public class PacketManager implements IPacketHandler, IPacketReceiver -{ - public enum PacketType - { - UNSPECIFIED, TILEENTITY; - - public static PacketType get(int id) - { - if (id >= 0 && id < PacketType.values().length) - { - return PacketType.values()[id]; - } - return UNSPECIFIED; - } - } - - public static Packet getPacketWithID(String channelName, int id, Object... sendData) - { - ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - DataOutputStream data = new DataOutputStream(bytes); - - try - { - data.writeInt(id); - - data = encodeDataStream(data, sendData); - - Packet250CustomPayload packet = new Packet250CustomPayload(); - packet.channel = channelName; - packet.data = bytes.toByteArray(); - packet.length = packet.data.length; - - return packet; - } - catch (IOException e) - { - System.out.println("Failed to create packet."); - e.printStackTrace(); - } - - return null; - } - - public static Packet getPacket(String channelName, Object... sendData) - { - return getPacketWithID(channelName, PacketType.UNSPECIFIED.ordinal(), sendData); - } - - /** - * Gets a packet for the tile entity. - * @return - */ - public static Packet getPacket(String channelName, TileEntity sender, Object... sendData) - { - ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - DataOutputStream data = new DataOutputStream(bytes); - - try - { - data.writeInt(PacketType.TILEENTITY.ordinal()); - - data.writeInt(sender.xCoord); - data.writeInt(sender.yCoord); - data.writeInt(sender.zCoord); - data = encodeDataStream(data, sendData); - - Packet250CustomPayload packet = new Packet250CustomPayload(); - packet.channel = channelName; - packet.data = bytes.toByteArray(); - packet.length = packet.data.length; - - return packet; - } - catch (IOException e) - { - System.out.println("Failed to create packet."); - e.printStackTrace(); - } - - return null; - } - - /** - * Sends packets to clients around a specific coordinate. A wrapper using Vector3. - * See {@PacketDispatcher} for detailed information. - */ - public static void sendPacketToClients(Packet packet, World worldObj, Vector3 position, double range) - { - try - { - PacketDispatcher.sendPacketToAllAround(position.x, position.y, position.z, range, worldObj.provider.dimensionId, packet); - } - catch (Exception e) - { - System.out.println("Sending packet to client failed."); - e.printStackTrace(); - } - } - - /** - * Sends a packet to all the clients on this server. - */ - public static void sendPacketToClients(Packet packet, World worldObj) - { - try - { - PacketDispatcher.sendPacketToAllInDimension(packet, worldObj.provider.dimensionId); - } - catch (Exception e) - { - System.out.println("Sending packet to client failed."); - e.printStackTrace(); - } - } - - public static void sendPacketToClients(Packet packet) - { - try - { - if(FMLCommonHandler.instance().getMinecraftServerInstance() != null) - { - FMLCommonHandler.instance().getMinecraftServerInstance().getConfigurationManager().sendPacketToAllPlayers(packet); - } - } - catch (Exception e) - { - System.out.println("Sending packet to client failed."); - e.printStackTrace(); - } - } - - public static DataOutputStream encodeDataStream(DataOutputStream data, Object... sendData) - { - try - { - for(Object dataValue : sendData) - { - if(dataValue instanceof Integer) - { - data.writeInt((Integer)dataValue); - } - else if(dataValue instanceof Float) - { - data.writeFloat((Float)dataValue); - } - else if(dataValue instanceof Double) - { - data.writeDouble((Double)dataValue); - } - else if(dataValue instanceof Byte) - { - data.writeByte((Byte)dataValue); - } - else if(dataValue instanceof Boolean) - { - data.writeBoolean((Boolean)dataValue); - } - else if(dataValue instanceof String) - { - data.writeUTF((String)dataValue); - } - else if(dataValue instanceof Short) - { - data.writeShort((Short)dataValue); - } - else if(dataValue instanceof Long) - { - data.writeLong((Long)dataValue); - } - } - - return data; - - } - catch (IOException e) - { - System.out.println("Packet data encoding failed."); - e.printStackTrace(); - } - - return data; - } - - @Override - public void onPacketData(NetworkManager network, Packet250CustomPayload packet, Player player) - { - try - { - ByteArrayDataInput data = ByteStreams.newDataInput(packet.data); - - int packetTypeID = data.readInt(); - - PacketType packetType = PacketType.get(packetTypeID); - - if(packetType == PacketType.TILEENTITY) - { - int x = data.readInt(); - int y = data.readInt(); - int z = data.readInt(); - - World world = ((EntityPlayer)player).worldObj; - - if(world != null) - { - TileEntity tileEntity = world.getBlockTileEntity(x, y, z); - - if(tileEntity != null) - { - if(tileEntity instanceof IPacketReceiver) - { - ((IPacketReceiver)tileEntity).handlePacketData(network, packetTypeID, packet, ((EntityPlayer)player), data); - } - } - } - } - else - { - this.handlePacketData(network, packetTypeID, packet, ((EntityPlayer)player), data); - } - } - catch(Exception e) - { - e.printStackTrace(); - } - } - - @Override - public void handlePacketData(NetworkManager network, int packetType, Packet250CustomPayload packet, EntityPlayer player, ByteArrayDataInput dataStream) - { - - } -} diff --git a/src/common/universalelectricity/network/UECommand.java b/src/common/universalelectricity/network/UECommand.java deleted file mode 100644 index 4e63aeabc..000000000 --- a/src/common/universalelectricity/network/UECommand.java +++ /dev/null @@ -1,49 +0,0 @@ -package universalelectricity.network; - -import java.util.Arrays; -import java.util.List; - -import net.minecraft.src.CommandBase; -import net.minecraft.src.ICommand; -import net.minecraft.src.ICommandSender; -import net.minecraft.src.WrongUsageException; -import universalelectricity.UniversalElectricity; - -public class UECommand extends CommandBase -{ - @Override - public int compareTo(Object arg0) - { - return this.getCommandName().compareTo(((ICommand)arg0).getCommandName()); - } - - @Override - public String getCommandName() - { - return "universalelectricity"; - } - - @Override - public String getCommandUsage(ICommandSender sender) - { - return "/" + this.getCommandName(); - } - - @Override - public List getCommandAliases() - { - return Arrays.asList(new String[]{"ue"}); - } - - @Override - public void processCommand(ICommandSender sender, String[] arguments) - { - if(arguments.length <= 0) - { - sender.sendChatToPlayer(String.format("You are using Universal Electricity v" + UniversalElectricity.VERSION)); - return; - } - - throw new WrongUsageException(this.getCommandUsage(sender)); - } -} \ No newline at end of file diff --git a/src/common/universalelectricity/ore/OreGenBase.java b/src/common/universalelectricity/ore/OreGenBase.java deleted file mode 100644 index d93f775e7..000000000 --- a/src/common/universalelectricity/ore/OreGenBase.java +++ /dev/null @@ -1,91 +0,0 @@ -package universalelectricity.ore; - -import java.util.Random; - -import net.minecraft.src.Block; -import net.minecraft.src.IChunkProvider; -import net.minecraft.src.ItemStack; -import net.minecraft.src.World; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.oredict.OreDictionary; -import universalelectricity.UEConfig; -import universalelectricity.UniversalElectricity; - -/** - * This class is used for storing ore generation data. If you are too - * lazy to generate your own ores, you can do {@link #OreGenerator.ORES_TO_GENERATE.add()} - * to add your ore to the list of ores to generate. - * @author Calclavia - * - */ -public abstract class OreGenBase -{ - public String name; - - public String oreDictionaryName; - - public boolean shouldGenerate; - - public int blockIndexTexture; - - public ItemStack oreStack; - - public int oreID; - - public int oreMeta; - - /** - * What harvest level does this machine need to be acquired? - */ - public int harvestLevel; - - /** - * The predefined tool classes are "pickaxe", "shovel", "axe". You can add others for custom tools. - */ - public String harvestTool; - - /** - * @param name - The name of the ore for display - * @param textureFile - The 16x16 png texture of your ore to override - * @param minGenerateLevel - The highest generation level of your ore - * @param maxGenerateLevel - The lowest generation level of your ore - * @param amountPerChunk - The amount of ores to generate per chunk - * @param amountPerBranch - The amount of ores to generate in a clutter. E.g coal generates with a lot of other coal next to it. How much do you want? - */ - public OreGenBase(String name, String oreDiectionaryName, ItemStack stack, String harvestTool, int harvestLevel) - { - this.name = name; - this.shouldGenerate = false; - this.harvestTool = harvestTool; - this.harvestLevel = harvestLevel; - this.oreDictionaryName = oreDiectionaryName; - this.oreStack = stack; - this.oreID = stack.itemID; - this.oreMeta = stack.getItemDamage(); - - OreDictionary.registerOre(oreDictionaryName, stack); - MinecraftForge.setBlockHarvestLevel(Block.blocksList[stack.itemID], stack.getItemDamage(), harvestTool, harvestLevel); - } - - public OreGenBase enable() - { - this.shouldGenerate = shouldGenerateOre(name); - return this; - } - - //You may inherit from this class and change this function if you want a custom texture render for your ore. - public int getBlockTextureFromSide(int side) - { - return this.blockIndexTexture; - } - - //Checks the config file and see if Universal Electricity should generate this ore - private static boolean shouldGenerateOre(String oreName) - { - return UEConfig.getConfigData(UniversalElectricity.CONFIGURATION, "Generate " + oreName, true); - } - - public abstract void generate(World world, Random random, int varX, int varZ); - - public abstract boolean isOreGeneratedInWorld(World world, IChunkProvider chunkGenerator); -} diff --git a/src/common/universalelectricity/ore/OreGenReplace.java b/src/common/universalelectricity/ore/OreGenReplace.java deleted file mode 100644 index cddc12b07..000000000 --- a/src/common/universalelectricity/ore/OreGenReplace.java +++ /dev/null @@ -1,128 +0,0 @@ -package universalelectricity.ore; - -import java.util.Random; - -import net.minecraft.src.ChunkProviderEnd; -import net.minecraft.src.ChunkProviderGenerate; -import net.minecraft.src.ChunkProviderHell; -import net.minecraft.src.IChunkProvider; -import net.minecraft.src.ItemStack; -import net.minecraft.src.MathHelper; -import net.minecraft.src.World; - -/** - * This class is used for storing ore generation data. If you are too - * lazy to generate your own ores, you can do {@link #OreGenerator.ORES_TO_GENERATE.add()} - * to add your ore to the list of ores to generate. - * @author Calclavia - * - */ -public class OreGenReplace extends OreGenBase -{ - - public int minGenerateLevel; - public int maxGenerateLevel; - public int amountPerChunk; - public int amountPerBranch; - public int replaceID; - - public boolean generateSurface; - public boolean generateNether; - public boolean generateEnd; - - /** - * @param name - The name of the ore for display - * @param textureFile - The 16x16 png texture of your ore to override - * @param minGenerateLevel - The highest generation level of your ore - * @param maxGenerateLevel - The lowest generation level of your ore - * @param amountPerChunk - The amount of ores to generate per chunk - * @param amountPerBranch - The amount of ores to generate in a clutter. E.g coal generates with a lot of other coal next to it. How much do you want? - */ - public OreGenReplace(String name, String oreDiectionaryName, ItemStack stack, int replaceID, int minGenerateLevel, int maxGenerateLevel, int amountPerChunk, int amountPerBranch, String harvestTool, int harvestLevel) - { - super(name, oreDiectionaryName, stack, harvestTool, harvestLevel); - this.minGenerateLevel = minGenerateLevel; - this.maxGenerateLevel = maxGenerateLevel; - this.amountPerChunk = amountPerChunk; - this.amountPerBranch = amountPerBranch; - this.replaceID = replaceID; - } - - public void generate(World world, Random random, int varX, int varZ) - { - - for (int i = 0; i < this.amountPerChunk; i++) - { - int x = varX + random.nextInt(16); - int z = varZ + random.nextInt(16); - int y = random.nextInt(this.maxGenerateLevel-this.minGenerateLevel) + this.minGenerateLevel; - generateReplace(world, random, x, y, z); - } - } - - - public boolean generateReplace(World par1World, Random par2Random, int par3, int par4, int par5) - { - float var6 = par2Random.nextFloat() * (float)Math.PI; - double var7 = (double)((float)(par3 + 8) + MathHelper.sin(var6) * (float)this.amountPerBranch / 8.0F); - double var9 = (double)((float)(par3 + 8) - MathHelper.sin(var6) * (float)this.amountPerBranch / 8.0F); - double var11 = (double)((float)(par5 + 8) + MathHelper.cos(var6) * (float)this.amountPerBranch / 8.0F); - double var13 = (double)((float)(par5 + 8) - MathHelper.cos(var6) * (float)this.amountPerBranch / 8.0F); - double var15 = (double)(par4 + par2Random.nextInt(3) - 2); - double var17 = (double)(par4 + par2Random.nextInt(3) - 2); - - for (int var19 = 0; var19 <= this.amountPerBranch; ++var19) - { - double var20 = var7 + (var9 - var7) * (double)var19 / (double)this.amountPerBranch; - double var22 = var15 + (var17 - var15) * (double)var19 / (double)this.amountPerBranch; - double var24 = var11 + (var13 - var11) * (double)var19 / (double)this.amountPerBranch; - double var26 = par2Random.nextDouble() * (double)this.amountPerBranch / 16.0D; - double var28 = (double)(MathHelper.sin((float)var19 * (float)Math.PI / (float)this.amountPerBranch) + 1.0F) * var26 + 1.0D; - double var30 = (double)(MathHelper.sin((float)var19 * (float)Math.PI / (float)this.amountPerBranch) + 1.0F) * var26 + 1.0D; - int var32 = MathHelper.floor_double(var20 - var28 / 2.0D); - int var33 = MathHelper.floor_double(var22 - var30 / 2.0D); - int var34 = MathHelper.floor_double(var24 - var28 / 2.0D); - int var35 = MathHelper.floor_double(var20 + var28 / 2.0D); - int var36 = MathHelper.floor_double(var22 + var30 / 2.0D); - int var37 = MathHelper.floor_double(var24 + var28 / 2.0D); - - for (int var38 = var32; var38 <= var35; ++var38) - { - double var39 = ((double)var38 + 0.5D - var20) / (var28 / 2.0D); - - if (var39 * var39 < 1.0D) - { - for (int var41 = var33; var41 <= var36; ++var41) - { - double var42 = ((double)var41 + 0.5D - var22) / (var30 / 2.0D); - - if (var39 * var39 + var42 * var42 < 1.0D) - { - for (int var44 = var34; var44 <= var37; ++var44) - { - double var45 = ((double)var44 + 0.5D - var24) / (var28 / 2.0D); - - int block = par1World.getBlockId(var38, var41, var44); - if (var39 * var39 + var42 * var42 + var45 * var45 < 1.0D && (this.replaceID == 0 || block==this.replaceID)) - { - par1World.setBlockAndMetadata(var38, var41, var44, this.oreID, this.oreMeta); - } - } - } - } - } - } - } - - return true; - } - - @Override - public boolean isOreGeneratedInWorld(World world, IChunkProvider chunkGenerator) - { - return ((this.generateSurface && chunkGenerator instanceof ChunkProviderGenerate) || - (this.generateNether && chunkGenerator instanceof ChunkProviderHell) || - (this.generateEnd && chunkGenerator instanceof ChunkProviderEnd) - ); - } -} diff --git a/src/common/universalelectricity/ore/OreGenReplaceStone.java b/src/common/universalelectricity/ore/OreGenReplaceStone.java deleted file mode 100644 index 094574265..000000000 --- a/src/common/universalelectricity/ore/OreGenReplaceStone.java +++ /dev/null @@ -1,18 +0,0 @@ -package universalelectricity.ore; - -import net.minecraft.src.ItemStack; - -public class OreGenReplaceStone extends OreGenReplace -{ - public OreGenReplaceStone(String name, String oreDiectionaryName, ItemStack stack, int replaceID, int minGenerateLevel, int maxGenerateLevel, int amountPerChunk, int amountPerBranch, String harvestTool, int harvestLevel) - { - super(name, oreDiectionaryName, stack, 1, minGenerateLevel, maxGenerateLevel, amountPerChunk, amountPerBranch, harvestTool, harvestLevel); - this.generateSurface = true; - } - - //A simplified version of the constructor - public OreGenReplaceStone(String name, String oreDiectionaryName, ItemStack stack, int replaceID, int maxGenerateLevel, int amountPerChunk, int amountPerBranch) - { - this(name, oreDiectionaryName, stack, 0, replaceID, maxGenerateLevel, amountPerChunk, amountPerBranch, "pickaxe", 1); - } -} \ No newline at end of file diff --git a/src/common/universalelectricity/prefab/AdvancedTile.java b/src/common/universalelectricity/prefab/AdvancedTile.java deleted file mode 100644 index a64cb44a7..000000000 --- a/src/common/universalelectricity/prefab/AdvancedTile.java +++ /dev/null @@ -1,57 +0,0 @@ -package universalelectricity.prefab; - -import net.minecraft.src.Block; -import net.minecraft.src.TileEntity; - -/** - * A TileEntity with some pre-added functionalities. - * @author Calclavia - * - */ -public abstract class AdvancedTile extends TileEntity -{ - protected long ticks = 0; - - @Override - public void updateEntity() - { - if(this.ticks == 0) - { - this.initiate(); - } - - if(this.ticks >= Long.MAX_VALUE) - { - this.ticks = 1; - } - - this.ticks ++; - } - - /** - * Called on the TileEntity's first tick. - */ - protected void initiate() { } - - @Override - public int getBlockMetadata() - { - if (this.blockMetadata == -1) - { - this.blockMetadata = this.worldObj.getBlockMetadata(this.xCoord, this.yCoord, this.zCoord); - } - - return this.blockMetadata; - } - - @Override - public Block getBlockType() - { - if (this.blockType == null) - { - this.blockType = Block.blocksList[this.worldObj.getBlockId(this.xCoord, this.yCoord, this.zCoord)]; - } - - return this.blockType; - } -} diff --git a/src/common/universalelectricity/prefab/BlockConductor.java b/src/common/universalelectricity/prefab/BlockConductor.java old mode 100644 new mode 100755 index 0f7583c9d..7522d4cb7 --- a/src/common/universalelectricity/prefab/BlockConductor.java +++ b/src/common/universalelectricity/prefab/BlockConductor.java @@ -4,52 +4,52 @@ import net.minecraft.src.BlockContainer; import net.minecraft.src.Material; import net.minecraft.src.TileEntity; import net.minecraft.src.World; -import net.minecraftforge.common.ForgeDirection; import universalelectricity.implement.IConductor; public abstract class BlockConductor extends BlockContainer { - public BlockConductor(int id, Material material) - { - super(id, material); - } + public BlockConductor(int id, Material material) + { + super(id, material); + } - /** - * Called whenever the block is added into the world. Args: world, x, y, z - */ - @Override - public void onBlockAdded(World world, int x, int y, int z) - { - super.onBlockAdded(world, x, y, z); - this.updateConductorTileEntity(world, x, y, z); - } + /** + * Called whenever the block is added into the world. Args: world, x, y, z + */ + @Override + public void onBlockAdded(World world, int x, int y, int z) + { + super.onBlockAdded(world, x, y, z); + + TileEntity tileEntity = world.getBlockTileEntity(x, y, z); + + if(tileEntity != null) + { + if(tileEntity instanceof IConductor) + { + ((IConductor)tileEntity).refreshConnectedBlocks(); + } + } + } - /** - * Lets the block know when one of its neighbor changes. Doesn't know which neighbor changed (coordinates passed are - * their own) Args: x, y, z, neighbor blockID - */ - @Override - public void onNeighborBlockChange(World world, int x, int y, int z, int blockID) - { - this.updateConductorTileEntity(world, x, y, z); - world.markBlockNeedsUpdate(x, y, z); - } - - public static void updateConductorTileEntity(World world, int x, int y, int z) - { - TileEntity tileEntity = world.getBlockTileEntity(x, y, z); - - if (tileEntity != null) - { - if(tileEntity instanceof IConductor) - { - IConductor conductorTileEntity = (IConductor)tileEntity; - - for (byte i = 0; i < 6; i++) - { - conductorTileEntity.updateConnection(Vector3.getConnectorFromSide(world, new Vector3(x, y, z), ForgeDirection.getOrientation(i)), ForgeDirection.getOrientation(i)); - } - } - } - } + /** + * Lets the block know when one of its neighbor changes. Doesn't know which + * neighbor changed (coordinates passed are their own) Args: x, y, z, + * neighbor blockID + */ + @Override + public void onNeighborBlockChange(World world, int x, int y, int z, int blockID) + { + TileEntity tileEntity = world.getBlockTileEntity(x, y, z); + + if(tileEntity != null) + { + if(tileEntity instanceof IConductor) + { + ((IConductor)tileEntity).refreshConnectedBlocks(); + } + } + + world.markBlockNeedsUpdate(x, y, z); + } } diff --git a/src/common/universalelectricity/prefab/BlockMachine.java b/src/common/universalelectricity/prefab/BlockMachine.java old mode 100644 new mode 100755 index 2dbfa1dd1..ea05c0bc5 --- a/src/common/universalelectricity/prefab/BlockMachine.java +++ b/src/common/universalelectricity/prefab/BlockMachine.java @@ -16,207 +16,211 @@ import universalelectricity.implement.IItemElectric; import buildcraft.api.tools.IToolWrench; /** - * A block you may extend from to create your machine blocks! You do not have to extend from this block if - * you do not want to. It's optional but it comes with some useful functions that will make coding easier - * for you. + * A block you may extend from to create your machine blocks! You do not have to + * extend from this block if you do not want to. It's optional but it comes with + * some useful functions that will make coding easier for you. */ public abstract class BlockMachine extends BlockContainer { - public BlockMachine(String name, int id, Material material) - { - super(id, material); - this.setBlockName(name); - this.setHardness(0.5F); - } - - public BlockMachine(String name, int id, Material material, CreativeTabs creativeTab) - { - this(name, id, material); - this.setCreativeTab(creativeTab); - } + public BlockMachine(String name, int id, Material material) + { + super(id, material); + this.setBlockName(name); + this.setHardness(0.5F); + } - @Override - protected int damageDropped(int metadata) - { - return metadata; - } + public BlockMachine(String name, int id, Material material, CreativeTabs creativeTab) + { + this(name, id, material); + this.setCreativeTab(creativeTab); + } - /** - * Returns the quantity of items to drop on block destruction. - */ - @Override - public int quantityDropped(Random par1Random) - { - return 1; - } + @Override + public int damageDropped(int metadata) + { + return metadata; + } - /** - * Returns the ID of the items to drop on destruction. - */ - @Override - public int idDropped(int par1, Random par2Random, int par3) - { - return this.blockID; - } + /** + * Returns the quantity of items to drop on block destruction. + */ + @Override + public int quantityDropped(Random par1Random) + { + return 1; + } - /** - * DO NOT OVERRIDE THIS FUNCTION! - * Called when the block is right clicked by the player. This modified version detects - * electric items and wrench actions on your machine block. Do not override this function. - * Use machineActivated instead! (It does the same thing) - */ - @Override - public boolean onBlockActivated(World par1World, int x, int y, int z, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) - { - int metadata = par1World.getBlockMetadata(x, y, z); + /** + * Returns the ID of the items to drop on destruction. + */ + @Override + public int idDropped(int par1, Random par2Random, int par3) + { + return this.blockID; + } - /** - * Check if the player is holding a wrench or an electric item. If so, do not open the GUI. - */ - if (par5EntityPlayer.inventory.getCurrentItem() != null) - { - if (par5EntityPlayer.inventory.getCurrentItem().getItem() instanceof IToolWrench) - { - par1World.notifyBlocksOfNeighborChange(x, y, z, this.blockID); - ((IToolWrench)par5EntityPlayer.inventory.getCurrentItem().getItem()).wrenchUsed(par5EntityPlayer, x, y, z); - - if(par5EntityPlayer.isSneaking()) - { - return this.onSneakUseWrench(par1World, x, y, z, par5EntityPlayer); - } - else - { - return this.onUseWrench(par1World, x, y, z, par5EntityPlayer); - } - } - else if (par5EntityPlayer.inventory.getCurrentItem().getItem() instanceof IItemElectric) - { - if(this.onUseElectricItem(par1World, x, y, z, par5EntityPlayer)) - { - return true; - } - } - } + /** + * DO NOT OVERRIDE THIS FUNCTION! Called when the block is right clicked by + * the player. This modified version detects electric items and wrench + * actions on your machine block. Do not override this function. Use + * machineActivated instead! (It does the same thing) + */ + @Override + public boolean onBlockActivated(World par1World, int x, int y, int z, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) + { + int metadata = par1World.getBlockMetadata(x, y, z); - if(par5EntityPlayer.isSneaking()) - { - return this.onSneakMachineActivated(par1World, x, y, z, par5EntityPlayer); - } - else - { - return this.onMachineActivated(par1World, x, y, z, par5EntityPlayer); - } - } + /** + * Check if the player is holding a wrench or an electric item. If so, + * do not open the GUI. + */ + if (par5EntityPlayer.inventory.getCurrentItem() != null) + { + if (par5EntityPlayer.inventory.getCurrentItem().getItem() instanceof IToolWrench) + { + par1World.notifyBlocksOfNeighborChange(x, y, z, this.blockID); + ((IToolWrench) par5EntityPlayer.inventory.getCurrentItem().getItem()).wrenchUsed(par5EntityPlayer, x, y, z); - /** - * Called when the machine is right clicked by the player - * @return True if something happens - */ - public boolean onMachineActivated(World par1World, int x, int y, int z, EntityPlayer par5EntityPlayer) - { - return false; - } - - /** - * Called when the machine is right clicked by the player while sneaking (shift clicking) - * @return True if something happens - */ - public boolean onSneakMachineActivated(World par1World, int x, int y, int z, EntityPlayer par5EntityPlayer) - { - return false; - } + if (par5EntityPlayer.isSneaking()) + { + return this.onSneakUseWrench(par1World, x, y, z, par5EntityPlayer); + } + else + { + return this.onUseWrench(par1World, x, y, z, par5EntityPlayer); + } + } + else if (par5EntityPlayer.inventory.getCurrentItem().getItem() instanceof IItemElectric) + { + if (this.onUseElectricItem(par1World, x, y, z, par5EntityPlayer)) { return true; } + } + } - /** - * Called when a player uses an electric item on the machine - * @return True if some happens - */ - public boolean onUseElectricItem(World par1World, int x, int y, int z, EntityPlayer par5EntityPlayer) - { - return false; - } + if (par5EntityPlayer.isSneaking()) + { + return this.onSneakMachineActivated(par1World, x, y, z, par5EntityPlayer); + } + else + { + return this.onMachineActivated(par1World, x, y, z, par5EntityPlayer); + } + } - /** - * Called when a player uses a wrench on the machine - * @return True if some happens - */ - public boolean onUseWrench(World par1World, int x, int y, int z, EntityPlayer par5EntityPlayer) - { - return false; - } - - /** - * Called when a player uses a wrench on the machine while sneaking - * @return True if some happens - */ - public boolean onSneakUseWrench(World par1World, int x, int y, int z, EntityPlayer par5EntityPlayer) - { - return this.onUseWrench(par1World, x, y, z, par5EntityPlayer); - } + /** + * Called when the machine is right clicked by the player + * + * @return True if something happens + */ + public boolean onMachineActivated(World par1World, int x, int y, int z, EntityPlayer par5EntityPlayer) + { + return false; + } - /** - * Returns the TileEntity used by this block. - * You should use the metadata sensitive version of this to get the maximum optimization! - */ - @Override - public TileEntity createNewTileEntity(World var1) - { - return null; - } + /** + * Called when the machine is right clicked by the player while sneaking + * (shift clicking) + * + * @return True if something happens + */ + public boolean onSneakMachineActivated(World par1World, int x, int y, int z, EntityPlayer par5EntityPlayer) + { + return false; + } - /** - * Override this if you don't need it. This will eject all items out - * of this machine if it has an inventory - */ - @Override - public void breakBlock(World par1World, int x, int y, int z, int par5, int par6) - { - TileEntity tileEntity = par1World.getBlockTileEntity(x, y, z); + /** + * Called when a player uses an electric item on the machine + * + * @return True if some happens + */ + public boolean onUseElectricItem(World par1World, int x, int y, int z, EntityPlayer par5EntityPlayer) + { + return false; + } - if(tileEntity != null) - { - if(tileEntity instanceof IInventory) - { - IInventory inventory = (IInventory)tileEntity; - - for (int var6 = 0; var6 < inventory.getSizeInventory(); ++var6) - { - ItemStack var7 = inventory.getStackInSlot(var6); - - if (var7 != null) - { - Random random = new Random(); - float var8 = random.nextFloat() * 0.8F + 0.1F; - float var9 = random.nextFloat() * 0.8F + 0.1F; - float var10 = random.nextFloat() * 0.8F + 0.1F; - - while (var7.stackSize > 0) - { - int var11 = random.nextInt(21) + 10; - - if (var11 > var7.stackSize) - { - var11 = var7.stackSize; - } - - var7.stackSize -= var11; - EntityItem var12 = new EntityItem(par1World, (x + var8), (y + var9), (z + var10), new ItemStack(var7.itemID, var11, var7.getItemDamage())); - - if (var7.hasTagCompound()) - { - var12.item.setTagCompound((NBTTagCompound)var7.getTagCompound().copy()); - } - - float var13 = 0.05F; - var12.motionX = ((float)random.nextGaussian() * var13); - var12.motionY = ((float)random.nextGaussian() * var13 + 0.2F); - var12.motionZ = ((float)random.nextGaussian() * var13); - par1World.spawnEntityInWorld(var12); - } - } - } - } - } + /** + * Called when a player uses a wrench on the machine + * + * @return True if some happens + */ + public boolean onUseWrench(World par1World, int x, int y, int z, EntityPlayer par5EntityPlayer) + { + return false; + } - super.breakBlock(par1World, x, y, z, par5, par6); - } + /** + * Called when a player uses a wrench on the machine while sneaking + * + * @return True if some happens + */ + public boolean onSneakUseWrench(World par1World, int x, int y, int z, EntityPlayer par5EntityPlayer) + { + return this.onUseWrench(par1World, x, y, z, par5EntityPlayer); + } + + /** + * Returns the TileEntity used by this block. You should use the metadata + * sensitive version of this to get the maximum optimization! + */ + @Override + public TileEntity createNewTileEntity(World var1) + { + return null; + } + + /** + * Override this if you don't need it. This will eject all items out of this + * machine if it has an inventory + */ + @Override + public void breakBlock(World par1World, int x, int y, int z, int par5, int par6) + { + TileEntity tileEntity = par1World.getBlockTileEntity(x, y, z); + + if (tileEntity != null) + { + if (tileEntity instanceof IInventory) + { + IInventory inventory = (IInventory) tileEntity; + + for (int var6 = 0; var6 < inventory.getSizeInventory(); ++var6) + { + ItemStack var7 = inventory.getStackInSlot(var6); + + if (var7 != null) + { + Random random = new Random(); + float var8 = random.nextFloat() * 0.8F + 0.1F; + float var9 = random.nextFloat() * 0.8F + 0.1F; + float var10 = random.nextFloat() * 0.8F + 0.1F; + + while (var7.stackSize > 0) + { + int var11 = random.nextInt(21) + 10; + + if (var11 > var7.stackSize) + { + var11 = var7.stackSize; + } + + var7.stackSize -= var11; + EntityItem var12 = new EntityItem(par1World, (x + var8), (y + var9), (z + var10), new ItemStack(var7.itemID, var11, var7.getItemDamage())); + + if (var7.hasTagCompound()) + { + var12.item.setTagCompound((NBTTagCompound) var7.getTagCompound().copy()); + } + + float var13 = 0.05F; + var12.motionX = ((float) random.nextGaussian() * var13); + var12.motionY = ((float) random.nextGaussian() * var13 + 0.2F); + var12.motionZ = ((float) random.nextGaussian() * var13); + par1World.spawnEntityInWorld(var12); + } + } + } + } + } + + super.breakBlock(par1World, x, y, z, par5, par6); + } } diff --git a/src/common/universalelectricity/prefab/CommonProxy.java b/src/common/universalelectricity/prefab/CommonProxy.java deleted file mode 100644 index f8202f001..000000000 --- a/src/common/universalelectricity/prefab/CommonProxy.java +++ /dev/null @@ -1,25 +0,0 @@ -package universalelectricity.prefab; - -import net.minecraft.src.EntityPlayer; -import net.minecraft.src.World; -import cpw.mods.fml.common.network.IGuiHandler; - -/** - * A class used to easily manuver between client and server. - * - */ -public abstract class CommonProxy implements IGuiHandler -{ - public void preInit() { } - - public void init() { } - - public void postInit() { } - - @Override - public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { return null; } - - @Override - public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { return null; } - -} diff --git a/src/common/universalelectricity/prefab/ItemElectric.java b/src/common/universalelectricity/prefab/ItemElectric.java old mode 100644 new mode 100755 index 7ba23a0d4..5451bdf71 --- a/src/common/universalelectricity/prefab/ItemElectric.java +++ b/src/common/universalelectricity/prefab/ItemElectric.java @@ -15,174 +15,193 @@ import universalelectricity.electricity.ElectricInfo.ElectricUnit; import universalelectricity.implement.IItemElectric; /** - * Extend from this class if your item requires electricity or to be charged. Optionally, you can implement IItemElectric instead. + * Extend from this class if your item requires electricity or to be charged. + * Optionally, you can implement IItemElectric instead. + * * @author Calclavia - * + * */ public abstract class ItemElectric extends Item implements IItemElectric { - public ItemElectric(int id, CreativeTabs tabs) - { - super(id); - this.setMaxStackSize(1); - this.setMaxDamage((int)this.getMaxJoules()); - this.setNoRepair(); - this.setCreativeTab(tabs); - } - - public ItemElectric(int id) - { - this(id, CreativeTabs.tabTools); - } + public ItemElectric(int id, CreativeTabs tabs) + { + super(id); + this.setMaxStackSize(1); + this.setMaxDamage((int) this.getMaxJoules()); + this.setNoRepair(); + this.setCreativeTab(tabs); + } - /** - * Allows items to add custom lines of information to the mouseover description. If you want to add more - * information to your item, you can super.addInformation() to keep the electiricty info in the item info bar. - */ - @Override - public void addInformation(ItemStack par1ItemStack, List par2List) - { - String color = ""; - double joules = this.getJoules(par1ItemStack); + public ItemElectric(int id) + { + this(id, CreativeTabs.tabTools); + } - if (joules <= this.getMaxJoules() / 3) - { - color = "\u00a74"; - } - else if (joules > this.getMaxJoules() * 2 / 3) - { - color = "\u00a72"; - } - else - { - color = "\u00a76"; - } + /** + * Allows items to add custom lines of information to the mouseover + * description. If you want to add more information to your item, you can + * super.addInformation() to keep the electiricty info in the item info bar. + */ + @Override + public void addInformation(ItemStack par1ItemStack, EntityPlayer par2EntityPlayer, List par3List, boolean par4) + { + String color = ""; + double joules = this.getJoules(par1ItemStack); - par2List.add(color + ElectricInfo.getDisplay(joules, ElectricUnit.JOULES) + " - " + Math.round((joules / this.getMaxJoules()) * 100) + "%"); - } + if (joules <= this.getMaxJoules() / 3) + { + color = "\u00a74"; + } + else if (joules > this.getMaxJoules() * 2 / 3) + { + color = "\u00a72"; + } + else + { + color = "\u00a76"; + } - /** - * Make sure you super this method! - */ - @Override - public void onUpdate(ItemStack par1ItemStack, World par2World, Entity par3Entity, int par4, boolean par5) - { - //Makes sure the damage is set correctly for this electric item! - ItemElectric item = ((ItemElectric)par1ItemStack.getItem()); - item.setJoules(item.getJoules(par1ItemStack), par1ItemStack); - } - - /** - * Makes sure the item is uncharged when it is crafted and not charged. - * Change this if you do not want this to happen! - */ - @Override - public void onCreated(ItemStack par1ItemStack, World par2World, EntityPlayer par3EntityPlayer) - { - par1ItemStack = this.getUnchargedItemStack(); - } + par3List.add(color + ElectricInfo.getDisplay(joules, ElectricUnit.JOULES) + " - " + Math.round((joules / this.getMaxJoules()) * 100) + "%"); + } - @Override - public double onReceive(double amps, double voltage, ItemStack itemStack) - { - double rejectedElectricity = Math.max((this.getJoules(itemStack) + ElectricInfo.getJoules(amps, voltage, 1)) - this.getMaxJoules(), 0); - this.setJoules(this.getJoules(itemStack) + ElectricInfo.getJoules(amps, voltage, 1) - rejectedElectricity, itemStack); - return rejectedElectricity; - } + /** + * Make sure you super this method! + */ + @Override + public void onUpdate(ItemStack par1ItemStack, World par2World, Entity par3Entity, int par4, boolean par5) + { + // Makes sure the damage is set correctly for this electric item! + ItemElectric item = ((ItemElectric) par1ItemStack.getItem()); + item.setJoules(item.getJoules(par1ItemStack), par1ItemStack); + } - @Override - public double onUse(double joulesNeeded, ItemStack itemStack) - { - double electricityToUse = Math.min(this.getJoules(itemStack), joulesNeeded); - this.setJoules(this.getJoules(itemStack) - electricityToUse, itemStack); - return electricityToUse; - } + /** + * Makes sure the item is uncharged when it is crafted and not charged. + * Change this if you do not want this to happen! + */ + @Override + public void onCreated(ItemStack par1ItemStack, World par2World, EntityPlayer par3EntityPlayer) + { + par1ItemStack = this.getUncharged(); + } - public boolean canReceiveElectricity() - { - return true; - } + @Override + public double onReceive(double amps, double voltage, ItemStack itemStack) + { + double rejectedElectricity = Math.max((this.getJoules(itemStack) + ElectricInfo.getJoules(amps, voltage, 1)) - this.getMaxJoules(), 0); + this.setJoules(this.getJoules(itemStack) + ElectricInfo.getJoules(amps, voltage, 1) - rejectedElectricity, itemStack); + return rejectedElectricity; + } - public boolean canProduceElectricity() - { - return false; - } + @Override + public double onUse(double joulesNeeded, ItemStack itemStack) + { + double electricityToUse = Math.min(this.getJoules(itemStack), joulesNeeded); + this.setJoules(this.getJoules(itemStack) - electricityToUse, itemStack); + return electricityToUse; + } - /** - * This function sets the electriicty. Do not directly call this function. - * Try to use onReceiveElectricity or onUseElectricity instead. - * @param wattHours - The amount of electricity in joules - */ - @Override - public void setJoules(double wattHours, Object... data) - { - if(data[0] instanceof ItemStack) - { - ItemStack itemStack = (ItemStack)data[0]; - - //Saves the frequency in the itemstack - if (itemStack.stackTagCompound == null) - { - itemStack.setTagCompound(new NBTTagCompound()); - } + public boolean canReceiveElectricity() + { + return true; + } - double electricityStored = Math.max(Math.min(wattHours, this.getMaxJoules()), 0); - itemStack.stackTagCompound.setDouble("electricity", electricityStored); - itemStack.setItemDamage((int)(getMaxJoules() - electricityStored)); - } - } + public boolean canProduceElectricity() + { + return false; + } - /** - * This function is called to get the electricity stored in this item - * @return - The amount of electricity stored in watts - */ - @Override - public double getJoules(Object... data) - { - if(data[0] instanceof ItemStack) - { - ItemStack itemStack = (ItemStack)data[0]; + /** + * This function sets the electriicty. Do not directly call this function. + * Try to use onReceiveElectricity or onUseElectricity instead. + * + * @param wattHours + * - The amount of electricity in joules + */ + @Override + public void setJoules(double wattHours, Object... data) + { + if (data[0] instanceof ItemStack) + { + ItemStack itemStack = (ItemStack) data[0]; - if(itemStack.stackTagCompound == null) - { - return 0; - } - double electricityStored=0; - if (itemStack.stackTagCompound.getTag("electricity") instanceof NBTTagFloat){ - electricityStored = itemStack.stackTagCompound.getFloat("electricity"); - }else{ - electricityStored = itemStack.stackTagCompound.getDouble("electricity"); - } - itemStack.setItemDamage((int)(getMaxJoules() - electricityStored)); - return electricityStored; - } - - return -1; - } + // Saves the frequency in the itemstack + if (itemStack.stackTagCompound == null) + { + itemStack.setTagCompound(new NBTTagCompound()); + } - /** - * Returns an uncharged version of the electric item. Use this if you want - * the crafting recipe to use a charged version of the electric item - * instead of an empty version of the electric item - * @return The ItemStack of a fully charged electric item - */ - public ItemStack getUnchargedItemStack() - { - ItemStack chargedItem = new ItemStack(this); - chargedItem.setItemDamage((int) this.getMaxJoules()); - return chargedItem; - } + double electricityStored = Math.max(Math.min(wattHours, this.getMaxJoules()), 0); + itemStack.stackTagCompound.setDouble("electricity", electricityStored); + itemStack.setItemDamage((int) (getMaxJoules() - electricityStored)); + } + } - @Override - public void getSubItems(int par1, CreativeTabs par2CreativeTabs, List par3List) - { - //Add an uncharged version of the electric item - ItemStack unchargedItem = new ItemStack(this, 1); - unchargedItem.setItemDamage((int) this.getMaxJoules()); - par3List.add(unchargedItem); - //Add an electric item to the creative list that is fully charged - ItemStack chargedItem = new ItemStack(this, 1); - this.setJoules(((IItemElectric)chargedItem.getItem()).getMaxJoules(), chargedItem); - par3List.add(chargedItem); - } + /** + * This function is called to get the electricity stored in this item + * + * @return - The amount of electricity stored in watts + */ + @Override + public double getJoules(Object... data) + { + if (data[0] instanceof ItemStack) + { + ItemStack itemStack = (ItemStack) data[0]; + + if (itemStack.stackTagCompound == null) { return 0; } + double electricityStored = 0; + if (itemStack.stackTagCompound.getTag("electricity") instanceof NBTTagFloat) + { + electricityStored = itemStack.stackTagCompound.getFloat("electricity"); + } + else + { + electricityStored = itemStack.stackTagCompound.getDouble("electricity"); + } + itemStack.setItemDamage((int) (getMaxJoules() - electricityStored)); + return electricityStored; + } + + return -1; + } + + /** + * Returns an uncharged version of the electric item. Use this if you want + * the crafting recipe to use a charged version of the electric item instead + * of an empty version of the electric item + * + * @return The ItemStack of a fully charged electric item + */ + public ItemStack getUncharged() + { + ItemStack chargedItem = new ItemStack(this); + chargedItem.setItemDamage((int) this.getMaxJoules()); + return chargedItem; + } + + public static ItemStack getUncharged(ItemStack itemStack) + { + if(itemStack.getItem() instanceof IItemElectric) + { + ItemStack chargedItem = itemStack.copy(); + chargedItem.setItemDamage((int)((IItemElectric)itemStack.getItem()).getMaxJoules()); + return chargedItem; + } + + return null; + } + + @Override + public void getSubItems(int par1, CreativeTabs par2CreativeTabs, List par3List) + { + // Add an uncharged version of the electric item + ItemStack unchargedItem = new ItemStack(this, 1); + unchargedItem.setItemDamage((int) this.getMaxJoules()); + par3List.add(unchargedItem); + // Add an electric item to the creative list that is fully charged + ItemStack chargedItem = new ItemStack(this, 1); + this.setJoules(((IItemElectric) chargedItem.getItem()).getMaxJoules(), chargedItem); + par3List.add(chargedItem); + } } diff --git a/src/common/universalelectricity/prefab/RecipeHelper.java b/src/common/universalelectricity/prefab/RecipeHelper.java new file mode 100755 index 000000000..366ab3ef6 --- /dev/null +++ b/src/common/universalelectricity/prefab/RecipeHelper.java @@ -0,0 +1,96 @@ +package universalelectricity.prefab; + +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.src.CraftingManager; +import net.minecraft.src.IRecipe; +import net.minecraft.src.ItemStack; +import net.minecraftforge.common.Configuration; +import universalelectricity.core.UEConfig; +import cpw.mods.fml.common.registry.GameRegistry; + +/** + * This class is used to replace recipes that are already added in the existing + * recipe pool for crafting and smelting. All recipe functions take account of + * the Forge Ore Dictionary. It also includes some recipe helper functions to + * shorten some of your function calls. + * + * @author Calclavia + * + */ +public class RecipeHelper +{ + public static List getRecipesByOutput(ItemStack output) + { + List list = new ArrayList(); + + for (Object obj : CraftingManager.getInstance().getRecipeList()) + { + if (obj instanceof IRecipe) + { + if (((IRecipe) obj).getRecipeOutput() == output) + { + list.add((IRecipe)obj); + } + } + } + + return list; + } + + public static boolean replaceRecipe(IRecipe recipe, IRecipe newRecipe) + { + for (Object obj : CraftingManager.getInstance().getRecipeList()) + { + if (obj instanceof IRecipe) + { + if (((IRecipe) obj).equals(recipe) || obj == recipe) + { + CraftingManager.getInstance().getRecipeList().remove(obj); + CraftingManager.getInstance().getRecipeList().add(newRecipe); + return true; + } + } + } + + return false; + } + + public static boolean removeRecipe(IRecipe recipe) + { + for (Object obj : CraftingManager.getInstance().getRecipeList()) + { + if (obj instanceof IRecipe) + { + if (((IRecipe) obj).equals(recipe) || obj == recipe) + { + CraftingManager.getInstance().getRecipeList().remove(obj); + return true; + } + } + } + + return false; + } + + /** + * Use this function if you want to check if the recipe is allowed in the + * configuration file. + */ + public static void addRecipe(IRecipe recipe, String name, Configuration config, boolean defaultBoolean) + { + if (config != null) + { + if (UEConfig.getConfigData(config, "Allow " + name + " Crafting", defaultBoolean)) + { + GameRegistry.addRecipe(recipe); + } + } + } + + public static void addRecipe(IRecipe recipe, Configuration config, boolean defaultBoolean) + { + addRecipe(recipe, recipe.getRecipeOutput().getItemName(), config, defaultBoolean); + } +} diff --git a/src/common/universalelectricity/prefab/SlotElectricItem.java b/src/common/universalelectricity/prefab/SlotElectricItem.java new file mode 100755 index 000000000..c4e4570b6 --- /dev/null +++ b/src/common/universalelectricity/prefab/SlotElectricItem.java @@ -0,0 +1,31 @@ +package universalelectricity.prefab; + +import net.minecraft.src.IInventory; +import net.minecraft.src.ItemStack; +import net.minecraft.src.Slot; +import universalelectricity.implement.IItemElectric; + +/** + * This slot should be used by any container that needs the slot for an electric + * items only. + * + * @author Calclavia + * + */ +public class SlotElectricItem extends Slot +{ + public SlotElectricItem(IInventory par2IInventory, int par3, int par4, int par5) + { + super(par2IInventory, par3, par4, par5); + } + + /** + * Check if the stack is a valid item for this slot. Always true beside for + * the armor slots. + */ + @Override + public boolean isItemValid(ItemStack par1ItemStack) + { + return par1ItemStack.getItem() instanceof IItemElectric; + } +} diff --git a/src/common/universalelectricity/prefab/TileEntityAdvanced.java b/src/common/universalelectricity/prefab/TileEntityAdvanced.java new file mode 100755 index 000000000..214829362 --- /dev/null +++ b/src/common/universalelectricity/prefab/TileEntityAdvanced.java @@ -0,0 +1,60 @@ +package universalelectricity.prefab; + +import net.minecraft.src.Block; +import net.minecraft.src.TileEntity; + +/** + * A TileEntity with some pre-added functionalities. + * + * @author Calclavia + * + */ +public abstract class TileEntityAdvanced extends TileEntity +{ + protected long ticks = 0; + + @Override + public void updateEntity() + { + if (this.ticks == 0) + { + this.initiate(); + } + + if (this.ticks >= Long.MAX_VALUE) + { + this.ticks = 1; + } + + this.ticks++; + } + + /** + * Called on the TileEntity's first tick. + */ + protected void initiate() + { + } + + @Override + public int getBlockMetadata() + { + if (this.blockMetadata == -1) + { + this.blockMetadata = this.worldObj.getBlockMetadata(this.xCoord, this.yCoord, this.zCoord); + } + + return this.blockMetadata; + } + + @Override + public Block getBlockType() + { + if (this.blockType == null) + { + this.blockType = Block.blocksList[this.worldObj.getBlockId(this.xCoord, this.yCoord, this.zCoord)]; + } + + return this.blockType; + } +} diff --git a/src/common/universalelectricity/prefab/TileEntityConductor.java b/src/common/universalelectricity/prefab/TileEntityConductor.java old mode 100644 new mode 100755 index 8ee563da1..e199ba551 --- a/src/common/universalelectricity/prefab/TileEntityConductor.java +++ b/src/common/universalelectricity/prefab/TileEntityConductor.java @@ -1,175 +1,171 @@ package universalelectricity.prefab; -import net.minecraft.src.Block; import net.minecraft.src.EntityPlayer; -import net.minecraft.src.NetworkManager; +import net.minecraft.src.INetworkManager; import net.minecraft.src.Packet250CustomPayload; import net.minecraft.src.TileEntity; import net.minecraft.src.World; import net.minecraftforge.common.ForgeDirection; +import universalelectricity.core.Vector3; import universalelectricity.electricity.ElectricityManager; +import universalelectricity.electricity.ElectricityNetwork; import universalelectricity.implement.IConductor; import universalelectricity.implement.IConnector; -import universalelectricity.network.IPacketReceiver; +import universalelectricity.prefab.network.IPacketReceiver; import com.google.common.io.ByteArrayDataInput; /** - * This tile entity prefabricated for all conductors. + * This tile entity pre-fabricated for all + * conductors. + * * @author Calclavia - * + * */ -public abstract class TileEntityConductor extends AdvancedTile implements IConductor, IPacketReceiver +public abstract class TileEntityConductor extends TileEntityAdvanced implements IConductor, IPacketReceiver { - private int connectionID = 0; + private ElectricityNetwork network; - /** - * Stores information on the blocks that this conductor is connected to - */ - public TileEntity[] connectedBlocks = {null, null, null, null, null, null}; + /** + * Stores information on the blocks that this + * conductor is connected to + */ + public TileEntity[] connectedBlocks = + { null, null, null, null, null, null }; - public TileEntityConductor() - { - this.reset(); - } - - @Override - public int getConnectionID() - { - return this.connectionID; - } - - @Override - public void setConnectionID(int ID) - { - this.connectionID = ID; - } - - @Override - public TileEntity[] getConnectedBlocks() - { - return connectedBlocks; - } - - @Override - public void initiate() - { - this.refreshConnectedBlocks(); - } + public TileEntityConductor() + { + this.reset(); + } - /** - * Adds a connection between this conductor and a UE unit - * @param tileEntity - Must be either a producer, consumer or a conductor - * @param side - side in which the connection is coming from - */ - @Override - public void updateConnection(TileEntity tileEntity, ForgeDirection side) - { - if(tileEntity != null) + @Override + public ElectricityNetwork getNetwork() + { + return this.network; + } + + @Override + public void setNetwork(ElectricityNetwork network) + { + this.network = network; + } + + @Override + public TileEntity[] getConnectedBlocks() + { + return connectedBlocks; + } + + @Override + public void initiate() + { + this.refreshConnectedBlocks(); + } + + @Override + public void updateConnection(TileEntity tileEntity, ForgeDirection side) + { + if (tileEntity != null) { - if(tileEntity instanceof IConnector) - { - this.connectedBlocks[side.ordinal()] = tileEntity; - - if (tileEntity.getClass() == this.getClass()) - { - ElectricityManager.instance.mergeConnection(this.connectionID, ((TileEntityConductor)tileEntity).connectionID); - } - - return; - } + if (tileEntity instanceof IConnector) + { + this.connectedBlocks[side.ordinal()] = tileEntity; + + if (tileEntity.getClass() == this.getClass()) + { + ElectricityManager.instance.mergeConnection(this.getNetwork(), ((TileEntityConductor) tileEntity).getNetwork()); + } + + return; + } } - - if (this.connectedBlocks[side.ordinal()] != null) - { - if (this.connectedBlocks[side.ordinal()] instanceof IConductor) - { - ElectricityManager.instance.splitConnection(this, (IConductor)this.getConnectedBlocks()[side.ordinal()]); - } - } - this.connectedBlocks[side.ordinal()] = null; - } - - @Override - public void updateConnectionWithoutSplit(TileEntity tileEntity, ForgeDirection side) - { - if(tileEntity != null) + if (this.connectedBlocks[side.ordinal()] != null) { - if(tileEntity instanceof IConnector) - { - this.connectedBlocks[side.ordinal()] = tileEntity; - - if (tileEntity.getClass() == this.getClass()) - { - ElectricityManager.instance.mergeConnection(this.connectionID, ((TileEntityConductor)tileEntity).connectionID); - } - - return; - } - } - - this.connectedBlocks[side.ordinal()] = null; - } - - @Override - public void handlePacketData(NetworkManager network, int type, Packet250CustomPayload packet, EntityPlayer player, ByteArrayDataInput dataStream) - { - if(this.worldObj.isRemote) - { - this.refreshConnectedBlocks(); - } - } - - /** - * Determines if this TileEntity requires update calls. - * @return True if you want updateEntity() to be called, false if not - */ - @Override - public boolean canUpdate() - { - return false; - } + if (this.connectedBlocks[side.ordinal()] instanceof IConductor) + { + ElectricityManager.instance.splitConnection(this, (IConductor) this.getConnectedBlocks()[side.ordinal()]); + } + } - @Override - public void reset() - { - this.connectionID = 0; - - if(ElectricityManager.instance != null) - { - ElectricityManager.instance.registerConductor(this); - } - } + this.connectedBlocks[side.ordinal()] = null; + } - @Override - public void refreshConnectedBlocks() - { - if (this.worldObj != null) - { - BlockConductor.updateConductorTileEntity(this.worldObj, this.xCoord, this.yCoord, this.zCoord); - } - } + @Override + public void updateConnectionWithoutSplit(TileEntity tileEntity, ForgeDirection side) + { + if (tileEntity != null) + { + if (tileEntity instanceof IConnector) + { + this.connectedBlocks[side.ordinal()] = tileEntity; - @Override - public World getWorld() - { - return this.worldObj; - } - - @Override - public boolean canConnect(ForgeDirection side) - { + if (tileEntity.getClass() == this.getClass()) + { + ElectricityManager.instance.mergeConnection(this.getNetwork(), ((TileEntityConductor) tileEntity).getNetwork()); + } + + return; + } + } + + this.connectedBlocks[side.ordinal()] = null; + } + + @Override + public void handlePacketData(INetworkManager network, int type, Packet250CustomPayload packet, EntityPlayer player, ByteArrayDataInput dataStream) + { + if (this.worldObj.isRemote) + { + this.refreshConnectedBlocks(); + } + } + + /** + * Determines if this TileEntity requires + * update calls. + * + * @return True if you want updateEntity() to + * be called, false if not + */ + @Override + public boolean canUpdate() + { + return false; + } + + @Override + public void reset() + { + this.network = null; + + if (ElectricityManager.instance != null) + { + ElectricityManager.instance.registerConductor(this); + } + } + + @Override + public void refreshConnectedBlocks() + { + if (this.worldObj != null) + { + for (byte i = 0; i < 6; i++) + { + this.updateConnection(Vector3.getConnectorFromSide(this.worldObj, Vector3.get(this), ForgeDirection.getOrientation(i)), ForgeDirection.getOrientation(i)); + } + } + } + + @Override + public World getWorld() + { + return this.worldObj; + } + + @Override + public boolean canConnect(ForgeDirection side) + { return true; } - - public Block getBlockType() - { - if (this.blockType == null) - { - this.blockType = Block.blocksList[this.worldObj.getBlockId(this.xCoord, this.yCoord, this.zCoord)]; - } - - return this.blockType; - } } diff --git a/src/common/universalelectricity/prefab/TileEntityDisableable.java b/src/common/universalelectricity/prefab/TileEntityDisableable.java old mode 100644 new mode 100755 index 3d6c4ceac..55e51e521 --- a/src/common/universalelectricity/prefab/TileEntityDisableable.java +++ b/src/common/universalelectricity/prefab/TileEntityDisableable.java @@ -3,43 +3,45 @@ package universalelectricity.prefab; import universalelectricity.implement.IDisableable; /** - * An easier way to implement the methods from IElectricityDisableable with default values set. + * An easier way to implement the methods from IElectricityDisableable with + * default values set. + * * @author Calclavia */ -public abstract class TileEntityDisableable extends AdvancedTile implements IDisableable +public abstract class TileEntityDisableable extends TileEntityAdvanced implements IDisableable { - protected int disabledTicks = 0; + protected int disabledTicks = 0; - @Override - public void updateEntity() - { - super.updateEntity(); - - if(this.disabledTicks > 0) - { - this.disabledTicks --; + @Override + public void updateEntity() + { + super.updateEntity(); + + if (this.disabledTicks > 0) + { + this.disabledTicks--; this.whileDisable(); return; - } - } - - /** - * Called every tick while this tile entity is disabled. - */ - protected void whileDisable() - { - + } } - @Override - public void onDisable(int duration) - { - this.disabledTicks = duration; - } + /** + * Called every tick while this tile entity is disabled. + */ + protected void whileDisable() + { - @Override - public boolean isDisabled() - { - return this.disabledTicks > 0; - } + } + + @Override + public void onDisable(int duration) + { + this.disabledTicks = duration; + } + + @Override + public boolean isDisabled() + { + return this.disabledTicks > 0; + } } diff --git a/src/common/universalelectricity/prefab/TileEntityElectricityReceiver.java b/src/common/universalelectricity/prefab/TileEntityElectricityReceiver.java old mode 100644 new mode 100755 index bf213fbe0..598cdac8c --- a/src/common/universalelectricity/prefab/TileEntityElectricityReceiver.java +++ b/src/common/universalelectricity/prefab/TileEntityElectricityReceiver.java @@ -1,35 +1,36 @@ package universalelectricity.prefab; import net.minecraftforge.common.ForgeDirection; -import universalelectricity.electricity.ElectricityManager; import universalelectricity.implement.IElectricityReceiver; /** - * An easier way to implement the methods from IElectricityReceiver with default values set. + * An easier way to implement the methods from IElectricityReceiver with default + * values set. + * * @author Calclavia */ public abstract class TileEntityElectricityReceiver extends TileEntityDisableable implements IElectricityReceiver { - public TileEntityElectricityReceiver() - { - ElectricityManager.instance.registerElectricUnit(this); - } - - @Override - public void updateEntity() - { - super.updateEntity(); - } - - @Override - public boolean canConnect(ForgeDirection side) - { - return this.canReceiveFromSide(side); - } + public TileEntityElectricityReceiver() + { + super(); + } - @Override - public double getVoltage() - { - return 120; - } + @Override + public void updateEntity() + { + super.updateEntity(); + } + + @Override + public boolean canConnect(ForgeDirection side) + { + return this.canReceiveFromSide(side); + } + + @Override + public double getVoltage() + { + return 120; + } } diff --git a/src/common/universalelectricity/prefab/Vector2.java b/src/common/universalelectricity/prefab/Vector2.java deleted file mode 100644 index 18e6b178f..000000000 --- a/src/common/universalelectricity/prefab/Vector2.java +++ /dev/null @@ -1,106 +0,0 @@ -package universalelectricity.prefab; - -import net.minecraft.src.MathHelper; - -/** - * Vector2 Class is used for defining objects in a 2D space. Vector2 makes it easier to handle the coordinates of objects. Instead of - * fumbling with x and y variables, all x and y variables are stored in one class. Vector3.x, Vector3.y. - * - * Constructor: int x, int y - * Constructor: () - default would set x, y to 0. - * @author Calclavia - */ - -public class Vector2 implements Cloneable -{ - public double x; - public double y; - - public Vector2() - { - this(0, 0); - } - - public Vector2(int x, int y) - { - this.x = x; - this.y = y; - } - - public Vector2(double x, double y) - { - this.x = x; - this.y = y; - } - - //Returns the values as an int - public int intX() - { - return (int)Math.floor(this.x); - } - public int intY() - { - return (int)Math.floor(this.y); - } - - /** - * Makes a new copy of this Vector. Prevents variable referencing problems. - */ - @Override - public Vector2 clone() - { - return new Vector2(this.x, this.y); - } - - - public static boolean isPointInRegion(Vector2 point, Vector2 minPoint, Vector2 maxPoint) - { - return (point.x > minPoint.x && point.x < maxPoint.x) && (point.y > minPoint.y && point.y < maxPoint.y); - } - - public static double distance(Vector2 par1, Vector2 par2) - { - double var2 = par1.x - par2.x; - double var4 = par1.y - par2.y; - return MathHelper.sqrt_double(var2 * var2 + var4 * var4); - } - - public static double slope(Vector2 par1, Vector2 par2) - { - double var2 = par1.x - par2.x; - double var4 = par1.y - par2.y; - return var4 / var2; - } - - public void add(Vector2 par1) - { - this.x += par1.x; - this.y += par1.y; - } - - public void add(double par1) - { - this.x += par1; - this.y += par1; - } - - public Vector2 round() - { - return new Vector2(Math.round(this.x), Math.round(this.y)); - } - - public Vector2 floor() - { - return new Vector2(Math.floor(this.x), Math.floor(this.y)); - } - - public String output() - { - return "Vector2: " + this.x + "," + this.y; - } - - public void printVector() - { - System.out.println(output()); - } -} \ No newline at end of file diff --git a/src/common/universalelectricity/prefab/Vector3.java b/src/common/universalelectricity/prefab/Vector3.java deleted file mode 100644 index 60ece17c9..000000000 --- a/src/common/universalelectricity/prefab/Vector3.java +++ /dev/null @@ -1,421 +0,0 @@ -package universalelectricity.prefab; - -import net.minecraft.src.ChunkCoordinates; -import net.minecraft.src.Entity; -import net.minecraft.src.MathHelper; -import net.minecraft.src.MovingObjectPosition; -import net.minecraft.src.NBTTagCompound; -import net.minecraft.src.TileEntity; -import net.minecraft.src.Vec3; -import net.minecraft.src.World; -import net.minecraftforge.common.ForgeDirection; -import universalelectricity.implement.IConnector; - -/** - * Vector3 Class is used for defining objects in a 3D space. Vector3 makes it easier to handle the coordinates of objects. Instead of - * fumbling with x, y and z variables, all x, y and z variables are stored in one class. Vector3.x, Vector3.y, Vector3.z. - * @author Calclavia - */ - -public class Vector3 extends Vector2 implements Cloneable -{ - public double z; - - public static final Vector3[] side = {new Vector3(0, -1, 0), new Vector3(0, 1, 0), new Vector3(0, 0, -1), new Vector3(0, 0, 1), new Vector3(-1, 0, 0), new Vector3(1, 0, 0)}; - - public Vector3() - { - this(0, 0, 0); - } - - public Vector3(int x, int y, int z) - { - this.x = x; - this.y = y; - this.z = z; - } - - public Vector3(double x, double y, double z) - { - this.x = x; - this.y = y; - this.z = z; - } - - /** - * Returns the coordinates as integers - */ - public int intX() - { - return (int)Math.floor(this.x); - } - public int intY() - { - return (int)Math.floor(this.y); - } - public int intZ() - { - return (int)Math.floor(this.z); - } - - /** - * Makes a new copy of this Vector. Prevents variable referencing problems. - */ - @Override - public Vector3 clone() - { - return new Vector3(this.x, this.y, this.z); - } - - /** - * Converts a TileEntity's position into Vector3 - */ - public static Vector3 get(Entity par1) - { - return new Vector3(par1.posX, par1.posY, par1.posZ); - } - - /** - * Converts an entity's position into Vector3 - */ - public static Vector3 get(TileEntity par1) - { - return new Vector3(par1.xCoord, par1.yCoord, par1.zCoord); - } - - /** - * Converts from Vec3 into a Vector3 - */ - public static Vector3 get(Vec3 par1) - { - return new Vector3(par1.xCoord, par1.yCoord, par1.zCoord); - } - - /** - * Converts a MovingObjectPosition to Vector3 - */ - public static Vector3 get(MovingObjectPosition par1) - { - return new Vector3(par1.blockX, par1.blockY, par1.blockZ); - } - - /** - * Converts a MovingObjectPosition to Vector3 - */ - public static Vector3 get(ChunkCoordinates par1) - { - return new Vector3(par1.posX, par1.posY, par1.posZ); - } - - public int getBlockID(World world) - { - return world.getBlockId(this.intX(), this.intY(), this.intZ()); - } - - public int getBlockMetadata(World world) - { - return world.getBlockMetadata(this.intX(), this.intY(), this.intZ()); - } - - public TileEntity getTileEntity(World world) - { - return world.getBlockTileEntity(this.intX(), this.intY(), this.intZ()); - } - - public void setBlock(World world, int id, int metadata) - { - world.setBlockAndMetadata(this.intX(), this.intY(), this.intZ(), id, metadata); - } - - public void setBlock(World world, int id) - { - world.setBlock(this.intX(), this.intY(), this.intZ(), id); - } - - public void setBlockWithNotify(World world, int id, int metadata) - { - world.setBlockAndMetadataWithNotify(this.intX(), this.intY(), this.intZ(), id, metadata); - } - - public void setBlockWithNotify(World world, int id) - { - world.setBlockWithNotify(this.intX(), this.intY(), this.intZ(), id); - } - - /** - * Converts this Vector3 into a Vector2 by dropping the Y axis. - */ - public Vector2 toVector2() - { - return new Vector2(this.x, this.z); - } - - /** - * Converts this vector three into a Minecraft Vec3 object - */ - public Vec3 toVec3() - { - return Vec3.createVectorHelper(this.x, this.y, this.z); - } - - /** - * Checks if a Vector3 point is located inside a region - */ - public static boolean isPointInRegion(Vector3 point, Vector3 minPoint, Vector3 maxPoint) - { - return (point.x > minPoint.x && point.x < maxPoint.x) && (point.y > minPoint.y && point.y < maxPoint.y) && (point.z > minPoint.z && point.z < maxPoint.z); - } - - /** - * Compares two vectors and see if they are equal. True if so. - */ - public boolean isEqual(Vector3 vector3) - { - return (this.x == vector3.x && this.y == vector3.y && this.z == vector3.z); - } - - /** - * Gets the distance between two vectors - * @return The distance - */ - public static double distance(Vector3 par1, Vector3 par2) - { - double var2 = par1.x - par2.x; - double var4 = par1.y - par2.y; - double var6 = par1.z - par2.z; - return MathHelper.sqrt_double(var2 * var2 + var4 * var4 + var6 * var6); - } - - public double distanceTo(Vector3 vector3) - { - double var2 = vector3.x - this.x; - double var4 = vector3.y - this.y; - double var6 = vector3.z - this.z; - return MathHelper.sqrt_double(var2 * var2 + var4 * var4 + var6 * var6); - } - - public static Vector3 subtract(Vector3 par1, Vector3 par2) - { - return new Vector3(par1.x - par2.x, par1.y - par2.y, par1.z - par2.z); - } - - public static Vector3 add(Vector3 par1, Vector3 par2) - { - return new Vector3(par1.x + par2.x, par1.y + par2.y, par1.z + par2.z); - } - - public static Vector3 add(Vector3 par1, double par2) - { - return new Vector3(par1.x + par2, par1.y + par2, par1.z + par2); - } - - public void add(Vector3 par1) - { - this.x += par1.x; - this.y += par1.y; - this.z += par1.z; - } - - @Override - public void add(double par1) - { - this.x += par1; - this.y += par1; - this.z += par1; - } - - public static Vector3 multiply(Vector3 par1, Vector3 par2) - { - return new Vector3(par1.x * par2.x, par1.y * par2.y, par1.z * par2.z); - } - - public static Vector3 multiply(Vector3 par1, double par2) - { - return new Vector3(par1.x * par2, par1.y * par2, par1.z * par2); - } - - public static Vector3 readFromNBT(String prefix, NBTTagCompound par1NBTTagCompound) - { - Vector3 tempVector = new Vector3(); - tempVector.x = par1NBTTagCompound.getDouble(prefix + "X"); - tempVector.y = par1NBTTagCompound.getDouble(prefix + "Y"); - tempVector.z = par1NBTTagCompound.getDouble(prefix + "Z"); - return tempVector; - } - - /** - * Saves this Vector3 to disk - * @param prefix - The prefix of this save. Use some unique string. - * @param par1NBTTagCompound - The NBT compound object to save the data in - */ - public void writeToNBT(String prefix, NBTTagCompound par1NBTTagCompound) - { - par1NBTTagCompound.setDouble(prefix + "X", this.x); - par1NBTTagCompound.setDouble(prefix + "Y", this.y); - par1NBTTagCompound.setDouble(prefix + "Z", this.z); - } - - @Override - public Vector3 round() - { - return new Vector3(Math.round(this.x), Math.round(this.y), Math.round(this.z)); - } - @Override - public Vector3 floor() - { - return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z)); - } - public Vector3 top() - { - return add(this, side[0]); - } - public Vector3 bottom() - { - return add(this, side[1]); - } - public Vector3 front() - { - return add(this, side[2]); - } - public Vector3 back() - { - return add(this, side[3]); - } - public Vector3 left() - { - return add(this, side[4]); - } - public Vector3 right() - { - return add(this, side[5]); - } - @Override - public String output() - { - return "Vector3: " + this.x + "," + this.y + "," + this.z; - } - - /** - * Gets a position relative to another position's side - * @param position - The position - * @param side - The side. 0-5 - * @return The position relative to the original position's side - */ - public void modifyPositionFromSide(ForgeDirection side) - { - switch (side.ordinal()) - { - case 0: this.y -= 1; break; - case 1: this.y += 1; break; - case 2: this.z -= 1; break; - case 3: this.z += 1; break; - case 4: this.x -= 1; break; - case 5: this.x += 1; break; - } - } - - public static TileEntity getTileEntityFromSide(World world, Vector3 position, ForgeDirection side) - { - position.modifyPositionFromSide(side); - return world.getBlockTileEntity(position.intX(), position.intY(), position.intZ()); - } - - /** - * Gets a connector unit based on the given side. - */ - public static TileEntity getConnectorFromSide(World world, Vector3 position, ForgeDirection side) - { - TileEntity tileEntity = getTileEntityFromSide(world, position, side); - - if (tileEntity instanceof IConnector) - { - if (((IConnector)tileEntity).canConnect(getOrientationFromSide(side, ForgeDirection.NORTH))) - { - return tileEntity; - } - } - - return null; - } - - /** - * Finds the side of a block depending on it's facing direction from the given side. - * The side numbers are compatible with the function"getBlockTextureFromSideAndMetadata". - * - * Bottom: 0; - * Top: 1; - * Back: 2; - * Front: 3; - * Left: 4; - * Right: 5; - * @param front - The direction in which this block is facing/front. Use a number between 0 and 5. Default is 3. - * @param side - The side you are trying to find. A number between 0 and 5. - * @return The side relative to the facing direction. - */ - - public static ForgeDirection getOrientationFromSide(ForgeDirection front, ForgeDirection side) - { - switch (front.ordinal()) - { - case 0: - switch (side.ordinal()) - { - case 0: return ForgeDirection.getOrientation(3); - case 1: return ForgeDirection.getOrientation(2); - case 2: return ForgeDirection.getOrientation(1); - case 3: return ForgeDirection.getOrientation(0); - case 4: return ForgeDirection.getOrientation(5); - case 5: return ForgeDirection.getOrientation(4); - } - - case 1: - switch (side.ordinal()) - { - case 0: return ForgeDirection.getOrientation(4); - case 1: return ForgeDirection.getOrientation(5); - case 2: return ForgeDirection.getOrientation(0); - case 3: return ForgeDirection.getOrientation(1); - case 4: return ForgeDirection.getOrientation(2); - case 5: return ForgeDirection.getOrientation(3); - } - - case 2: - switch (side.ordinal()) - { - case 0: return ForgeDirection.getOrientation(0); - case 1: return ForgeDirection.getOrientation(1); - case 2: return ForgeDirection.getOrientation(3); - case 3: return ForgeDirection.getOrientation(2); - case 4: return ForgeDirection.getOrientation(5); - case 5: return ForgeDirection.getOrientation(4); - } - - case 3: - return side; - - case 4: - switch (side.ordinal()) - { - case 0: return ForgeDirection.getOrientation(0); - case 1: return ForgeDirection.getOrientation(1); - case 2: return ForgeDirection.getOrientation(5); - case 3: return ForgeDirection.getOrientation(4); - case 4: return ForgeDirection.getOrientation(3); - case 5: return ForgeDirection.getOrientation(2); - } - - case 5: - switch (side.ordinal()) - { - case 0: return ForgeDirection.getOrientation(0); - case 1: return ForgeDirection.getOrientation(1); - case 2: return ForgeDirection.getOrientation(4); - case 3: return ForgeDirection.getOrientation(5); - case 4: return ForgeDirection.getOrientation(2); - case 5: return ForgeDirection.getOrientation(3); - } - } - - return ForgeDirection.UNKNOWN; - } -} \ No newline at end of file diff --git a/src/common/universalelectricity/prefab/chunk/ChunkEventCaller.java b/src/common/universalelectricity/prefab/chunk/ChunkEventCaller.java deleted file mode 100644 index cbecda5d8..000000000 --- a/src/common/universalelectricity/prefab/chunk/ChunkEventCaller.java +++ /dev/null @@ -1,105 +0,0 @@ -package universalelectricity.prefab.chunk; - -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.src.Chunk; -import net.minecraft.src.TileEntity; -import net.minecraftforge.event.ForgeSubscribe; -import net.minecraftforge.event.world.ChunkEvent.Load; -import net.minecraftforge.event.world.ChunkEvent.Unload; -import universalelectricity.prefab.Vector2; - -public class ChunkEventCaller -{ - public static final ChunkEventCaller INSTANCE = new ChunkEventCaller(); - - private static final List HANDLERS = new ArrayList(); - - public static void register(IChunkLoadHandler handler) - { - if(!HANDLERS.contains(handler)) - { - HANDLERS.add(handler); - } - } - - public static void remove(IChunkLoadHandler handler) - { - if(HANDLERS.contains(handler)) - { - HANDLERS.remove(handler); - } - } - - public void cleanUpChunkHandler() - { - List removeList = new ArrayList(); - - for(IChunkLoadHandler handler : HANDLERS) - { - if(handler == null) - { - removeList.add(handler); - continue; - } - - if(handler instanceof TileEntity) - { - if(((TileEntity)handler).isInvalid()) - { - removeList.add(handler); - continue; - } - } - } - - HANDLERS.removeAll(removeList); - } - - @ForgeSubscribe - public void onChunkLoad(Load event) - { - this.cleanUpChunkHandler(); - - for(IChunkLoadHandler handler : HANDLERS) - { - Chunk chunk = event.getChunk(); - - if(handler instanceof TileEntity) - { - if(Vector2.isPointInRegion(new Vector2(((TileEntity)handler).xCoord, ((TileEntity)handler).zCoord), new Vector2(chunk.xPosition << 4, chunk.zPosition << 4), new Vector2((chunk.xPosition << 4) + 16, (chunk.zPosition << 4) + 16))) - { - handler.onChunkLoad(chunk); - } - } - else - { - handler.onChunkLoad(chunk); - } - } - } - - @ForgeSubscribe - public void onChunkUnload(Unload event) - { - this.cleanUpChunkHandler(); - - for(IChunkLoadHandler handler : HANDLERS) - { - Chunk chunk = event.getChunk(); - - if(handler instanceof TileEntity) - { - if(Vector2.isPointInRegion(new Vector2(((TileEntity)handler).xCoord, ((TileEntity)handler).zCoord), new Vector2(chunk.xPosition << 4, chunk.zPosition << 4), new Vector2((chunk.xPosition << 4) + 16, (chunk.zPosition << 4) + 16))) - { - handler.onChunkUnload(chunk); - } - } - else - { - handler.onChunkUnload(chunk); - } - } - } -} diff --git a/src/common/universalelectricity/prefab/chunk/IChunkLoadHandler.java b/src/common/universalelectricity/prefab/chunk/IChunkLoadHandler.java deleted file mode 100644 index ea6940d50..000000000 --- a/src/common/universalelectricity/prefab/chunk/IChunkLoadHandler.java +++ /dev/null @@ -1,21 +0,0 @@ -package universalelectricity.prefab.chunk; - -import net.minecraft.src.Chunk; - -/** - * Applied to all objects that requires to be called when a chunk loads. When applied to tile entities, it will - * @author Calclavia - * - */ -public interface IChunkLoadHandler -{ - /** - * Called when a chunk loads. - */ - public void onChunkLoad(Chunk chunk); - - /** - * Called when a chunk loads. - */ - public void onChunkUnload(Chunk chunk); -} diff --git a/src/common/universalelectricity/prefab/multiblock/BlockMulti.java b/src/common/universalelectricity/prefab/multiblock/BlockMulti.java new file mode 100755 index 000000000..73f29f3f7 --- /dev/null +++ b/src/common/universalelectricity/prefab/multiblock/BlockMulti.java @@ -0,0 +1,99 @@ +package universalelectricity.prefab.multiblock; + +import java.util.Random; + +import net.minecraft.src.Block; +import net.minecraft.src.BlockContainer; +import net.minecraft.src.EntityPlayer; +import net.minecraft.src.ItemStack; +import net.minecraft.src.MovingObjectPosition; +import net.minecraft.src.TileEntity; +import net.minecraft.src.World; +import universalelectricity.core.UniversalElectricity; +import universalelectricity.core.Vector3; + +public class BlockMulti extends BlockContainer +{ + public BlockMulti(int id) + { + super(id, UniversalElectricity.machine); + this.setHardness(0.8F); + this.setBlockName("MultiBlock"); + } + + public void makeFakeBlock(World worldObj, Vector3 position, Vector3 mainBlock) + { + worldObj.setBlockWithNotify(position.intX(), position.intY(), position.intZ(), this.blockID); + ((TileEntityMulti) worldObj.getBlockTileEntity(position.intX(), position.intY(), position.intZ())).setMainBlock(mainBlock); + } + + @Override + public void breakBlock(World par1World, int x, int y, int z, int par5, int par6) + { + TileEntityMulti tileEntity = (TileEntityMulti) par1World.getBlockTileEntity(x, y, z); + tileEntity.onBlockRemoval(); + super.breakBlock(par1World, x, y, z, par5, par6); + } + + /** + * Called when the block is right clicked by the player. This modified + * version detects electric items and wrench actions on your machine block. + * Do not override this function. Use machineActivated instead! (It does the + * same thing) + */ + @Override + public boolean onBlockActivated(World par1World, int x, int y, int z, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) + { + TileEntityMulti tileEntity = (TileEntityMulti) par1World.getBlockTileEntity(x, y, z); + return tileEntity.onBlockActivated(par1World, x, y, z, par5EntityPlayer); + } + + /** + * Returns the quantity of items to drop on block destruction. + */ + @Override + public int quantityDropped(Random par1Random) + { + return 0; + } + + @Override + public int getRenderType() + { + return -1; + } + + @Override + public boolean isOpaqueCube() + { + return false; + } + + @Override + public boolean renderAsNormalBlock() + { + return false; + } + + @Override + public TileEntity createNewTileEntity(World var1) + { + return new TileEntityMulti(); + } + + @Override + public ItemStack getPickBlock(MovingObjectPosition target, World par1World, int x, int y, int z) + { + TileEntity tileEntity = par1World.getBlockTileEntity(x, y, z); + Vector3 mainBlockPosition = ((TileEntityMulti) tileEntity).mainBlockPosition; + + if (mainBlockPosition != null) + { + int mainBlockID = par1World.getBlockId(mainBlockPosition.intX(), mainBlockPosition.intY(), mainBlockPosition.intZ()); + + if (mainBlockID > 0) { return Block.blocksList[mainBlockID].getPickBlock(target, par1World, mainBlockPosition.intX(), mainBlockPosition.intY(), mainBlockPosition.intZ()); } + } + + return null; + } +} \ No newline at end of file diff --git a/src/common/universalelectricity/prefab/multiblock/IBlockActivate.java b/src/common/universalelectricity/prefab/multiblock/IBlockActivate.java new file mode 100755 index 000000000..1eaa350a7 --- /dev/null +++ b/src/common/universalelectricity/prefab/multiblock/IBlockActivate.java @@ -0,0 +1,17 @@ +package universalelectricity.prefab.multiblock; + +import net.minecraft.src.EntityPlayer; + +/** + * A general interface to be implemented by anything that needs it. + * + * @author Calclavia + * + */ +public interface IBlockActivate +{ + /** + * Called when activated + */ + public boolean onActivated(EntityPlayer entityPlayer); +} \ No newline at end of file diff --git a/src/common/universalelectricity/prefab/multiblock/IMultiBlock.java b/src/common/universalelectricity/prefab/multiblock/IMultiBlock.java new file mode 100755 index 000000000..1e05c3777 --- /dev/null +++ b/src/common/universalelectricity/prefab/multiblock/IMultiBlock.java @@ -0,0 +1,30 @@ +package universalelectricity.prefab.multiblock; + +import net.minecraft.src.TileEntity; +import universalelectricity.core.Vector3; + +/** + * Interface to be applied to tile entity blocks that occupies more than one + * block space. Useful for large machines. + * + * @author Calclavia + * + */ +public interface IMultiBlock extends IBlockActivate +{ + /** + * Called when this multiblock is created + * + * @param placedPosition + * - The position the block was placed at + */ + public void onCreate(Vector3 placedPosition); + + /** + * Called when one of the multiblocks of this block is destroyed + * + * @param callingBlock + * - The tile entity who called the onDestroy function + */ + public void onDestroy(TileEntity callingBlock); +} diff --git a/src/common/universalelectricity/prefab/multiblock/TileEntityMulti.java b/src/common/universalelectricity/prefab/multiblock/TileEntityMulti.java new file mode 100755 index 000000000..c840de016 --- /dev/null +++ b/src/common/universalelectricity/prefab/multiblock/TileEntityMulti.java @@ -0,0 +1,120 @@ +package universalelectricity.prefab.multiblock; + +import net.minecraft.src.EntityPlayer; +import net.minecraft.src.INetworkManager; +import net.minecraft.src.NBTTagCompound; +import net.minecraft.src.Packet; +import net.minecraft.src.Packet250CustomPayload; +import net.minecraft.src.TileEntity; +import net.minecraft.src.World; +import universalelectricity.core.Vector3; +import universalelectricity.prefab.network.IPacketReceiver; +import universalelectricity.prefab.network.PacketManager; + +import com.google.common.io.ByteArrayDataInput; + +/** + * This is a multiblock to be used for blocks that are bigger than one block. + * + * @author Calclavia + * + */ +public class TileEntityMulti extends TileEntity implements IPacketReceiver +{ + // The the position of the main block + public Vector3 mainBlockPosition; + + public void setMainBlock(Vector3 mainBlock) + { + this.mainBlockPosition = mainBlock; + + if (!this.worldObj.isRemote) + { + PacketManager.sendPacketToClients(this.getDescriptionPacket()); + } + } + + @Override + public Packet getDescriptionPacket() + { + return PacketManager.getPacket("BasicComponents", this, this.mainBlockPosition.x, this.mainBlockPosition.y, this.mainBlockPosition.z); + } + + public void onBlockRemoval() + { + if (mainBlockPosition != null) + { + TileEntity tileEntity = this.worldObj.getBlockTileEntity((int) mainBlockPosition.x, (int) mainBlockPosition.y, (int) mainBlockPosition.z); + + if (tileEntity != null && tileEntity instanceof IMultiBlock) + { + IMultiBlock mainBlock = (IMultiBlock) tileEntity; + + if (mainBlock != null) + { + mainBlock.onDestroy(this); + } + } + } + } + + public boolean onBlockActivated(World par1World, int x, int y, int z, EntityPlayer par5EntityPlayer) + { + if (mainBlockPosition != null) + { + TileEntity tileEntity = this.worldObj.getBlockTileEntity((int) mainBlockPosition.x, (int) mainBlockPosition.y, (int) mainBlockPosition.z); + + if (tileEntity != null) + { + if (tileEntity instanceof IMultiBlock) { return ((IMultiBlock) tileEntity).onActivated(par5EntityPlayer); } + } + } + + return false; + } + + /** + * Reads a tile entity from NBT. + */ + @Override + public void readFromNBT(NBTTagCompound par1NBTTagCompound) + { + super.readFromNBT(par1NBTTagCompound); + + this.mainBlockPosition = Vector3.readFromNBT("mainBlockPosition", par1NBTTagCompound); + } + + /** + * Writes a tile entity to NBT. + */ + @Override + public void writeToNBT(NBTTagCompound par1NBTTagCompound) + { + super.writeToNBT(par1NBTTagCompound); + + this.mainBlockPosition.writeToNBT("mainBlockPosition", par1NBTTagCompound); + } + + /** + * Determines if this TileEntity requires update calls. + * + * @return True if you want updateEntity() to be called, false if not + */ + public boolean canUpdate() + { + return false; + } + + @Override + public void handlePacketData(INetworkManager network, int packetType, Packet250CustomPayload packet, EntityPlayer player, ByteArrayDataInput dataStream) + { + try + { + this.mainBlockPosition = new Vector3(dataStream.readDouble(), dataStream.readDouble(), dataStream.readDouble()); + } + catch (Exception e) + { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/src/common/universalelectricity/network/ConnectionHandler.java b/src/common/universalelectricity/prefab/network/ConnectionHandler.java old mode 100644 new mode 100755 similarity index 52% rename from src/common/universalelectricity/network/ConnectionHandler.java rename to src/common/universalelectricity/prefab/network/ConnectionHandler.java index f9e07c8f1..30250c64b --- a/src/common/universalelectricity/network/ConnectionHandler.java +++ b/src/common/universalelectricity/prefab/network/ConnectionHandler.java @@ -1,12 +1,12 @@ -package universalelectricity.network; +package universalelectricity.prefab.network; import java.util.ArrayList; import java.util.List; import net.minecraft.server.MinecraftServer; +import net.minecraft.src.INetworkManager; import net.minecraft.src.NetHandler; import net.minecraft.src.NetLoginHandler; -import net.minecraft.src.NetworkManager; import net.minecraft.src.Packet1Login; import cpw.mods.fml.common.network.IConnectionHandler; import cpw.mods.fml.common.network.Player; @@ -14,74 +14,75 @@ import cpw.mods.fml.common.network.Player; public class ConnectionHandler implements IConnectionHandler { private static final List simpleConnectionHandlers = new ArrayList(); - + public static enum ConnectionType { LOGIN_SERVER, LOGIN_CLIENT, RECEIVED, OPEN_REMOTE, OPEN_LOCAL, CLOSED } - - /** - * Registers a simple connection handler - * @param tileEntity - */ - public static void registerConnectionHandler(ISimpleConnectionHandler tileEntity) - { - simpleConnectionHandlers.add(tileEntity); - } + + /** + * Registers a simple connection handler + * + * @param tileEntity + */ + public static void registerConnectionHandler(ISimpleConnectionHandler tileEntity) + { + simpleConnectionHandlers.add(tileEntity); + } @Override - public void playerLoggedIn(Player player, NetHandler netHandler, NetworkManager manager) - { - for(ISimpleConnectionHandler handler : simpleConnectionHandlers) - { + public void playerLoggedIn(Player player, NetHandler netHandler, INetworkManager manager) + { + for (ISimpleConnectionHandler handler : simpleConnectionHandlers) + { handler.handelConnection(ConnectionType.LOGIN_SERVER, player, netHandler, manager); - } - } - - @Override - public void clientLoggedIn(NetHandler clientHandler, NetworkManager manager, Packet1Login login) - { - for(ISimpleConnectionHandler handler : simpleConnectionHandlers) - { - handler.handelConnection(ConnectionType.LOGIN_CLIENT, clientHandler, manager, login); - } + } } @Override - public String connectionReceived(NetLoginHandler netHandler, NetworkManager manager) + public void clientLoggedIn(NetHandler clientHandler, INetworkManager manager, Packet1Login login) { - for(ISimpleConnectionHandler handler : simpleConnectionHandlers) - { + for (ISimpleConnectionHandler handler : simpleConnectionHandlers) + { + handler.handelConnection(ConnectionType.LOGIN_CLIENT, clientHandler, manager, login); + } + } + + @Override + public String connectionReceived(NetLoginHandler netHandler, INetworkManager manager) + { + for (ISimpleConnectionHandler handler : simpleConnectionHandlers) + { handler.handelConnection(ConnectionType.RECEIVED, netHandler, manager); - } - + } + return null; } @Override - public void connectionOpened(NetHandler netClientHandler, String server, int port, NetworkManager manager) + public void connectionOpened(NetHandler netClientHandler, String server, int port, INetworkManager manager) { - for(ISimpleConnectionHandler handler : simpleConnectionHandlers) - { + for (ISimpleConnectionHandler handler : simpleConnectionHandlers) + { handler.handelConnection(ConnectionType.OPEN_REMOTE, netClientHandler, server, port, manager); - } + } } @Override - public void connectionOpened(NetHandler netClientHandler, MinecraftServer server, NetworkManager manager) + public void connectionOpened(NetHandler netClientHandler, MinecraftServer server, INetworkManager manager) { - for(ISimpleConnectionHandler handler : simpleConnectionHandlers) - { + for (ISimpleConnectionHandler handler : simpleConnectionHandlers) + { handler.handelConnection(ConnectionType.OPEN_LOCAL, netClientHandler, server, manager); - } + } } @Override - public void connectionClosed(NetworkManager manager) + public void connectionClosed(INetworkManager manager) { - for(ISimpleConnectionHandler handler : simpleConnectionHandlers) - { + for (ISimpleConnectionHandler handler : simpleConnectionHandlers) + { handler.handelConnection(ConnectionType.CLOSED, manager); - } + } } } diff --git a/src/common/universalelectricity/prefab/network/IPacketReceiver.java b/src/common/universalelectricity/prefab/network/IPacketReceiver.java new file mode 100755 index 000000000..cac1133cd --- /dev/null +++ b/src/common/universalelectricity/prefab/network/IPacketReceiver.java @@ -0,0 +1,15 @@ +package universalelectricity.prefab.network; + +import net.minecraft.src.EntityPlayer; +import net.minecraft.src.INetworkManager; +import net.minecraft.src.Packet250CustomPayload; + +import com.google.common.io.ByteArrayDataInput; + +public interface IPacketReceiver +{ + /** + * Sends some data to the tile entity. + */ + public void handlePacketData(INetworkManager network, int packetType, Packet250CustomPayload packet, EntityPlayer player, ByteArrayDataInput dataStream); +} diff --git a/src/common/universalelectricity/prefab/network/ISimpleConnectionHandler.java b/src/common/universalelectricity/prefab/network/ISimpleConnectionHandler.java new file mode 100755 index 000000000..a07979975 --- /dev/null +++ b/src/common/universalelectricity/prefab/network/ISimpleConnectionHandler.java @@ -0,0 +1,14 @@ +package universalelectricity.prefab.network; + +import universalelectricity.prefab.network.ConnectionHandler.ConnectionType; + +public interface ISimpleConnectionHandler +{ + /** + * Called when a player logs in. Use this to reset some tile entities + * variables if you need to. + * + * @param player + */ + public void handelConnection(ConnectionType type, Object... data); +} diff --git a/src/common/universalelectricity/prefab/network/PacketManager.java b/src/common/universalelectricity/prefab/network/PacketManager.java new file mode 100755 index 000000000..217172815 --- /dev/null +++ b/src/common/universalelectricity/prefab/network/PacketManager.java @@ -0,0 +1,266 @@ +package universalelectricity.prefab.network; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; + +import net.minecraft.src.EntityPlayer; +import net.minecraft.src.INetworkManager; +import net.minecraft.src.Packet; +import net.minecraft.src.Packet250CustomPayload; +import net.minecraft.src.TileEntity; +import net.minecraft.src.World; +import universalelectricity.core.Vector3; + +import com.google.common.io.ByteArrayDataInput; +import com.google.common.io.ByteStreams; + +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.network.IPacketHandler; +import cpw.mods.fml.common.network.PacketDispatcher; +import cpw.mods.fml.common.network.Player; + +/** + * This class is used for sending and receiving packets between the server and + * the client. You can directly use this by registering this packet manager with + * NetworkMod. Example: + * + * @NetworkMod(channels = { "BasicComponents" }, clientSideRequired = true, + * serverSideRequired = false, packetHandler = + * PacketManager.class) + * + * Check out {@link #BasicComponents} for better reference. + * + * @author Calclavia + */ +public class PacketManager implements IPacketHandler, IPacketReceiver +{ + public enum PacketType + { + UNSPECIFIED, TILEENTITY; + + public static PacketType get(int id) + { + if (id >= 0 && id < PacketType.values().length) { return PacketType.values()[id]; } + return UNSPECIFIED; + } + } + + public static Packet getPacketWithID(String channelName, int id, Object... sendData) + { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + DataOutputStream data = new DataOutputStream(bytes); + + try + { + data.writeInt(id); + + data = encodeDataStream(data, sendData); + + Packet250CustomPayload packet = new Packet250CustomPayload(); + packet.channel = channelName; + packet.data = bytes.toByteArray(); + packet.length = packet.data.length; + + return packet; + } + catch (IOException e) + { + System.out.println("Failed to create packet."); + e.printStackTrace(); + } + + return null; + } + + public static Packet getPacket(String channelName, Object... sendData) + { + return getPacketWithID(channelName, PacketType.UNSPECIFIED.ordinal(), sendData); + } + + /** + * Gets a packet for the tile entity. + * + * @return + */ + public static Packet getPacket(String channelName, TileEntity sender, Object... sendData) + { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + DataOutputStream data = new DataOutputStream(bytes); + + try + { + data.writeInt(PacketType.TILEENTITY.ordinal()); + + data.writeInt(sender.xCoord); + data.writeInt(sender.yCoord); + data.writeInt(sender.zCoord); + data = encodeDataStream(data, sendData); + + Packet250CustomPayload packet = new Packet250CustomPayload(); + packet.channel = channelName; + packet.data = bytes.toByteArray(); + packet.length = packet.data.length; + + return packet; + } + catch (IOException e) + { + System.out.println("Failed to create packet."); + e.printStackTrace(); + } + + return null; + } + + /** + * Sends packets to clients around a specific coordinate. A wrapper using + * Vector3. See {@PacketDispatcher} for detailed + * information. + */ + public static void sendPacketToClients(Packet packet, World worldObj, Vector3 position, double range) + { + try + { + PacketDispatcher.sendPacketToAllAround(position.x, position.y, position.z, range, worldObj.provider.dimensionId, packet); + } + catch (Exception e) + { + System.out.println("Sending packet to client failed."); + e.printStackTrace(); + } + } + + /** + * Sends a packet to all the clients on this server. + */ + public static void sendPacketToClients(Packet packet, World worldObj) + { + try + { + PacketDispatcher.sendPacketToAllInDimension(packet, worldObj.provider.dimensionId); + } + catch (Exception e) + { + System.out.println("Sending packet to client failed."); + e.printStackTrace(); + } + } + + public static void sendPacketToClients(Packet packet) + { + try + { + if (FMLCommonHandler.instance().getMinecraftServerInstance() != null) + { + FMLCommonHandler.instance().getMinecraftServerInstance().getConfigurationManager().sendPacketToAllPlayers(packet); + } + } + catch (Exception e) + { + System.out.println("Sending packet to client failed."); + e.printStackTrace(); + } + } + + public static DataOutputStream encodeDataStream(DataOutputStream data, Object... sendData) + { + try + { + for (Object dataValue : sendData) + { + if (dataValue instanceof Integer) + { + data.writeInt((Integer) dataValue); + } + else if (dataValue instanceof Float) + { + data.writeFloat((Float) dataValue); + } + else if (dataValue instanceof Double) + { + data.writeDouble((Double) dataValue); + } + else if (dataValue instanceof Byte) + { + data.writeByte((Byte) dataValue); + } + else if (dataValue instanceof Boolean) + { + data.writeBoolean((Boolean) dataValue); + } + else if (dataValue instanceof String) + { + data.writeUTF((String) dataValue); + } + else if (dataValue instanceof Short) + { + data.writeShort((Short) dataValue); + } + else if (dataValue instanceof Long) + { + data.writeLong((Long) dataValue); + } + } + + return data; + + } + catch (IOException e) + { + System.out.println("Packet data encoding failed."); + e.printStackTrace(); + } + + return data; + } + + @Override + public void onPacketData(INetworkManager network, Packet250CustomPayload packet, Player player) + { + try + { + ByteArrayDataInput data = ByteStreams.newDataInput(packet.data); + + int packetTypeID = data.readInt(); + + PacketType packetType = PacketType.get(packetTypeID); + + if (packetType == PacketType.TILEENTITY) + { + int x = data.readInt(); + int y = data.readInt(); + int z = data.readInt(); + + World world = ((EntityPlayer) player).worldObj; + + if (world != null) + { + TileEntity tileEntity = world.getBlockTileEntity(x, y, z); + + if (tileEntity != null) + { + if (tileEntity instanceof IPacketReceiver) + { + ((IPacketReceiver) tileEntity).handlePacketData(network, packetTypeID, packet, ((EntityPlayer) player), data); + } + } + } + } + else + { + this.handlePacketData(network, packetTypeID, packet, ((EntityPlayer) player), data); + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + @Override + public void handlePacketData(INetworkManager network, int packetType, Packet250CustomPayload packet, EntityPlayer player, ByteArrayDataInput dataStream) + { + + } +} diff --git a/src/common/universalelectricity/prefab/ore/OreGenBase.java b/src/common/universalelectricity/prefab/ore/OreGenBase.java new file mode 100755 index 000000000..f2b4b7a29 --- /dev/null +++ b/src/common/universalelectricity/prefab/ore/OreGenBase.java @@ -0,0 +1,104 @@ +package universalelectricity.prefab.ore; + +import java.util.Random; + +import net.minecraft.src.Block; +import net.minecraft.src.IChunkProvider; +import net.minecraft.src.ItemStack; +import net.minecraft.src.World; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.oredict.OreDictionary; +import universalelectricity.core.UEConfig; +import universalelectricity.core.UniversalElectricity; + +/** + * This class is used for storing ore generation data. If you are too lazy to + * generate your own ores, you can do + * {@link #OreGenerator.ORES_TO_GENERATE.add()} to add your ore to the list of + * ores to generate. + * + * @author Calclavia + * + */ +public abstract class OreGenBase +{ + public String name; + + public String oreDictionaryName; + + public boolean shouldGenerate; + + public int blockIndexTexture; + + public ItemStack oreStack; + + public int oreID; + + public int oreMeta; + + /** + * What harvest level does this machine need to be acquired? + */ + public int harvestLevel; + + /** + * The predefined tool classes are "pickaxe", "shovel", "axe". You can add + * others for custom tools. + */ + public String harvestTool; + + /** + * @param name + * - The name of the ore for display + * @param textureFile + * - The 16x16 png texture of your ore to override + * @param minGenerateLevel + * - The highest generation level of your ore + * @param maxGenerateLevel + * - The lowest generation level of your ore + * @param amountPerChunk + * - The amount of ores to generate per chunk + * @param amountPerBranch + * - The amount of ores to generate in a clutter. E.g coal + * generates with a lot of other coal next to it. How much do you + * want? + */ + public OreGenBase(String name, String oreDiectionaryName, ItemStack stack, String harvestTool, int harvestLevel) + { + this.name = name; + this.shouldGenerate = false; + this.harvestTool = harvestTool; + this.harvestLevel = harvestLevel; + this.oreDictionaryName = oreDiectionaryName; + this.oreStack = stack; + this.oreID = stack.itemID; + this.oreMeta = stack.getItemDamage(); + + OreDictionary.registerOre(oreDictionaryName, stack); + MinecraftForge.setBlockHarvestLevel(Block.blocksList[stack.itemID], stack.getItemDamage(), harvestTool, harvestLevel); + } + + public OreGenBase enable() + { + this.shouldGenerate = shouldGenerateOre(name); + return this; + } + + // You may inherit from this class and change this function if you want a + // custom texture render for your ore. + public int getBlockTextureFromSide(int side) + { + return this.blockIndexTexture; + } + + // Checks the config file and see if Universal Electricity should generate + // this ore + private static boolean shouldGenerateOre(String oreName) + { + return UEConfig.getConfigData(UniversalElectricity.CONFIGURATION, "Generate " + oreName, true); + } + + public abstract void generate(World world, Random random, int varX, int varZ); + + public abstract boolean isOreGeneratedInWorld(World world, IChunkProvider chunkGenerator); +} diff --git a/src/common/universalelectricity/prefab/ore/OreGenReplace.java b/src/common/universalelectricity/prefab/ore/OreGenReplace.java new file mode 100755 index 000000000..c9bbbedc1 --- /dev/null +++ b/src/common/universalelectricity/prefab/ore/OreGenReplace.java @@ -0,0 +1,134 @@ +package universalelectricity.prefab.ore; + +import java.util.Random; + +import net.minecraft.src.ChunkProviderEnd; +import net.minecraft.src.ChunkProviderGenerate; +import net.minecraft.src.ChunkProviderHell; +import net.minecraft.src.IChunkProvider; +import net.minecraft.src.ItemStack; +import net.minecraft.src.MathHelper; +import net.minecraft.src.World; + +/** + * This class is used for storing ore generation data. If you are too lazy to + * generate your own ores, you can do + * {@link #OreGenerator.ORES_TO_GENERATE.add()} to add your ore to the list of + * ores to generate. + * + * @author Calclavia + * + */ +public class OreGenReplace extends OreGenBase +{ + + public int minGenerateLevel; + public int maxGenerateLevel; + public int amountPerChunk; + public int amountPerBranch; + public int replaceID; + + public boolean generateSurface; + public boolean generateNether; + public boolean generateEnd; + + /** + * @param name + * - The name of the ore for display + * @param textureFile + * - The 16x16 png texture of your ore to override + * @param minGenerateLevel + * - The highest generation level of your ore + * @param maxGenerateLevel + * - The lowest generation level of your ore + * @param amountPerChunk + * - The amount of ores to generate per chunk + * @param amountPerBranch + * - The amount of ores to generate in a clutter. E.g coal + * generates with a lot of other coal next to it. How much do you + * want? + */ + public OreGenReplace(String name, String oreDiectionaryName, ItemStack stack, int replaceID, int minGenerateLevel, int maxGenerateLevel, int amountPerChunk, int amountPerBranch, String harvestTool, int harvestLevel) + { + super(name, oreDiectionaryName, stack, harvestTool, harvestLevel); + this.minGenerateLevel = minGenerateLevel; + this.maxGenerateLevel = maxGenerateLevel; + this.amountPerChunk = amountPerChunk; + this.amountPerBranch = amountPerBranch; + this.replaceID = replaceID; + } + + public void generate(World world, Random random, int varX, int varZ) + { + + for (int i = 0; i < this.amountPerChunk; i++) + { + int x = varX + random.nextInt(16); + int z = varZ + random.nextInt(16); + int y = random.nextInt(this.maxGenerateLevel - this.minGenerateLevel) + this.minGenerateLevel; + generateReplace(world, random, x, y, z); + } + } + + public boolean generateReplace(World par1World, Random par2Random, int par3, int par4, int par5) + { + float var6 = par2Random.nextFloat() * (float) Math.PI; + double var7 = (double) ((float) (par3 + 8) + MathHelper.sin(var6) * (float) this.amountPerBranch / 8.0F); + double var9 = (double) ((float) (par3 + 8) - MathHelper.sin(var6) * (float) this.amountPerBranch / 8.0F); + double var11 = (double) ((float) (par5 + 8) + MathHelper.cos(var6) * (float) this.amountPerBranch / 8.0F); + double var13 = (double) ((float) (par5 + 8) - MathHelper.cos(var6) * (float) this.amountPerBranch / 8.0F); + double var15 = (double) (par4 + par2Random.nextInt(3) - 2); + double var17 = (double) (par4 + par2Random.nextInt(3) - 2); + + for (int var19 = 0; var19 <= this.amountPerBranch; ++var19) + { + double var20 = var7 + (var9 - var7) * (double) var19 / (double) this.amountPerBranch; + double var22 = var15 + (var17 - var15) * (double) var19 / (double) this.amountPerBranch; + double var24 = var11 + (var13 - var11) * (double) var19 / (double) this.amountPerBranch; + double var26 = par2Random.nextDouble() * (double) this.amountPerBranch / 16.0D; + double var28 = (double) (MathHelper.sin((float) var19 * (float) Math.PI / (float) this.amountPerBranch) + 1.0F) * var26 + 1.0D; + double var30 = (double) (MathHelper.sin((float) var19 * (float) Math.PI / (float) this.amountPerBranch) + 1.0F) * var26 + 1.0D; + int var32 = MathHelper.floor_double(var20 - var28 / 2.0D); + int var33 = MathHelper.floor_double(var22 - var30 / 2.0D); + int var34 = MathHelper.floor_double(var24 - var28 / 2.0D); + int var35 = MathHelper.floor_double(var20 + var28 / 2.0D); + int var36 = MathHelper.floor_double(var22 + var30 / 2.0D); + int var37 = MathHelper.floor_double(var24 + var28 / 2.0D); + + for (int var38 = var32; var38 <= var35; ++var38) + { + double var39 = ((double) var38 + 0.5D - var20) / (var28 / 2.0D); + + if (var39 * var39 < 1.0D) + { + for (int var41 = var33; var41 <= var36; ++var41) + { + double var42 = ((double) var41 + 0.5D - var22) / (var30 / 2.0D); + + if (var39 * var39 + var42 * var42 < 1.0D) + { + for (int var44 = var34; var44 <= var37; ++var44) + { + double var45 = ((double) var44 + 0.5D - var24) / (var28 / 2.0D); + + int block = par1World.getBlockId(var38, var41, var44); + if (var39 * var39 + var42 * var42 + var45 * var45 < 1.0D && (this.replaceID == 0 || block == this.replaceID)) + { + par1World.setBlockAndMetadata(var38, var41, var44, this.oreID, this.oreMeta); + } + } + } + } + } + } + } + + return true; + } + + @Override + public boolean isOreGeneratedInWorld(World world, IChunkProvider chunkGenerator) + { + return ((this.generateSurface && chunkGenerator instanceof ChunkProviderGenerate) || (this.generateNether && chunkGenerator instanceof ChunkProviderHell) || (this.generateEnd && chunkGenerator instanceof ChunkProviderEnd)); + } +} diff --git a/src/common/universalelectricity/prefab/ore/OreGenReplaceStone.java b/src/common/universalelectricity/prefab/ore/OreGenReplaceStone.java new file mode 100755 index 000000000..bc4c4e2a4 --- /dev/null +++ b/src/common/universalelectricity/prefab/ore/OreGenReplaceStone.java @@ -0,0 +1,18 @@ +package universalelectricity.prefab.ore; + +import net.minecraft.src.ItemStack; + +public class OreGenReplaceStone extends OreGenReplace +{ + public OreGenReplaceStone(String name, String oreDiectionaryName, ItemStack stack, int replaceID, int minGenerateLevel, int maxGenerateLevel, int amountPerChunk, int amountPerBranch, String harvestTool, int harvestLevel) + { + super(name, oreDiectionaryName, stack, 1, minGenerateLevel, maxGenerateLevel, amountPerChunk, amountPerBranch, harvestTool, harvestLevel); + this.generateSurface = true; + } + + // A simplified version of the constructor + public OreGenReplaceStone(String name, String oreDiectionaryName, ItemStack stack, int replaceID, int maxGenerateLevel, int amountPerChunk, int amountPerBranch) + { + this(name, oreDiectionaryName, stack, 0, replaceID, maxGenerateLevel, amountPerChunk, amountPerBranch, "pickaxe", 1); + } +} \ No newline at end of file diff --git a/src/common/universalelectricity/ore/OreGenerator.java b/src/common/universalelectricity/prefab/ore/OreGenerator.java old mode 100644 new mode 100755 similarity index 59% rename from src/common/universalelectricity/ore/OreGenerator.java rename to src/common/universalelectricity/prefab/ore/OreGenerator.java index 54a958fc7..f51a52674 --- a/src/common/universalelectricity/ore/OreGenerator.java +++ b/src/common/universalelectricity/prefab/ore/OreGenerator.java @@ -1,4 +1,4 @@ -package universalelectricity.ore; +package universalelectricity.prefab.ore; import java.util.ArrayList; import java.util.List; @@ -7,40 +7,47 @@ import java.util.Random; import net.minecraft.src.IChunkProvider; import net.minecraft.src.World; import cpw.mods.fml.common.IWorldGenerator; +import cpw.mods.fml.common.registry.GameRegistry; public class OreGenerator implements IWorldGenerator { + public static boolean isInitiated = false; + /** - * Add your ore data to this list of ores for it to automatically generate! No hassle indeed! + * Add your ore data to this list of ores for it to automatically generate! + * No hassle indeed! */ private static final List ORES_TO_GENERATE = new ArrayList(); - + /** * Adds an ore to the ore generate list. Do this in pre-init. */ public static void addOre(OreGenBase data) { + if (!isInitiated) + { + GameRegistry.registerWorldGenerator(new OreGenerator()); + } + ORES_TO_GENERATE.add(data); } - + /** - * Checks to see if this ore + * Checks to see if this ore + * * @param oreName * @return */ public static boolean oreExists(String oreName) { - for(OreGenBase ore: ORES_TO_GENERATE) + for (OreGenBase ore : ORES_TO_GENERATE) { - if(ore.oreDictionaryName == oreName) - { - return true; - } + if (ore.oreDictionaryName == oreName) { return true; } } - + return false; } - + /** * Removes an ore to the ore generate list. Do this in init. */ @@ -48,21 +55,21 @@ public class OreGenerator implements IWorldGenerator { ORES_TO_GENERATE.remove(data); } - + @Override public void generate(Random rand, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider) { chunkX = chunkX << 4; chunkZ = chunkZ << 4; - - //Checks to make sure this is the normal world - for(OreGenBase oreData : ORES_TO_GENERATE) - { - if(oreData.shouldGenerate && oreData.isOreGeneratedInWorld(world, chunkGenerator)) - { - oreData.generate(world, rand, chunkX, chunkZ); - } - - } + + // Checks to make sure this is the normal world + for (OreGenBase oreData : ORES_TO_GENERATE) + { + if (oreData.shouldGenerate && oreData.isOreGeneratedInWorld(world, chunkGenerator)) + { + oreData.generate(world, rand, chunkX, chunkZ); + } + + } } } diff --git a/src/common/universalelectricity/prefab/potion/CustomPotion.java b/src/common/universalelectricity/prefab/potion/CustomPotion.java old mode 100644 new mode 100755 index e3f56ba51..90a5fa8e5 --- a/src/common/universalelectricity/prefab/potion/CustomPotion.java +++ b/src/common/universalelectricity/prefab/potion/CustomPotion.java @@ -7,29 +7,34 @@ public abstract class CustomPotion extends Potion { /** * Creates a new type of potion - * @param id - The ID of this potion. Make it greater than 20. - * @param isBadEffect - Is this potion a good potion or a bad one? - * @param color - The color of this potion. - * @param name - The name of this potion. + * + * @param id + * - The ID of this potion. Make it greater than 20. + * @param isBadEffect + * - Is this potion a good potion or a bad one? + * @param color + * - The color of this potion. + * @param name + * - The name of this potion. */ - public CustomPotion(int id, boolean isBadEffect, int color, String name) - { - super(id, isBadEffect, color); - this.setPotionName("potion."+name); - LanguageRegistry.instance().addStringLocalization(this.getName(), name); - } - - @Override - public Potion setIconIndex(int par1, int par2) - { - super.setIconIndex(par1, par2); - return this; - } - - /** - * You must register all your potion effects during mod initialization! - */ - public void register() + public CustomPotion(int id, boolean isBadEffect, int color, String name) + { + super(id, isBadEffect, color); + this.setPotionName("potion." + name); + LanguageRegistry.instance().addStringLocalization(this.getName(), name); + } + + @Override + public Potion setIconIndex(int par1, int par2) + { + super.setIconIndex(par1, par2); + return this; + } + + /** + * You must register all your potion effects during mod initialization! + */ + public void register() { Potion.potionTypes[this.getId()] = this; } diff --git a/src/common/universalelectricity/prefab/potion/CustomPotionEffect.java b/src/common/universalelectricity/prefab/potion/CustomPotionEffect.java old mode 100644 new mode 100755 index a37b7b9d1..401359d4d --- a/src/common/universalelectricity/prefab/potion/CustomPotionEffect.java +++ b/src/common/universalelectricity/prefab/potion/CustomPotionEffect.java @@ -13,21 +13,23 @@ public class CustomPotionEffect extends PotionEffect { super(potionID, duration, amplifier); } - + public CustomPotionEffect(Potion potion, int duration, int amplifier) { this(potion.getId(), duration, amplifier); } - + /** * Creates a potion effect with custom curable items. - * @param curativeItems - ItemStacks that can cure this potion effect + * + * @param curativeItems + * - ItemStacks that can cure this potion effect */ public CustomPotionEffect(int potionID, int duration, int amplifier, List curativeItems) { super(potionID, duration, amplifier); - - if(curativeItems == null) + + if (curativeItems == null) { this.setCurativeItems(new ArrayList()); } diff --git a/src/common/universalelectricity/recipe/CraftingRecipe.java b/src/common/universalelectricity/recipe/CraftingRecipe.java deleted file mode 100644 index 289bfc9ca..000000000 --- a/src/common/universalelectricity/recipe/CraftingRecipe.java +++ /dev/null @@ -1,25 +0,0 @@ -package universalelectricity.recipe; - -import net.minecraft.src.ItemStack; - -public class CraftingRecipe -{ - public ItemStack output; - public Object[] input; - - public CraftingRecipe(ItemStack output, Object[] input) - { - this.output = output; - this.input = input; - } - - public boolean isEqual(CraftingRecipe comparingRecipe) - { - if(this.input == comparingRecipe.input && this.output == comparingRecipe.output) - { - return true; - } - - return false; - } -} diff --git a/src/common/universalelectricity/recipe/IRecipeHandler.java b/src/common/universalelectricity/recipe/IRecipeHandler.java deleted file mode 100644 index 3ecd43977..000000000 --- a/src/common/universalelectricity/recipe/IRecipeHandler.java +++ /dev/null @@ -1,24 +0,0 @@ -package universalelectricity.recipe; - -import java.util.List; - -public interface IRecipeHandler -{ - /** - * Called to add a recipe - * @param input - The input of the recipe - * @param output - The output of the recipe - */ - public void addRecipe(Object[] input, Object[] output); - - /** - * Gets a recipe's output by it's input - * @return - The output. Most likely an ItemStack. - */ - public Object getRecipeOutputByInput(Object[] input); - - /** - * Returns all recipes from this recipe handler - */ - public List getAllRecipes(); -} diff --git a/src/common/universalelectricity/recipe/RecipeManager.java b/src/common/universalelectricity/recipe/RecipeManager.java deleted file mode 100644 index d81399c9b..000000000 --- a/src/common/universalelectricity/recipe/RecipeManager.java +++ /dev/null @@ -1,386 +0,0 @@ -package universalelectricity.recipe; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import net.minecraft.src.Block; -import net.minecraft.src.CraftingManager; -import net.minecraft.src.FurnaceRecipes; -import net.minecraft.src.Item; -import net.minecraft.src.ItemStack; -import net.minecraftforge.common.Configuration; -import net.minecraftforge.oredict.ShapedOreRecipe; -import net.minecraftforge.oredict.ShapelessOreRecipe; -import universalelectricity.UEConfig; - -/** - * Adds recipes with full Forge ore dictionary support and replaceable by add-ons. - * Use UERecipes.addRecipe(....) like how you use ModLoader.addRecipe. - * - * MAKE SURE YOU ADD/REPLACE YOUR RECIPE BEFORE @PostInit OR IT WONT BE REPLACABLE! - * @author Calclavia - * - */ -public class RecipeManager -{ - //Crafting Recipes - private static final List SHAPED_RECIPES = new ArrayList(); - private static final List SHAPELESS_RECIPES = new ArrayList(); - - //Smelting Recipes - private static final List SMELTING_RECIPES = new ArrayList(); - - //Custom recipe handlers for UE machines - private static final Map RECIPE_HANDLERS = new HashMap(); - - //Shaped Recipes - public static void addRecipe(ItemStack output, Object[] input) - { - SHAPED_RECIPES.add(new CraftingRecipe(output, input)); - } - - public static void addRecipe(Item output, Object[] input) - { - addRecipe(new ItemStack(output), input); - } - - public static void addRecipe(Block output, Object[] input) - { - addRecipe(new ItemStack(output), input); - } - - /** - * Use this function if you want to check if the recipe is allowed in the configuration file. - */ - public static void addRecipe(ItemStack output, Object[] input, String name, Configuration config, boolean defaultBoolean) - { - if(config != null) - { - if(UEConfig.getConfigData(config, "Allow "+name+" Crafting", defaultBoolean)) - { - addRecipe(output, input); - } - } - } - - public static void addRecipe(ItemStack output, Object[] input, Configuration config, boolean defaultBoolean) - { - addRecipe(output, input, output.getItemName(), config, defaultBoolean); - } - - public static List getRecipes() { return SHAPED_RECIPES; } - - public static CraftingRecipe getRecipeByOutput(ItemStack output) - { - for(CraftingRecipe recipe : SHAPED_RECIPES) - { - if(recipe.output == output) - { - return recipe; - } - } - return null; - } - - //Shapeless Recipes - public static void addShapelessRecipe(ItemStack output, Object[] input) - { - SHAPELESS_RECIPES.add(new CraftingRecipe(output, input)); - } - - public static void addShapelessRecipe(Item output, Object[] input) - { - addShapelessRecipe(new ItemStack(output), input); - } - - public static void addShapelessRecipe(Block output, Object[] input) - { - addShapelessRecipe(new ItemStack(output), input); - } - - /** - * Use this function if you want to check if the recipe is allowed in the configuration file. - */ - public static void addShapelessRecipe(ItemStack output, Object[] input, String name, Configuration config, boolean defaultBoolean) - { - if(config != null) - { - if(UEConfig.getConfigData(config, "Allow "+name+" Crafting", defaultBoolean)) - { - addShapelessRecipe(output, input); - } - } - } - public static void addShapelessRecipe(ItemStack output, Object[] input, Configuration config, boolean defaultBoolean) - { - addShapelessRecipe(output, input, output.getItemName(), config, defaultBoolean); - } - - public static List getShapelessRecipes() { return SHAPELESS_RECIPES; } - - public static CraftingRecipe getShapelessRecipeByOutput(ItemStack output) - { - for(CraftingRecipe recipe : SHAPELESS_RECIPES) - { - if(recipe.output == output) - { - return recipe; - } - } - return null; - } - - //Furnace Smelting Recipes - public static void addSmelting(ItemStack input, ItemStack output) - { - SMELTING_RECIPES.add(new SmeltingRecipe(input, output)); - } - - public static void addSmelting(Item input, ItemStack output) - { - addSmelting(new ItemStack(input), output); - } - - public static void addSmelting(Block input, ItemStack output) - { - addSmelting(new ItemStack(input), output); - } - - /** - * Use this function if you want to check if the recipe is allowed in the configuration file. - */ - public static void addSmelting(ItemStack input, ItemStack output, String name, Configuration config, boolean defaultBoolean) - { - if(config != null) - { - if(UEConfig.getConfigData(config, "Allow "+name+" Smelting", defaultBoolean)) - { - addSmelting(input, output); - } - } - } - - public static void addSmelting(ItemStack input, ItemStack output, Configuration config, boolean defaultBoolean) - { - addSmelting(input, output, output.getItemName(), config, defaultBoolean); - } - - - public static List getSmeltingRecipes() { return SMELTING_RECIPES; } - - public static SmeltingRecipe getSmeltingRecipeByOutput(ItemStack output) - { - for(SmeltingRecipe recipe : SMELTING_RECIPES) - { - if(recipe.output == output) - { - return recipe; - } - } - return null; - } - /** - * Registers your {@link #IRecipeHandler} to the Recipe Manager so other UE mods can access and modify your recipes. - * @param handlerName - The name of your recipe handler. Make it something unique. This String is what other mods - * will be using to access your recipe handler. - * @param handler - An instance of your IRecipeHandler - */ - public static void registerRecipeHandler(String handlerName, IRecipeHandler handler) - { - if(!RECIPE_HANDLERS.containsKey(handlerName)) - { - RECIPE_HANDLERS.put(handlerName, handler); - } - } - - public static IRecipeHandler getRecipeHandler(String name) - { - return RECIPE_HANDLERS.get(name); - } - - public static Map getAllCustomRecipes() { return RECIPE_HANDLERS; } - - /** - * Replacement functions must be called before post mod initialization! - */ - public static void replaceRecipe(CraftingRecipe recipeToReplace, CraftingRecipe newRecipe) - { - for(CraftingRecipe recipe : SHAPED_RECIPES) - { - if(recipe.isEqual(recipeToReplace)) - { - recipe = newRecipe; - } - } - } - - - public static void replaceShapelessRecipe(CraftingRecipe recipeToReplace, CraftingRecipe newRecipe) - { - for(CraftingRecipe recipe : SHAPELESS_RECIPES) - { - if(recipe.isEqual(recipeToReplace)) - { - recipe = newRecipe; - } - } - } - - public static void replaceSmeltingRecipe(SmeltingRecipe recipeToReplace, SmeltingRecipe newRecipe) - { - for(SmeltingRecipe recipe : SMELTING_RECIPES) - { - if(recipe.isEqual(recipeToReplace)) - { - recipe = newRecipe; - } - } - } - - /** - * Finds and returns all recipes that have this specific output - * @param output - The output of the recipe. - */ - public static List findRecipe(ItemStack output) - { - List returnList = new ArrayList(); - - for(CraftingRecipe recipe : SHAPED_RECIPES) - { - if(recipe.output.isItemEqual(output)) - { - returnList.add(recipe); - } - } - - return returnList; - } - - public static List findShapelessRecipe(ItemStack output) - { - List returnList = new ArrayList(); - - for(CraftingRecipe recipe : SHAPELESS_RECIPES) - { - if(recipe.output.isItemEqual(output)) - { - returnList.add(recipe); - } - } - - return returnList; - } - - public static List findSmeltingRecipe(ItemStack output) - { - List returnList = new ArrayList(); - - for(SmeltingRecipe recipe : SMELTING_RECIPES) - { - if(recipe.output.isItemEqual(output)) - { - returnList.add(recipe); - } - } - - return returnList; - } - - /** - * Removes all recipes with the specific output. - */ - public static void removeRecipe(ItemStack output) - { - for(CraftingRecipe recipe : SHAPED_RECIPES) - { - if(recipe.output.isItemEqual(output)) - { - SHAPED_RECIPES.remove(recipe); - } - } - } - - public static void removeShapelessRecipe(ItemStack output) - { - for(CraftingRecipe recipe : SHAPELESS_RECIPES) - { - if(recipe.output.isItemEqual(output)) - { - SHAPELESS_RECIPES.remove(recipe); - } - } - } - - public static void removeSmeltingRecipe(ItemStack output) - { - for(SmeltingRecipe recipe : SMELTING_RECIPES) - { - if(recipe.output.isItemEqual(output)) - { - SMELTING_RECIPES.remove(recipe); - } - } - } - - /** - * Removes a specific recipe from the list. - */ - public static void removeRecipe(CraftingRecipe output) - { - for(CraftingRecipe recipe : SHAPED_RECIPES) - { - if(recipe.isEqual(output)) - { - SHAPED_RECIPES.remove(recipe); - return; - } - } - } - - public static void removeShapelessRecipe(CraftingRecipe output) - { - for(CraftingRecipe recipe : SHAPELESS_RECIPES) - { - if(recipe.isEqual(output)) - { - SHAPELESS_RECIPES.remove(recipe); - return; - } - } - } - - public static void removeSmeltingRecipe(SmeltingRecipe output) - { - for(SmeltingRecipe recipe : SMELTING_RECIPES) - { - if(recipe.isEqual(output)) - { - SMELTING_RECIPES.remove(recipe); - return; - } - } - } - - /** - * Called in post init by {@link #BasicComponenets} to add all recipes. Don't call this function. - */ - public static void addRecipes() - { - for (CraftingRecipe recipe : SHAPED_RECIPES) - { - CraftingManager.getInstance().getRecipeList().add(new ShapedOreRecipe(recipe.output, recipe.input)); - } - - for (CraftingRecipe recipe : SHAPELESS_RECIPES) - { - CraftingManager.getInstance().getRecipeList().add(new ShapelessOreRecipe(recipe.output, recipe.input)); - } - - for (SmeltingRecipe recipe : SMELTING_RECIPES) - { - FurnaceRecipes.smelting().addSmelting(recipe.input.itemID, recipe.input.getItemDamage(), recipe.output); - } - } -} diff --git a/src/common/universalelectricity/recipe/SmeltingRecipe.java b/src/common/universalelectricity/recipe/SmeltingRecipe.java deleted file mode 100644 index 60c70aec6..000000000 --- a/src/common/universalelectricity/recipe/SmeltingRecipe.java +++ /dev/null @@ -1,25 +0,0 @@ -package universalelectricity.recipe; - -import net.minecraft.src.ItemStack; - -public class SmeltingRecipe -{ - public ItemStack input; - public ItemStack output; - - public SmeltingRecipe(ItemStack input, ItemStack output) - { - this.input = input; - this.output = output; - } - - public boolean isEqual(SmeltingRecipe comparingRecipe) - { - if(this.input == comparingRecipe.input && this.output == comparingRecipe.output) - { - return true; - } - - return false; - } -} diff --git a/src/minecraft/net/uberkat/obsidian/client/ClientProxy.java b/src/minecraft/net/uberkat/obsidian/client/ClientProxy.java index d9c64b943..5944211d8 100644 --- a/src/minecraft/net/uberkat/obsidian/client/ClientProxy.java +++ b/src/minecraft/net/uberkat/obsidian/client/ClientProxy.java @@ -8,6 +8,7 @@ import java.util.Properties; import cpw.mods.fml.client.FMLClientHandler; import cpw.mods.fml.client.TextureFXManager; +import cpw.mods.fml.client.registry.ClientRegistry; import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; import cpw.mods.fml.client.registry.RenderingRegistry; import cpw.mods.fml.common.Side; @@ -58,6 +59,7 @@ public class ClientProxy extends CommonProxy MinecraftForgeClient.preloadTexture("/textures/ElementizerFront.png"); MinecraftForgeClient.preloadTexture("/textures/ElementizerBack.png"); MinecraftForgeClient.preloadTexture("/textures/ElementizerSide.png"); + MinecraftForgeClient.preloadTexture("/texture/PlatinumCable.png"); //Register animated TextureFX for machines try { @@ -73,6 +75,7 @@ public class ClientProxy extends CommonProxy //Register entity rendering handlers RenderingRegistry.registerEntityRenderingHandler(EntityObsidianTNT.class, new RenderObsidianTNT()); RenderingRegistry.registerEntityRenderingHandler(EntityKnife.class, new RenderKnife()); + System.out.println("[ObsidianIngots] Render initiative complete."); }