Removed more UE stuff

This commit is contained in:
Aidan Brady 2013-12-22 01:04:35 -05:00
parent 3210153f38
commit 87ce53f3fe
45 changed files with 26 additions and 4978 deletions

View file

@ -1,6 +1,7 @@
package mekanism.api;
import net.minecraft.entity.Entity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.MathHelper;
public class Pos3D
@ -26,6 +27,11 @@ public class Pos3D
this(entity.posX, entity.posY, entity.posZ);
}
public Pos3D(TileEntity tileEntity)
{
this(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord);
}
public Pos3D diff(Pos3D pos)
{
return new Pos3D(xPos-pos.xPos, yPos-pos.yPos, zPos-pos.zPos);

View file

@ -1,8 +1,8 @@
package mekanism.client.sound;
import mekanism.api.Pos3D;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import universalelectricity.core.vector.Vector3;
public abstract class PlayerSound extends Sound
{
@ -13,7 +13,7 @@ public abstract class PlayerSound extends Sound
public PlayerSound(String id, String sound, EntityPlayer entity)
{
super(id, sound, entity, new Vector3(entity));
super(id, sound, entity, new Pos3D(entity));
player = entity;
}
@ -44,9 +44,9 @@ public abstract class PlayerSound extends Sound
}
@Override
public Vector3 getLocation()
public Pos3D getLocation()
{
return new Vector3(player);
return new Pos3D(player);
}
@Override

View file

@ -2,11 +2,10 @@ package mekanism.client.sound;
import java.net.URL;
import mekanism.api.Pos3D;
import mekanism.client.MekanismClient;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import universalelectricity.core.vector.Vector3;
public abstract class Sound
{
@ -29,7 +28,7 @@ public abstract class Sound
* @param sound - bundled path to the sound
* @param tileentity - the tile this sound is playing from.
*/
public Sound(String id, String sound, Object obj, Vector3 loc)
public Sound(String id, String sound, Object obj, Pos3D loc)
{
if(MekanismClient.audioHandler.getFrom(obj) != null)
{
@ -51,7 +50,7 @@ public abstract class Sound
if(SoundHandler.getSoundSystem() != null)
{
SoundHandler.getSoundSystem().newSource(false, id, url, sound, true, (float)loc.x, (float)loc.y, (float)loc.z, 0, 16F);
SoundHandler.getSoundSystem().newSource(false, id, url, sound, true, (float)loc.xPos, (float)loc.yPos, (float)loc.zPos, 0, 16F);
updateVolume();
SoundHandler.getSoundSystem().activate(id);
}
@ -128,7 +127,7 @@ public abstract class Sound
public abstract boolean update(World world);
public abstract Vector3 getLocation();
public abstract Pos3D getLocation();
public abstract float getMultiplier();
@ -145,7 +144,7 @@ public abstract class Sound
float volume = 0;
float masterVolume = MekanismClient.audioHandler.masterVolume;
double distance = mc.thePlayer.getDistance(getLocation().x, getLocation().y, getLocation().z);
double distance = mc.thePlayer.getDistance(getLocation().xPos, getLocation().yPos, getLocation().zPos);
volume = (float)Math.min(Math.max(masterVolume-((distance*.08F)*masterVolume), 0)*multiplier, 1);
volume *= Math.max(0, Math.min(1, MekanismClient.baseSoundVolume));

View file

@ -1,13 +1,9 @@
package mekanism.client.sound;
import java.net.URL;
import mekanism.client.MekanismClient;
import mekanism.api.Pos3D;
import mekanism.common.IActiveState;
import net.minecraft.client.Minecraft;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import universalelectricity.core.vector.Vector3;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@ -33,7 +29,7 @@ public class TileSound extends Sound
*/
public TileSound(String id, String sound, TileEntity tileentity)
{
super(id, sound, tileentity, new Vector3(tileentity));
super(id, sound, tileentity, new Pos3D(tileentity));
tileEntity = tileentity;
}
@ -45,9 +41,9 @@ public class TileSound extends Sound
}
@Override
public Vector3 getLocation()
public Pos3D getLocation()
{
return new Vector3(tileEntity);
return new Pos3D(tileEntity);
}
@Override

View file

@ -2,6 +2,7 @@ package mekanism.common;
import mekanism.api.Coord4D;
import mekanism.api.EnumColor;
import mekanism.api.Pos3D;
import net.minecraft.client.Minecraft;
import net.minecraft.client.particle.EntityFX;
import net.minecraft.client.particle.EntityReddustFX;
@ -9,7 +10,6 @@ import net.minecraft.entity.Entity;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import universalelectricity.core.vector.Vector3;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
@ -114,9 +114,9 @@ public class EntityBalloon extends Entity implements IEntityAdditionalSpawnData
for(int i = 0; i < 10; i++)
{
try {
Vector3 vec = new Vector3(posX + (rand.nextFloat()*.6 - 0.3), posY - 0.8 + (rand.nextFloat()*.6 - 0.3), posZ + (rand.nextFloat()*.6 - 0.3));
Pos3D pos = new Pos3D(posX + (rand.nextFloat()*.6 - 0.3), posY - 0.8 + (rand.nextFloat()*.6 - 0.3), posZ + (rand.nextFloat()*.6 - 0.3));
EntityFX fx = new EntityReddustFX(worldObj, vec.x, vec.y, vec.z, 1, 0, 0, 0);
EntityFX fx = new EntityReddustFX(worldObj, pos.xPos, pos.yPos, pos.zPos, 1, 0, 0, 0);
fx.setRBGColorF(color.getColor(0), color.getColor(1), color.getColor(2));
Minecraft.getMinecraft().effectRenderer.addEffect(fx);

View file

@ -115,7 +115,6 @@ import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.oredict.ShapelessOreRecipe;
import rebelkeithy.mods.metallurgy.api.IOreInfo;
import rebelkeithy.mods.metallurgy.api.MetallurgyAPI;
import universalelectricity.compatibility.Compatibility;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
@ -1330,18 +1329,6 @@ public class Mekanism
addIntegratedItems();
if(overrideUERatios)
{
try {
Compatibility.BC3_RATIO = (float)FROM_BC;
Compatibility.TO_BC_RATIO = (float)TO_BC;
Compatibility.IC2_RATIO = (float)FROM_IC2;
Compatibility.TO_IC2_RATIO = (float)TO_IC2;
Compatibility.TE_RATIO = (float)FROM_TE;
Compatibility.TO_TE_RATIO = (float)TO_TE;
} catch(Throwable t) {}
}
System.out.println("[Mekanism] Hooking complete.");
}

View file

@ -11,7 +11,6 @@ import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import universalelectricity.core.item.IItemElectric;
public class ContainerEnergyCube extends Container
{
@ -182,9 +181,6 @@ public class ContainerEnergyCube extends Container
private boolean canTransfer(ItemStack slotStack)
{
return (slotStack.getItem() instanceof IItemElectric &&
((IItemElectric)slotStack.getItem()).recharge(slotStack, 1, false) != 0) ||
(slotStack.getItem() instanceof IElectricItem && (!(slotStack.getItem() instanceof IItemElectric) ||
((IItemElectric)slotStack.getItem()).discharge(slotStack, 1, false) == 0));
return slotStack.getItem() instanceof IElectricItem;
}
}

View file

@ -13,7 +13,6 @@ import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import universalelectricity.core.vector.Vector3;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

View file

@ -55,8 +55,6 @@ import net.minecraftforge.fluids.FluidStack;
import org.lwjgl.input.Keyboard;
import universalelectricity.core.item.ElectricItemHelper;
import universalelectricity.core.item.IItemElectric;
import cofh.api.energy.IEnergyContainerItem;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@ -387,10 +385,6 @@ public class ItemBlockMachine extends ItemBlock implements IEnergizedItem, ISpec
{
setEnergy(itemstack, getEnergy(itemstack) + EnergizedItemManager.discharge(inv.getStackInSlot(54), getMaxEnergy(itemstack) - getEnergy(itemstack)));
}
else if(inv.getStackInSlot(54).getItem() instanceof IItemElectric)
{
setEnergy(itemstack, getEnergy(itemstack) + ElectricItemHelper.dischargeItem(inv.getStackInSlot(54), (float)((getMaxEnergy(itemstack) - getEnergy(itemstack))*Mekanism.TO_UE)));
}
else if(Mekanism.hooks.IC2Loaded && inv.getStackInSlot(54).getItem() instanceof IElectricItem)
{
IElectricItem item = (IElectricItem)inv.getStackInSlot(54).getItem();

View file

@ -18,22 +18,16 @@ import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeDirection;
import net.minecraftforge.common.MinecraftForge;
import universalelectricity.core.block.IElectrical;
import universalelectricity.core.electricity.ElectricityPack;
import universalelectricity.core.grid.IElectricityNetwork;
import buildcraft.api.power.IPowerReceptor;
import buildcraft.api.power.PowerHandler;
import buildcraft.api.power.PowerHandler.PowerReceiver;
import cofh.api.energy.IEnergyHandler;
public class TileEntityUniversalCable extends TileEntityTransmitter<EnergyNetwork> implements IPowerReceptor, IEnergySink, IEnergyHandler, IElectrical
public class TileEntityUniversalCable extends TileEntityTransmitter<EnergyNetwork> implements IPowerReceptor, IEnergySink, IEnergyHandler
{
/** A fake power handler used to initiate energy transfer calculations. */
public PowerHandler powerHandler;
/** A fake UE ElectricityNetwork used to accept power from EU machines */
public IElectricityNetwork ueNetwork;
public double energyScale;
public TileEntityUniversalCable()
@ -298,47 +292,6 @@ public class TileEntityUniversalCable extends TileEntityTransmitter<EnergyNetwor
{
return (int)Math.round(getTransmitterNetwork().getEnergyNeeded()*Mekanism.TO_TE);
}
@Override
public boolean canConnect(ForgeDirection direction)
{
return true;
}
@Override
public float receiveElectricity(ForgeDirection from, ElectricityPack receive, boolean doReceive)
{
if(doReceive && receive != null && receive.getWatts() > 0)
{
return receive.getWatts() - (float)(getTransmitterNetwork().emit(receive.getWatts()*Mekanism.FROM_UE));
}
return 0;
}
@Override
public ElectricityPack provideElectricity(ForgeDirection from, ElectricityPack request, boolean doProvide)
{
return null;
}
@Override
public float getRequest(ForgeDirection direction)
{
return (float)(getTransmitterNetwork().getEnergyNeeded()*Mekanism.TO_UE);
}
@Override
public float getProvide(ForgeDirection direction)
{
return 0;
}
@Override
public float getVoltage()
{
return 120;
}
@Override
public int getCapacity()

View file

@ -8,7 +8,6 @@ import mekanism.common.Mekanism;
import mekanism.common.tileentity.TileEntityElectricBlock;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import universalelectricity.core.item.IItemElectric;
import cofh.api.energy.IEnergyContainerItem;
public final class ChargeUtils
@ -126,13 +125,10 @@ public final class ChargeUtils
{
if(chargeSlot)
{
return (itemstack.getItem() instanceof IElectricItem && (!(itemstack.getItem() instanceof IItemElectric) ||
((IItemElectric)itemstack.getItem()).recharge(itemstack, 1, false) == 0));
return itemstack.getItem() instanceof IElectricItem;
}
else {
return (itemstack.getItem() instanceof IElectricItem && ((IElectricItem)itemstack.getItem()).canProvideEnergy(itemstack) &&
(!(itemstack.getItem() instanceof IItemElectric) ||
((IItemElectric)itemstack.getItem()).discharge(itemstack, 1, false) == 0));
return itemstack.getItem() instanceof IElectricItem && ((IElectricItem)itemstack.getItem()).canProvideEnergy(itemstack);
}
}
}

View file

@ -1,95 +0,0 @@
package universalelectricity.compatibility;
import universalelectricity.core.UniversalElectricity;
import universalelectricity.core.electricity.NetworkLoader;
import cpw.mods.fml.common.Loader;
/**
* The Universal Electricity compatibility module allows your mod to be compatible with most major
* power systems in Minecraft.
*
* @author Calclavia, Micdoodle
*/
public class Compatibility
{
/** Version of BuildCraft api compiled with */
public static String BCx_VERSION = "@BCxVersion@";
/** Version of Industrial Craft api compiled with */
public static String ICx_VERSION = "@ICxVersion@";
/** Version of Thermal Expansion api compiled with */
public static String TEx_VERSION = "@TExVersion@";
/** Has the initiate method been called */
public static boolean INIT = false;
/** Ratio of Build craft(MJ) power to UE power(Kw). Multiply BC3 power by this to convert to UE */
public static float BC3_RATIO = 2.814f;
/** Ratio of Redstone Flux power to UE power(Kw). Multiply TE power by this to convert to UE */
public static float TE_RATIO = BC3_RATIO / 10;
/**
* Ratio of Industrial craft(EU) power to UE power(Kw). Multiply IC2 power by this to convert to
* UE
*/
public static float IC2_RATIO = 0.11256f;
/**
* Ratio of UE power(Kw) to Build craft(MJ) power. Multiply UE power by this to convert it to
* BC3 power
*/
public static float TO_BC_RATIO = 1 / BC3_RATIO;
/**
* Ratio of UE power(Kw) to Redstone Flux power. Multiply UE power by this to convert it to TE
* power
*/
public static float TO_TE_RATIO = 1 / TE_RATIO;
/**
* Ratio of UE power(KW) to Industrial craft(EU) power. Multiply UE power by this to convert it
* to IC2 power
*/
public static float TO_IC2_RATIO = 1 / IC2_RATIO;
/** You must call this function to enable the Universal Network module. */
public static void initiate()
{
if (!INIT)
{
/** Outputs basic version information */
System.out.println("[UniversalElectricity] Loading compatibility API version " + UniversalElectricity.VERSION);
System.out.println("[UniversalElectricity] Compiled with IndustrialCraft API version " + Compatibility.ICx_VERSION);
System.out.println("[UniversalElectricity] Compiled with BuildCraft API version " + Compatibility.BCx_VERSION);
System.out.println("[UniversalElectricity] Compiled with ThermalExpansion API version " + Compatibility.TEx_VERSION);
/** Loads the configuration and sets all the values. */
UniversalElectricity.CONFIGURATION.load();
IC2_RATIO = (float) UniversalElectricity.CONFIGURATION.get("Compatiblity", "IndustrialCraft Conversion Ratio", IC2_RATIO).getDouble(IC2_RATIO);
TE_RATIO = (float) UniversalElectricity.CONFIGURATION.get("Compatiblity", "Thermal Expansion Conversion Ratio", TE_RATIO).getDouble(TE_RATIO);
BC3_RATIO = (float) UniversalElectricity.CONFIGURATION.get("Compatiblity", "BuildCraft Conversion Ratio", BC3_RATIO).getDouble(BC3_RATIO);
TO_IC2_RATIO = 1 / IC2_RATIO;
TO_BC_RATIO = 1 / BC3_RATIO;
UniversalElectricity.CONFIGURATION.save();
NetworkLoader.setNetworkClass(UniversalNetwork.class);
}
}
/** Checks using the FML loader too see if IC2 is loaded */
public static boolean isIndustrialCraft2Loaded()
{
return Loader.isModLoaded("IC2");
}
/** Checks using the FML loader too see if BC3 is loaded */
public static boolean isBuildcraftLoaded()
{
return Loader.isModLoaded("BuildCraft|Energy");
}
public static boolean isThermalExpansionLoaded()
{
return Loader.isModLoaded("ThermalExpansion");
}
}

View file

@ -1,150 +0,0 @@
package universalelectricity.compatibility;
import ic2.api.item.IElectricItemManager;
import ic2.api.item.ISpecialElectricItem;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import universalelectricity.core.item.IItemElectric;
import universalelectricity.core.item.ItemElectric;
import cofh.api.energy.IEnergyContainerItem;
public abstract class ItemUniversalElectric extends ItemElectric implements ISpecialElectricItem, IEnergyContainerItem
{
public static final float CHARGE_RATE = 0.005f;
public ItemUniversalElectric(int id)
{
super(id);
}
/**
* IC2
*/
@Override
public int getChargedItemId(ItemStack itemStack)
{
return this.itemID;
}
@Override
public int getEmptyItemId(ItemStack itemStack)
{
return this.itemID;
}
@Override
public int getMaxCharge(ItemStack itemStack)
{
return (int) (this.getMaxElectricityStored(itemStack) * Compatibility.TO_IC2_RATIO);
}
@Override
public int getTier(ItemStack itemStack)
{
return 1;
}
@Override
public int getTransferLimit(ItemStack itemStack)
{
return (int) ((this.getMaxElectricityStored(itemStack) * CHARGE_RATE) * Compatibility.TO_IC2_RATIO);
}
@Override
public IElectricItemManager getManager(ItemStack itemStack)
{
return IC2ElectricItemManager.MANAGER;
}
@Override
public boolean canProvideEnergy(ItemStack itemStack)
{
return this.recharge(itemStack, 1, false) > 0;
}
/**
* Thermal Expansion
*/
@Override
public int receiveEnergy(ItemStack theItem, int energy, boolean doReceive)
{
return (int) (this.recharge(theItem, energy * Compatibility.BC3_RATIO, doReceive) * Compatibility.TO_BC_RATIO);
}
@Override
public int extractEnergy(ItemStack theItem, int energy, boolean doTransfer)
{
return (int) (this.discharge(theItem, energy * Compatibility.BC3_RATIO, doTransfer) * Compatibility.TO_BC_RATIO);
}
@Override
public int getEnergyStored(ItemStack theItem)
{
return (int) (this.getElectricityStored(theItem) * Compatibility.TO_BC_RATIO);
}
@Override
public int getMaxEnergyStored(ItemStack theItem)
{
return (int) (this.getMaxElectricityStored(theItem) * Compatibility.TO_BC_RATIO);
}
public static class IC2ElectricItemManager implements IElectricItemManager
{
public static final IElectricItemManager MANAGER = new IC2ElectricItemManager();
private IItemElectric getElectricItem(ItemStack itemStack)
{
if (itemStack.getItem() instanceof IItemElectric)
{
return ((IItemElectric) itemStack.getItem());
}
return null;
}
@Override
public int charge(ItemStack itemStack, int amount, int tier, boolean ignoreTransferLimit, boolean simulate)
{
float inputElectricity = amount * Compatibility.IC2_RATIO;
return (int) (getElectricItem(itemStack).recharge(itemStack, inputElectricity, !simulate) * Compatibility.TO_IC2_RATIO);
}
@Override
public int discharge(ItemStack itemStack, int amount, int tier, boolean ignoreTransferLimit, boolean simulate)
{
float outputElectricity = amount * Compatibility.IC2_RATIO;
return (int) (getElectricItem(itemStack).discharge(itemStack, outputElectricity, !simulate) * Compatibility.TO_IC2_RATIO);
}
@Override
public boolean canUse(ItemStack itemStack, int amount)
{
return false;
}
@Override
public int getCharge(ItemStack itemStack)
{
return 0;
}
@Override
public boolean use(ItemStack itemStack, int amount, EntityLivingBase entity)
{
return false;
}
@Override
public void chargeFromArmor(ItemStack itemStack, EntityLivingBase entity)
{
}
@Override
public String getToolTip(ItemStack itemStack)
{
return null;
}
}
}

View file

@ -1,267 +0,0 @@
package universalelectricity.compatibility;
import ic2.api.energy.event.EnergyTileLoadEvent;
import ic2.api.energy.event.EnergyTileUnloadEvent;
import ic2.api.energy.tile.IEnergyAcceptor;
import ic2.api.energy.tile.IEnergyEmitter;
import ic2.api.energy.tile.IEnergySink;
import ic2.api.energy.tile.IEnergyTile;
import java.util.HashSet;
import java.util.Set;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeDirection;
import net.minecraftforge.common.MinecraftForge;
import universalelectricity.core.block.IConnector;
import universalelectricity.core.electricity.ElectricityPack;
import universalelectricity.core.vector.Vector3;
import universalelectricity.core.vector.VectorHelper;
import universalelectricity.prefab.tile.TileEntityConductor;
import buildcraft.api.power.IPowerReceptor;
import buildcraft.api.power.PowerHandler;
import buildcraft.api.power.PowerHandler.PowerReceiver;
import buildcraft.api.power.PowerHandler.Type;
import cofh.api.energy.IEnergyHandler;
/**
* A universal conductor class.
*
* Extend this class or use as a reference for your own implementation of compatible conductor
* tiles.
*
* @author Calclavia, micdoodle8
*
*/
public abstract class TileEntityUniversalConductor extends TileEntityConductor implements IEnergySink, IPowerReceptor, IEnergyHandler
{
protected boolean isAddedToEnergyNet;
public PowerHandler powerHandler;
public float buildcraftBuffer = Compatibility.BC3_RATIO * 50;
public TileEntityUniversalConductor()
{
this.powerHandler = new PowerHandler(this, Type.PIPE);
this.powerHandler.configure(0, this.buildcraftBuffer, this.buildcraftBuffer, this.buildcraftBuffer * 2);
this.powerHandler.configurePowerPerdition(0, 0);
}
@Override
public TileEntity[] getAdjacentConnections()
{
if (this.adjacentConnections == null)
{
this.adjacentConnections = new TileEntity[6];
for (byte i = 0; i < 6; i++)
{
ForgeDirection side = ForgeDirection.getOrientation(i);
TileEntity tileEntity = VectorHelper.getTileEntityFromSide(this.worldObj, new Vector3(this), side);
if (tileEntity instanceof IConnector)
{
if (((IConnector) tileEntity).canConnect(side.getOpposite()))
{
this.adjacentConnections[i] = tileEntity;
}
}
else if (tileEntity instanceof IEnergyTile)
{
if (tileEntity instanceof IEnergyAcceptor)
{
if (((IEnergyAcceptor) tileEntity).acceptsEnergyFrom(this, side.getOpposite()))
{
this.adjacentConnections[i] = tileEntity;
continue;
}
}
if (tileEntity instanceof IEnergyEmitter)
{
if (((IEnergyEmitter) tileEntity).emitsEnergyTo(tileEntity, side.getOpposite()))
{
this.adjacentConnections[i] = tileEntity;
continue;
}
}
this.adjacentConnections[i] = tileEntity;
}
else if (tileEntity instanceof IPowerReceptor)
{
if (((IPowerReceptor) tileEntity).getPowerReceiver(side.getOpposite()) != null)
{
this.adjacentConnections[i] = tileEntity;
}
}
else if (tileEntity instanceof IEnergyHandler)
{
if (((IEnergyHandler) tileEntity).canInterface(side.getOpposite()))
{
this.adjacentConnections[i] = tileEntity;
}
}
}
}
return this.adjacentConnections;
}
@Override
public void validate()
{
super.validate();
if (!this.worldObj.isRemote)
{
if (!this.isAddedToEnergyNet)
{
this.initIC();
}
}
}
@Override
public void invalidate()
{
this.unloadTileIC2();
super.invalidate();
}
@Override
public void onChunkUnload()
{
this.unloadTileIC2();
super.onChunkUnload();
}
protected void initIC()
{
MinecraftForge.EVENT_BUS.post(new EnergyTileLoadEvent(this));
this.isAddedToEnergyNet = true;
}
protected void unloadTileIC2()
{
if (this.isAddedToEnergyNet && this.worldObj != null)
{
if (Compatibility.isIndustrialCraft2Loaded())
{
MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this));
}
this.isAddedToEnergyNet = false;
}
}
@Override
public double demandedEnergyUnits()
{
if (this.getNetwork() == null)
{
return 0.0;
}
return this.getNetwork().getRequest(this).getWatts() * Compatibility.TO_IC2_RATIO;
}
@Override
public double injectEnergyUnits(ForgeDirection directionFrom, double amount)
{
TileEntity tile = VectorHelper.getTileEntityFromSide(this.worldObj, new Vector3(this), directionFrom);
ElectricityPack pack = ElectricityPack.getFromWatts((float) (amount * Compatibility.IC2_RATIO), 1);
return this.getNetwork().produce(pack, this, tile) * Compatibility.TO_IC2_RATIO;
}
@Override
public int getMaxSafeInput()
{
return Integer.MAX_VALUE;
}
@Override
public boolean acceptsEnergyFrom(TileEntity emitter, ForgeDirection direction)
{
return true;
}
/**
* BuildCraft Functions
*/
@Override
public PowerReceiver getPowerReceiver(ForgeDirection side)
{
return this.powerHandler.getPowerReceiver();
}
@Override
public void doWork(PowerHandler workProvider)
{
Set<TileEntity> ignoreTiles = new HashSet<TileEntity>();
ignoreTiles.add(this);
for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS)
{
TileEntity tile = new Vector3(this).modifyPositionFromSide(direction).getTileEntity(this.worldObj);
ignoreTiles.add(tile);
}
ElectricityPack pack = ElectricityPack.getFromWatts(workProvider.useEnergy(0, this.getNetwork().getRequest(this).getWatts() * Compatibility.TO_BC_RATIO, true) * Compatibility.BC3_RATIO, 1);
this.getNetwork().produce(pack, ignoreTiles.toArray(new TileEntity[0]));
}
@Override
public World getWorld()
{
return this.getWorldObj();
}
/**
* Thermal Expansion Functions
*/
@Override
public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate)
{
ElectricityPack pack = ElectricityPack.getFromWatts(maxReceive * Compatibility.TE_RATIO, 1);
float request = this.getMaxEnergyStored(from);
if (!simulate)
{
if (request > 0)
{
float reject = this.getNetwork().produce(pack, new Vector3(this).modifyPositionFromSide(from).getTileEntity(this.worldObj));
return (int) (maxReceive - (reject * Compatibility.TO_TE_RATIO));
}
return 0;
}
return (int) Math.min(maxReceive, request * Compatibility.TO_TE_RATIO);
}
@Override
public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate)
{
return 0;
}
@Override
public boolean canInterface(ForgeDirection from)
{
return true;
}
@Override
public int getEnergyStored(ForgeDirection from)
{
return 0;
}
@Override
public int getMaxEnergyStored(ForgeDirection from)
{
return (int) (this.getNetwork().getRequest(new Vector3(this).modifyPositionFromSide(from).getTileEntity(this.worldObj)).getWatts() * Compatibility.TO_TE_RATIO);
}
}

View file

@ -1,385 +0,0 @@
package universalelectricity.compatibility;
import ic2.api.energy.event.EnergyTileLoadEvent;
import ic2.api.energy.event.EnergyTileUnloadEvent;
import ic2.api.energy.tile.IEnergySink;
import ic2.api.energy.tile.IEnergySource;
import ic2.api.energy.tile.IEnergyTile;
import ic2.api.item.IElectricItemManager;
import ic2.api.item.ISpecialElectricItem;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeDirection;
import net.minecraftforge.common.MinecraftForge;
import universalelectricity.core.electricity.ElectricityPack;
import universalelectricity.core.item.IItemElectric;
import universalelectricity.core.vector.Vector3;
import universalelectricity.prefab.tile.TileEntityElectrical;
import buildcraft.api.power.IPowerReceptor;
import buildcraft.api.power.PowerHandler;
import buildcraft.api.power.PowerHandler.PowerReceiver;
import buildcraft.api.power.PowerHandler.Type;
import cofh.api.energy.IEnergyContainerItem;
import cofh.api.energy.IEnergyHandler;
/**
* A universal electricity tile used for tiles that consume or produce electricity.
*
* Extend this class or use as a reference for your own implementation of compatible electrical
* tiles.
*
* @author micdoodle8, Calclavia
*
*/
public abstract class TileEntityUniversalElectrical extends TileEntityElectrical implements IEnergySink, IEnergySource, IPowerReceptor, IEnergyHandler
{
protected boolean isAddedToEnergyNet;
public PowerHandler bcPowerHandler;
public Type bcBlockType = Type.MACHINE;
public float maxInputEnergy = 100;
/**
* Recharges electric item.
*/
@Override
public void recharge(ItemStack itemStack)
{
if (itemStack != null)
{
if (itemStack.getItem() instanceof IItemElectric)
{
super.recharge(itemStack);
}
else if (itemStack.getItem() instanceof ISpecialElectricItem)
{
ISpecialElectricItem electricItem = (ISpecialElectricItem) itemStack.getItem();
IElectricItemManager manager = electricItem.getManager(itemStack);
float energy = Math.max(this.getProvide(ForgeDirection.UNKNOWN) * Compatibility.IC2_RATIO, 0);
energy = manager.charge(itemStack, (int) (energy * Compatibility.TO_IC2_RATIO), 0, false, false) * Compatibility.IC2_RATIO;
this.provideElectricity(energy, true);
}
else if (itemStack.getItem() instanceof IEnergyContainerItem)
{
float forgienEnergyAccepted = ((IEnergyContainerItem) itemStack.getItem()).receiveEnergy(itemStack, (int) (this.getProvide(ForgeDirection.UNKNOWN) * Compatibility.TO_TE_RATIO), false);
this.provideElectricity(forgienEnergyAccepted * Compatibility.TE_RATIO, true);
}
}
}
/**
* Discharges electric item.
*/
@Override
public void discharge(ItemStack itemStack)
{
if (itemStack != null)
{
if (itemStack.getItem() instanceof IItemElectric)
{
super.discharge(itemStack);
}
else if (itemStack.getItem() instanceof ISpecialElectricItem)
{
ISpecialElectricItem electricItem = (ISpecialElectricItem) itemStack.getItem();
if (electricItem.canProvideEnergy(itemStack))
{
IElectricItemManager manager = electricItem.getManager(itemStack);
float energy = Math.max(this.getRequest(ForgeDirection.UNKNOWN) * Compatibility.IC2_RATIO, 0);
energy = manager.discharge(itemStack, (int) (energy * Compatibility.TO_IC2_RATIO), 0, false, false);
this.receiveElectricity(energy, true);
}
}
else if (itemStack.getItem() instanceof IEnergyContainerItem)
{
float forgienEnergy = ((IEnergyContainerItem) itemStack.getItem()).extractEnergy(itemStack, (int) (this.getRequest(ForgeDirection.UNKNOWN) * Compatibility.TO_TE_RATIO), false);
this.receiveElectricity(forgienEnergy * Compatibility.TE_RATIO, true);
}
}
}
@Override
public void initiate()
{
super.initiate();
this.initBuildCraft();
}
@Override
public void updateEntity()
{
super.updateEntity();
// Register to the IC2 Network
if (!this.worldObj.isRemote)
{
if (!this.isAddedToEnergyNet)
{
this.initIC();
}
if (this.bcPowerHandler == null)
{
this.initBuildCraft();
}
if (Compatibility.isBuildcraftLoaded())
{
if (this.bcPowerHandler.getEnergyStored() > 0)
{
/**
* Cheat BuildCraft powerHandler and always empty energy inside of it.
*/
this.receiveElectricity(this.bcPowerHandler.getEnergyStored() * Compatibility.BC3_RATIO, true);
this.bcPowerHandler.setEnergy(0);
}
}
}
}
@Override
public void produce()
{
if (!this.worldObj.isRemote)
{
for (ForgeDirection outputDirection : this.getOutputDirections())
{
if (outputDirection != ForgeDirection.UNKNOWN)
{
if (!this.produceUE(outputDirection))
{
if (!this.produceThermalExpansion(outputDirection))
{
this.produceBuildCraft(outputDirection);
}
}
}
}
}
}
public boolean produceThermalExpansion(ForgeDirection outputDirection)
{
if (!this.worldObj.isRemote && outputDirection != null && outputDirection != ForgeDirection.UNKNOWN)
{
float provide = this.getProvide(outputDirection);
if (this.getEnergyStored() >= provide && provide > 0)
{
if (Compatibility.isThermalExpansionLoaded())
{
TileEntity tileEntity = new Vector3(this).modifyPositionFromSide(outputDirection).getTileEntity(this.worldObj);
if (tileEntity instanceof IEnergyHandler)
{
IEnergyHandler receiver = (IEnergyHandler) tileEntity;
int convertedProvide = (int) (provide * Compatibility.TO_TE_RATIO);
if (receiver.canInterface(outputDirection.getOpposite()) && receiver.receiveEnergy(outputDirection.getOpposite(), convertedProvide, true) > 0)
{
int forgienEnergyUsed = receiver.receiveEnergy(outputDirection.getOpposite(), convertedProvide, false);
this.provideElectricity(forgienEnergyUsed * Compatibility.TE_RATIO, true);
return true;
}
}
}
}
}
return false;
}
public boolean produceBuildCraft(ForgeDirection outputDirection)
{
if (!this.worldObj.isRemote && outputDirection != null && outputDirection != ForgeDirection.UNKNOWN)
{
float provide = this.getProvide(outputDirection);
if (this.getEnergyStored() >= provide && provide > 0)
{
if (Compatibility.isBuildcraftLoaded())
{
TileEntity tileEntity = new Vector3(this).modifyPositionFromSide(outputDirection).getTileEntity(this.worldObj);
if (tileEntity instanceof IPowerReceptor)
{
PowerReceiver receiver = ((IPowerReceptor) tileEntity).getPowerReceiver(outputDirection.getOpposite());
if (receiver != null)
{
if (receiver.powerRequest() > 0)
{
float convertedProvide = provide * Compatibility.TO_BC_RATIO;
float forgienEnergyUsed = receiver.receiveEnergy(this.bcBlockType, convertedProvide, outputDirection.getOpposite());
this.provideElectricity(forgienEnergyUsed * Compatibility.BC3_RATIO, true);
return true;
}
}
}
}
}
}
return false;
}
/**
* TE Methods
*/
public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate)
{
return (int) (this.receiveElectricity(from, ElectricityPack.getFromWatts(maxReceive * Compatibility.TE_RATIO, this.getVoltage()), !simulate) * Compatibility.TO_TE_RATIO);
}
public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate)
{
return (int) (this.provideElectricity(from, ElectricityPack.getFromWatts(maxExtract * Compatibility.TE_RATIO, this.getVoltage()), !simulate).getWatts() * Compatibility.TO_TE_RATIO);
}
public boolean canInterface(ForgeDirection from)
{
return this.canConnect(from);
}
/**
* Returns the amount of energy currently stored.
*/
public int getEnergyStored(ForgeDirection from)
{
return (int) (this.getEnergyStored() * Compatibility.TO_TE_RATIO);
}
/**
* Returns the maximum amount of energy that can be stored.
*/
public int getMaxEnergyStored(ForgeDirection from)
{
return (int) (this.getMaxEnergyStored() * Compatibility.TO_TE_RATIO);
}
/**
* IC2 Methods
*/
@Override
public boolean acceptsEnergyFrom(TileEntity emitter, ForgeDirection direction)
{
return this.getInputDirections().contains(direction);
}
@Override
public double getOfferedEnergy()
{
return this.getProvide(ForgeDirection.UNKNOWN) * Compatibility.TO_IC2_RATIO;
}
@Override
public void drawEnergy(double amount)
{
this.provideElectricity((float) amount * Compatibility.IC2_RATIO, true);
}
@Override
public void invalidate()
{
this.unloadTileIC2();
super.invalidate();
}
@Override
public void onChunkUnload()
{
this.unloadTileIC2();
super.onChunkUnload();
}
protected void initIC()
{
if (Compatibility.isIndustrialCraft2Loaded())
{
MinecraftForge.EVENT_BUS.post(new EnergyTileLoadEvent(this));
}
this.isAddedToEnergyNet = true;
}
private void unloadTileIC2()
{
if (this.isAddedToEnergyNet && this.worldObj != null)
{
if (Compatibility.isIndustrialCraft2Loaded())
{
MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this));
}
this.isAddedToEnergyNet = false;
}
}
@Override
public double demandedEnergyUnits()
{
return this.getRequest(ForgeDirection.UNKNOWN) * Compatibility.TO_IC2_RATIO;
}
@Override
public double injectEnergyUnits(ForgeDirection direction, double amount)
{
if (this.getInputDirections().contains(direction))
{
float convertedEnergy = (float) (amount * Compatibility.IC2_RATIO);
ElectricityPack toSend = ElectricityPack.getFromWatts(convertedEnergy, this.getVoltage());
float receive = this.receiveElectricity(direction, toSend, true);
// Return the difference, since injectEnergy returns left over energy, and
// receiveElectricity returns energy used.
return Math.round(amount - (receive * Compatibility.TO_IC2_RATIO));
}
return amount;
}
@Override
public boolean emitsEnergyTo(TileEntity receiver, ForgeDirection direction)
{
return receiver instanceof IEnergyTile && this.getOutputDirections().contains(direction);
}
@Override
public int getMaxSafeInput()
{
return Integer.MAX_VALUE;
}
/**
* BuildCraft power support
*/
public void initBuildCraft()
{
if (this.bcPowerHandler == null)
{
this.bcPowerHandler = new PowerHandler(this, this.bcBlockType);
}
this.bcPowerHandler.configure(0, this.maxInputEnergy, 0, (int) Math.ceil(this.getMaxEnergyStored() * Compatibility.BC3_RATIO));
}
@Override
public PowerReceiver getPowerReceiver(ForgeDirection side)
{
this.initBuildCraft();
return this.bcPowerHandler.getPowerReceiver();
}
@Override
public void doWork(PowerHandler workProvider)
{
}
@Override
public World getWorld()
{
return this.getWorldObj();
}
}

View file

@ -1,461 +0,0 @@
package universalelectricity.compatibility;
import ic2.api.energy.tile.IEnergyAcceptor;
import ic2.api.energy.tile.IEnergySink;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.ForgeDirection;
import net.minecraftforge.common.MinecraftForge;
import universalelectricity.core.block.IConductor;
import universalelectricity.core.block.IElectrical;
import universalelectricity.core.block.INetworkConnection;
import universalelectricity.core.block.INetworkProvider;
import universalelectricity.core.electricity.ElectricalEvent.ElectricityProductionEvent;
import universalelectricity.core.electricity.ElectricalEvent.ElectricityRequestEvent;
import universalelectricity.core.electricity.ElectricityPack;
import universalelectricity.core.grid.ElectricityNetwork;
import universalelectricity.core.grid.IElectricityNetwork;
import universalelectricity.core.path.Pathfinder;
import universalelectricity.core.path.PathfinderChecker;
import universalelectricity.core.vector.Vector3;
import universalelectricity.core.vector.VectorHelper;
import buildcraft.api.power.IPowerReceptor;
import buildcraft.api.power.PowerHandler.PowerReceiver;
import buildcraft.api.power.PowerHandler.Type;
import cofh.api.energy.IEnergyHandler;
import cpw.mods.fml.common.FMLLog;
/**
* A universal network that words with multiple energy systems.
*
* @author micdoodle8, Calclavia, Aidancbrady
*
*/
public class UniversalNetwork extends ElectricityNetwork
{
@Override
public float produce(ElectricityPack electricity, TileEntity... ignoreTiles)
{
ElectricityProductionEvent evt = new ElectricityProductionEvent(this, electricity, ignoreTiles);
MinecraftForge.EVENT_BUS.post(evt);
float totalEnergy = electricity.getWatts();
float networkResistance = getTotalResistance();
float proportionWasted = getTotalResistance() / (getTotalResistance() + acceptorResistance);
float energyWasted = totalEnergy * proportionWasted;
float totalUsableEnergy = totalEnergy - energyWasted;
float remainingUsableEnergy = totalUsableEnergy;
float voltage = electricity.voltage;
if (!evt.isCanceled())
{
Set<TileEntity> avaliableEnergyTiles = this.getAcceptors();
if (!avaliableEnergyTiles.isEmpty())
{
final float totalEnergyRequest = this.getRequest(ignoreTiles).getWatts();
if (totalEnergyRequest > 0)
{
boolean markRefresh = false;
for (TileEntity tileEntity : avaliableEnergyTiles)
{
if (tileEntity != null && !tileEntity.isInvalid())
{
if (remainingUsableEnergy > 0 && !Arrays.asList(ignoreTiles).contains(tileEntity))
{
if (tileEntity instanceof IElectrical)
{
IElectrical electricalTile = (IElectrical) tileEntity;
for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS)
{
if (electricalTile.canConnect(direction) && this.getConductors().contains(VectorHelper.getConnectorFromSide(tileEntity.worldObj, new Vector3(tileEntity), direction)))
{
float energyToSend = totalUsableEnergy * (Math.min(electricalTile.getRequest(direction), totalEnergyRequest) / totalEnergyRequest);
if (energyToSend > 0)
{
ElectricityPack electricityToSend = ElectricityPack.getFromWatts(energyToSend, voltage);
remainingUsableEnergy -= electricalTile.receiveElectricity(direction, electricityToSend, true);
}
}
}
}
else if (tileEntity instanceof IEnergySink)
{
IEnergySink electricalTile = (IEnergySink) tileEntity;
for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS)
{
TileEntity conductor = VectorHelper.getConnectorFromSide(tileEntity.worldObj, new Vector3(tileEntity), direction);
if (this.getConductors().contains(conductor) && electricalTile.acceptsEnergyFrom(conductor, direction))
{
float energyToSend = (float) Math.min(totalUsableEnergy * ((electricalTile.demandedEnergyUnits() * Compatibility.IC2_RATIO) / totalEnergyRequest), electricalTile.getMaxSafeInput() * Compatibility.IC2_RATIO);
if (energyToSend > 0)
{
remainingUsableEnergy -= electricalTile.injectEnergyUnits(direction, energyToSend * Compatibility.TO_IC2_RATIO) * Compatibility.IC2_RATIO;
}
}
}
}
else if (tileEntity instanceof IPowerReceptor)
{
IPowerReceptor electricalTile = (IPowerReceptor) tileEntity;
for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS)
{
TileEntity conductor = VectorHelper.getConnectorFromSide(tileEntity.worldObj, new Vector3(tileEntity), direction);
PowerReceiver receiver = electricalTile.getPowerReceiver(direction);
if (receiver != null)
{
if (this.getConductors().contains(conductor))
{
float energyToSend = totalUsableEnergy * ((receiver.powerRequest() * Compatibility.BC3_RATIO) / totalEnergyRequest);
if (energyToSend > 0)
{
remainingUsableEnergy -= receiver.receiveEnergy(Type.PIPE, energyToSend * Compatibility.TO_BC_RATIO, direction) * Compatibility.BC3_RATIO;
}
}
}
}
}
else if (tileEntity instanceof IEnergyHandler)
{
IEnergyHandler receiver = (IEnergyHandler) tileEntity;
for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS)
{
TileEntity conductor = VectorHelper.getConnectorFromSide(tileEntity.worldObj, new Vector3(tileEntity), direction);
if (receiver.canInterface(direction))
{
if (this.getConductors().contains(conductor))
{
float energyToSend = totalUsableEnergy * ((receiver.receiveEnergy(direction, (int) (remainingUsableEnergy * Compatibility.TO_TE_RATIO), true) * Compatibility.TE_RATIO) / totalEnergyRequest);
if (energyToSend > 0)
{
remainingUsableEnergy -= receiver.receiveEnergy(direction, (int) (energyToSend * Compatibility.TO_TE_RATIO), false) * Compatibility.TE_RATIO;
}
}
}
}
}
}
}
else
{
markRefresh = true;
}
}
if (markRefresh)
{
this.refresh();
}
}
}
}
return remainingUsableEnergy;
}
@Override
public ElectricityPack getRequest(TileEntity... ignoreTiles)
{
List<ElectricityPack> requests = new ArrayList<ElectricityPack>();
Iterator<TileEntity> it = new HashSet(this.getAcceptors()).iterator();
while (it.hasNext())
{
TileEntity tileEntity = it.next();
if (Arrays.asList(ignoreTiles).contains(tileEntity))
{
continue;
}
if (tileEntity != null && !tileEntity.isInvalid())
{
if (tileEntity.worldObj.getBlockTileEntity(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord) == tileEntity)
{
if (tileEntity instanceof IElectrical)
{
for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS)
{
if (((IElectrical) tileEntity).canConnect(direction) && this.getConductors().contains(VectorHelper.getConnectorFromSide(tileEntity.worldObj, new Vector3(tileEntity), direction)))
{
requests.add(ElectricityPack.getFromWatts(((IElectrical) tileEntity).getRequest(direction), ((IElectrical) tileEntity).getVoltage()));
}
}
continue;
}
if (tileEntity instanceof IEnergyHandler)
{
IEnergyHandler receiver = (IEnergyHandler) tileEntity;
for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS)
{
TileEntity conductor = VectorHelper.getConnectorFromSide(tileEntity.worldObj, new Vector3(tileEntity), direction);
if (receiver.canInterface(direction) && this.getConductors().contains(conductor))
{
ElectricityPack pack = ElectricityPack.getFromWatts(receiver.receiveEnergy(direction, (int) Integer.MAX_VALUE, true) * Compatibility.TE_RATIO, 1);
if (pack.getWatts() > 0)
{
requests.add(pack);
break;
}
}
}
continue;
}
if (tileEntity instanceof IEnergySink)
{
for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS)
{
if (((IEnergySink) tileEntity).acceptsEnergyFrom(VectorHelper.getTileEntityFromSide(tileEntity.worldObj, new Vector3(tileEntity), direction), direction) && this.getConductors().contains(VectorHelper.getConnectorFromSide(tileEntity.worldObj, new Vector3(tileEntity), direction)))
{
ElectricityPack pack = ElectricityPack.getFromWatts((float) (((IEnergySink) tileEntity).demandedEnergyUnits() * Compatibility.IC2_RATIO), 1);
if (pack.getWatts() > 0)
{
requests.add(pack);
}
}
}
continue;
}
if (tileEntity instanceof IPowerReceptor)
{
for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS)
{
if (((IPowerReceptor) tileEntity).getPowerReceiver(direction) != null)
{
ElectricityPack pack = ElectricityPack.getFromWatts(((IPowerReceptor) tileEntity).getPowerReceiver(direction).powerRequest() * Compatibility.BC3_RATIO, 1);
if (pack.getWatts() > 0)
{
requests.add(pack);
break;
}
}
}
continue;
}
}
}
}
ElectricityPack mergedPack = ElectricityPack.merge(requests);
ElectricityRequestEvent evt = new ElectricityRequestEvent(this, mergedPack, ignoreTiles);
MinecraftForge.EVENT_BUS.post(evt);
return mergedPack;
}
@Override
public void refresh()
{
this.electricalTiles.clear();
try
{
Iterator<IConductor> it = this.getConductors().iterator();
while (it.hasNext())
{
IConductor conductor = it.next();
if (conductor == null)
{
it.remove();
continue;
}
else if (((TileEntity) conductor).isInvalid() || ((TileEntity) conductor).getWorldObj() == null)
{
it.remove();
continue;
}
else if (((TileEntity) conductor).getWorldObj().getBlockTileEntity(((TileEntity) conductor).xCoord, ((TileEntity) conductor).yCoord, ((TileEntity) conductor).zCoord) != conductor)
{
it.remove();
continue;
}
else
{
conductor.setNetwork(this);
}
for (int i = 0; i < conductor.getAdjacentConnections().length; i++)
{
TileEntity acceptor = conductor.getAdjacentConnections()[i];
// The direction is from the perspective of the conductor.
ForgeDirection direction = ForgeDirection.getOrientation(i);
if (!(acceptor instanceof IConductor))
{
if (acceptor instanceof IElectrical || acceptor instanceof IEnergyHandler || acceptor instanceof IEnergyAcceptor || acceptor instanceof IPowerReceptor)
{
ArrayList<ForgeDirection> possibleDirections = null;
if (this.electricalTiles.containsKey(acceptor))
{
possibleDirections = this.electricalTiles.get(acceptor);
}
else
{
possibleDirections = new ArrayList<ForgeDirection>();
}
if (acceptor instanceof IElectrical && ((IElectrical) acceptor).canConnect(direction))
{
possibleDirections.add(direction);
}
else if (acceptor instanceof IEnergyHandler && ((IEnergyHandler) acceptor).canInterface(direction))
{
possibleDirections.add(direction);
}
else if (acceptor instanceof IEnergyAcceptor && ((IEnergyAcceptor) acceptor).acceptsEnergyFrom((TileEntity) conductor, direction))
{
possibleDirections.add(direction);
}
else if (acceptor instanceof IPowerReceptor && ((IPowerReceptor) acceptor).getPowerReceiver(direction) != null)
{
possibleDirections.add(direction);
}
if (!possibleDirections.isEmpty())
{
this.electricalTiles.put(acceptor, possibleDirections);
}
continue;
}
}
}
}
}
catch (Exception e)
{
FMLLog.severe("Universal Electricity: Failed to refresh conductor.");
e.printStackTrace();
}
}
@Override
public void merge(IElectricityNetwork network)
{
if (network != null && network != this)
{
UniversalNetwork newNetwork = new UniversalNetwork();
newNetwork.getConductors().addAll(this.getConductors());
newNetwork.getConductors().addAll(network.getConductors());
newNetwork.refresh();
}
}
@Override
public void split(IConductor splitPoint)
{
if (splitPoint instanceof TileEntity)
{
this.getConductors().remove(splitPoint);
/**
* Loop through the connected blocks and attempt to see if there are connections between
* the two points elsewhere.
*/
TileEntity[] connectedBlocks = splitPoint.getAdjacentConnections();
for (int i = 0; i < connectedBlocks.length; i++)
{
TileEntity connectedBlockA = connectedBlocks[i];
if (connectedBlockA instanceof INetworkConnection)
{
for (int ii = 0; ii < connectedBlocks.length; ii++)
{
final TileEntity connectedBlockB = connectedBlocks[ii];
if (connectedBlockA != connectedBlockB && connectedBlockB instanceof INetworkConnection)
{
Pathfinder finder = new PathfinderChecker(((TileEntity) splitPoint).worldObj, (INetworkConnection) connectedBlockB, splitPoint);
finder.init(new Vector3(connectedBlockA));
if (finder.results.size() > 0)
{
/**
* The connections A and B are still intact elsewhere. Set all
* references of wire connection into one network.
*/
for (Vector3 node : finder.closedSet)
{
TileEntity nodeTile = node.getTileEntity(((TileEntity) splitPoint).worldObj);
if (nodeTile instanceof INetworkProvider)
{
if (nodeTile != splitPoint)
{
((INetworkProvider) nodeTile).setNetwork(this);
}
}
}
}
else
{
/**
* The connections A and B are not connected anymore. Give both of
* them a new network.
*/
IElectricityNetwork newNetwork = new UniversalNetwork();
for (Vector3 node : finder.closedSet)
{
TileEntity nodeTile = node.getTileEntity(((TileEntity) splitPoint).worldObj);
if (nodeTile instanceof INetworkProvider)
{
if (nodeTile != splitPoint)
{
newNetwork.getConductors().add((IConductor) nodeTile);
}
}
}
newNetwork.refresh();
}
}
}
}
}
}
}
@Override
public String toString()
{
return "UniversalNetwork[" + this.hashCode() + "|Wires:" + this.getConductors().size() + "|Acceptors:" + this.electricalTiles.size() + "]";
}
}

View file

@ -1,86 +0,0 @@
package universalelectricity.core;
import java.io.File;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import net.minecraftforge.common.Configuration;
import net.minecraftforge.common.MinecraftForge;
import cpw.mods.fml.common.Loader;
/**
* General Universal Electricity class.
*
* @author Calclavia
*
*/
public class UniversalElectricity
{
/**
* The version of the Universal Electricity API.
*/
public static final String MAJOR_VERSION = "@MAJOR@";
public static final String MINOR_VERSION = "@MINOR@";
public static final String REVISION_VERSION = "@REVIS@";
public static final String BUILD_VERSION = "@BUILD@";
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.cfg"));
/**
* Is Universal Electricity currently being voltage sensitive? If so, all machines should
* explode under high voltage and react to different amounts of voltage differently.
*/
public static boolean isVoltageSensitive = false;
//TODO: Enable this next major MC version
//public static float DEFAULT_VOLTAGE = 1;
/**
* Set this value to true if your mod contains and has the ability to transfer electricity via
* the ElectricityNetwork. Examples would be a mod that adds any sort of wire. This value will
* be true as long as there is a way to conduct electricity.
*/
@Deprecated
public static boolean isNetworkActive = false;
/**
* A general material that can be used by machines. Breakable by hand, suitable for machines.
*/
public static final Material machine = new Material(MapColor.ironColor);
private static boolean INIT = false;
static
{
initiate();
}
public static void initiate()
{
if (!INIT)
{
/**
* Loads the configuration and sets all the values.
*/
CONFIGURATION.load();
isVoltageSensitive = CONFIGURATION.get("Compatiblity", "Is Voltage Sensitive", isVoltageSensitive).getBoolean(isVoltageSensitive);
isNetworkActive = CONFIGURATION.get("Compatiblity", "Is Network Active", isNetworkActive).getBoolean(isNetworkActive);
CONFIGURATION.save();
try
{
MinecraftForge.EVENT_BUS.register(Class.forName("universalelectricity.core.electricity.ElectricityHelper").newInstance());
}
catch (Exception e)
{
e.printStackTrace();
}
}
INIT = true;
}
}

View file

@ -1,17 +0,0 @@
package universalelectricity.core.block;
public interface IConductor extends INetworkProvider, INetworkConnection
{
/**
* Gets the resistance of the conductor. Used to calculate energy loss. A higher resistance
* means a higher energy loss.
*
* @return The amount of resistance in Ohms.
*/
public float getResistance();
/**
* @return The maximum amount of amps this conductor can handle before melting down.
*/
public float getCurrentCapacity();
}

View file

@ -1,18 +0,0 @@
package universalelectricity.core.block;
import net.minecraftforge.common.ForgeDirection;
/**
* Applied to TileEntities that can connect to an electrical network.
*
* @author Calclavia
*
*/
public interface IConnector
{
/**
* @return If the connection is possible.
*/
public boolean canConnect(ForgeDirection direction);
}

View file

@ -1,53 +0,0 @@
package universalelectricity.core.block;
import net.minecraftforge.common.ForgeDirection;
import universalelectricity.core.electricity.ElectricityPack;
/**
* Applied to all TileEntities that can interact with electricity.
*
* @author Calclavia, King_Lemming
*
*/
public interface IElectrical extends IConnector
{
/**
* Adds electricity to an block. Returns the quantity of electricity that was accepted. This
* should always return 0 if the block cannot be externally charged.
*
* @param from Orientation the electricity is sent in from.
* @param receive Maximum amount of electricity to be sent into the block.
* @param doReceive If false, the charge will only be simulated.
* @return Amount of energy that was accepted by the block.
*/
public float receiveElectricity(ForgeDirection from, ElectricityPack receive, boolean doReceive);
/**
* Adds electricity to an block. Returns the ElectricityPack, the electricity provided. This
* should always return null if the block cannot be externally discharged.
*
* @param from Orientation the electricity is requested from.
* @param energy Maximum amount of energy to be sent into the block.
* @param doReceive If false, the charge will only be simulated.
* @return Amount of energy that was given out by the block.
*/
public ElectricityPack provideElectricity(ForgeDirection from, ElectricityPack request, boolean doProvide);
/**
* @return How much energy does this TileEntity want?
*/
public float getRequest(ForgeDirection direction);
/**
* @return How much energy does this TileEntity want to provide?
*/
public float getProvide(ForgeDirection direction);
/**
* Gets the voltage of this TileEntity.
*
* @return The amount of volts. E.g 120v or 240v
*/
public float getVoltage();
}

View file

@ -1,24 +0,0 @@
package universalelectricity.core.block;
/**
* This interface is to be applied to all TileEntities which stores electricity within them.
*
* @author Calclavia
*/
public interface IElectricalStorage
{
/**
* Sets the amount of joules this unit has stored.
*/
public void setEnergyStored(float energy);
/**
* * @return Get the amount of energy currently stored in the block.
*/
public float getEnergyStored();
/**
* @return Get the max amount of energy that can be stored in the block.
*/
public float getMaxEnergyStored();
}

View file

@ -1,26 +0,0 @@
package universalelectricity.core.block;
import net.minecraft.tileentity.TileEntity;
/**
* Applied to TileEntities.
*
* @author Calclavia
*
*/
public interface INetworkConnection extends IConnector
{
/**
* Gets a list of all the connected TileEntities that this conductor is connected to. The
* array's length should be always the 6 adjacent wires.
*
* @return
*/
public TileEntity[] getAdjacentConnections();
/**
* Refreshes the conductor
*/
public void refresh();
}

View file

@ -1,16 +0,0 @@
package universalelectricity.core.block;
import universalelectricity.core.grid.IElectricityNetwork;
/**
* Applied to TileEntities that has an instance of an electricity network.
*
* @author Calclavia
*
*/
public interface INetworkProvider
{
public IElectricityNetwork getNetwork();
public void setNetwork(IElectricityNetwork network);
}

View file

@ -1,68 +0,0 @@
package universalelectricity.core.electricity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraftforge.event.Cancelable;
import net.minecraftforge.event.Event;
import universalelectricity.core.block.IElectrical;
import universalelectricity.core.grid.IElectricityNetwork;
public class ElectricalEvent extends Event
{
/**
* Call this to have your TileEntity produce power into the network.
*
* @author Calclavia
*
*/
@Cancelable
public static class ElectricityProduceEvent extends ElectricalEvent
{
public World world;
public IElectrical tileEntity;
public ElectricityProduceEvent(IElectrical tileEntity)
{
this.tileEntity = tileEntity;
this.world = ((TileEntity) this.tileEntity).worldObj;
}
}
public static class NetworkEvent extends ElectricalEvent
{
public final IElectricityNetwork network;
public ElectricityPack electricityPack;
public TileEntity[] ignoreTiles;
public NetworkEvent(IElectricityNetwork network, ElectricityPack electricityPack, TileEntity... ignoreTiles)
{
this.network = network;
this.electricityPack = electricityPack;
this.ignoreTiles = ignoreTiles;
}
}
/**
* Internal Events. These events are fired when something happens in the network.
*
* @author Calclavia
*
*/
@Cancelable
public static class ElectricityProductionEvent extends NetworkEvent
{
public ElectricityProductionEvent(IElectricityNetwork network, ElectricityPack electricityPack, TileEntity... ignoreTiles)
{
super(network, electricityPack, ignoreTiles);
}
}
public static class ElectricityRequestEvent extends NetworkEvent
{
public ElectricityRequestEvent(IElectricityNetwork network, ElectricityPack electricityPack, TileEntity... ignoreTiles)
{
super(network, electricityPack, ignoreTiles);
}
}
}

View file

@ -1,152 +0,0 @@
package universalelectricity.core.electricity;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.ForgeDirection;
import universalelectricity.core.block.IConnector;
import universalelectricity.core.block.INetworkProvider;
import universalelectricity.core.grid.IElectricityNetwork;
import universalelectricity.core.vector.Vector3;
/**
* A helper class that provides additional useful functions to interact with the ElectricityNetwork
*
* @author Calclavia
*
*/
public class ElectricityHelper
{
public static EnumSet<ForgeDirection> getDirections(TileEntity tileEntity)
{
EnumSet<ForgeDirection> possibleSides = EnumSet.noneOf(ForgeDirection.class);
if (tileEntity instanceof IConnector)
{
for (int i = 0; i < 6; i++)
{
ForgeDirection direction = ForgeDirection.getOrientation(i);
if (((IConnector) tileEntity).canConnect(direction))
{
possibleSides.add(direction);
}
}
}
return possibleSides;
}
@Deprecated
public static ElectricityPack produceFromMultipleSides(TileEntity tileEntity, ElectricityPack electricityPack)
{
return ElectricityHelper.produceFromMultipleSides(tileEntity, getDirections(tileEntity), electricityPack);
}
/**
* Produces electricity from all specified sides. Use this as a simple helper function.
*
* @param tileEntity - The TileEntity consuming the electricity.
* @param approachDirection - The sides in which you can connect to.
* @param producePack - The amount of electricity to be produced.
* @return What remained in the electricity pack.
*/
@Deprecated
public static ElectricityPack produceFromMultipleSides(TileEntity tileEntity, EnumSet<ForgeDirection> approachingDirection, ElectricityPack producingPack)
{
ElectricityPack remainingElectricity = producingPack.clone();
if (tileEntity != null && approachingDirection != null)
{
final Set<IElectricityNetwork> connectedNetworks = ElectricityHelper.getNetworksFromMultipleSides(tileEntity, approachingDirection);
if (connectedNetworks.size() > 0)
{
/**
* Requests an even amount of electricity from all sides.
*/
float wattsPerSide = (producingPack.getWatts() / connectedNetworks.size());
float voltage = producingPack.voltage;
for (IElectricityNetwork network : connectedNetworks)
{
if (wattsPerSide > 0 && producingPack.getWatts() > 0)
{
float amperes = Math.min(wattsPerSide / voltage, network.getRequest(tileEntity).getWatts() / voltage);
if (amperes > 0)
{
network.produce(new ElectricityPack(amperes, voltage));
remainingElectricity.amperes -= amperes;
}
}
}
}
}
return remainingElectricity;
}
/**
* @param tileEntity - The TileEntity's sides.
* @param approachingDirection - The directions that can be connected.
* @return A list of networks from all specified sides. There will be no repeated
* ElectricityNetworks and it will never return null.
*/
public static Set<IElectricityNetwork> getNetworksFromMultipleSides(TileEntity tileEntity, EnumSet<ForgeDirection> approachingDirection)
{
final Set<IElectricityNetwork> connectedNetworks = new HashSet<IElectricityNetwork>();
for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS)
{
if (approachingDirection.contains(side))
{
Vector3 position = new Vector3(tileEntity);
position.modifyPositionFromSide(side);
TileEntity outputConductor = position.getTileEntity(tileEntity.worldObj);
IElectricityNetwork electricityNetwork = ElectricityHelper.getNetworkFromTileEntity(outputConductor, side);
if (electricityNetwork != null)
{
connectedNetworks.add(electricityNetwork);
}
}
}
return connectedNetworks;
}
/**
* Tries to find the electricity network based in a tile entity and checks to see if it is a
* conductor. All machines should use this function to search for a connecting conductor around
* it.
*
* @param conductor - The TileEntity conductor
* @param approachDirection - The direction you are approaching this wire from.
* @return The ElectricityNetwork or null if not found.
*/
public static IElectricityNetwork getNetworkFromTileEntity(TileEntity tileEntity, ForgeDirection approachDirection)
{
if (tileEntity != null)
{
if (tileEntity instanceof INetworkProvider)
{
if (tileEntity instanceof IConnector)
{
if (((IConnector) tileEntity).canConnect(approachDirection.getOpposite()))
{
return ((INetworkProvider) tileEntity).getNetwork();
}
}
else
{
return ((INetworkProvider) tileEntity).getNetwork();
}
}
}
return null;
}
}

View file

@ -1,196 +0,0 @@
package universalelectricity.core.electricity;
import java.util.List;
/**
* A simple way to store electrical data.
*
* @author Calclavia
*
*/
public class ElectricityPack implements Cloneable
{
public float amperes;
public float voltage;
public ElectricityPack(float amperes, float voltage)
{
this.amperes = amperes;
this.voltage = voltage;
}
public ElectricityPack()
{
this(0, 0);
}
public static ElectricityPack getFromWatts(float watts, float voltage)
{
return new ElectricityPack(watts / voltage, voltage);
}
/**
* Merges multiple ElectricityPacks together to form one with an average voltage.
*/
public static ElectricityPack merge(ElectricityPack... packs)
{
float totalEnergy = 0;
float totalVoltage = 0;
for (ElectricityPack pack : packs)
{
totalEnergy += pack.getWatts();
totalVoltage += pack.voltage;
}
if (totalEnergy <= 0 || totalVoltage <= 0)
{
return new ElectricityPack();
}
return ElectricityPack.getFromWatts(totalEnergy, totalVoltage / packs.length);
}
public static ElectricityPack merge(List<ElectricityPack> providedPacks)
{
return merge(providedPacks.toArray(new ElectricityPack[0]));
}
/**
* @return Returns the ElectricityPack with the largest amount of energy.
*/
public static ElectricityPack max(ElectricityPack... packs)
{
ElectricityPack optimalPack = null;
for (ElectricityPack pack : packs)
{
if (optimalPack == null || (optimalPack != null && pack.getWatts() > optimalPack.getWatts()))
{
optimalPack = pack;
}
}
return optimalPack;
}
/**
* @return Returns the ElectricityPack with the smallest amount of energy.
*/
public static ElectricityPack min(ElectricityPack... packs)
{
ElectricityPack optimalPack = null;
for (ElectricityPack pack : packs)
{
if (optimalPack == null || (optimalPack != null && pack.getWatts() < optimalPack.getWatts()))
{
optimalPack = pack;
}
}
return optimalPack;
}
public float getWatts()
{
return getWatts(amperes, voltage);
}
public float getConductance()
{
return getConductance(amperes, voltage);
}
public float getResistance()
{
return getResistance(amperes, voltage);
}
public static float getJoules(float watts, float seconds)
{
return watts * seconds;
}
public static float getJoules(float amps, float voltage, float seconds)
{
return amps * voltage * seconds;
}
public static float getWattsFromJoules(float joules, float seconds)
{
return joules / seconds;
}
public static float getAmps(float watts, float voltage)
{
return watts / voltage;
}
public static float getAmps(float ampHours)
{
return ampHours * 3600;
}
public static float getAmpsFromWattHours(float wattHours, float voltage)
{
return getWatts(wattHours) / voltage;
}
public static float getWattHoursFromAmpHours(float ampHours, float voltage)
{
return ampHours * voltage;
}
public static float getAmpHours(float amps)
{
return amps / 3600;
}
public static float getWatts(float amps, float voltage)
{
return amps * voltage;
}
public static float getWatts(float wattHours)
{
return wattHours * 3600;
}
public static float getWattHours(float watts)
{
return watts / 3600;
}
public static float getWattHours(float amps, float voltage)
{
return getWattHours(getWatts(amps, voltage));
}
public static float getResistance(float amps, float voltage)
{
return voltage / amps;
}
public static float getConductance(float amps, float voltage)
{
return amps / voltage;
}
@Override
public String toString()
{
return "ElectricityPack [Amps:" + this.amperes + " Volts:" + this.voltage + "]";
}
@Override
public ElectricityPack clone()
{
return new ElectricityPack(this.amperes, this.voltage);
}
public boolean isEqual(ElectricityPack electricityPack)
{
return this.amperes == electricityPack.amperes && this.voltage == electricityPack.voltage;
}
}

View file

@ -1,64 +0,0 @@
package universalelectricity.core.electricity;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import universalelectricity.core.block.IConductor;
import universalelectricity.core.grid.IElectricityNetwork;
import cpw.mods.fml.common.FMLLog;
@SuppressWarnings("unchecked")
public class NetworkLoader
{
/**
* The default IElectricityNetwork used for primary electrical networks.
*/
public static Class<? extends IElectricityNetwork> NETWORK_CLASS;
public static final Set<Class<? extends IElectricityNetwork>> NETWORK_CLASS_REGISTRY = new HashSet<Class<? extends IElectricityNetwork>>();
static
{
setNetworkClass("universalelectricity.core.grid.ElectricityNetwork");
}
public static void setNetworkClass(Class<? extends IElectricityNetwork> networkClass)
{
NETWORK_CLASS_REGISTRY.add(networkClass);
NETWORK_CLASS = networkClass;
}
public static void setNetworkClass(String className)
{
try
{
setNetworkClass((Class<? extends IElectricityNetwork>) Class.forName(className));
}
catch (Exception e)
{
FMLLog.severe("Universal Electricity: Failed to set network class with name " + className);
e.printStackTrace();
}
}
public static IElectricityNetwork getNewNetwork(IConductor... conductors)
{
try
{
IElectricityNetwork network = NETWORK_CLASS.newInstance();
network.getConductors().addAll(Arrays.asList(conductors));
return network;
}
catch (InstantiationException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
return null;
}
}

View file

@ -1,356 +0,0 @@
package universalelectricity.core.grid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.ForgeDirection;
import net.minecraftforge.common.MinecraftForge;
import universalelectricity.core.block.IConductor;
import universalelectricity.core.block.IConnector;
import universalelectricity.core.block.IElectrical;
import universalelectricity.core.block.INetworkConnection;
import universalelectricity.core.block.INetworkProvider;
import universalelectricity.core.electricity.ElectricalEvent.ElectricityProductionEvent;
import universalelectricity.core.electricity.ElectricalEvent.ElectricityRequestEvent;
import universalelectricity.core.electricity.ElectricityPack;
import universalelectricity.core.path.Pathfinder;
import universalelectricity.core.path.PathfinderChecker;
import universalelectricity.core.vector.Vector3;
import universalelectricity.core.vector.VectorHelper;
import cpw.mods.fml.common.FMLLog;
/**
* An Electrical Network specifies a wire connection. Each wire connection line will have its own
* electrical network.
*
* !! Do not include this class if you do not intend to have custom wires in your mod. This will
* increase future compatibility. !!
*
* @author Calclavia
*
*/
public class ElectricityNetwork implements IElectricityNetwork
{
public Map<TileEntity, ArrayList<ForgeDirection>> electricalTiles = new HashMap<TileEntity, ArrayList<ForgeDirection>>();
private final Set<IConductor> conductors = new HashSet<IConductor>();
public float acceptorResistance = 500;
@Override
public float produce(ElectricityPack electricity, TileEntity... ignoreTiles)
{
ElectricityProductionEvent evt = new ElectricityProductionEvent(this, electricity, ignoreTiles);
MinecraftForge.EVENT_BUS.post(evt);
float totalEnergy = electricity.getWatts();
float networkResistance = getTotalResistance();
float proportionWasted = getTotalResistance() / (getTotalResistance() + acceptorResistance);
float energyWasted = totalEnergy * proportionWasted;
float totalUsableEnergy = totalEnergy - energyWasted;
float remainingUsableEnergy = totalUsableEnergy;
float voltage = electricity.voltage;
if (!evt.isCanceled())
{
Set<TileEntity> avaliableEnergyTiles = this.getAcceptors();
if (!avaliableEnergyTiles.isEmpty())
{
final float totalEnergyRequest = this.getRequest(ignoreTiles).getWatts();
if (totalEnergyRequest > 0)
{
for (TileEntity tileEntity : avaliableEnergyTiles)
{
if (!Arrays.asList(ignoreTiles).contains(tileEntity))
{
if (tileEntity instanceof IElectrical)
{
IElectrical electricalTile = (IElectrical) tileEntity;
for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS)
{
if (electricalTile.canConnect(direction) && this.getConductors().contains(VectorHelper.getConnectorFromSide(tileEntity.worldObj, new Vector3(tileEntity), direction)))
{
float energyToSend = totalUsableEnergy * (electricalTile.getRequest(direction) / totalEnergyRequest);
if (energyToSend > 0)
{
ElectricityPack electricityToSend = ElectricityPack.getFromWatts(energyToSend, voltage);
remainingUsableEnergy -= ((IElectrical) tileEntity).receiveElectricity(direction, electricityToSend, true);
}
}
}
}
}
}
}
}
}
return remainingUsableEnergy;
}
/**
* @return How much electricity this network needs.
*/
@Override
public ElectricityPack getRequest(TileEntity... ignoreTiles)
{
List<ElectricityPack> requests = new ArrayList<ElectricityPack>();
Iterator<TileEntity> it = this.getAcceptors().iterator();
while (it.hasNext())
{
TileEntity tileEntity = it.next();
if (Arrays.asList(ignoreTiles).contains(tileEntity))
{
continue;
}
if (tileEntity instanceof IElectrical)
{
if (!tileEntity.isInvalid())
{
if (tileEntity.worldObj.getBlockTileEntity(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord) == tileEntity)
{
for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS)
{
if (((IElectrical) tileEntity).canConnect(direction) && this.getConductors().contains(VectorHelper.getConnectorFromSide(tileEntity.worldObj, new Vector3(tileEntity), direction)))
{
requests.add(ElectricityPack.getFromWatts(((IElectrical) tileEntity).getRequest(direction), ((IElectrical) tileEntity).getVoltage()));
continue;
}
}
}
}
}
}
ElectricityPack mergedPack = ElectricityPack.merge(requests);
ElectricityRequestEvent evt = new ElectricityRequestEvent(this, mergedPack, ignoreTiles);
MinecraftForge.EVENT_BUS.post(evt);
return mergedPack;
}
/**
* @return Returns all producers in this electricity network.
*/
@Override
public Set<TileEntity> getAcceptors()
{
return this.electricalTiles.keySet();
}
/**
* @param tile The tile to get connections for
* @return The list of directions that can be connected to for the provided tile
*/
@Override
public ArrayList<ForgeDirection> getPossibleDirections(TileEntity tile)
{
return this.electricalTiles.containsKey(tile) ? this.electricalTiles.get(tile) : null;
}
/**
* This function is called to refresh all conductors in this network
*/
@Override
public void refresh()
{
this.electricalTiles.clear();
try
{
Iterator<IConductor> it = this.conductors.iterator();
while (it.hasNext())
{
IConductor conductor = it.next();
if (conductor == null)
{
it.remove();
}
else if (((TileEntity) conductor).isInvalid())
{
it.remove();
}
else
{
conductor.setNetwork(this);
}
for (int i = 0; i < conductor.getAdjacentConnections().length; i++)
{
TileEntity acceptor = conductor.getAdjacentConnections()[i];
if (!(acceptor instanceof IConductor) && acceptor instanceof IConnector)
{
ArrayList<ForgeDirection> possibleDirections = null;
if (this.electricalTiles.containsKey(acceptor))
{
possibleDirections = this.electricalTiles.get(acceptor);
}
else
{
possibleDirections = new ArrayList<ForgeDirection>();
}
possibleDirections.add(ForgeDirection.getOrientation(i));
this.electricalTiles.put(acceptor, possibleDirections);
}
}
}
}
catch (Exception e)
{
FMLLog.severe("Universal Electricity: Failed to refresh conductor.");
e.printStackTrace();
}
}
@Override
public float getTotalResistance()
{
float resistance = 0;
for (IConductor conductor : this.conductors)
{
resistance += conductor.getResistance();
}
return resistance;
}
@Override
public float getLowestCurrentCapacity()
{
float lowestAmperage = 0;
for (IConductor conductor : this.conductors)
{
if (lowestAmperage == 0 || conductor.getCurrentCapacity() < lowestAmperage)
{
lowestAmperage = conductor.getCurrentCapacity();
}
}
return lowestAmperage;
}
@Override
public Set<IConductor> getConductors()
{
return this.conductors;
}
@Override
public void merge(IElectricityNetwork network)
{
if (network != null && network != this)
{
ElectricityNetwork newNetwork = new ElectricityNetwork();
newNetwork.getConductors().addAll(this.getConductors());
newNetwork.getConductors().addAll(network.getConductors());
newNetwork.refresh();
}
}
@Override
public void split(IConductor splitPoint)
{
if (splitPoint instanceof TileEntity)
{
this.getConductors().remove(splitPoint);
/**
* Loop through the connected blocks and attempt to see if there are connections between
* the two points elsewhere.
*/
TileEntity[] connectedBlocks = splitPoint.getAdjacentConnections();
for (int i = 0; i < connectedBlocks.length; i++)
{
TileEntity connectedBlockA = connectedBlocks[i];
if (connectedBlockA instanceof INetworkConnection)
{
for (int ii = 0; ii < connectedBlocks.length; ii++)
{
final TileEntity connectedBlockB = connectedBlocks[ii];
if (connectedBlockA != connectedBlockB && connectedBlockB instanceof INetworkConnection)
{
Pathfinder finder = new PathfinderChecker(((TileEntity) splitPoint).worldObj, (INetworkConnection) connectedBlockB, splitPoint);
finder.init(new Vector3(connectedBlockA));
if (finder.results.size() > 0)
{
/**
* The connections A and B are still intact elsewhere. Set all
* references of wire connection into one network.
*/
for (Vector3 node : finder.closedSet)
{
TileEntity nodeTile = node.getTileEntity(((TileEntity) splitPoint).worldObj);
if (nodeTile instanceof INetworkProvider)
{
if (nodeTile != splitPoint)
{
((INetworkProvider) nodeTile).setNetwork(this);
}
}
}
}
else
{
/**
* The connections A and B are not connected anymore. Give both of
* them a new network.
*/
IElectricityNetwork newNetwork = new ElectricityNetwork();
for (Vector3 node : finder.closedSet)
{
TileEntity nodeTile = node.getTileEntity(((TileEntity) splitPoint).worldObj);
if (nodeTile instanceof INetworkProvider)
{
if (nodeTile != splitPoint)
{
newNetwork.getConductors().add((IConductor) nodeTile);
}
}
}
newNetwork.refresh();
}
}
}
}
}
}
}
@Override
public String toString()
{
return "ElectricityNetwork[" + this.hashCode() + "|Wires:" + this.conductors.size() + "|Acceptors:" + this.electricalTiles.size() + "]";
}
}

View file

@ -1,38 +0,0 @@
package universalelectricity.core.grid;
import net.minecraft.tileentity.TileEntity;
import universalelectricity.core.block.IConductor;
import universalelectricity.core.electricity.ElectricityPack;
/**
* The Electrical Network in interface form.
*
* @author Calclavia
*
*/
public interface IElectricityNetwork extends IGridNetwork<IElectricityNetwork, IConductor, TileEntity>
{
/**
* Produces electricity in this electrical network.
*
* @return Rejected energy in Joules.
*/
public float produce(ElectricityPack electricityPack, TileEntity... ignoreTiles);
/**
* Gets the total amount of electricity requested/needed in the electricity network.
*
* @param ignoreTiles The TileEntities to ignore during this calculation (optional).
*/
public ElectricityPack getRequest(TileEntity... ignoreTiles);
/**
* @return The total amount of resistance of this electrical network. In Ohms.
*/
public float getTotalResistance();
/**
* @return The lowest amount of current (amperage) that this electrical network can tolerate.
*/
public float getLowestCurrentCapacity();
}

View file

@ -1,66 +0,0 @@
package universalelectricity.core.grid;
import java.util.ArrayList;
import java.util.Set;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.ForgeDirection;
/**
* Implement this in your network class/interface if you plan to have your own network defined by
* specific conductors and acceptors.
*
* @author aidancbrady
*
* @param <N> - the class/interface Type value in which you implement this
* @param <C> - the class/interface Type which makes up the network's conductor Set
* @param <A> - the class/interface Type which makes up the network's acceptor Set
*/
public interface IGridNetwork<N, C, A>
{
/**
* Refreshes and cleans up conductor references of this network, as well as updating the
* acceptor set.
*/
public void refresh();
/**
* Gets the Set of conductors that make up this network.
*
* @return conductor set
*/
public Set<C> getConductors();
/**
* Gets the Set of AVAILABLE acceptors in this network. Make sure this doesn't include any stray
* acceptors which cannot accept resources.
*
* @return available acceptor set
*/
public Set<A> getAcceptors();
/**
* Gets the list of possible connection directions for the provided TileEntity. Tile must be in
* this network.
*
* @param tile The tile to get connections for
* @return The list of directions that can be connected to for the provided tile
*/
public ArrayList<ForgeDirection> getPossibleDirections(TileEntity tile);
/**
* Creates a new network that makes up the current network and the network defined in the
* parameters. Be sure to refresh the new network inside this method.
*
* @param network - network to merge
*/
public void merge(N network);
/**
* Splits a network by the conductor referenced in the parameters. It will then create and
* refresh the new independent networks possibly created by this operation.
*
* @param connection
*/
public void split(C connection);
}

View file

@ -1,92 +0,0 @@
package universalelectricity.core.item;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
/**
* Some helper functions for electric items.
*
* @author Calclavia
*
*/
public class ElectricItemHelper
{
/**
* Recharges an electric item.
*
* @param joules - The joules being provided to the electric item
* @return The total amount of joules provided by the provider.
*/
public static float chargeItem(ItemStack itemStack, float joules)
{
if (itemStack != null)
{
if (itemStack.getItem() instanceof IItemElectric)
{
return ((IItemElectric) itemStack.getItem()).recharge(itemStack, Math.min(((IItemElectric) itemStack.getItem()).getTransfer(itemStack), joules), true);
}
}
return 0;
}
/**
* Decharges an electric item.
*
* @param joules - The joules being withdrawn from the electric item
* @return The total amount of joules the provider received.
*/
public static float dischargeItem(ItemStack itemStack, float joules)
{
if (itemStack != null)
{
if (itemStack.getItem() instanceof IItemElectric)
{
return ((IItemElectric) itemStack.getItem()).discharge(itemStack, Math.min(((IItemElectric) itemStack.getItem()).getMaxElectricityStored(itemStack), joules), true);
}
}
return 0;
}
/**
* 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 An electrical ItemStack with a specific charge.
*/
public static ItemStack getWithCharge(ItemStack itemStack, float joules)
{
if (itemStack != null)
{
if (itemStack.getItem() instanceof IItemElectric)
{
((IItemElectric) itemStack.getItem()).setElectricity(itemStack, joules);
return itemStack;
}
}
return itemStack;
}
public static ItemStack getWithCharge(Item item, float joules)
{
return getWithCharge(new ItemStack(item), joules);
}
public static ItemStack getCloneWithCharge(ItemStack itemStack, float joules)
{
return getWithCharge(itemStack.copy(), joules);
}
public static ItemStack getUncharged(ItemStack itemStack)
{
return getWithCharge(itemStack, 0);
}
public static ItemStack getUncharged(Item item)
{
return getUncharged(new ItemStack(item));
}
}

View file

@ -1,56 +0,0 @@
package universalelectricity.core.item;
import net.minecraft.item.ItemStack;
public interface IItemElectric
{
/**
* Adds energy to an item. Returns the quantity of energy that was accepted. This should always
* return 0 if the item cannot be externally charged.
*
* @param itemStack ItemStack to be charged.
* @param energy Maximum amount of energy to be sent into the item.
* @param doRecharge If false, the charge will only be simulated.
* @return Amount of energy that was accepted by the item.
*/
public float recharge(ItemStack itemStack, float energy, boolean doRecharge);
/**
* Removes energy from an item. Returns the quantity of energy that was removed. This should
* always return 0 if the item cannot be externally discharged.
*
* @param itemStack ItemStack to be discharged.
* @param energy Maximum amount of energy to be removed from the item.
* @param doDischarge If false, the discharge will only be simulated.
* @return Amount of energy that was removed from the item.
*/
public float discharge(ItemStack itemStack, float energy, boolean doDischarge);
/**
* Get the amount of energy currently stored in the item.
*/
public float getElectricityStored(ItemStack theItem);
/**
* Get the max amount of energy that can be stored in the item.
*/
public float getMaxElectricityStored(ItemStack theItem);
/**
* Sets the amount of energy in the ItemStack.
*
* @param itemStack - the ItemStack.
* @param joules - Amount of electrical energy.
*/
public void setElectricity(ItemStack itemStack, float joules);
/**
* @return the energy request this ItemStack demands.
*/
public float getTransfer(ItemStack itemStack);
/**
* @return The voltage in which this item runs on.
*/
public float getVoltage(ItemStack itemStack);
}

View file

@ -1,149 +0,0 @@
package universalelectricity.core.item;
import java.util.List;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagDouble;
import net.minecraft.nbt.NBTTagFloat;
import net.minecraft.world.World;
import universalelectricity.core.electricity.ElectricityDisplay;
import universalelectricity.core.electricity.ElectricityDisplay.ElectricUnit;
/** 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)
{
super(id);
this.setMaxStackSize(1);
this.setMaxDamage(100);
this.setNoRepair();
}
@Override
public void addInformation(ItemStack itemStack, EntityPlayer entityPlayer, List list, boolean par4)
{
String color = "";
float joules = this.getElectricityStored(itemStack);
if (joules <= this.getMaxElectricityStored(itemStack) / 3)
{
color = "\u00a74";
}
else if (joules > this.getMaxElectricityStored(itemStack) * 2 / 3)
{
color = "\u00a72";
}
else
{
color = "\u00a76";
}
list.add(color + ElectricityDisplay.getDisplayShort(joules, ElectricUnit.JOULES) + "/" + ElectricityDisplay.getDisplayShort(this.getMaxElectricityStored(itemStack), ElectricUnit.JOULES));
}
/** 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 itemStack, World par2World, EntityPlayer par3EntityPlayer)
{
this.setElectricity(itemStack, 0);
}
@Override
public float recharge(ItemStack itemStack, float energy, boolean doReceive)
{
float rejectedElectricity = Math.max((this.getElectricityStored(itemStack) + energy) - this.getMaxElectricityStored(itemStack), 0);
float energyToReceive = energy - rejectedElectricity;
if (doReceive)
{
this.setElectricity(itemStack, this.getElectricityStored(itemStack) + energyToReceive);
}
return energyToReceive;
}
@Override
public float discharge(ItemStack itemStack, float energy, boolean doTransfer)
{
float energyToTransfer = Math.min(this.getElectricityStored(itemStack), energy);
if (doTransfer)
{
this.setElectricity(itemStack, this.getElectricityStored(itemStack) - energyToTransfer);
}
return energyToTransfer;
}
@Override
public float getVoltage(ItemStack itemStack)
{
return 0.120f;
}
@Override
public void setElectricity(ItemStack itemStack, float joules)
{
// Saves the frequency in the ItemStack
if (itemStack.getTagCompound() == null)
{
itemStack.setTagCompound(new NBTTagCompound());
}
float electricityStored = Math.max(Math.min(joules, this.getMaxElectricityStored(itemStack)), 0);
itemStack.getTagCompound().setFloat("electricity", electricityStored);
/** Sets the damage as a percentage to render the bar properly. */
itemStack.setItemDamage((int) (100 - (electricityStored / getMaxElectricityStored(itemStack)) * 100));
}
@Override
public float getTransfer(ItemStack itemStack)
{
return this.getMaxElectricityStored(itemStack) - this.getElectricityStored(itemStack);
}
/** Gets the energy stored in the item. Energy is stored using item NBT */
@Override
public float getElectricityStored(ItemStack itemStack)
{
if (itemStack.getTagCompound() == null)
{
itemStack.setTagCompound(new NBTTagCompound());
}
float energyStored = 0f;
if (itemStack.getTagCompound().hasKey("electricity"))
{
NBTBase obj = itemStack.getTagCompound().getTag("electricity");
if (obj instanceof NBTTagDouble)
{
energyStored = (float) ((NBTTagDouble) obj).data;
}
else if (obj instanceof NBTTagFloat)
{
energyStored = ((NBTTagFloat) obj).data;
}
}
/** Sets the damage as a percentage to render the bar properly. */
itemStack.setItemDamage((int) (100 - (energyStored / getMaxElectricityStored(itemStack)) * 100));
return energyStored;
}
@Override
public void getSubItems(int par1, CreativeTabs par2CreativeTabs, List par3List)
{
par3List.add(ElectricItemHelper.getUncharged(new ItemStack(this)));
par3List.add(ElectricItemHelper.getWithCharge(new ItemStack(this), this.getMaxElectricityStored(new ItemStack(this))));
}
}

View file

@ -1,25 +0,0 @@
package universalelectricity.core.path;
import java.util.Set;
import universalelectricity.core.vector.Vector3;
public interface IPathCallBack
{
/**
* @param finder - The Pathfinder object.
* @param currentNode - The node being iterated through.
* @return A set of nodes connected to the currentNode. Essentially one should return a set of
* neighboring nodes.
*/
public Set<Vector3> getConnectedNodes(Pathfinder finder, Vector3 currentNode);
/**
* Called when looping through nodes.
*
* @param finder - The Pathfinder.
* @param node - The node being searched.
* @return True to stop the path finding operation.
*/
public boolean onSearch(Pathfinder finder, Vector3 node);
}

View file

@ -1,79 +0,0 @@
package universalelectricity.core.path;
import java.util.HashSet;
import java.util.Set;
import universalelectricity.core.vector.Vector3;
/**
* A class that allows flexible pathfinding for different positions. Compared to AStar pathfinding,
* this version is faster but does not calculated the most optimal path.
*
* @author Calclavia
*
*/
public class Pathfinder
{
/**
* A pathfinding call back interface used to call back on paths.
*/
public IPathCallBack callBackCheck;
/**
* A list of nodes that the pathfinder already went through.
*/
public Set<Vector3> closedSet;
/**
* The resulted path found by the pathfinder. Could be null if no path was found.
*/
public Set<Vector3> results;
public Pathfinder(IPathCallBack callBack)
{
this.callBackCheck = callBack;
this.reset();
}
/**
* @return True on success finding, false on failure.
*/
public boolean findNodes(Vector3 currentNode)
{
this.closedSet.add(currentNode);
if (this.callBackCheck.onSearch(this, currentNode))
{
return false;
}
for (Vector3 node : this.callBackCheck.getConnectedNodes(this, currentNode))
{
if (!this.closedSet.contains(node))
{
if (this.findNodes(node))
{
return true;
}
}
}
return false;
}
/**
* Called to execute the pathfinding operation.
*/
public Pathfinder init(Vector3 startNode)
{
this.findNodes(startNode);
return this;
}
public Pathfinder reset()
{
this.closedSet = new HashSet<Vector3>();
this.results = new HashSet<Vector3>();
return this;
}
}

View file

@ -1,175 +0,0 @@
package universalelectricity.core.path;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import net.minecraftforge.common.ForgeDirection;
import universalelectricity.core.vector.Vector3;
/**
* An advanced version of pathfinding to find the shortest path between two points. Uses the A*
* Pathfinding algorithm.
*
* @author Calclavia
*
*/
public class PathfinderAStar extends Pathfinder
{
/**
* A pathfinding call back interface used to call back on paths.
*/
public IPathCallBack callBackCheck;
/**
* The set of tentative nodes to be evaluated, initially containing the start node
*/
public Set<Vector3> openSet;
/**
* The map of navigated nodes storing the data of which position came from which in the format
* of: X came from Y.
*/
public HashMap<Vector3, Vector3> navigationMap;
/**
* Score values, used to determine the score for a path to evaluate how optimal the path is.
* G-Score is the cost along the best known path while F-Score is the total cost.
*/
public HashMap<Vector3, Double> gScore, fScore;
/**
* The node in which the pathfinder is trying to reach.
*/
public Vector3 goal;
public PathfinderAStar(IPathCallBack callBack, Vector3 goal)
{
super(callBack);
this.goal = goal;
}
@Override
public boolean findNodes(Vector3 start)
{
this.openSet.add(start);
this.gScore.put(start, 0d);
this.fScore.put(start, this.gScore.get(start) + getHeuristicEstimatedCost(start, this.goal));
while (!this.openSet.isEmpty())
{
// Current is the node in openset having the lowest f_score[] value
Vector3 currentNode = null;
double lowestFScore = 0;
for (Vector3 node : this.openSet)
{
if (currentNode == null || this.fScore.get(node) < lowestFScore)
{
currentNode = node;
lowestFScore = this.fScore.get(node);
}
}
if (currentNode == null)
{
break;
}
if (this.callBackCheck.onSearch(this, currentNode))
{
return false;
}
if (currentNode.equals(this.goal))
{
this.results = reconstructPath(this.navigationMap, goal);
return true;
}
this.openSet.remove(currentNode);
this.closedSet.add(currentNode);
for (Vector3 neighbor : getNeighborNodes(currentNode))
{
double tentativeGScore = this.gScore.get(currentNode) + currentNode.distanceTo(neighbor);
if (this.closedSet.contains(neighbor))
{
if (tentativeGScore >= this.gScore.get(neighbor))
{
continue;
}
}
if (!this.openSet.contains(neighbor) || tentativeGScore < this.gScore.get(neighbor))
{
this.navigationMap.put(neighbor, currentNode);
this.gScore.put(neighbor, tentativeGScore);
this.fScore.put(neighbor, gScore.get(neighbor) + getHeuristicEstimatedCost(neighbor, goal));
this.openSet.add(neighbor);
}
}
}
return false;
}
@Override
public Pathfinder reset()
{
this.openSet = new HashSet<Vector3>();
this.navigationMap = new HashMap<Vector3, Vector3>();
return super.reset();
}
/**
* A recursive function to back track and find the path in which we have analyzed.
*/
public Set<Vector3> reconstructPath(HashMap<Vector3, Vector3> nagivationMap, Vector3 current_node)
{
Set<Vector3> path = new HashSet<Vector3>();
path.add(current_node);
if (nagivationMap.containsKey(current_node))
{
path.addAll(reconstructPath(nagivationMap, nagivationMap.get(current_node)));
return path;
}
else
{
return path;
}
}
/**
* @return An estimated cost between two points.
*/
public double getHeuristicEstimatedCost(Vector3 start, Vector3 goal)
{
return start.distanceTo(goal);
}
/**
* @return A Set of neighboring Vector3 positions.
*/
public Set<Vector3> getNeighborNodes(Vector3 vector)
{
if (this.callBackCheck != null)
{
return this.callBackCheck.getConnectedNodes(this, vector);
}
else
{
Set<Vector3> neighbors = new HashSet<Vector3>();
for (int i = 0; i < 6; i++)
{
neighbors.add(vector.clone().modifyPositionFromSide(ForgeDirection.getOrientation(i)));
}
return neighbors;
}
}
}

View file

@ -1,62 +0,0 @@
package universalelectricity.core.path;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeDirection;
import universalelectricity.core.block.IConductor;
import universalelectricity.core.block.INetworkConnection;
import universalelectricity.core.vector.Vector3;
/**
* Check if a conductor connects with another.
*
* @author Calclavia
*
*/
public class PathfinderChecker extends Pathfinder
{
public PathfinderChecker(final World world, final INetworkConnection targetConnector, final INetworkConnection... ignoreConnector)
{
super(new IPathCallBack()
{
@Override
public Set<Vector3> getConnectedNodes(Pathfinder finder, Vector3 currentNode)
{
Set<Vector3> neighbors = new HashSet<Vector3>();
for (int i = 0; i < 6; i++)
{
ForgeDirection direction = ForgeDirection.getOrientation(i);
Vector3 position = currentNode.clone().modifyPositionFromSide(direction);
TileEntity connectedBlock = position.getTileEntity(world);
if (connectedBlock instanceof IConductor && !Arrays.asList(ignoreConnector).contains(connectedBlock))
{
if (((IConductor) connectedBlock).canConnect(direction.getOpposite()))
{
neighbors.add(position);
}
}
}
return neighbors;
}
@Override
public boolean onSearch(Pathfinder finder, Vector3 node)
{
if (node.getTileEntity(world) == targetConnector)
{
finder.results.add(node);
return true;
}
return false;
}
});
}
}

View file

@ -1,213 +0,0 @@
package universalelectricity.core.vector;
/**
* Quaternion class designed to be used for the rotation of objects.
*
* Do not use in MC 1.6.4, subject to change!
*
* @author DarkGuardsman, Calclavia
*/
public class Quaternion implements Cloneable
{
public static final float TOLERANCE = 0.00001f;
public double x, y, z, w;
public Quaternion()
{
this(0, 0, 0, 1);
}
public Quaternion(Quaternion copy)
{
this(copy.x, copy.y, copy.z, copy.w);
}
public Quaternion(double x, double y, double z, double w)
{
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
/**
* Convert from Euler Angles. Basically we create 3 Quaternions, one for pitch, one for yaw, one
* for roll and multiply those together. the calculation below does the same, just shorter
*/
public Quaternion(float pitch, float yaw, float roll)
{
float p = (float) (pitch * (Math.PI / 180) / 2.0);
float y = (float) (yaw * (Math.PI / 180) / 2.0);
float r = (float) (roll * (Math.PI / 180) / 2.0);
float sinp = (float) Math.sin(p);
float siny = (float) Math.sin(y);
float sinr = (float) Math.sin(r);
float cosp = (float) Math.cos(p);
float cosy = (float) Math.cos(y);
float cosr = (float) Math.cos(r);
this.x = sinr * cosp * cosy - cosr * sinp * siny;
this.y = cosr * sinp * cosy + sinr * cosp * siny;
this.z = cosr * cosp * siny - sinr * sinp * cosy;
this.w = cosr * cosp * cosy + sinr * sinp * siny;
this.normalize();
}
public Quaternion(Vector3 vector, double w)
{
this(vector.x, vector.y, vector.z, w);
}
public static Quaternion IDENTITY()
{
return new Quaternion();
}
public Quaternion set(Quaternion quaternion)
{
this.w = quaternion.w;
this.x = quaternion.x;
this.y = quaternion.y;
this.z = quaternion.z;
return this;
}
public Quaternion set(double x, double y, double z, double w)
{
return this.set(new Quaternion(x, y, z, w));
}
public Quaternion normalize()
{
double magnitude = this.magnitude();
this.x /= magnitude;
this.y /= magnitude;
this.z /= magnitude;
this.w /= magnitude;
return this;
}
public double magnitude()
{
return Math.sqrt(this.magnitudeSquared());
}
public double magnitudeSquared()
{
return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
}
public Quaternion inverse()
{
double d = this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
return new Quaternion(this.x / d, -this.y / d, -this.z / d, -this.w / d);
}
/**
* Gets the conjugate of this Quaternion
*/
public Quaternion getConjugate()
{
return this.clone().conjugate();
}
public Quaternion conjugate()
{
this.y = -this.y;
this.z = -this.z;
this.w = -this.w;
return this;
}
/**
* Let the current quaternion be "a". Multiplying the a with b applies the rotation a to b.
*/
public Quaternion getMultiply(Quaternion b)
{
return this.clone().multiply(b);
}
public Quaternion multiply(Quaternion b)
{
Quaternion a = this;
double newX = a.x * b.x - a.y * b.y - a.z * b.z - a.w * b.w;
double newY = a.x * b.y + a.y * b.x + a.z * b.w - a.w * b.z;
double newZ = a.x * b.z - a.y * b.w + a.z * b.x + a.w * b.y;
double newW = a.x * b.w + a.y * b.z - a.z * b.y + a.w * b.x;
this.set(newX, newY, newZ, newW);
return this;
}
public Quaternion divide(Quaternion b)
{
Quaternion a = this;
return a.inverse().multiply(b);
}
/** Multi a vector against this in other words applying rotation */
public Vector3 multi(Vector3 vec)
{
Vector3 vn = vec.clone();
Quaternion vecQuat = new Quaternion(0, 0, 0, 1), resQuat;
vecQuat.x = (float) vn.x;
vecQuat.y = (float) vn.y;
vecQuat.z = (float) vn.z;
vecQuat.w = 0.0f;
resQuat = vecQuat.multiply(this.getConjugate());
resQuat = this.multiply(resQuat);
return new Vector3(resQuat.x, resQuat.y, resQuat.z);
}
public static Quaternion fromAxis(Vector3 vector, double angle)
{
angle *= 0.5f;
Vector3 vn = vector.clone().normalize();
float sinAngle = (float) Math.sin(angle);
return new Quaternion(vn.x * sinAngle, vn.y * sinAngle, vn.z * sinAngle, Math.cos(angle));
}
/*
* Convert to Matrix public Matrix4 getMatrix() { float x2 = (float) (x * x); float y2 = (float)
* (y * y); float z2 = (float) (z * z); float xy = (float) (x * y); float xz = (float) (x * z);
* float yz = (float) (y * z); float wx = (float) (w * x); float wy = (float) (w * y); float wz
* = (float) (w * z);
*
* // This calculation would be a lot more complicated for non-unit length quaternions // Note:
* The constructor of Matrix4 expects the Matrix in column-major format like expected // by //
* OpenGL return new Matrix4(1.0f - 2.0f * (y2 + z2), 2.0f * (xy - wz), 2.0f * (xz + wy), 0.0f,
* 2.0f * (xy + wz), 1.0f - 2.0f * (x2 + z2), 2.0f * (yz - wx), 0.0f, 2.0f * (xz - wy), 2.0f *
* (yz + wx), 1.0f - 2.0f * (x2 + y2), 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); }
*/
/**
* Convert to Axis/Angles
*
* @param axis - The axis of rotation
* @param angle - The angle of rotation
*/
public void getAxisAngle(Vector3 axis, float angle)
{
float scale = (float) axis.getMagnitude();
this.x = this.x / scale;
this.y = this.y / scale;
this.z = this.z / scale;
angle = (float) (Math.acos(this.w) * 2.0f);
}
@Override
public Quaternion clone()
{
return new Quaternion(this);
}
@Override
public String toString()
{
return "Quaternion [" + x + ", " + y + ", " + z + ", " + w + "]";
}
}

View file

@ -1,135 +0,0 @@
package universalelectricity.core.vector;
/**
* Vector2 Class is used for defining objects in a 2D space.
*
* @author Calclavia
*/
public class Vector2 implements Cloneable
{
public double x;
public double y;
public Vector2()
{
this(0, 0);
}
public Vector2(double x, double y)
{
this.x = x;
this.y = y;
}
/**
* Returns the integer floor value.
*
* @return
*/
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 double distance(Vector2 point1, Vector2 point2)
{
double xDifference = point1.x - point2.x;
double yDiference = point1.y - point2.y;
return Math.sqrt(xDifference * xDifference + yDiference * yDiference);
}
public static double slope(Vector2 point1, Vector2 point2)
{
double xDifference = point1.x - point2.x;
double yDiference = point1.y - point2.y;
return yDiference / xDifference;
}
public double distanceTo(Vector2 target)
{
double xDifference = this.x - target.x;
double yDifference = this.y - target.y;
return Math.sqrt(xDifference * xDifference + yDifference * yDifference);
}
public Vector2 add(Vector2 par1)
{
this.x += par1.x;
this.y += par1.y;
return this;
}
public Vector2 add(double par1)
{
this.x += par1;
this.y += par1;
return this;
}
public Vector2 invert()
{
this.multiply(-1);
return this;
}
public Vector2 multiply(double amount)
{
this.x *= amount;
this.y *= amount;
return this;
}
public Vector2 round()
{
return new Vector2(Math.round(this.x), Math.round(this.y));
}
public Vector2 ceil()
{
return new Vector2(Math.ceil(this.x), Math.ceil(this.y));
}
public Vector2 floor()
{
return new Vector2(Math.floor(this.x), Math.floor(this.y));
}
@Override
public int hashCode()
{
return ("X:" + this.x + "Y:" + this.y).hashCode();
}
@Override
public boolean equals(Object o)
{
if (o instanceof Vector2)
{
Vector2 vector = (Vector2) o;
return this.x == vector.x && this.y == vector.y;
}
return false;
}
@Override
public String toString()
{
return "Vector2 [" + this.x + "," + this.y + "]";
}
}

View file

@ -1,849 +0,0 @@
package universalelectricity.core.vector;
import java.util.List;
import net.minecraft.entity.Entity;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeDirection;
/**
* Vector3 Class is used for defining objects in a 3D space.
*
* @author Calclavia
*/
public class Vector3 implements Cloneable
{
public double x;
public double y;
public double z;
public Vector3(double x, double y, double z)
{
this.x = x;
this.y = y;
this.z = z;
}
public Vector3()
{
this(0, 0, 0);
}
public Vector3(Vector3 vector)
{
this(vector.x, vector.y, vector.z);
}
public Vector3(double amount)
{
this(amount, amount, amount);
}
public Vector3(Entity par1)
{
this(par1.posX, par1.posY, par1.posZ);
}
public Vector3(TileEntity par1)
{
this(par1.xCoord, par1.yCoord, par1.zCoord);
}
public Vector3(Vec3 par1)
{
this(par1.xCoord, par1.yCoord, par1.zCoord);
}
public Vector3(MovingObjectPosition par1)
{
this(par1.blockX, par1.blockY, par1.blockZ);
}
public Vector3(ChunkCoordinates par1)
{
this(par1.posX, par1.posY, par1.posZ);
}
public Vector3(ForgeDirection direction)
{
this(direction.offsetX, direction.offsetY, direction.offsetZ);
}
/**
* Loads a Vector3 from an NBT compound.
*/
public Vector3(NBTTagCompound nbt)
{
this(nbt.getDouble("x"), nbt.getDouble("y"), nbt.getDouble("z"));
}
/**
* Get a Vector3 based on the rotationYaw and rotationPitch.
*
* @param rotationYaw - Degree
* @param rotationPitch- Degree
*/
public Vector3(float rotationYaw, float rotationPitch)
{
this(Math.cos(Math.toRadians(rotationYaw + 90)), Math.sin(Math.toRadians(-rotationPitch)), Math.sin(Math.toRadians(rotationYaw + 90)));
}
/**
* Returns the coordinates as integers, ideal for block placement.
*/
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);
}
public float floatX()
{
return (float) this.x;
}
public float floatY()
{
return (float) this.y;
}
public float floatZ()
{
return (float) this.z;
}
/**
* Makes a new copy of this Vector. Prevents variable referencing problems.
*/
@Override
public Vector3 clone()
{
return new Vector3(this);
}
/**
* Easy block access functions.
*
* @param world
* @return
*/
public int getBlockID(IBlockAccess world)
{
return world.getBlockId(this.intX(), this.intY(), this.intZ());
}
public int getBlockMetadata(IBlockAccess world)
{
return world.getBlockMetadata(this.intX(), this.intY(), this.intZ());
}
public TileEntity getTileEntity(IBlockAccess world)
{
return world.getBlockTileEntity(this.intX(), this.intY(), this.intZ());
}
public boolean setBlock(World world, int id, int metadata, int notify)
{
return world.setBlock(this.intX(), this.intY(), this.intZ(), id, metadata, notify);
}
public boolean setBlock(World world, int id, int metadata)
{
return this.setBlock(world, id, metadata, 3);
}
public boolean setBlock(World world, int id)
{
return this.setBlock(world, id, 0);
}
/**
* ---------------------- CONVERSION FUNCTIONS ----------------------------
*/
/**
* 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);
}
/**
* Converts Vector3 into a ForgeDirection.
*/
public ForgeDirection toForgeDirection()
{
for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS)
{
if (this.x == direction.offsetX && this.y == direction.offsetY && this.z == direction.offsetZ)
{
return direction;
}
}
return ForgeDirection.UNKNOWN;
}
public double getMagnitude()
{
return Math.sqrt(this.getMagnitudeSquared());
}
public double getMagnitudeSquared()
{
return this.x * this.x + this.y * this.y + this.z * this.z;
}
public Vector3 normalize()
{
double d = this.getMagnitude();
if (d != 0)
{
this.scale(1 / d);
}
return this;
}
/**
* Gets the distance between two vectors
*
* @return The distance
*/
public static double distance(Vector3 vec1, Vector3 vec2)
{
return vec1.distance(vec2);
}
@Deprecated
public double distanceTo(Vector3 vector3)
{
return this.distance(vector3);
}
public double distance(Vector3 compare)
{
Vector3 difference = this.clone().difference(compare);
return difference.getMagnitude();
}
/**
* Multiplies the vector by negative one.
*/
public Vector3 invert()
{
this.scale(-1);
return this;
}
public Vector3 translate(Vector3 par1)
{
this.x += par1.x;
this.y += par1.y;
this.z += par1.z;
return this;
}
public Vector3 translate(double par1)
{
this.x += par1;
this.y += par1;
this.z += par1;
return this;
}
public static Vector3 translate(Vector3 translate, Vector3 par1)
{
translate.x += par1.x;
translate.y += par1.y;
translate.z += par1.z;
return translate;
}
public static Vector3 translate(Vector3 translate, double par1)
{
translate.x += par1;
translate.y += par1;
translate.z += par1;
return translate;
}
@Deprecated
public Vector3 add(Vector3 amount)
{
return translate(amount);
}
@Deprecated
public Vector3 add(double amount)
{
return translate(amount);
}
@Deprecated
public Vector3 subtract(Vector3 amount)
{
return this.translate(amount.clone().invert());
}
@Deprecated
public Vector3 subtract(double amount)
{
return this.translate(-amount);
}
public Vector3 difference(Vector3 amount)
{
return this.translate(amount.clone().invert());
}
public Vector3 difference(double amount)
{
return this.translate(-amount);
}
public Vector3 scale(double amount)
{
this.x *= amount;
this.y *= amount;
this.z *= amount;
return this;
}
public Vector3 scale(Vector3 amount)
{
this.x *= amount.x;
this.y *= amount.y;
this.z *= amount.z;
return this;
}
public static Vector3 scale(Vector3 vec, double amount)
{
return vec.scale(amount);
}
public static Vector3 scale(Vector3 vec, Vector3 amount)
{
return vec.scale(amount);
}
@Deprecated
public Vector3 multiply(double amount)
{
return this.scale(amount);
}
@Deprecated
public Vector3 multiply(Vector3 amount)
{
return this.scale(amount);
}
/**
* Static versions of a lot of functions
*/
@Deprecated
public static Vector3 subtract(Vector3 par1, Vector3 par2)
{
return new Vector3(par1.x - par2.x, par1.y - par2.y, par1.z - par2.z);
}
@Deprecated
public static Vector3 add(Vector3 par1, Vector3 par2)
{
return new Vector3(par1.x + par2.x, par1.y + par2.y, par1.z + par2.z);
}
@Deprecated
public static Vector3 add(Vector3 par1, double par2)
{
return new Vector3(par1.x + par2, par1.y + par2, par1.z + par2);
}
@Deprecated
public static Vector3 multiply(Vector3 vec1, Vector3 vec2)
{
return new Vector3(vec1.x * vec2.x, vec1.y * vec2.y, vec1.z * vec2.z);
}
@Deprecated
public static Vector3 multiply(Vector3 vec1, double vec2)
{
return new Vector3(vec1.x * vec2, vec1.y * vec2, vec1.z * vec2);
}
public Vector3 round()
{
return new Vector3(Math.round(this.x), Math.round(this.y), Math.round(this.z));
}
public Vector3 ceil()
{
return new Vector3(Math.ceil(this.x), Math.ceil(this.y), Math.ceil(this.z));
}
public Vector3 floor()
{
return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
}
public Vector3 toRound()
{
this.x = Math.round(this.x);
this.y = Math.round(this.y);
this.z = Math.round(this.z);
return this;
}
public Vector3 toCeil()
{
this.x = Math.ceil(this.x);
this.y = Math.ceil(this.y);
this.z = Math.ceil(this.z);
return this;
}
public Vector3 toFloor()
{
this.x = Math.floor(this.x);
this.y = Math.floor(this.y);
this.z = Math.floor(this.z);
return this;
}
/**
* Gets all entities inside of this position in block space.
*/
public List<Entity> getEntitiesWithin(World worldObj, Class<? extends Entity> par1Class)
{
return worldObj.getEntitiesWithinAABB(par1Class, AxisAlignedBB.getBoundingBox(this.intX(), this.intY(), this.intZ(), this.intX() + 1, this.intY() + 1, this.intZ() + 1));
}
/**
* Gets a position relative to a position's side
*
* @param position - The position
* @param side - The side. 0-5
* @return The position relative to the original position's side
*/
public Vector3 modifyPositionFromSide(ForgeDirection side, double amount)
{
return this.translate(new Vector3(side).scale(amount));
}
public Vector3 modifyPositionFromSide(ForgeDirection side)
{
this.modifyPositionFromSide(side, 1);
return this;
}
/**
* Cross product functions
*
* @return The cross product between this vector and another.
*/
public Vector3 toCrossProduct(Vector3 compare)
{
double newX = this.y * compare.z - this.z * compare.y;
double newY = this.z * compare.x - this.x * compare.z;
double newZ = this.x * compare.y - this.y * compare.x;
this.x = newX;
this.y = newY;
this.z = newZ;
return this;
}
public Vector3 crossProduct(Vector3 compare)
{
return this.clone().toCrossProduct(compare);
}
public Vector3 xCrossProduct()
{
return new Vector3(0.0D, this.z, -this.y);
}
public Vector3 zCrossProduct()
{
return new Vector3(-this.y, this.x, 0.0D);
}
public double dotProduct(Vector3 vec2)
{
return this.x * vec2.x + this.y * vec2.y + this.z * vec2.z;
}
/**
* @return The perpendicular vector.
*/
public Vector3 getPerpendicular()
{
if (this.z == 0.0F)
{
return this.zCrossProduct();
}
return this.xCrossProduct();
}
/**
* @return True if this Vector3 is zero.
*/
public boolean isZero()
{
return (this.x == 0) && (this.y == 0) && (this.z == 0);
}
/**
* Rotate by a this vector around an axis.
*
* @return The new Vector3 rotation.
*/
public Vector3 rotate(float angle, Vector3 axis)
{
return translateMatrix(getRotationMatrix(angle, axis), this.clone());
}
public double[] getRotationMatrix(float angle)
{
double[] matrix = new double[16];
Vector3 axis = this.clone().normalize();
double x = axis.x;
double y = axis.y;
double z = axis.z;
angle *= 0.0174532925D;
float cos = (float) Math.cos(angle);
float ocos = 1.0F - cos;
float sin = (float) Math.sin(angle);
matrix[0] = (x * x * ocos + cos);
matrix[1] = (y * x * ocos + z * sin);
matrix[2] = (x * z * ocos - y * sin);
matrix[4] = (x * y * ocos - z * sin);
matrix[5] = (y * y * ocos + cos);
matrix[6] = (y * z * ocos + x * sin);
matrix[8] = (x * z * ocos + y * sin);
matrix[9] = (y * z * ocos - x * sin);
matrix[10] = (z * z * ocos + cos);
matrix[15] = 1.0F;
return matrix;
}
public static Vector3 translateMatrix(double[] matrix, Vector3 translation)
{
double x = translation.x * matrix[0] + translation.y * matrix[1] + translation.z * matrix[2] + matrix[3];
double y = translation.x * matrix[4] + translation.y * matrix[5] + translation.z * matrix[6] + matrix[7];
double z = translation.x * matrix[8] + translation.y * matrix[9] + translation.z * matrix[10] + matrix[11];
translation.x = x;
translation.y = y;
translation.z = z;
return translation;
}
public static double[] getRotationMatrix(float angle, Vector3 axis)
{
return axis.getRotationMatrix(angle);
}
/**
* Rotates this Vector by a yaw, pitch and roll value.
*/
public void rotate(double yaw, double pitch, double roll)
{
double yawRadians = Math.toRadians(yaw);
double pitchRadians = Math.toRadians(pitch);
double rollRadians = Math.toRadians(roll);
double x = this.x;
double y = this.y;
double z = this.z;
this.x = x * Math.cos(yawRadians) * Math.cos(pitchRadians) + z * (Math.cos(yawRadians) * Math.sin(pitchRadians) * Math.sin(rollRadians) - Math.sin(yawRadians) * Math.cos(rollRadians)) + y * (Math.cos(yawRadians) * Math.sin(pitchRadians) * Math.cos(rollRadians) + Math.sin(yawRadians) * Math.sin(rollRadians));
this.z = x * Math.sin(yawRadians) * Math.cos(pitchRadians) + z * (Math.sin(yawRadians) * Math.sin(pitchRadians) * Math.sin(rollRadians) + Math.cos(yawRadians) * Math.cos(rollRadians)) + y * (Math.sin(yawRadians) * Math.sin(pitchRadians) * Math.cos(rollRadians) - Math.cos(yawRadians) * Math.sin(rollRadians));
this.y = -x * Math.sin(pitchRadians) + z * Math.cos(pitchRadians) * Math.sin(rollRadians) + y * Math.cos(pitchRadians) * Math.cos(rollRadians);
}
/**
* Rotates a point by a yaw and pitch around the anchor 0,0 by a specific angle.
*/
public void rotate(double yaw, double pitch)
{
this.rotate(yaw, pitch, 0);
}
public void rotate(double yaw)
{
double yawRadians = Math.toRadians(yaw);
double x = this.x;
double z = this.z;
if (yaw != 0)
{
this.x = x * Math.cos(yawRadians) - z * Math.sin(yawRadians);
this.z = x * Math.sin(yawRadians) + z * Math.cos(yawRadians);
}
}
/**
* Gets the delta look position based on the rotation yaw and pitch. Minecraft coordinates are
* messed up. Y and Z are flipped. Yaw is displaced by 90 degrees. Pitch is inversed.
*
* @param rotationYaw
* @param rotationPitch
*/
public static Vector3 getDeltaPositionFromRotation(float rotationYaw, float rotationPitch)
{
return new Vector3(rotationYaw, rotationPitch);
}
/**
* Gets the angle between this vector and another vector.
*
* @return Angle in degrees
*/
public double getAngle(Vector3 vec2)
{
return anglePreNorm(this.clone().normalize(), vec2.clone().normalize());
}
public static double getAngle(Vector3 vec1, Vector3 vec2)
{
return vec1.getAngle(vec2);
}
public double anglePreNorm(Vector3 vec2)
{
return Math.acos(this.dotProduct(vec2));
}
public static double anglePreNorm(Vector3 vec1, Vector3 vec2)
{
return Math.acos(vec1.clone().dotProduct(vec2));
}
/**
* Loads a Vector3 from an NBT compound.
*/
@Deprecated
public static Vector3 readFromNBT(NBTTagCompound nbt)
{
return new Vector3(nbt);
}
/**
* Saves this Vector3 to disk
*
* @param prefix - The prefix of this save. Use some unique string.
* @param nbt - The NBT compound object to save the data in
*/
public NBTTagCompound writeToNBT(NBTTagCompound nbt)
{
nbt.setDouble("x", this.x);
nbt.setDouble("y", this.y);
nbt.setDouble("z", this.z);
return nbt;
}
public static Vector3 UP()
{
return new Vector3(0, 1, 0);
}
public static Vector3 DOWN()
{
return new Vector3(0, -1, 0);
}
public static Vector3 NORTH()
{
return new Vector3(0, 0, -1);
}
public static Vector3 SOUTH()
{
return new Vector3(0, 0, 1);
}
public static Vector3 WEST()
{
return new Vector3(-1, 0, 0);
}
public static Vector3 EAST()
{
return new Vector3(1, 0, 0);
}
/**
* RayTrace Code, retrieved from MachineMuse.
*
* @author MachineMuse
*/
public MovingObjectPosition rayTrace(World world, float rotationYaw, float rotationPitch, boolean collisionFlag, double reachDistance)
{
// Somehow this destroys the playerPosition vector -.-
MovingObjectPosition pickedBlock = this.rayTraceBlocks(world, rotationYaw, rotationPitch, collisionFlag, reachDistance);
MovingObjectPosition pickedEntity = this.rayTraceEntities(world, rotationYaw, rotationPitch, reachDistance);
if (pickedBlock == null)
{
return pickedEntity;
}
else if (pickedEntity == null)
{
return pickedBlock;
}
else
{
double dBlock = this.distance(new Vector3(pickedBlock.hitVec));
double dEntity = this.distance(new Vector3(pickedEntity.hitVec));
if (dEntity < dBlock)
{
return pickedEntity;
}
else
{
return pickedBlock;
}
}
}
public MovingObjectPosition rayTraceBlocks(World world, float rotationYaw, float rotationPitch, boolean collisionFlag, double reachDistance)
{
Vector3 lookVector = this.getDeltaPositionFromRotation(rotationYaw, rotationPitch);
Vector3 reachPoint = this.clone().translate(lookVector.clone().scale(reachDistance));
return world.rayTraceBlocks_do_do(this.toVec3(), reachPoint.toVec3(), collisionFlag, !collisionFlag);
}
@Deprecated
public MovingObjectPosition rayTraceEntities(World world, float rotationYaw, float rotationPitch, boolean collisionFlag, double reachDistance)
{
return this.rayTraceEntities(world, rotationYaw, rotationPitch, reachDistance);
}
public MovingObjectPosition rayTraceEntities(World world, float rotationYaw, float rotationPitch, double reachDistance)
{
return this.rayTraceEntities(world, getDeltaPositionFromRotation(rotationYaw, rotationPitch).scale(reachDistance));
}
/**
* Does an entity raytrace.
*
* @param world - The world object.
* @param target - The rotation in terms of Vector3. Convert using
* getDeltaPositionFromRotation()
* @return The target hit.
*/
public MovingObjectPosition rayTraceEntities(World world, Vector3 target)
{
MovingObjectPosition pickedEntity = null;
Vec3 startingPosition = this.toVec3();
Vec3 look = target.toVec3();
double reachDistance = this.distance(target);
Vec3 reachPoint = Vec3.createVectorHelper(startingPosition.xCoord + look.xCoord * reachDistance, startingPosition.yCoord + look.yCoord * reachDistance, startingPosition.zCoord + look.zCoord * reachDistance);
double checkBorder = 1.1 * reachDistance;
AxisAlignedBB boxToScan = AxisAlignedBB.getAABBPool().getAABB(-checkBorder, -checkBorder, -checkBorder, checkBorder, checkBorder, checkBorder).offset(this.x, this.y, this.z);
@SuppressWarnings("unchecked")
List<Entity> entitiesHit = world.getEntitiesWithinAABBExcludingEntity(null, boxToScan);
double closestEntity = reachDistance;
if (entitiesHit == null || entitiesHit.isEmpty())
{
return null;
}
for (Entity entityHit : entitiesHit)
{
if (entityHit != null && entityHit.canBeCollidedWith() && entityHit.boundingBox != null)
{
float border = entityHit.getCollisionBorderSize();
AxisAlignedBB aabb = entityHit.boundingBox.expand(border, border, border);
MovingObjectPosition hitMOP = aabb.calculateIntercept(startingPosition, reachPoint);
if (hitMOP != null)
{
if (aabb.isVecInside(startingPosition))
{
if (0.0D < closestEntity || closestEntity == 0.0D)
{
pickedEntity = new MovingObjectPosition(entityHit);
if (pickedEntity != null)
{
pickedEntity.hitVec = hitMOP.hitVec;
closestEntity = 0.0D;
}
}
}
else
{
double distance = startingPosition.distanceTo(hitMOP.hitVec);
if (distance < closestEntity || closestEntity == 0.0D)
{
pickedEntity = new MovingObjectPosition(entityHit);
pickedEntity.hitVec = hitMOP.hitVec;
closestEntity = distance;
}
}
}
}
}
return pickedEntity;
}
@Override
public int hashCode()
{
return ("X:" + this.x + "Y:" + this.y + "Z:" + this.z).hashCode();
}
@Override
public boolean equals(Object o)
{
if (o instanceof Vector3)
{
Vector3 vector3 = (Vector3) o;
return this.x == vector3.x && this.y == vector3.y && this.z == vector3.z;
}
return false;
}
@Override
public String toString()
{
return "Vector3 [" + this.x + "," + this.y + "," + this.z + "]";
}
}

View file

@ -1,52 +0,0 @@
package universalelectricity.core.vector;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeDirection;
import universalelectricity.core.block.IConnector;
public class VectorHelper
{
public static final int[][] RELATIVE_MATRIX = { { 3, 2, 1, 0, 5, 4 }, { 4, 5, 0, 1, 2, 3 }, { 0, 1, 3, 2, 4, 5 }, { 0, 1, 2, 3, 5, 4 }, { 0, 1, 5, 4, 3, 2 }, { 0, 1, 4, 5, 2, 3 } };
/**
* Finds the direction relative to a base direction.
*
* @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)
{
if (front != ForgeDirection.UNKNOWN && side != ForgeDirection.UNKNOWN)
{
return ForgeDirection.getOrientation(RELATIVE_MATRIX[front.ordinal()][side.ordinal()]);
}
return ForgeDirection.UNKNOWN;
}
/**
* Gets a connector unit based on the given side.
*/
public static TileEntity getConnectorFromSide(World world, Vector3 position, ForgeDirection side)
{
TileEntity tileEntity = VectorHelper.getTileEntityFromSide(world, position, side);
if (tileEntity instanceof IConnector)
{
if (((IConnector) tileEntity).canConnect(getOrientationFromSide(side, ForgeDirection.NORTH)))
{
return tileEntity;
}
}
return null;
}
public static TileEntity getTileEntityFromSide(World world, Vector3 position, ForgeDirection side)
{
return position.clone().modifyPositionFromSide(side).getTileEntity(world);
}
}

View file

@ -1,23 +0,0 @@
package universalelectricity.prefab.tile;
import net.minecraftforge.common.ForgeDirection;
/**
* The interface is applied to TileEntities that can rotate.
*
* @author Calclavia
*
*/
public interface IRotatable
{
/**
* @return Gets the facing direction. Always returns the front side of the block.
*/
public ForgeDirection getDirection();
/**
* @param Sets the facing direction.
*/
public void setDirection(ForgeDirection direection);
}

View file

@ -1,60 +0,0 @@
package universalelectricity.prefab.tile;
import net.minecraft.block.Block;
import net.minecraft.tileentity.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.
*/
public 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;
}
}

View file

@ -1,126 +0,0 @@
package universalelectricity.prefab.tile;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraftforge.common.ForgeDirection;
import universalelectricity.core.block.IConductor;
import universalelectricity.core.block.IConnector;
import universalelectricity.core.block.INetworkProvider;
import universalelectricity.core.electricity.NetworkLoader;
import universalelectricity.core.grid.IElectricityNetwork;
import universalelectricity.core.vector.Vector3;
import universalelectricity.core.vector.VectorHelper;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
/**
* This tile entity pre-fabricated for all conductors.
*
* @author Calclavia
*
*/
public abstract class TileEntityConductor extends TileEntityAdvanced implements IConductor
{
private IElectricityNetwork network;
public TileEntity[] adjacentConnections = null;
@Override
public void invalidate()
{
if (!this.worldObj.isRemote)
{
this.getNetwork().split(this);
}
super.invalidate();
}
@Override
public boolean canUpdate()
{
return false;
}
@Override
public IElectricityNetwork getNetwork()
{
if (this.network == null)
{
this.setNetwork(NetworkLoader.getNewNetwork(this));
}
return this.network;
}
@Override
public void setNetwork(IElectricityNetwork network)
{
this.network = network;
}
@Override
public void refresh()
{
if (!this.worldObj.isRemote)
{
this.adjacentConnections = null;
for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS)
{
TileEntity tileEntity = VectorHelper.getConnectorFromSide(this.worldObj, new Vector3(this), side);
if (tileEntity != null)
{
if (tileEntity.getClass() == this.getClass() && tileEntity instanceof INetworkProvider)
{
this.getNetwork().merge(((INetworkProvider) tileEntity).getNetwork());
}
}
}
this.getNetwork().refresh();
}
}
@Override
public TileEntity[] getAdjacentConnections()
{
/**
* Cache the adjacentConnections.
*/
if (this.adjacentConnections == null)
{
this.adjacentConnections = new TileEntity[6];
for (byte i = 0; i < 6; i++)
{
ForgeDirection side = ForgeDirection.getOrientation(i);
TileEntity tileEntity = VectorHelper.getConnectorFromSide(this.worldObj, new Vector3(this), side);
if (tileEntity instanceof IConnector)
{
if (((IConnector) tileEntity).canConnect(side.getOpposite()))
{
this.adjacentConnections[i] = tileEntity;
}
}
}
}
return this.adjacentConnections;
}
@Override
public boolean canConnect(ForgeDirection direction)
{
return true;
}
@Override
@SideOnly(Side.CLIENT)
public AxisAlignedBB getRenderBoundingBox()
{
return AxisAlignedBB.getAABBPool().getAABB(this.xCoord, this.yCoord, this.zCoord, this.xCoord + 1, this.yCoord + 1, this.zCoord + 1);
}
}

View file

@ -1,244 +0,0 @@
package universalelectricity.prefab.tile;
import java.util.EnumSet;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.ForgeDirection;
import universalelectricity.core.block.IElectrical;
import universalelectricity.core.block.IElectricalStorage;
import universalelectricity.core.electricity.ElectricityHelper;
import universalelectricity.core.electricity.ElectricityPack;
import universalelectricity.core.grid.IElectricityNetwork;
import universalelectricity.core.item.ElectricItemHelper;
import universalelectricity.core.vector.Vector3;
import universalelectricity.core.vector.VectorHelper;
public abstract class TileEntityElectrical extends TileEntityAdvanced implements IElectrical, IElectricalStorage
{
public float energyStored = 0;
/**
* Recharges electric item.
*/
public void recharge(ItemStack itemStack)
{
this.setEnergyStored(this.getEnergyStored() - ElectricItemHelper.chargeItem(itemStack, this.getProvide(ForgeDirection.UNKNOWN)));
}
/**
* Discharges electric item.
*/
public void discharge(ItemStack itemStack)
{
this.setEnergyStored(this.getEnergyStored() + ElectricItemHelper.dischargeItem(itemStack, this.getRequest(ForgeDirection.UNKNOWN)));
}
/**
* Called to produce the potential electricity inside this block.
*/
public void produce()
{
if (!this.worldObj.isRemote)
{
for (ForgeDirection outputDirection : this.getOutputDirections())
{
this.produceUE(outputDirection);
}
}
}
/**
* Produces UE power towards a specific direction.
*
* @param outputDirection - The output direction.
*/
public boolean produceUE(ForgeDirection outputDirection)
{
if (!this.worldObj.isRemote && outputDirection != null && outputDirection != ForgeDirection.UNKNOWN)
{
float provide = this.getProvide(outputDirection);
if (provide > 0)
{
TileEntity outputTile = VectorHelper.getConnectorFromSide(this.worldObj, new Vector3(this), outputDirection);
IElectricityNetwork outputNetwork = ElectricityHelper.getNetworkFromTileEntity(outputTile, outputDirection);
if (outputNetwork != null)
{
ElectricityPack powerRequest = outputNetwork.getRequest(this);
if (powerRequest.getWatts() > 0)
{
ElectricityPack sendPack = ElectricityPack.min(ElectricityPack.getFromWatts(this.getEnergyStored(), this.getVoltage()), ElectricityPack.getFromWatts(provide, this.getVoltage()));
float rejectedPower = outputNetwork.produce(sendPack, this);
this.provideElectricity(Math.max(sendPack.getWatts() - rejectedPower, 0), true);
return true;
}
}
else if (outputTile instanceof IElectrical)
{
float requestedEnergy = ((IElectrical) outputTile).getRequest(outputDirection.getOpposite());
if (requestedEnergy > 0)
{
ElectricityPack sendPack = ElectricityPack.min(ElectricityPack.getFromWatts(this.getEnergyStored(), this.getVoltage()), ElectricityPack.getFromWatts(provide, this.getVoltage()));
float acceptedEnergy = ((IElectrical) outputTile).receiveElectricity(outputDirection.getOpposite(), sendPack, true);
this.provideElectricity(acceptedEnergy, true);
return true;
}
}
}
}
return false;
}
/**
* The electrical input direction.
*
* @return The direction that electricity is entered into the tile. Return null for no input. By
* default you can accept power from all sides.
*/
public EnumSet<ForgeDirection> getInputDirections()
{
return EnumSet.allOf(ForgeDirection.class);
}
/**
* The electrical output direction.
*
* @return The direction that electricity is output from the tile. Return null for no output. By
* default it will return an empty EnumSet.
*/
public EnumSet<ForgeDirection> getOutputDirections()
{
return EnumSet.noneOf(ForgeDirection.class);
}
@Override
public float receiveElectricity(ForgeDirection from, ElectricityPack receive, boolean doReceive)
{
if (this.getInputDirections().contains(from))
{
if (!doReceive)
{
return this.getRequest(from);
}
return this.receiveElectricity(receive, doReceive);
}
return 0;
}
@Override
public ElectricityPack provideElectricity(ForgeDirection from, ElectricityPack request, boolean doProvide)
{
if (this.getOutputDirections().contains(from))
{
if (!doProvide)
{
return ElectricityPack.getFromWatts(this.getProvide(from), this.getVoltage());
}
return this.provideElectricity(request, doProvide);
}
return new ElectricityPack();
}
/**
* A non-side specific version of receiveElectricity for you to optionally use it internally.
*/
public float receiveElectricity(ElectricityPack receive, boolean doReceive)
{
if (receive != null)
{
float prevEnergyStored = this.getEnergyStored();
float newStoredEnergy = Math.min(this.getEnergyStored() + receive.getWatts(), this.getMaxEnergyStored());
if (doReceive)
{
this.setEnergyStored(newStoredEnergy);
}
return Math.max(newStoredEnergy - prevEnergyStored, 0);
}
return 0;
}
public float receiveElectricity(float energy, boolean doReceive)
{
return this.receiveElectricity(ElectricityPack.getFromWatts(energy, this.getVoltage()), doReceive);
}
/**
* A non-side specific version of provideElectricity for you to optionally use it internally.
*/
public ElectricityPack provideElectricity(ElectricityPack request, boolean doProvide)
{
if (request != null)
{
float requestedEnergy = Math.min(request.getWatts(), this.energyStored);
if (doProvide)
{
this.setEnergyStored(this.energyStored - requestedEnergy);
}
return ElectricityPack.getFromWatts(requestedEnergy, this.getVoltage());
}
return new ElectricityPack();
}
public ElectricityPack provideElectricity(float energy, boolean doProvide)
{
return this.provideElectricity(ElectricityPack.getFromWatts(energy, this.getVoltage()), doProvide);
}
@Override
public void setEnergyStored(float energy)
{
this.energyStored = Math.max(Math.min(energy, this.getMaxEnergyStored()), 0);
}
@Override
public float getEnergyStored()
{
return this.energyStored;
}
@Override
public boolean canConnect(ForgeDirection direction)
{
if (direction == null || direction.equals(ForgeDirection.UNKNOWN))
{
return false;
}
return this.getInputDirections().contains(direction) || this.getOutputDirections().contains(direction);
}
@Override
public float getVoltage()
{
return 0.120F;
}
@Override
public void readFromNBT(NBTTagCompound nbt)
{
super.readFromNBT(nbt);
this.energyStored = nbt.getFloat("energyStored");
}
@Override
public void writeToNBT(NBTTagCompound nbt)
{
super.writeToNBT(nbt);
nbt.setFloat("energyStored", this.energyStored);
}
}