Cleanup and add ant script for jenkins

This commit is contained in:
Rseifert 2013-04-10 05:35:51 -04:00
parent 4e2f1243a4
commit 5dea05a1d5
74 changed files with 92 additions and 6419 deletions

1
.gitignore vendored
View file

@ -14,7 +14,6 @@ CHANGELOG
/src/minecraft/*
!/src/minecraft/assemblyline/
!/src/minecraft/dark/
!/src/minecraft/universalelectricity/
!/src/minecraft/dan200
!/src/minecraft/ic2
!/src/minecraft/buildcraft

3
.gitmodules vendored Normal file
View file

@ -0,0 +1,3 @@
[submodule "Universal-Electricity"]
path = Universal-Electricity
url = git://github.com/calclavia/Universal-Electricity

6
build.properties Normal file
View file

@ -0,0 +1,6 @@
dir.development=./
dir.mcp=${dir.development}forge/mcp
version.minecraft=1.5+
version.mod.major=0
version.mod.minor=4
version.mod.revis=0

83
build.xml Normal file
View file

@ -0,0 +1,83 @@
<?xml version="1.0" encoding="UTF-8" ?>
<project name="Assembly%20Line" default="build">
<property file="build.properties" />
<property environment="env" />
<property name="file.EEjar" value= "AssemblyLine_v${version.mod.major}.${version.mod.minor}.${version.mod.revis}.${env.BUILD_NUMBER}.jar" />
<target name="build">
<delete dir="contents" />
<delete dir="build" />
<delete dir="${dir.development}/forge" />
<copy todir="${dir.development}">
<fileset dir="../Minecraft Forge/" />
</copy>
<copy todir="${dir.mcp}/src/minecraft">
<fileset dir="${dir.development}src">
<exclude name=".git/**"/>
<exclude name="**/*.xml"/>
</fileset>
<fileset dir="${dir.development}../Universal Electricity/src/minecraft">
<exclude name=".git/**"/>
<exclude name="**/*.xml"/>
</fileset>
</copy>
<mkdir dir="contents" />
<mkdir dir="build" />
<replace dir="${dir.mcp}/src/minecraft" token="@MAJOR@" value="${version.mod.major}" />
<replace dir="${dir.mcp}/src/minecraft" token="@MINOR@" value="${version.mod.minor}" />
<replace dir="${dir.mcp}/src/minecraft" token="@REVIS@" value="${version.mod.revis}" />
<replace dir="${dir.mcp}/src/minecraft" token="@BUILD@" value="${env.BUILD_NUMBER}" />
<exec dir="${dir.mcp}" executable="cmd" osfamily="windows">
<arg line="recompile.bat" />
</exec>
<exec dir="${dir.mcp}" executable="cmd" osfamily="windows">
<arg line="reobfuscate_srg.bat" />
</exec>
<exec dir="${dir.mcp}" executable="bash" osfamily="unix">
<arg line="recompile.sh" />
</exec>
<exec dir="${dir.mcp}" executable="bash" osfamily="unix">
<arg line="reobfuscate_srg.sh" />
</exec>
<copy todir="contents">
<fileset dir="${dir.mcp}/reobf/minecraft" excludes=".git/**">
<exclude name="**/BCLoader.class"/>
</fileset>
<fileset dir="${dir.development}resources">
<exclude name=".git/**"/>
<exclude name="**/*.tcn"/>
<exclude name="**/*.java"/>
<exclude name="**/*.xml"/>
</fileset>
<fileset dir="${dir.development}../Universal Electricity/resources">
<exclude name=".git/**"/>
<exclude name="**/*.java"/>
<exclude name="**/*.xml"/>
</fileset>
</copy>
<jar destfile="output/${file.EEjar}">
<fileset dir="contents" />
</jar>
<echo file="${env.JENKINS_HOME}/jobs/${env.JOB_NAME}/info.txt" append="true" >
@ ${env.BUILD_NUMBER} ${version.minecraft} ${file.EEjar}</echo>
<copy todir="output" file="build.properties" />
</target>
</project>

View file

@ -1,68 +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 cpw.mods.fml.common.Loader;
/**
* General Universal Electricity class.
*
* @author Calclavia
*
*/
public class UniversalElectricity
{
/**
* The version of the Universal Electricity API.
*/
public static final int MAJOR_VERSION = 1;
public static final int MINOR_VERSION = 3;
public static final int REVISION_VERSION = 0;
public static final String VERSION = MAJOR_VERSION + "." + MINOR_VERSION + "." + REVISION_VERSION;
/**
* The Universal Electricity configuration file.
*/
public static final Configuration CONFIGURATION = new Configuration(new File(Loader.instance().getConfigDir(), "UniversalElectricity/UniversalElectricity.cfg"));
/**
* Multiply this to convert foreign energy into UE Joules.
*/
public static double IC2_RATIO = 40;
public static double BC3_RATIO = 100;
/**
* Multiply this to convert UE Joules into foreign energy.
*/
public static double TO_IC2_RATIO = 1 / IC2_RATIO;
public static double TO_BC_RATIO = 1 / BC3_RATIO;
/**
* 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;
/**
* A general material that can be used by machines. Breakable by hand, suitable for machines.
*/
public static final Material machine = new Material(MapColor.ironColor);
static
{
/**
* Loads the configuration and sets all the values.
*/
CONFIGURATION.load();
IC2_RATIO = CONFIGURATION.get("Compatiblity", "IndustrialCraft Conversion Ratio", IC2_RATIO).getDouble(IC2_RATIO);
BC3_RATIO = CONFIGURATION.get("Compatiblity", "BuildCraft Conversion Ratio", BC3_RATIO).getDouble(BC3_RATIO);
TO_IC2_RATIO = 1 / IC2_RATIO;
TO_BC_RATIO = 1 / BC3_RATIO;
isVoltageSensitive = CONFIGURATION.get("Compatiblity", "Is Voltage Sensitive", isVoltageSensitive).getBoolean(isVoltageSensitive);
CONFIGURATION.save();
}
}

View file

@ -1,24 +0,0 @@
package universalelectricity.core.block;
/**
* Must be applied to all tile entities that are conductors.
*
* @author Calclavia
*
*/
public interface IConductor extends INetworkProvider, IConnectionProvider
{
/**
* 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 double getResistance();
/**
* @return The maximum amount of amps this conductor can handle before melting down.
*/
public double getCurrentCapcity();
}

View file

@ -1,27 +0,0 @@
package universalelectricity.core.block;
import net.minecraft.tileentity.TileEntity;
/**
* Applied to TileEntities.
*
* @author Calclavia
*
*/
public interface IConnectionProvider 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();
/**
* Instantly refreshes all connected blocks around the conductor, recalculating the connected
* blocks.
*/
public void updateAdjacentConnections();
}

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,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 IElectricityStorage
{
/**
* Returns the amount of joules this unit has stored.
*/
public double getJoules();
/**
* Sets the amount of joules this unit has stored.
*/
public void setJoules(double joules);
/**
* Gets the maximum amount of joules this unit can store.
*/
public double getMaxJoules();
}

View file

@ -1,16 +0,0 @@
package universalelectricity.core.block;
import universalelectricity.core.electricity.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,17 +0,0 @@
package universalelectricity.core.block;
/**
* Applies to all objects that has a voltage.
*
* @author Calclavia
*
*/
public interface IVoltage
{
/**
* Gets the voltage of this object.
*
* @return The amount of volts. E.g 120v or 240v
*/
public double getVoltage();
}

View file

@ -1,161 +0,0 @@
package universalelectricity.core.electricity;
/**
* An easy way to display information on electricity for the client.
*
* @author Calclavia
*/
public class ElectricityDisplay
{
public static enum ElectricUnit
{
AMPERE("Amp", "I"), AMP_HOUR("Amp Hour", "Ah"), VOLTAGE("Volt", "V"), WATT("Watt", "W"),
WATT_HOUR("Watt Hour", "Wh"), RESISTANCE("Ohm", "R"), CONDUCTANCE("Siemen", "S"),
JOULES("Joule", "J");
public String name;
public String symbol;
private ElectricUnit(String name, String symbol)
{
this.name = name;
this.symbol = symbol;
}
public String getPlural()
{
return this.name + "s";
}
}
public static enum MeasurementUnit
{
MICRO("Micro", "mi", 0.000001), MILLI("Milli", "m", 0.001), KILO("Kilo", "k", 1000),
MEGA("Mega", "M", 1000000);
public String name;
public String symbol;
public double value;
private MeasurementUnit(String name, String symbol, double value)
{
this.name = name;
this.symbol = symbol;
this.value = value;
}
public String getName(boolean isSymbol)
{
if (isSymbol)
{
return symbol;
}
else
{
return name;
}
}
public double process(double value)
{
return value / this.value;
}
}
/**
* Displays the unit as text. Works only for positive numbers.
*/
public static String getDisplay(double value, ElectricUnit unit, int decimalPlaces, boolean isShort)
{
String unitName = unit.name;
if (isShort)
{
unitName = unit.symbol;
}
else if (value > 1)
{
unitName = unit.getPlural();
}
if (value == 0)
{
return value + " " + unitName;
}
if (value <= MeasurementUnit.MILLI.value)
{
return roundDecimals(MeasurementUnit.MICRO.process(value), decimalPlaces) + " " + MeasurementUnit.MICRO.getName(isShort) + unitName;
}
if (value < 1)
{
return roundDecimals(MeasurementUnit.MILLI.process(value), decimalPlaces) + " " + MeasurementUnit.MILLI.getName(isShort) + unitName;
}
if (value > MeasurementUnit.MEGA.value)
{
return roundDecimals(MeasurementUnit.MEGA.process(value), decimalPlaces) + " " + MeasurementUnit.MEGA.getName(isShort) + unitName;
}
if (value > MeasurementUnit.KILO.value)
{
return roundDecimals(MeasurementUnit.KILO.process(value), decimalPlaces) + " " + MeasurementUnit.KILO.getName(isShort) + unitName;
}
return roundDecimals(value, decimalPlaces) + " " + unitName;
}
public static String getDisplay(double value, ElectricUnit unit)
{
return getDisplay(value, unit, 2, false);
}
public static String getDisplayShort(double value, ElectricUnit unit)
{
return getDisplay(value, unit, 2, true);
}
public static String getDisplayShort(double value, ElectricUnit unit, int decimalPlaces)
{
return getDisplay(value, unit, decimalPlaces, true);
}
public static String getDisplaySimple(double value, ElectricUnit unit, int decimalPlaces)
{
if (value > 1)
{
if (decimalPlaces < 1)
{
return (int) value + " " + unit.getPlural();
}
return roundDecimals(value, decimalPlaces) + " " + unit.getPlural();
}
if (decimalPlaces < 1)
{
return (int) value + " " + unit.name;
}
return roundDecimals(value, decimalPlaces) + " " + unit.name;
}
/**
* Rounds a number to a specific number place places
*
* @param The number
* @return The rounded number
*/
public static double roundDecimals(double d, int decimalPlaces)
{
int j = (int) (d * Math.pow(10, decimalPlaces));
return j / (double) Math.pow(10, decimalPlaces);
}
public static double roundDecimals(double d)
{
return roundDecimals(d, 2);
}
}

View file

@ -1,490 +0,0 @@
package universalelectricity.core.electricity;
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 universalelectricity.core.block.IConductor;
import universalelectricity.core.block.IConnectionProvider;
import universalelectricity.core.block.INetworkProvider;
import universalelectricity.core.path.Pathfinder;
import universalelectricity.core.path.PathfinderChecker;
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
{
private final HashMap<TileEntity, ElectricityPack> producers = new HashMap<TileEntity, ElectricityPack>();
private final HashMap<TileEntity, ElectricityPack> consumers = new HashMap<TileEntity, ElectricityPack>();
private final Set<IConductor> conductors = new HashSet<IConductor>();
public ElectricityNetwork()
{
}
public ElectricityNetwork(IConductor... conductors)
{
this.conductors.addAll(Arrays.asList(conductors));
}
@Override
public void startProducing(TileEntity tileEntity, ElectricityPack electricityPack)
{
if (tileEntity != null && electricityPack.getWatts() > 0)
{
this.producers.put(tileEntity, electricityPack);
}
}
@Override
public void startProducing(TileEntity tileEntity, double amperes, double voltage)
{
this.startProducing(tileEntity, new ElectricityPack(amperes, voltage));
}
@Override
public boolean isProducing(TileEntity tileEntity)
{
return this.producers.containsKey(tileEntity);
}
/**
* Sets this tile entity to stop producing energy in this network.
*/
@Override
public void stopProducing(TileEntity tileEntity)
{
this.producers.remove(tileEntity);
}
/**
* Sets this tile entity to start producing energy in this network.
*/
@Override
public void startRequesting(TileEntity tileEntity, ElectricityPack electricityPack)
{
if (tileEntity != null && electricityPack.getWatts() > 0)
{
this.consumers.put(tileEntity, electricityPack);
}
}
@Override
public void startRequesting(TileEntity tileEntity, double amperes, double voltage)
{
this.startRequesting(tileEntity, new ElectricityPack(amperes, voltage));
}
@Override
public boolean isRequesting(TileEntity tileEntity)
{
return this.consumers.containsKey(tileEntity);
}
/**
* Sets this tile entity to stop producing energy in this network.
*/
@Override
public void stopRequesting(TileEntity tileEntity)
{
this.consumers.remove(tileEntity);
}
/**
* @param ignoreTiles The TileEntities to ignore during this calculation. Null will make it not
* ignore any.
* @return The electricity produced in this electricity network
*/
@Override
public ElectricityPack getProduced(TileEntity... ignoreTiles)
{
ElectricityPack totalElectricity = new ElectricityPack(0, 0);
Iterator it = this.producers.entrySet().iterator();
loop:
while (it.hasNext())
{
Map.Entry pairs = (Map.Entry) it.next();
if (pairs != null)
{
TileEntity tileEntity = (TileEntity) pairs.getKey();
if (tileEntity == null)
{
it.remove();
continue;
}
if (tileEntity.isInvalid())
{
it.remove();
continue;
}
if (tileEntity.worldObj.getBlockTileEntity(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord) != tileEntity)
{
it.remove();
continue;
}
if (ignoreTiles != null)
{
for (TileEntity ignoreTile : ignoreTiles)
{
if (tileEntity == ignoreTile)
{
continue loop;
}
}
}
ElectricityPack pack = (ElectricityPack) pairs.getValue();
if (pairs.getKey() != null && pairs.getValue() != null && pack != null)
{
double newWatts = totalElectricity.getWatts() + pack.getWatts();
double newVoltage = Math.max(totalElectricity.voltage, pack.voltage);
totalElectricity.amperes = newWatts / newVoltage;
totalElectricity.voltage = newVoltage;
}
}
}
return totalElectricity;
}
/**
* @return How much electricity this network needs.
*/
@Override
public ElectricityPack getRequest(TileEntity... ignoreTiles)
{
ElectricityPack totalElectricity = this.getRequestWithoutReduction();
totalElectricity.amperes = Math.max(totalElectricity.amperes - this.getProduced(ignoreTiles).amperes, 0);
return totalElectricity;
}
@Override
public ElectricityPack getRequestWithoutReduction()
{
ElectricityPack totalElectricity = new ElectricityPack(0, 0);
Iterator it = this.consumers.entrySet().iterator();
while (it.hasNext())
{
Map.Entry pairs = (Map.Entry) it.next();
if (pairs != null)
{
TileEntity tileEntity = (TileEntity) pairs.getKey();
if (tileEntity == null)
{
it.remove();
continue;
}
if (tileEntity.isInvalid())
{
it.remove();
continue;
}
if (tileEntity.worldObj.getBlockTileEntity(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord) != tileEntity)
{
it.remove();
continue;
}
ElectricityPack pack = (ElectricityPack) pairs.getValue();
if (pack != null)
{
totalElectricity.amperes += pack.amperes;
totalElectricity.voltage = Math.max(totalElectricity.voltage, pack.voltage);
}
}
}
return totalElectricity;
}
/**
* @param tileEntity
* @return The electricity being input into this tile entity.
*/
@Override
public ElectricityPack consumeElectricity(TileEntity tileEntity)
{
ElectricityPack totalElectricity = new ElectricityPack(0, 0);
try
{
ElectricityPack tileRequest = this.consumers.get(tileEntity);
if (this.consumers.containsKey(tileEntity) && tileRequest != null)
{
// Calculate the electricity this TileEntity is receiving in percentage.
totalElectricity = this.getProduced();
if (totalElectricity.getWatts() > 0)
{
ElectricityPack totalRequest = this.getRequestWithoutReduction();
totalElectricity.amperes *= (tileRequest.amperes / totalRequest.amperes);
int distance = this.conductors.size();
double ampsReceived = totalElectricity.amperes - (totalElectricity.amperes * totalElectricity.amperes * this.getTotalResistance()) / totalElectricity.voltage;
double voltsReceived = totalElectricity.voltage - (totalElectricity.amperes * this.getTotalResistance());
totalElectricity.amperes = ampsReceived;
totalElectricity.voltage = voltsReceived;
return totalElectricity;
}
}
}
catch (Exception e)
{
FMLLog.severe("Failed to consume electricity!");
e.printStackTrace();
}
return totalElectricity;
}
/**
* @return Returns all producers in this electricity network.
*/
@Override
public HashMap<TileEntity, ElectricityPack> getProducers()
{
return this.producers;
}
/**
* Gets all the electricity receivers.
*/
@Override
public List<TileEntity> getProviders()
{
List<TileEntity> providers = new ArrayList<TileEntity>();
providers.addAll(this.producers.keySet());
return providers;
}
/**
* @return Returns all consumers in this electricity network.
*/
@Override
public HashMap<TileEntity, ElectricityPack> getConsumers()
{
return this.consumers;
}
/**
* Gets all the electricity receivers.
*/
@Override
public List<TileEntity> getReceivers()
{
List<TileEntity> receivers = new ArrayList<TileEntity>();
receivers.addAll(this.consumers.keySet());
return receivers;
}
@Override
public void cleanUpConductors()
{
Iterator it = this.conductors.iterator();
while (it.hasNext())
{
IConductor conductor = (IConductor) it.next();
if (conductor == null)
{
it.remove();
}
else if (((TileEntity) conductor).isInvalid())
{
it.remove();
}
else
{
conductor.setNetwork(this);
}
}
}
/**
* This function is called to refresh all conductors in this network
*/
@Override
public void refreshConductors()
{
this.cleanUpConductors();
try
{
Iterator<IConductor> it = this.conductors.iterator();
while (it.hasNext())
{
IConductor conductor = it.next();
conductor.updateAdjacentConnections();
}
}
catch (Exception e)
{
FMLLog.severe("Universal Electricity: Failed to refresh conductor.");
e.printStackTrace();
}
}
@Override
public double getTotalResistance()
{
double resistance = 0;
for (IConductor conductor : this.conductors)
{
resistance += conductor.getResistance();
}
return resistance;
}
@Override
public double getLowestCurrentCapacity()
{
double lowestAmp = 0;
for (IConductor conductor : this.conductors)
{
if (lowestAmp == 0 || conductor.getCurrentCapcity() < lowestAmp)
{
lowestAmp = conductor.getCurrentCapcity();
}
}
return lowestAmp;
}
@Override
public Set<IConductor> getConductors()
{
return this.conductors;
}
@Override
public void mergeConnection(IElectricityNetwork network)
{
if (network != null && network != this)
{
ElectricityNetwork newNetwork = new ElectricityNetwork();
newNetwork.getConductors().addAll(this.getConductors());
newNetwork.getConductors().addAll(network.getConductors());
newNetwork.cleanUpConductors();
}
}
@Override
public void splitNetwork(IConnectionProvider 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 IConnectionProvider)
{
for (int ii = 0; ii < connectedBlocks.length; ii++)
{
final TileEntity connectedBlockB = connectedBlocks[ii];
if (connectedBlockA != connectedBlockB && connectedBlockB instanceof IConnectionProvider)
{
Pathfinder finder = new PathfinderChecker((IConnectionProvider) connectedBlockB, splitPoint);
finder.init((IConnectionProvider) 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 (IConnectionProvider node : finder.iteratedNodes)
{
if (node instanceof INetworkProvider)
{
if (node != splitPoint)
{
((INetworkProvider) node).setNetwork(this);
}
}
}
}
else
{
/**
* The connections A and B are not connected anymore. Give both of
* them a new network.
*/
IElectricityNetwork newNetwork = new ElectricityNetwork();
for (IConnectionProvider node : finder.iteratedNodes)
{
if (node instanceof IConductor)
{
if (node != splitPoint)
{
newNetwork.getConductors().add((IConductor) node);
}
}
}
newNetwork.cleanUpConductors();
}
}
}
}
}
}
}
@Override
public String toString()
{
return "ElectricityNetwork[" + this.hashCode() + "|Wires:" + this.conductors.size() + "]";
}
}

View file

@ -1,226 +0,0 @@
package universalelectricity.core.electricity;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.ForgeDirection;
import universalelectricity.core.block.IConnector;
import universalelectricity.core.block.INetworkProvider;
import universalelectricity.core.vector.Vector3;
import universalelectricity.core.vector.VectorHelper;
/**
* A helper class that provides additional useful functions to interact with the ElectricityNetwork
*
* @author Calclavia
*
*/
public class ElectricityNetworkHelper
{
/**
* Invalidates a TileEntity from the electrical network, thereby removing it from all
* electricity network that are adjacent to it.
*/
public static void invalidate(TileEntity tileEntity)
{
for (int i = 0; i < 6; i++)
{
ForgeDirection direction = ForgeDirection.getOrientation(i);
TileEntity checkTile = VectorHelper.getConnectorFromSide(tileEntity.worldObj, new Vector3(tileEntity), direction);
if (checkTile instanceof INetworkProvider)
{
IElectricityNetwork network = ((INetworkProvider) checkTile).getNetwork();
if (network != null)
{
network.stopRequesting(tileEntity);
network.stopProducing(tileEntity);
}
}
}
}
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;
}
public static ElectricityPack produceFromMultipleSides(TileEntity tileEntity, ElectricityPack electricityPack)
{
return ElectricityNetworkHelper.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.
*/
public static ElectricityPack produceFromMultipleSides(TileEntity tileEntity, EnumSet<ForgeDirection> approachingDirection, ElectricityPack producingPack)
{
ElectricityPack remainingElectricity = producingPack.clone();
if (tileEntity != null && approachingDirection != null)
{
final List<IElectricityNetwork> connectedNetworks = ElectricityNetworkHelper.getNetworksFromMultipleSides(tileEntity, approachingDirection);
if (connectedNetworks.size() > 0)
{
/**
* Requests an even amount of electricity from all sides.
*/
double wattsPerSide = (producingPack.getWatts() / connectedNetworks.size());
double voltage = producingPack.voltage;
for (IElectricityNetwork network : connectedNetworks)
{
if (wattsPerSide > 0 && producingPack.getWatts() > 0)
{
double amperes = wattsPerSide / voltage;
network.startProducing(tileEntity, amperes, voltage);
remainingElectricity.amperes -= amperes;
}
else
{
network.stopProducing(tileEntity);
}
}
}
}
return remainingElectricity;
}
public static ElectricityPack consumeFromMultipleSides(TileEntity tileEntity, ElectricityPack electricityPack)
{
return ElectricityNetworkHelper.consumeFromMultipleSides(tileEntity, getDirections(tileEntity), electricityPack);
}
/**
* Requests and attempts to consume 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.
* @param requestPack - The amount of electricity to be requested.
* @return The consumed ElectricityPack.
*/
public static ElectricityPack consumeFromMultipleSides(TileEntity tileEntity, EnumSet<ForgeDirection> approachingDirection, ElectricityPack requestPack)
{
ElectricityPack consumedPack = new ElectricityPack();
if (tileEntity != null && approachingDirection != null)
{
final List<IElectricityNetwork> connectedNetworks = ElectricityNetworkHelper.getNetworksFromMultipleSides(tileEntity, approachingDirection);
if (connectedNetworks.size() > 0)
{
/**
* Requests an even amount of electricity from all sides.
*/
double wattsPerSide = (requestPack.getWatts() / connectedNetworks.size());
double voltage = requestPack.voltage;
for (IElectricityNetwork network : connectedNetworks)
{
if (wattsPerSide > 0 && requestPack.getWatts() > 0)
{
network.startRequesting(tileEntity, wattsPerSide / voltage, voltage);
ElectricityPack receivedPack = network.consumeElectricity(tileEntity);
consumedPack.amperes += receivedPack.amperes;
consumedPack.voltage = Math.max(consumedPack.voltage, receivedPack.voltage);
}
else
{
network.stopRequesting(tileEntity);
}
}
}
}
return consumedPack;
}
/**
* @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 List<IElectricityNetwork> getNetworksFromMultipleSides(TileEntity tileEntity, EnumSet<ForgeDirection> approachingDirection)
{
final List<IElectricityNetwork> connectedNetworks = new ArrayList<IElectricityNetwork>();
for (int i = 0; i < 6; i++)
{
ForgeDirection direction = ForgeDirection.getOrientation(i);
if (approachingDirection.contains(direction))
{
Vector3 position = new Vector3(tileEntity);
position.modifyPositionFromSide(direction);
TileEntity outputConductor = position.getTileEntity(tileEntity.worldObj);
IElectricityNetwork electricityNetwork = ElectricityNetworkHelper.getNetworkFromTileEntity(outputConductor, direction);
if (electricityNetwork != null && !connectedNetworks.contains(connectedNetworks))
{
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,131 +0,0 @@
package universalelectricity.core.electricity;
/**
* A simple way to store electrical data.
*
* @author Calclavia
*
*/
public class ElectricityPack implements Cloneable
{
public double amperes;
public double voltage;
public ElectricityPack(double amperes, double voltage)
{
this.amperes = amperes;
this.voltage = voltage;
}
public ElectricityPack()
{
this(0, 0);
}
public static ElectricityPack getFromWatts(double watts, double voltage)
{
return new ElectricityPack(watts / voltage, voltage);
}
public double getWatts()
{
return getWatts(amperes, voltage);
}
public double getConductance()
{
return getConductance(amperes, voltage);
}
public double getResistance()
{
return getResistance(amperes, voltage);
}
public static double getJoules(double watts, double seconds)
{
return watts * seconds;
}
public static double getJoules(double amps, double voltage, double seconds)
{
return amps * voltage * seconds;
}
public static double getWattsFromJoules(double joules, double seconds)
{
return joules / seconds;
}
public static double getAmps(double watts, double voltage)
{
return watts / voltage;
}
public static double getAmps(double ampHours)
{
return ampHours * 3600;
}
public static double getAmpsFromWattHours(double wattHours, double voltage)
{
return getWatts(wattHours) / voltage;
}
public static double getWattHoursFromAmpHours(double ampHours, double voltage)
{
return ampHours * voltage;
}
public static double getAmpHours(double amps)
{
return amps / 3600;
}
public static double getWatts(double amps, double voltage)
{
return amps * voltage;
}
public static double getWatts(double wattHours)
{
return wattHours * 3600;
}
public static double getWattHours(double watts)
{
return watts / 3600;
}
public static double getWattHours(double amps, double voltage)
{
return getWattHours(getWatts(amps, voltage));
}
public static double getResistance(double amps, double voltage)
{
return voltage / amps;
}
public static double getConductance(double amps, double 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,17 +0,0 @@
package universalelectricity.core.electricity;
import java.util.List;
import universalelectricity.core.block.IConductor;
public interface IConductorRegistry
{
void register(IConductor conductor);
void cleanConductors();
void resetAllConnections();
List<IConductor> getConductors();
}

View file

@ -1,138 +0,0 @@
package universalelectricity.core.electricity;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import net.minecraft.tileentity.TileEntity;
import universalelectricity.core.block.IConductor;
import universalelectricity.core.block.IConnectionProvider;
/**
* The Electrical Network in interface form.
*
* @author Calclavia
*
*/
public interface IElectricityNetwork
{
/**
* Sets this TileEntity to start producing energy in this network.
*/
public void startProducing(TileEntity tileEntity, ElectricityPack electricityPack);
public void startProducing(TileEntity tileEntity, double amperes, double voltage);
/**
* Is this TileEntity producing electricity?
*/
public boolean isProducing(TileEntity tileEntity);
/**
* Stops the TileEntity from producing electricity.
*/
public void stopProducing(TileEntity tileEntity);
/**
* Sets a TileEntity to start requesting electricity from the network.
*/
public void startRequesting(TileEntity tileEntity, ElectricityPack electricityPack);
public void startRequesting(TileEntity tileEntity, double amperes, double voltage);
/**
* Is this TileEntity requesting electricity?
*/
public boolean isRequesting(TileEntity tileEntity);
/**
* Stops the TileEntity from requesting electricity from the network.
*/
public void stopRequesting(TileEntity tileEntity);
/**
* Gets the total amount of electricity produced in the electricity network.
*
* @param ignoreTiles The TileEntities to ignore during this calculation (optional).
*/
public ElectricityPack getProduced(TileEntity... ignoreTiles);
/**
* Gets the total amount of electricity requested in the electricity network. Takes account of
* electricity being produced in the network.
*
* @param ignoreTiles The TileEntities to ignore during this calculation (optional).
*/
public ElectricityPack getRequest(TileEntity... ignoreTiles);
/**
* Gets the total amount of electricity requested WITHOUT accounting in the electricity already
* being produced.
*/
public ElectricityPack getRequestWithoutReduction();
/**
* Attemps to consume electricity for this TileEntity based on what was requested.
*
* @return The actual amount of electricity consumed.
*/
public ElectricityPack consumeElectricity(TileEntity tileEntity);
/**
* @return Gets a list of TileEntities currently producing electricity in the network.
*
*/
public HashMap<TileEntity, ElectricityPack> getProducers();
public List<TileEntity> getProviders();
/**
* @return Gets a list of TileEntities currently receiving electricity from the network.
*
*/
public HashMap<TileEntity, ElectricityPack> getConsumers();
public List<TileEntity> getReceivers();
/**
* @return A list of all conductors in this electrical network.
*/
public Set<IConductor> getConductors();
/**
* @return The total amount of resistance of this electrical network. In Ohms.
*/
public double getTotalResistance();
/**
* @return The lowest amount of current (amperage) that this electrical network can tolerate.
*/
public double getLowestCurrentCapacity();
/**
* Cleans up and updates the list of conductors in the electricity network, removing dead ones.
*/
public void cleanUpConductors();
/**
* Refreshes and recalculates wire connections in this electrical network.
*
*/
public void refreshConductors();
/**
* Merges another electrical network into this one, destroying the other network's existence.
*
* @param network
*/
public void mergeConnection(IElectricityNetwork network);
/**
* Splits the electricity network at a given TileEntity position. Called usually when a wire is
* broken to split the electrical network.
*
* @param splitPoint - The TileEntity that is being split.
*/
public void splitNetwork(IConnectionProvider splitPoint);
}

View file

@ -1,109 +0,0 @@
package universalelectricity.core.item;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import universalelectricity.core.electricity.ElectricityPack;
/**
* 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
* @param voltage - The voltage in which is used to charge the electric item
* @return The total amount of joules provided by the provider.
*/
public static double chargeItem(ItemStack itemStack, double joules, double voltage)
{
if (itemStack != null)
{
if (itemStack.getItem() instanceof IItemElectric)
{
IItemElectric electricItem = (IItemElectric) itemStack.getItem();
double providingWatts = Math.min(joules, electricItem.getReceiveRequest(itemStack).getWatts());
if (providingWatts > 0)
{
ElectricityPack providedElectricity = electricItem.onReceive(ElectricityPack.getFromWatts(providingWatts, voltage), itemStack);
return providedElectricity.getWatts();
}
}
}
return 0;
}
/**
* Decharge an electric item.
*
* @param joules - The joules being withdrawn from the electric item
* @param voltage - The voltage in which is used to decharge the electric item
* @return The total amount of joules the provider received.
*/
public static double dechargeItem(ItemStack itemStack, double joules, double voltage)
{
if (itemStack != null)
{
if (itemStack.getItem() instanceof IItemElectric)
{
IItemElectric electricItem = (IItemElectric) itemStack.getItem();
double requestingWatts = Math.min(joules, electricItem.getProvideRequest(itemStack).getWatts());
if (requestingWatts > 0)
{
ElectricityPack receivedElectricity = electricItem.onProvide(ElectricityPack.getFromWatts(requestingWatts, voltage), itemStack);
return receivedElectricity.getWatts();
}
}
}
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, double joules)
{
if (itemStack != null)
{
if (itemStack.getItem() instanceof IItemElectric)
{
((IItemElectric) itemStack.getItem()).setJoules(joules, itemStack);
return itemStack;
}
}
return itemStack;
}
public static ItemStack getWithCharge(Item item, double joules)
{
return getWithCharge(new ItemStack(item), joules);
}
public static ItemStack getCloneWithCharge(ItemStack itemStack, double 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,40 +0,0 @@
package universalelectricity.core.item;
import net.minecraft.item.ItemStack;
import universalelectricity.core.electricity.ElectricityPack;
/**
* An interface applied to all electrical items. Should be applied to the Item class.
*
* @author Calclavia
*
*/
public interface IItemElectric extends IItemElectricityStorage, IItemVoltage
{
/**
* Called when this item receives electricity; being charged.
*
* @return The amount of electricity that was added to the electric item.
*/
public ElectricityPack onReceive(ElectricityPack electricityPack, ItemStack itemStack);
/**
* Called when something requests electricity from this item; being decharged.
*
* @return - The amount of electricity that was removed from the electric item.
*/
public ElectricityPack onProvide(ElectricityPack electricityPack, ItemStack itemStack);
/**
* @return How much electricity does this item want to receive/take? This will affect the speed
* in which items get charged per tick.
*/
public ElectricityPack getReceiveRequest(ItemStack itemStack);
/**
*
* @return How much electricity does this item want to provide/give out? This will affect the
* speed in which items get decharged per tick.
*/
public ElectricityPack getProvideRequest(ItemStack itemStack);
}

View file

@ -1,21 +0,0 @@
package universalelectricity.core.item;
import net.minecraft.item.ItemStack;
public interface IItemElectricityStorage
{
/**
* Returns the amount of joules this unit has stored.
*/
public double getJoules(ItemStack itemStack);
/**
* Sets the amount of joules this unit has stored.
*/
public void setJoules(double joules, ItemStack itemStack);
/**
* Gets the maximum amount of joules this unit can store.
*/
public double getMaxJoules(ItemStack itemStack);
}

View file

@ -1,18 +0,0 @@
package universalelectricity.core.item;
import net.minecraft.item.ItemStack;
/**
* Applies to items that has a voltage.
*
* @author Calclavia
*
*/
public interface IItemVoltage
{
/**
* @return The voltage in which this item runs on.
*/
public double getVoltage(ItemStack itemStack);
}

View file

@ -1,153 +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.NBTTagCompound;
import net.minecraft.world.World;
import universalelectricity.core.electricity.ElectricityDisplay;
import universalelectricity.core.electricity.ElectricityDisplay.ElectricUnit;
import universalelectricity.core.electricity.ElectricityPack;
/**
* 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 = "";
double joules = this.getJoules(itemStack);
if (joules <= this.getMaxJoules(itemStack) / 3)
{
color = "\u00a74";
}
else if (joules > this.getMaxJoules(itemStack) * 2 / 3)
{
color = "\u00a72";
}
else
{
color = "\u00a76";
}
list.add(color + ElectricityDisplay.getDisplay(joules, ElectricUnit.JOULES) + "/" + ElectricityDisplay.getDisplay(this.getMaxJoules(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)
{
itemStack = ElectricItemHelper.getUncharged(itemStack);
}
@Override
public ElectricityPack onReceive(ElectricityPack electricityPack, ItemStack itemStack)
{
double rejectedElectricity = Math.max((this.getJoules(itemStack) + electricityPack.getWatts()) - this.getMaxJoules(itemStack), 0);
double joulesToStore = electricityPack.getWatts() - rejectedElectricity;
this.setJoules(this.getJoules(itemStack) + joulesToStore, itemStack);
return ElectricityPack.getFromWatts(joulesToStore, this.getVoltage(itemStack));
}
@Override
public ElectricityPack onProvide(ElectricityPack electricityPack, ItemStack itemStack)
{
double electricityToUse = Math.min(this.getJoules(itemStack), electricityPack.getWatts());
this.setJoules(this.getJoules(itemStack) - electricityToUse, itemStack);
return ElectricityPack.getFromWatts(electricityToUse, this.getVoltage(itemStack));
}
@Override
public ElectricityPack getReceiveRequest(ItemStack itemStack)
{
return ElectricityPack.getFromWatts(Math.min(this.getMaxJoules(itemStack) - this.getJoules(itemStack), this.getTransferRate(itemStack)), this.getVoltage(itemStack));
}
@Override
public ElectricityPack getProvideRequest(ItemStack itemStack)
{
return ElectricityPack.getFromWatts(Math.min(this.getJoules(itemStack), this.getTransferRate(itemStack)), this.getVoltage(itemStack));
}
public double getTransferRate(ItemStack itemStack)
{
return this.getMaxJoules(itemStack) * 0.01;
}
/**
* This function sets the electriicty. Do not directly call this function. Try to use
* onReceiveElectricity or onUseElectricity instead.
*
* @param joules - The amount of electricity in joules
*/
@Override
public void setJoules(double joules, ItemStack itemStack)
{
// Saves the frequency in the ItemStack
if (itemStack.getTagCompound() == null)
{
itemStack.setTagCompound(new NBTTagCompound());
}
double electricityStored = Math.max(Math.min(joules, this.getMaxJoules(itemStack)), 0);
itemStack.getTagCompound().setDouble("electricity", electricityStored);
/**
* Sets the damage as a percentage to render the bar properly.
*/
itemStack.setItemDamage((int) (100 - (electricityStored / getMaxJoules(itemStack)) * 100));
}
/**
* This function is called to get the electricity stored in this item
*
* @return - The amount of electricity stored in watts
*/
@Override
public double getJoules(ItemStack itemStack)
{
if (itemStack.getTagCompound() == null)
{
return 0;
}
double electricityStored = itemStack.getTagCompound().getDouble("electricity");
/**
* Sets the damage as a percentage to render the bar properly.
*/
itemStack.setItemDamage((int) (100 - (electricityStored / getMaxJoules(itemStack)) * 100));
return electricityStored;
}
@Override
public void getSubItems(int par1, CreativeTabs par2CreativeTabs, List par3List)
{
// Add an uncharged version of the electric item
par3List.add(ElectricItemHelper.getUncharged(new ItemStack(this)));
// Add an electric item to the creative list that is fully charged
ItemStack chargedItem = new ItemStack(this);
par3List.add(ElectricItemHelper.getWithCharge(chargedItem, this.getMaxJoules(chargedItem)));
}
}

View file

@ -1,107 +0,0 @@
package universalelectricity.core.path;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.ForgeDirection;
import universalelectricity.core.block.IConnectionProvider;
/**
* A class that allows flexible path finding in Minecraft Blocks.
*
* @author Calclavia
*
*/
public class Pathfinder
{
public interface IPathCallBack
{
/**
* Is this a valid node to search for?
*
* @return
*/
public boolean isValidNode(Pathfinder finder, ForgeDirection direction, IConnectionProvider provider, IConnectionProvider node);
/**
* Called when looping through nodes.
*
* @param finder
* @param provider
* @return True to stop the path finding operation.
*/
public boolean onSearch(Pathfinder finder, IConnectionProvider provider);
}
/**
* A pathfinding call back interface used to call back on paths.
*/
public IPathCallBack callBackCheck;
/**
* A list of nodes that the pathfinder went through.
*/
public List<IConnectionProvider> iteratedNodes;
/**
* The results and findings found by the pathfinder.
*/
public List results;
public Pathfinder(IPathCallBack callBack)
{
this.callBackCheck = callBack;
this.clear();
}
public boolean findNodes(IConnectionProvider provider)
{
TileEntity[] connectedBlocks = provider.getAdjacentConnections();
this.iteratedNodes.add(provider);
if (this.callBackCheck.onSearch(this, provider))
{
return false;
}
for (int i = 0; i < connectedBlocks.length; i++)
{
TileEntity connectedBlock = connectedBlocks[i];
if (connectedBlock instanceof IConnectionProvider)
{
if (!iteratedNodes.contains(connectedBlock))
{
if (this.callBackCheck.isValidNode(this, ForgeDirection.getOrientation(i), provider, (IConnectionProvider) connectedBlock))
{
if (!this.findNodes((IConnectionProvider) connectedBlock))
{
return false;
}
}
}
}
}
return true;
}
/**
* Called to execute the pathfinding operation.
*/
public Pathfinder init(IConnectionProvider provider)
{
this.findNodes(provider);
return this;
}
public Pathfinder clear()
{
this.iteratedNodes = new ArrayList<IConnectionProvider>();
this.results = new ArrayList();
return this;
}
}

View file

@ -1,47 +0,0 @@
package universalelectricity.core.path;
import java.util.Arrays;
import net.minecraftforge.common.ForgeDirection;
import universalelectricity.core.block.IConductor;
import universalelectricity.core.block.IConnectionProvider;
/**
* Check if a conductor connects with another.
*
* @author Calclavia
*
*/
public class PathfinderChecker extends Pathfinder
{
public PathfinderChecker(final IConnectionProvider targetConnector, final IConnectionProvider... ignoreConnector)
{
super(new IPathCallBack()
{
@Override
public boolean isValidNode(Pathfinder finder, ForgeDirection direction, IConnectionProvider provider, IConnectionProvider connectedBlock)
{
if (connectedBlock instanceof IConductor && !Arrays.asList(ignoreConnector).contains(connectedBlock))
{
if (((IConductor) connectedBlock).canConnect(direction.getOpposite()))
{
return true;
}
}
return false;
}
@Override
public boolean onSearch(Pathfinder finder, IConnectionProvider provider)
{
if (provider == targetConnector)
{
finder.results.add(provider);
return true;
}
return false;
}
});
}
}

View file

@ -1,53 +0,0 @@
package universalelectricity.core.path;
import java.util.HashMap;
import net.minecraftforge.common.ForgeDirection;
import universalelectricity.core.block.IConductor;
import universalelectricity.core.block.IConnectionProvider;
/**
* Finds all the possible conductors. Inspired by A* Pathfinding Algorithm.
*
* @author Calclavia
*
*/
public class PathfinderShortestConnection extends Pathfinder
{
/**
* The score of this specific path. The higher the score, the better the path is.
*/
public HashMap<IConnectionProvider, Integer> gScore = new HashMap<IConnectionProvider, Integer>();
public PathfinderShortestConnection()
{
super(new IPathCallBack()
{
@Override
public boolean isValidNode(Pathfinder finder, ForgeDirection direction, IConnectionProvider provider, IConnectionProvider connectedBlock)
{
if (connectedBlock instanceof IConductor)
{
if (((IConductor) connectedBlock).canConnect(direction.getOpposite()))
{
return true;
}
}
return false;
}
@Override
public boolean onSearch(Pathfinder finder, IConnectionProvider provider)
{
return false;
}
});
}
@Override
public Pathfinder clear()
{
this.gScore.clear();
return super.clear();
}
}

View file

@ -1,119 +0,0 @@
package universalelectricity.core.vector;
import net.minecraft.util.MathHelper;
/**
* 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 MathHelper.sqrt_double(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 MathHelper.sqrt_double(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 floor()
{
return new Vector2(Math.floor(this.x), Math.floor(this.y));
}
public boolean isEqual(Vector2 vector)
{
return this.x == vector.x && this.y == vector.y;
}
@Override
public String toString()
{
return "Vector2 [" + this.x + "," + this.y + "]";
}
}

View file

@ -1,347 +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.MathHelper;
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()
{
this(0, 0, 0);
}
public Vector3(double x, double y, double z)
{
this.x = x;
this.y = y;
this.z = z;
}
public Vector3(Entity par1)
{
this.x = par1.posX;
this.y = par1.posY;
this.z = par1.posZ;
}
public Vector3(TileEntity par1)
{
this.x = par1.xCoord;
this.y = par1.yCoord;
this.z = par1.zCoord;
}
public Vector3(Vec3 par1)
{
this.x = par1.xCoord;
this.y = par1.yCoord;
this.z = par1.zCoord;
}
public Vector3(MovingObjectPosition par1)
{
this.x = par1.blockX;
this.y = par1.blockY;
this.z = par1.blockZ;
}
public Vector3(ChunkCoordinates par1)
{
this.x = par1.posX;
this.y = par1.posY;
this.z = par1.posZ;
}
/**
* 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);
}
/**
* Compares two vectors and see if they are equal. True if so.
*/
public boolean isEqual(Vector3 vector3)
{
return (this.x == vector3.x && this.y == vector3.y && this.z == vector3.z);
}
/**
* Makes a new copy of this Vector. Prevents variable referencing problems.
*/
@Override
public Vector3 clone()
{
return new Vector3(this.x, this.y, this.z);
}
/**
* 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)
{
return world.setBlock(this.intX(), this.intY(), this.intZ(), id, metadata, 2);
}
public boolean setBlock(World world, int id)
{
return world.setBlock(this.intX(), this.intY(), this.intZ(), id, 0, 2);
}
/**
* 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);
}
/**
* Gets the distance between two vectors
*
* @return The distance
*/
public static double distance(Vector3 par1, Vector3 par2)
{
double var2 = par1.x - par2.x;
double var4 = par1.y - par2.y;
double var6 = par1.z - par2.z;
return MathHelper.sqrt_double(var2 * var2 + var4 * var4 + var6 * var6);
}
public double distanceTo(Vector3 vector3)
{
double var2 = vector3.x - this.x;
double var4 = vector3.y - this.y;
double var6 = vector3.z - this.z;
return MathHelper.sqrt_double(var2 * var2 + var4 * var4 + var6 * var6);
}
public Vector3 add(Vector3 par1)
{
this.x += par1.x;
this.y += par1.y;
this.z += par1.z;
return this;
}
public Vector3 add(double par1)
{
this.x += par1;
this.y += par1;
this.z += par1;
return this;
}
public Vector3 subtract(Vector3 amount)
{
this.x -= amount.x;
this.y -= amount.y;
this.z -= amount.z;
return this;
}
/**
* Multiplies the vector by negative one.
*/
public Vector3 invert()
{
this.multiply(-1);
return this;
}
public Vector3 multiply(double amount)
{
this.x *= amount;
this.y *= amount;
this.z *= amount;
return this;
}
public Vector3 multiply(Vector3 vec)
{
this.x *= vec.x;
this.y *= vec.y;
this.z *= vec.z;
return this;
}
public static Vector3 subtract(Vector3 par1, Vector3 par2)
{
return new Vector3(par1.x - par2.x, par1.y - par2.y, par1.z - par2.z);
}
public static Vector3 add(Vector3 par1, Vector3 par2)
{
return new Vector3(par1.x + par2.x, par1.y + par2.y, par1.z + par2.z);
}
public static Vector3 add(Vector3 par1, double par2)
{
return new Vector3(par1.x + par2, par1.y + par2, par1.z + par2);
}
public static Vector3 multiply(Vector3 vec1, Vector3 vec2)
{
return new Vector3(vec1.x * vec2.x, vec1.y * vec2.y, vec1.z * vec2.z);
}
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 floor()
{
return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
}
/**
* Gets all entities inside of this position in block space.
*/
public List<Entity> getEntitiesWithin(World worldObj, Class<? extends Entity> par1Class)
{
return (List<Entity>) 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)
{
switch (side.ordinal())
{
case 0:
this.y -= amount;
break;
case 1:
this.y += amount;
break;
case 2:
this.z -= amount;
break;
case 3:
this.z += amount;
break;
case 4:
this.x -= amount;
break;
case 5:
this.x += amount;
break;
}
return this;
}
public Vector3 modifyPositionFromSide(ForgeDirection side)
{
this.modifyPositionFromSide(side, 1);
return this;
}
/**
* Loads a Vector3 from an NBT compound.
*/
public static Vector3 readFromNBT(NBTTagCompound nbtCompound)
{
Vector3 tempVector = new Vector3();
tempVector.x = nbtCompound.getDouble("x");
tempVector.y = nbtCompound.getDouble("y");
tempVector.z = nbtCompound.getDouble("z");
return tempVector;
}
/**
* Saves this Vector3 to disk
*
* @param prefix - The prefix of this save. Use some unique string.
* @param par1NBTTagCompound - The NBT compound object to save the data in
*/
public NBTTagCompound writeToNBT(NBTTagCompound par1NBTTagCompound)
{
par1NBTTagCompound.setDouble("x", this.x);
par1NBTTagCompound.setDouble("y", this.y);
par1NBTTagCompound.setDouble("z", this.z);
return par1NBTTagCompound;
}
@Override
public int hashCode()
{
return ("X:" + this.x + "Y:" + this.y + "Z:" + this.z).hashCode();
}
@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, 5, 4 }, { 0, 1, 2, 3, 4, 5 }, { 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,38 +0,0 @@
package universalelectricity.prefab;
import net.minecraft.util.DamageSource;
import cpw.mods.fml.common.registry.LanguageRegistry;
public class CustomDamageSource extends DamageSource
{
/**
* Use this damage source for all types of electrical attacks.
*/
public static final CustomDamageSource electrocution = ((CustomDamageSource) new CustomDamageSource("electrocution").setDamageBypassesArmor()).setDeathMessage("%1$s got electrocuted!");
public CustomDamageSource(String damageType)
{
super(damageType);
}
public CustomDamageSource setDeathMessage(String deathMessage)
{
LanguageRegistry.instance().addStringLocalization("death.attack." + this.damageType, deathMessage);
return this;
}
public DamageSource setDamageBypassesArmor()
{
return super.setDamageBypassesArmor();
}
public DamageSource setDamageAllowedInCreativeMode()
{
return super.setDamageAllowedInCreativeMode();
}
public DamageSource setFireDamage()
{
return super.setFireDamage();
}
}

View file

@ -1,197 +0,0 @@
package universalelectricity.prefab;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.RenderHelper;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public abstract class GuiBase extends GuiScreen
{
/**
* The X size of the inventory window in pixels.
*/
protected int xSize = 176;
/**
* The Y size of the inventory window in pixels.
*/
protected int ySize = 166;
/**
* Starting X position for the Gui. Inconsistent use for Gui backgrounds.
*/
protected int guiLeft;
/**
* Starting Y position for the Gui. Inconsistent use for Gui backgrounds.
*/
protected int guiTop;
/**
* Adds the buttons (and other controls) to the screen in question.
*/
@Override
public void initGui()
{
super.initGui();
this.guiLeft = (this.width - this.xSize) / 2;
this.guiTop = (this.height - this.ySize) / 2;
}
/**
* Draws the screen and all the components in it.
*/
@Override
public void drawScreen(int par1, int par2, float par3)
{
this.drawDefaultBackground();
int var4 = this.guiLeft;
int var5 = this.guiTop;
this.drawBackgroundLayer(par1, par2, par3);
GL11.glPushMatrix();
GL11.glTranslatef((float) var4, (float) var5, 0.0F);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
short var7 = 240;
short var8 = 240;
OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float) var7 / 1.0F, (float) var8 / 1.0F);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
this.drawForegroundLayer(par1, par2, par3);
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glPopMatrix();
super.drawScreen(par1, par2, par3);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_DEPTH_TEST);
}
/**
* Draws the foreground layer for the GUI
*/
protected abstract void drawForegroundLayer(int var2, int var3, float var1);
/**
* Draws the background layer for the GUI
*/
protected abstract void drawBackgroundLayer(int var2, int var3, float var1);
/**
* Fired when a key is typed. This is the equivalent of KeyListener.keyTyped(KeyEvent e).
*/
@Override
protected void keyTyped(char x, int y)
{
if (y == 1 || y == this.mc.gameSettings.keyBindInventory.keyCode)
{
this.mc.thePlayer.closeScreen();
}
}
/**
* Returns true if this GUI should pause the game when it is displayed in single-player
*/
@Override
public boolean doesGuiPauseGame()
{
return false;
}
/**
* Called from the main game loop to update the screen.
*/
@Override
public void updateScreen()
{
super.updateScreen();
if (!this.mc.thePlayer.isEntityAlive() || this.mc.thePlayer.isDead)
{
this.mc.thePlayer.closeScreen();
}
}
public void drawTooltip(int x, int y, String... toolTips)
{
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
RenderHelper.disableStandardItemLighting();
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_DEPTH_TEST);
if (toolTips != null)
{
int var5 = 0;
int var6;
int var7;
for (var6 = 0; var6 < toolTips.length; ++var6)
{
var7 = this.fontRenderer.getStringWidth((String) toolTips[var6]);
if (var7 > var5)
{
var5 = var7;
}
}
var6 = x + 12;
var7 = y - 12;
int var9 = 8;
if (toolTips.length > 1)
{
var9 += 2 + (toolTips.length - 1) * 10;
}
if (this.guiTop + var7 + var9 + 6 > this.height)
{
var7 = this.height - var9 - this.guiTop - 6;
}
this.zLevel = 300.0F;
int var10 = -267386864;
this.drawGradientRect(var6 - 3, var7 - 4, var6 + var5 + 3, var7 - 3, var10, var10);
this.drawGradientRect(var6 - 3, var7 + var9 + 3, var6 + var5 + 3, var7 + var9 + 4, var10, var10);
this.drawGradientRect(var6 - 3, var7 - 3, var6 + var5 + 3, var7 + var9 + 3, var10, var10);
this.drawGradientRect(var6 - 4, var7 - 3, var6 - 3, var7 + var9 + 3, var10, var10);
this.drawGradientRect(var6 + var5 + 3, var7 - 3, var6 + var5 + 4, var7 + var9 + 3, var10, var10);
int var11 = 1347420415;
int var12 = (var11 & 16711422) >> 1 | var11 & -16777216;
this.drawGradientRect(var6 - 3, var7 - 3 + 1, var6 - 3 + 1, var7 + var9 + 3 - 1, var11, var12);
this.drawGradientRect(var6 + var5 + 2, var7 - 3 + 1, var6 + var5 + 3, var7 + var9 + 3 - 1, var11, var12);
this.drawGradientRect(var6 - 3, var7 - 3, var6 + var5 + 3, var7 - 3 + 1, var11, var11);
this.drawGradientRect(var6 - 3, var7 + var9 + 2, var6 + var5 + 3, var7 + var9 + 3, var12, var12);
for (int var13 = 0; var13 < toolTips.length; ++var13)
{
String var14 = toolTips[var13];
this.fontRenderer.drawStringWithShadow(var14, var6, var7, -1);
if (var13 == 0)
{
var7 += 2;
}
var7 += 10;
}
this.zLevel = 0.0F;
}
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glEnable(GL11.GL_LIGHTING);
RenderHelper.enableGUIStandardItemLighting();
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
}
}

View file

@ -1,192 +0,0 @@
package universalelectricity.prefab;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.IRecipe;
import net.minecraftforge.common.Configuration;
import cpw.mods.fml.common.registry.GameRegistry;
/**
* This class is used to replace recipes that are already added in the existing recipe pool for
* crafting and smelting. All recipe functions take account of the Forge Ore Dictionary. It also
* includes some recipe helper functions to shorten some of your function calls.
*
* @author Calclavia
*
*/
public class RecipeHelper
{
public static List<IRecipe> getRecipesByOutput(ItemStack output)
{
List<IRecipe> list = new ArrayList<IRecipe>();
for (Object obj : CraftingManager.getInstance().getRecipeList())
{
if (obj instanceof IRecipe)
{
if (((IRecipe) obj).getRecipeOutput() == output)
{
list.add((IRecipe) obj);
}
}
}
return list;
}
/**
* Replaces a recipe with a new IRecipe.
*
* @return True if successful
*/
public static boolean replaceRecipe(IRecipe recipe, IRecipe newRecipe)
{
for (Object obj : CraftingManager.getInstance().getRecipeList())
{
if (obj instanceof IRecipe)
{
if (((IRecipe) obj).equals(recipe) || obj == recipe)
{
CraftingManager.getInstance().getRecipeList().remove(obj);
CraftingManager.getInstance().getRecipeList().add(newRecipe);
return true;
}
}
}
return false;
}
/**
* Replaces a recipe with the resulting ItemStack with a new IRecipe.
*
* @return True if successful
*/
public static boolean replaceRecipe(ItemStack recipe, IRecipe newRecipe)
{
if (removeRecipe(recipe))
{
CraftingManager.getInstance().getRecipeList().add(newRecipe);
return true;
}
return false;
}
/**
* Removes a recipe by its IRecipe class.
*
* @return True if successful
*/
public static boolean removeRecipe(IRecipe recipe)
{
for (Object obj : CraftingManager.getInstance().getRecipeList())
{
if (obj != null)
{
if (obj instanceof IRecipe)
{
if (((IRecipe) obj).equals(recipe) || obj == recipe)
{
CraftingManager.getInstance().getRecipeList().remove(obj);
return true;
}
}
}
}
return false;
}
/**
* Removes the first recipe found by its output.
*
* @return True if successful
*/
public static boolean removeRecipe(ItemStack stack)
{
for (Object obj : CraftingManager.getInstance().getRecipeList())
{
if (obj != null)
{
if (obj instanceof IRecipe)
{
if (((IRecipe) obj).getRecipeOutput() != null)
{
if (((IRecipe) obj).getRecipeOutput().isItemEqual(stack))
{
CraftingManager.getInstance().getRecipeList().remove(obj);
return true;
}
}
}
}
}
return false;
}
/**
* Removes all recipes found that has this output. You may use this with Forge Ore Dictionary to
* remove all recipes with the FoD ID.
*
* @return True if successful
*/
public static boolean removeRecipes(ItemStack... itemStacks)
{
boolean didRemove = false;
for (Iterator itr = CraftingManager.getInstance().getRecipeList().iterator(); itr.hasNext();)
{
Object obj = itr.next();
if (obj != null)
{
if (obj instanceof IRecipe)
{
if (((IRecipe) obj).getRecipeOutput() != null)
{
for (ItemStack itemStack : itemStacks)
{
if (((IRecipe) obj).getRecipeOutput().isItemEqual(itemStack))
{
itr.remove();
didRemove = true;
break;
}
}
}
}
}
}
return didRemove;
}
/**
* Use this function if you want to check if the recipe is allowed in the configuration file.
*/
public static void addRecipe(IRecipe recipe, String name, Configuration configuration, boolean defaultBoolean)
{
if (configuration != null)
{
configuration.load();
if (configuration.get("Crafting", "Allow " + name + " Crafting", defaultBoolean).getBoolean(defaultBoolean))
{
GameRegistry.addRecipe(recipe);
}
configuration.save();
}
}
public static void addRecipe(IRecipe recipe, Configuration config, boolean defaultBoolean)
{
addRecipe(recipe, recipe.getRecipeOutput().getItemName(), config, defaultBoolean);
}
}

View file

@ -1,95 +0,0 @@
package universalelectricity.prefab;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
/**
* Creates a slot with a specific amount of items that matches the slot's requirements. Allows easy
* shift right clicking management and slot blocking in classes. In your container you can use
* this.getSlot(i).isItemValid to justify the player's shift clicking actions to match the slot.
*
* @author Calclavia
*
*/
public class SlotSpecific extends Slot
{
public ItemStack[] validItemStacks = new ItemStack[0];
public Class[] validClasses = new Class[0];
public boolean isInverted = false;
public boolean isMetadataSensitive = false;
public SlotSpecific(IInventory par2IInventory, int par3, int par4, int par5, ItemStack... itemStacks)
{
super(par2IInventory, par3, par4, par5);
this.setItemStacks(itemStacks);
}
public SlotSpecific(IInventory par2IInventory, int par3, int par4, int par5, Class... validClasses)
{
super(par2IInventory, par3, par4, par5);
this.setClasses(validClasses);
}
public SlotSpecific setMetadataSensitive()
{
this.isMetadataSensitive = true;
return this;
}
public SlotSpecific setItemStacks(ItemStack... validItemStacks)
{
this.validItemStacks = validItemStacks;
return this;
}
public SlotSpecific setClasses(Class... validClasses)
{
this.validClasses = validClasses;
return this;
}
public SlotSpecific toggleInverted()
{
this.isInverted = !this.isInverted;
return this;
}
/**
* Check if the stack is a valid item for this slot. Always true beside for the armor slots.
*/
@Override
public boolean isItemValid(ItemStack compareStack)
{
boolean returnValue = false;
for (ItemStack itemStack : this.validItemStacks)
{
if (compareStack.isItemEqual(itemStack) || (!this.isMetadataSensitive && compareStack.itemID == itemStack.itemID))
{
returnValue = true;
break;
}
}
if (!returnValue)
{
for (Class clazz : this.validClasses)
{
if (clazz.equals(compareStack.getItem().getClass()) || clazz.isInstance(compareStack.getItem()))
{
returnValue = true;
break;
}
}
}
if (this.isInverted)
{
return !returnValue;
}
return returnValue;
}
}

View file

@ -1,81 +0,0 @@
package universalelectricity.prefab;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.registry.LanguageRegistry;
/**
* A class to help you out with translations.
*
* @author Calclavia
*
*/
public class TranslationHelper
{
/**
* Loads all the language files for a mod. This supports the loading of "child" language files
* for sub-languages to be loaded all from one file instead of creating multiple of them. An
* example of this usage would be different Spanish sub-translations (es_MX, es_YU).
*
* @param languagePath - The path to the mod's language file folder.
* @param languageSupported - The languages supported. E.g: new String[]{"en_US", "en_AU",
* "en_UK"}
* @return The amount of language files loaded successfully.
*/
public static int loadLanguages(String languagePath, String[] languageSupported)
{
int languages = 0;
/**
* Load all languages.
*/
for (String language : languageSupported)
{
LanguageRegistry.instance().loadLocalization(languagePath + language + ".properties", language, false);
if (LanguageRegistry.instance().getStringLocalization("children", language) != "")
{
try
{
String[] children = LanguageRegistry.instance().getStringLocalization("children", language).split(",");
for (String child : children)
{
if (child != "" || child != null)
{
LanguageRegistry.instance().loadLocalization(languagePath + language + ".properties", child, false);
languages++;
}
}
}
catch (Exception e)
{
FMLLog.severe("Failed to load a child language file.");
e.printStackTrace();
}
}
languages++;
}
return languages;
}
/**
* Gets the local text of your translation based on the given key. This will look through your
* mod's translation file that was previously registered. Make sure you enter the full name
*
* @param key - e.g tile.block.name
* @return The translated string or the default English translation if none was found.
*/
public static String getLocal(String key)
{
String text = LanguageRegistry.instance().getStringLocalization(key);
if (text == null || text == "")
{
text = LanguageRegistry.instance().getStringLocalization(key, "en_US");
}
return text;
}
}

View file

@ -1,206 +0,0 @@
package universalelectricity.prefab.block;
import java.util.Random;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import universalelectricity.core.item.IItemElectric;
import universalelectricity.prefab.implement.IToolConfigurator;
/**
* An advanced block class that is to be extended for wrenching capabilities.
*/
public abstract class BlockAdvanced extends BlockContainer
{
public BlockAdvanced(int id, Material material)
{
super(id, material);
this.setHardness(0.6f);
}
/**
* DO NOT OVERRIDE THIS FUNCTION! Called when the block is right clicked by the player. This
* modified version detects electric items and wrench actions on your machine block. Do not
* override this function. Use onMachineActivated instead! (It does the same thing)
*
* @param world The World Object.
* @param x , y, z The coordinate of the block.
* @param side The side the player clicked on.
* @param hitX , hitY, hitZ The position the player clicked on relative to the block.
*/
@Override
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer entityPlayer, int side, float hitX, float hitY, float hitZ)
{
int metadata = world.getBlockMetadata(x, y, z);
/**
* Check if the player is holding a wrench or an electric item. If so, do not open the GUI.
*/
if (entityPlayer.inventory.getCurrentItem() != null)
{
if (entityPlayer.inventory.getCurrentItem().getItem() instanceof IToolConfigurator)
{
world.notifyBlocksOfNeighborChange(x, y, z, this.blockID);
((IToolConfigurator) entityPlayer.inventory.getCurrentItem().getItem()).wrenchUsed(entityPlayer, x, y, z);
if (entityPlayer.isSneaking())
{
if (this.onSneakUseWrench(world, x, y, z, entityPlayer, side, hitX, hitY, hitZ))
{
return true;
}
}
return this.onUseWrench(world, x, y, z, entityPlayer, side, hitX, hitY, hitZ);
}
else if (entityPlayer.inventory.getCurrentItem().getItem() instanceof IItemElectric)
{
if (this.onUseElectricItem(world, x, y, z, entityPlayer, side, hitX, hitY, hitZ))
{
return true;
}
}
}
if (entityPlayer.isSneaking())
{
if (this.onSneakMachineActivated(world, x, y, z, entityPlayer, side, hitX, hitY, hitZ))
{
return true;
}
}
return this.onMachineActivated(world, x, y, z, entityPlayer, side, hitX, hitY, hitZ);
}
/**
* Called when the machine is right clicked by the player
*
* @return True if something happens
*/
public boolean onMachineActivated(World world, int x, int y, int z, EntityPlayer entityPlayer, int side, float hitX, float hitY, float hitZ)
{
return false;
}
/**
* Called when the machine is being wrenched by a player while sneaking.
*
* @return True if something happens
*/
public boolean onSneakMachineActivated(World world, int x, int y, int z, EntityPlayer entityPlayer, int side, float hitX, float hitY, float hitZ)
{
return false;
}
/**
* Called when a player uses an electric item on the machine
*
* @return True if some happens
*/
public boolean onUseElectricItem(World world, int x, int y, int z, EntityPlayer entityPlayer, int side, float hitX, float hitY, float hitZ)
{
return false;
}
/**
* Called when a player uses a wrench on the machine
*
* @return True if some happens
*/
public boolean onUseWrench(World world, int x, int y, int z, EntityPlayer entityPlayer, int side, float hitX, float hitY, float hitZ)
{
return false;
}
/**
* Called when a player uses a wrench on the machine while sneaking. Only works with the UE
* wrench.
*
* @return True if some happens
*/
public boolean onSneakUseWrench(World world, int x, int y, int z, EntityPlayer entityPlayer, int side, float hitX, float hitY, float hitZ)
{
return this.onUseWrench(world, x, y, z, entityPlayer, side, hitX, hitY, hitZ);
}
/**
* Returns the TileEntity used by this block. You should use the metadata sensitive version of
* this to get the maximum optimization!
*/
@Override
public TileEntity createNewTileEntity(World var1)
{
return null;
}
@Override
public void breakBlock(World world, int x, int y, int z, int par5, int par6)
{
this.dropEntireInventory(world, x, y, z, par5, par6);
super.breakBlock(world, x, y, z, par5, par6);
}
/**
* Override this if you don't need it. This will eject all items out of this machine if it has
* an inventory.
*/
public void dropEntireInventory(World world, int x, int y, int z, int par5, int par6)
{
TileEntity tileEntity = world.getBlockTileEntity(x, y, z);
if (tileEntity != null)
{
if (tileEntity instanceof IInventory)
{
IInventory inventory = (IInventory) tileEntity;
for (int var6 = 0; var6 < inventory.getSizeInventory(); ++var6)
{
ItemStack var7 = inventory.getStackInSlot(var6);
if (var7 != null)
{
Random random = new Random();
float var8 = random.nextFloat() * 0.8F + 0.1F;
float var9 = random.nextFloat() * 0.8F + 0.1F;
float var10 = random.nextFloat() * 0.8F + 0.1F;
while (var7.stackSize > 0)
{
int var11 = random.nextInt(21) + 10;
if (var11 > var7.stackSize)
{
var11 = var7.stackSize;
}
var7.stackSize -= var11;
EntityItem var12 = new EntityItem(world, (x + var8), (y + var9), (z + var10), new ItemStack(var7.itemID, var11, var7.getItemDamage()));
if (var7.hasTagCompound())
{
var12.getEntityItem().setTagCompound((NBTTagCompound) var7.getTagCompound().copy());
}
float var13 = 0.05F;
var12.motionX = ((float) random.nextGaussian() * var13);
var12.motionY = ((float) random.nextGaussian() * var13 + 0.2F);
var12.motionZ = ((float) random.nextGaussian() * var13);
world.spawnEntityInWorld(var12);
}
}
}
}
}
}
}

View file

@ -1,46 +0,0 @@
package universalelectricity.prefab.block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import universalelectricity.core.block.IConductor;
public abstract class BlockConductor extends BlockContainer
{
public BlockConductor(int id, Material material)
{
super(id, material);
}
/**
* Called whenever the block is added into the world. Args: world, x, y, z
*/
@Override
public void onBlockAdded(World world, int x, int y, int z)
{
super.onBlockAdded(world, x, y, z);
TileEntity tileEntity = world.getBlockTileEntity(x, y, z);
if (tileEntity instanceof IConductor)
{
((IConductor) tileEntity).updateAdjacentConnections();
}
}
/**
* Lets the block know when one of its neighbor changes. Doesn't know which neighbor changed
* (coordinates passed are their own) Args: x, y, z, neighbor blockID
*/
@Override
public void onNeighborBlockChange(World world, int x, int y, int z, int blockID)
{
TileEntity tileEntity = world.getBlockTileEntity(x, y, z);
if (tileEntity instanceof IConductor)
{
((IConductor) tileEntity).updateAdjacentConnections();
}
}
}

View file

@ -1,75 +0,0 @@
package universalelectricity.prefab.block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeDirection;
import universalelectricity.prefab.implement.IRotatable;
/**
* A block that can rotate based on placed position and wrenching.
*
* @author Calclavia
*
*/
public abstract class BlockRotatable extends BlockAdvanced implements IRotatable
{
public BlockRotatable(int id, Material material)
{
super(id, material);
}
@Override
public void onBlockPlacedBy(World world, int x, int y, int z, EntityLiving entityLiving, ItemStack itemStack)
{
int angle = MathHelper.floor_double((entityLiving.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3;
int change = 3;
switch (angle)
{
case 0:
change = 2;
break;
case 1:
change = 5;
break;
case 2:
change = 3;
break;
case 3:
change = 4;
break;
}
this.setDirection(world, x, y, z, ForgeDirection.getOrientation(change));
}
@Override
public boolean onUseWrench(World world, int x, int y, int z, EntityPlayer par5EntityPlayer, int side, float hitX, float hitY, float hitZ)
{
/**
* NOTE! This will rotate the block only in all 4 horizontal directions. If your block
* rotates up or down, you should override this.
*/
this.setDirection(world, x, y, z, ForgeDirection.getOrientation(ForgeDirection.ROTATION_MATRIX[0][this.getDirection(world, x, y, z).ordinal()]));
return true;
}
@Override
public ForgeDirection getDirection(World world, int x, int y, int z)
{
return ForgeDirection.getOrientation(world.getBlockMetadata(x, y, z));
}
@Override
public void setDirection(World world, int x, int y, int z, ForgeDirection facingDirection)
{
world.setBlockMetadataWithNotify(x, y, z, facingDirection.ordinal(), 3);
}
}

View file

@ -1,319 +0,0 @@
package universalelectricity.prefab.flag;
import java.util.Iterator;
import java.util.List;
import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommandSender;
import net.minecraft.command.WrongUsageException;
import net.minecraft.entity.player.EntityPlayer;
import universalelectricity.core.vector.Vector3;
/**
* Commands used for flags and regions. This can be used for protection for specific mod components
* that might be dangerous.
*
* @author Calclavia
*
*/
public class CommandFlag extends CommandBase
{
public static final String[] COMMANDS = new String[] { "list", "setregion", "removeregion", "set" };
public String commandName = "modflag";
public ModFlag modFlagData;
public CommandFlag(ModFlag modFlag)
{
this.modFlagData = modFlag;
}
public CommandFlag(ModFlag modFlag, String commandName)
{
this(modFlag);
this.commandName = commandName;
}
@Override
public String getCommandName()
{
return commandName;
}
@Override
public String getCommandUsage(ICommandSender par1ICommandSender)
{
String returnString = "";
for (String command : COMMANDS)
{
returnString = returnString + "\n/" + this.getCommandName() + " " + command;
}
return returnString;
}
@Override
public void processCommand(ICommandSender sender, String[] args)
{
if (args.length > 0)
{
EntityPlayer entityPlayer = (EntityPlayer) sender;
// The world data the player is on.
FlagWorld flagWorld = this.modFlagData.getFlagWorld(entityPlayer.worldObj);
String commandName = args[0].toLowerCase();
if (commandName.equalsIgnoreCase("list"))
{
/**
* The list command lists out all regions in this world/region.
*/
if (args.length > 1)
{
String regionName = args[1];
if (regionName.equalsIgnoreCase("all"))
{
String msg = "";
Iterator<FlagWorld> itWorlds = this.modFlagData.getFlagWorlds().iterator();
while (itWorlds.hasNext())
{
Iterator<FlagRegion> itRegion = itWorlds.next().getRegions().iterator();
while (itRegion.hasNext())
{
FlagRegion flagRegion = itRegion.next();
msg = msg + " " + flagRegion.name + " (" + flagRegion.region.min.x + "," + flagRegion.region.min.z + ")" + ",";
}
}
if (msg != "")
{
msg = "List of regions in world:\n" + msg;
}
else
{
msg = "No regions in this world.";
}
sender.sendChatToPlayer(msg);
}
else if (flagWorld.getRegion(regionName) != null)
{
String msg = "";
Iterator<Flag> i = flagWorld.getRegion(regionName).getFlags().iterator();
while (i.hasNext())
{
Flag flag = i.next();
msg = msg + " " + flag.name + " => " + flag.value + ",";
}
if (msg != "")
{
msg = "List of flags in region " + regionName + ":\n" + msg;
}
else
{
msg = "No flags in this region.";
}
sender.sendChatToPlayer(msg);
}
else
{
String msg = "Region does not exist, but here are existing flags in the position you are standing on:\n";
Iterator<Flag> i = flagWorld.getFlagsInPosition(new Vector3(entityPlayer)).iterator();
while (i.hasNext())
{
Flag flag = i.next();
msg = msg + " " + flag.name + "=>" + flag.value + ",";
}
sender.sendChatToPlayer(msg);
}
}
else
{
String msg = "";
Iterator<FlagRegion> i = flagWorld.getRegions().iterator();
while (i.hasNext())
{
FlagRegion flagRegion = i.next();
msg = msg + " " + flagRegion.name + " (" + flagRegion.region.min.x + "," + flagRegion.region.min.z + ")" + ",";
}
if (msg != "")
{
msg = "List of regions in this dimension:\n" + msg;
}
else
{
msg = "No regions in this dimension.";
}
sender.sendChatToPlayer(msg);
}
return;
}
else if (commandName.equalsIgnoreCase("setregion"))
{
if (args.length > 1)
{
String regionName = args[1];
if (regionName.equalsIgnoreCase(FlagWorld.GLOBAL_REGION))
{
if (flagWorld.addRegion(regionName, new Vector3(entityPlayer), 1))
{
sender.sendChatToPlayer("Created global dimension region setting.");
return;
}
}
else if (args.length > 2)
{
int radius = 0;
try
{
radius = Integer.parseInt(args[2]);
}
catch (Exception e)
{
throw new WrongUsageException("Radius not a number!");
}
if (radius > 0)
{
FlagRegion region = flagWorld.getRegion(regionName);
if (region == null)
{
if (flagWorld.addRegion(regionName, new Vector3(entityPlayer), radius))
{
sender.sendChatToPlayer("Region " + regionName + " added.");
}
}
else
{
region.edit(new Vector3(entityPlayer), radius);
sender.sendChatToPlayer("Region " + regionName + " already exists. Modified region to have a radius of: " + radius);
}
}
else
{
throw new WrongUsageException("Radius has to be greater than zero!");
}
}
else
{
throw new WrongUsageException("/" + this.getCommandName() + " addregion <name> <radius>");
}
}
else
{
throw new WrongUsageException("Please specify the region name.");
}
return;
}
else if (commandName.equalsIgnoreCase("removeregion"))
{
if (args.length > 1)
{
String regionName = args[1];
if (flagWorld.removeRegion(regionName))
{
sender.sendChatToPlayer("Region with name " + regionName + " is removed.");
}
else
{
throw new WrongUsageException("The specified region does not exist in this world.");
}
}
else
{
throw new WrongUsageException("Please specify the region name.");
}
return;
}
else if (commandName.equalsIgnoreCase("set"))
{
if (args.length > 2)
{
String regionName = args[1];
String flagName = args[2];
FlagRegion flagRegion = flagWorld.getRegion(regionName);
if (flagRegion != null)
{
if (FlagRegistry.flags.contains(flagName))
{
if (args.length > 3)
{
String flagValue = args[3];
flagRegion.setFlag(flagName, flagValue);
sender.sendChatToPlayer("Flag '" + flagName + "' has been set to '" + flagValue + "' in " + regionName + ".");
}
else
{
flagRegion.removeFlag(flagName);
sender.sendChatToPlayer("Removed flag '" + flagName + "'.");
}
}
else
{
String flags = "Flag does not exist. Existing flags:\n";
for (String registeredFlag : FlagRegistry.flags)
{
flags = flags + registeredFlag + ", ";
}
throw new WrongUsageException(flags);
}
}
else
{
throw new WrongUsageException("The specified region '" + regionName + "' does not exist.");
}
}
else
{
throw new WrongUsageException("/" + this.getCommandName() + " set <regionName> <flagName> <value>");
}
return;
}
}
throw new WrongUsageException(this.getCommandUsage(sender));
}
@Override
public int getRequiredPermissionLevel()
{
return 2;
}
@Override
public List addTabCompletionOptions(ICommandSender sender, String[] args)
{
return args.length == 1 ? getListOfStringsMatchingLastWord(args, COMMANDS) : null;
}
}

View file

@ -1,43 +0,0 @@
package universalelectricity.prefab.flag;
import net.minecraft.nbt.NBTTagCompound;
public class Flag extends FlagBase
{
/**
* The region in which this flag has affect in.
*/
public FlagRegion flagRegion;
public String name;
public String value;
public Flag(FlagRegion flagRegion)
{
this.flagRegion = flagRegion;
}
public Flag(FlagRegion flagRegion, String name, String value)
{
this(flagRegion);
this.name = name;
this.value = value;
}
@Override
public void readFromNBT(NBTTagCompound nbt)
{
this.name = nbt.getString("name");
this.value = nbt.getString("value");
}
@Override
public void writeToNBT(NBTTagCompound nbt)
{
nbt.setString("name", this.name);
nbt.setString("value", this.value);
}
}

View file

@ -1,26 +0,0 @@
package universalelectricity.prefab.flag;
import net.minecraft.nbt.NBTTagCompound;
public abstract class FlagBase
{
public abstract void readFromNBT(NBTTagCompound nbt);
public abstract void writeToNBT(NBTTagCompound nbt);
public NBTTagCompound getNBT()
{
NBTTagCompound nbt = new NBTTagCompound();
try
{
this.writeToNBT(nbt);
}
catch (Exception e)
{
System.out.println("Failed to read flag");
e.printStackTrace();
}
return nbt;
}
}

View file

@ -1,184 +0,0 @@
package universalelectricity.prefab.flag;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import universalelectricity.core.vector.Vector3;
import universalelectricity.prefab.vector.Region3;
/**
* A defined region.
*
* @author Calclavia
*
*/
public class FlagRegion extends FlagBase
{
/**
* The region in which this flag has affect in.
*/
public FlagWorld flagWorld;
public String name;
public Region3 region;
private final List<Flag> flags = new ArrayList<Flag>();
public FlagRegion(FlagWorld worldFlagData)
{
this.flagWorld = worldFlagData;
}
public FlagRegion(FlagWorld flagWorld, String name, Region3 region)
{
this.flagWorld = flagWorld;
this.name = name;
this.region = region;
}
@Override
public void readFromNBT(NBTTagCompound nbt)
{
this.name = nbt.getName();
Vector3 startVector = Vector3.readFromNBT(nbt.getCompoundTag("min"));
Vector3 endVector = Vector3.readFromNBT(nbt.getCompoundTag("max"));
this.region = new Region3(startVector, endVector);
/**
* Child Data
*/
NBTTagList flagList = nbt.getTagList("flags");
for (int i = 0; i < flagList.tagCount(); i++)
{
NBTTagCompound childNode = (NBTTagCompound) flagList.tagAt(i);
try
{
Flag flag = new Flag(this);
flag.readFromNBT(childNode);
this.flags.add(flag);
}
catch (Exception e)
{
System.out.println("Mod Flag: Failed to read flag data: " + childNode.getName());
e.printStackTrace();
}
}
}
@Override
public void writeToNBT(NBTTagCompound nbt)
{
nbt.setName(this.name);
nbt.setTag("min", this.region.min.writeToNBT(new NBTTagCompound()));
nbt.setTag("max", this.region.max.writeToNBT(new NBTTagCompound()));
NBTTagList flagList = new NBTTagList();
for (Flag flag : this.getFlags())
{
try
{
flagList.appendTag(flag.getNBT());
}
catch (Exception e)
{
System.out.println("Failed to save world flag data: " + flag.name);
e.printStackTrace();
}
}
nbt.setTag("flags", flagList);
}
public boolean containsValue(String flagName, String checkValue, Vector3 position)
{
for (Flag flag : this.flags)
{
if (flag.name.equalsIgnoreCase(flagName) && flag.value.equalsIgnoreCase(checkValue))
{
return true;
}
}
return false;
}
public boolean setFlag(String flagName, String value)
{
this.removeFlag(flagName);
if (value != null && value != "")
{
if (!containsFlag(flagName))
{
return this.flags.add(new Flag(this, flagName, value));
}
}
return false;
}
public boolean containsFlag(String flagName)
{
for (Flag region : this.flags)
{
if (region.name.equalsIgnoreCase(flagName))
{
return true;
}
}
return false;
}
public boolean removeFlag(String flagName)
{
for (Flag region : this.flags)
{
if (region.name.equalsIgnoreCase(flagName))
{
this.flags.remove(region);
return true;
}
}
return false;
}
public List<Flag> getFlags()
{
Iterator<Flag> it = this.flags.iterator();
while (it.hasNext())
{
Flag flag = it.next();
if (flag == null)
{
it.remove();
continue;
}
if (flag.name == null || flag.name == "")
{
it.remove();
continue;
}
}
return this.flags;
}
public void edit(Vector3 position, int radius)
{
Vector3 minVec = new Vector3(position.intX() - radius, 0, position.intZ() - radius);
Vector3 maxVec = new Vector3(position.intX() + radius, this.flagWorld.world.getHeight(), position.intZ() + radius);
this.region = new Region3(minVec, maxVec);
}
}

View file

@ -1,52 +0,0 @@
package universalelectricity.prefab.flag;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* All the different types of flags that can be registered.
*
* @author Calclavia
*
*/
public class FlagRegistry
{
public static final String DEFAULT_NAME = "ModFlags";
private static final HashMap<String, ModFlag> MOD_FLAGS = new HashMap<String, ModFlag>();
public static final List<String> flags = new ArrayList<String>();
public static boolean isInitiated = false;
public static void registerModFlag(String name, ModFlag flagData)
{
MOD_FLAGS.put(name, flagData);
}
public static ModFlag getModFlag(String name)
{
return MOD_FLAGS.get(name);
}
/**
* Registers a flag name, allowing it to be used and called by the player. Call this in your
* mod's init function.
*/
public static String registerFlag(String name)
{
if (!isInitiated)
{
isInitiated = true;
}
name = name.toLowerCase();
if (!flags.contains(name))
{
flags.add(name);
}
return name;
}
}

View file

@ -1,200 +0,0 @@
package universalelectricity.prefab.flag;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import universalelectricity.core.vector.Vector3;
import universalelectricity.prefab.vector.Region3;
/**
* Data structure for world protection.
*
* @author Calclavia
*
*/
public class FlagWorld extends FlagBase
{
public static final String GLOBAL_REGION = "dimension";
public World world;
private final List<FlagRegion> regions = new ArrayList<FlagRegion>();
public FlagWorld(World world)
{
this.world = world;
}
@Override
public void readFromNBT(NBTTagCompound nbt)
{
// A list containing all flags within it for this world.
Iterator<NBTTagCompound> childCompounds = nbt.getTags().iterator();
while (childCompounds.hasNext())
{
NBTTagCompound childCompound = childCompounds.next();
try
{
FlagRegion flagRegion = new FlagRegion(this);
flagRegion.readFromNBT(childCompound);
this.regions.add(flagRegion);
}
catch (Exception e)
{
System.out.println("Mod Flag: Failed to read flag data: " + childCompound.getName());
e.printStackTrace();
}
}
}
@Override
public void writeToNBT(NBTTagCompound nbt)
{
for (FlagRegion region : this.regions)
{
try
{
NBTTagCompound flagCompound = new NBTTagCompound();
region.writeToNBT(flagCompound);
nbt.setTag(region.name, flagCompound);
}
catch (Exception e)
{
System.out.println("Failed to save world flag data: " + region.name);
e.printStackTrace();
}
}
}
/**
* Gets all the flags that have an effect in this position.
*
* @param position
* @return
*/
public List<Flag> getFlagsInPosition(Vector3 position)
{
List<Flag> returnFlags = new ArrayList<Flag>();
for (FlagRegion flagRegion : this.regions)
{
if (flagRegion.region.isIn(position) || flagRegion.name.equalsIgnoreCase(GLOBAL_REGION))
{
for (Flag flag : flagRegion.getFlags())
{
returnFlags.add(flag);
}
}
}
return returnFlags;
}
/**
* Gets all the values of the flags in this position.
*/
public List<String> getValues(String flagName, Vector3 position)
{
List<String> values = new ArrayList<String>();
for (Flag flag : this.getFlagsInPosition(position))
{
values.add(flag.value);
}
return values;
}
/**
* Checks if there is a flag in this position that has a specific value.
*/
public boolean containsValue(String flagName, String checkValue, Vector3 position)
{
for (Flag flag : this.getFlagsInPosition(position))
{
if (flag.name.equalsIgnoreCase(flagName) && flag.value.equalsIgnoreCase(checkValue))
{
return true;
}
}
return false;
}
public boolean addRegion(String name, Vector3 position, int radius)
{
Vector3 minVec = new Vector3(position.intX() - radius, 0, position.intZ() - radius);
Vector3 maxVec = new Vector3(position.intX() + radius, this.world.getHeight(), position.intZ() + radius);
return this.regions.add(new FlagRegion(this, name, new Region3(minVec, maxVec)));
}
public FlagRegion getRegion(String name)
{
for (FlagRegion region : this.regions)
{
if (region.name.equals(name))
{
return region;
}
}
return null;
}
/**
* Gets all regions that intersect this point.
*/
public List<FlagRegion> getRegions(Vector3 position)
{
List<FlagRegion> returnRegions = new ArrayList<FlagRegion>();
for (FlagRegion region : this.regions)
{
if (region.region.isIn(position))
{
returnRegions.add(region);
}
}
return returnRegions;
}
public boolean removeRegion(String name)
{
for (FlagRegion region : this.regions)
{
if (region.name.equals(name))
{
this.regions.remove(region);
return true;
}
}
return false;
}
public List<FlagRegion> getRegions()
{
Iterator<FlagRegion> it = this.regions.iterator();
while (it.hasNext())
{
FlagRegion region = it.next();
if (region == null)
{
it.remove();
continue;
}
if (region.name == null || region.name == "")
{
it.remove();
continue;
}
}
return this.regions;
}
}

View file

@ -1,111 +0,0 @@
package universalelectricity.prefab.flag;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import net.minecraftforge.common.DimensionManager;
import universalelectricity.core.vector.Vector3;
public class ModFlag extends FlagBase
{
/**
* An array of world flag data. Each representing a world.
*/
private final List<FlagWorld> flagWorlds = new ArrayList<FlagWorld>();
/**
* Initiates a new mod flag data and loads everything from NBT into memory. Only exists server
* side.
*
* @param nbt
*/
public ModFlag(NBTTagCompound nbt)
{
this.readFromNBT(nbt);
}
@Override
public void readFromNBT(NBTTagCompound nbt)
{
// A list containing all dimension ID and data within it.
Iterator dimensions = nbt.getTags().iterator();
while (dimensions.hasNext())
{
NBTTagCompound dimensionCompound = (NBTTagCompound) dimensions.next();
try
{
int dimensionID = Integer.parseInt(dimensionCompound.getName().replace("dim_", ""));
World world = DimensionManager.getWorld(dimensionID);
FlagWorld flagWorld = new FlagWorld(world);
flagWorld.readFromNBT(dimensionCompound);
this.flagWorlds.add(flagWorld);
}
catch (Exception e)
{
System.out.println("Mod Flag: Failed to read dimension data: " + dimensionCompound.getName());
e.printStackTrace();
}
}
}
@Override
public void writeToNBT(NBTTagCompound nbt)
{
for (FlagWorld worldData : this.flagWorlds)
{
try
{
nbt.setTag("dim_" + worldData.world.provider.dimensionId, worldData.getNBT());
}
catch (Exception e)
{
System.out.println("Mod Flag: Failed to save world flag data: " + worldData.world);
e.printStackTrace();
}
}
}
public FlagWorld getFlagWorld(World world)
{
FlagWorld worldData = null;
if (world != null)
{
for (FlagWorld data : this.flagWorlds)
{
if (data.world != null && data.world.provider != null)
{
if (data.world.provider.dimensionId == world.provider.dimensionId)
{
worldData = data;
break;
}
}
}
// If data is null, create it.
if (worldData == null)
{
worldData = new FlagWorld(world);
this.flagWorlds.add(worldData);
}
}
return worldData;
}
public boolean containsValue(World world, String flagName, String checkValue, Vector3 position)
{
return this.getFlagWorld(world).containsValue(flagName, checkValue, position);
}
public List<FlagWorld> getFlagWorlds()
{
return this.flagWorlds;
}
}

View file

@ -1,113 +0,0 @@
package universalelectricity.prefab.flag;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import net.minecraft.client.Minecraft;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.MinecraftServer;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.FMLLog;
public class NBTFileLoader
{
/**
* Saves NBT data in the world folder.
*
* @return True on success.
*/
public static boolean saveData(File saveDirectory, String filename, NBTTagCompound data)
{
try
{
File tempFile = new File(saveDirectory, filename + "_tmp.dat");
File file = new File(saveDirectory, filename + ".dat");
CompressedStreamTools.writeCompressed(data, new FileOutputStream(tempFile));
if (file.exists())
{
file.delete();
}
tempFile.renameTo(file);
FMLLog.fine("Saved " + filename + " NBT data file successfully.");
return true;
}
catch (Exception e)
{
System.out.println("Failed to save " + filename + ".dat!");
e.printStackTrace();
return false;
}
}
public static boolean saveData(String filename, NBTTagCompound data)
{
return saveData(getSaveDirectory(MinecraftServer.getServer().getFolderName()), filename, data);
}
/**
* Reads NBT data from the world folder.
*
* @return The NBT data
*/
public static NBTTagCompound loadData(File saveDirectory, String filename)
{
try
{
File file = new File(saveDirectory, filename + ".dat");
if (file.exists())
{
FMLLog.fine("Loaded " + filename + " data.");
return CompressedStreamTools.readCompressed(new FileInputStream(file));
}
else
{
FMLLog.fine("Created new " + filename + " data.");
return new NBTTagCompound();
}
}
catch (Exception e)
{
System.out.println("Failed to load " + filename + ".dat!");
e.printStackTrace();
return null;
}
}
public static NBTTagCompound loadData(String filename)
{
return loadData(getSaveDirectory(MinecraftServer.getServer().getFolderName()), filename);
}
public static File getSaveDirectory(String worldName)
{
File parent = getBaseDirectory();
if (FMLCommonHandler.instance().getSide().isClient())
{
parent = new File(getBaseDirectory(), "saves" + File.separator);
}
return new File(parent, worldName + File.separator);
}
public static File getBaseDirectory()
{
if (FMLCommonHandler.instance().getSide().isClient())
{
FMLClientHandler.instance().getClient();
return Minecraft.getMinecraftDir();
}
else
{
return new File(".");
}
}
}

View file

@ -1,25 +0,0 @@
package universalelectricity.prefab.implement;
/**
* This class should be applied to all tile entities (mainly machines) that can be disabled (by
* things like EMP, short circuit etc.).
*
* @author Calclavia
*
*/
public interface IDisableable
{
/**
* This is called when the tile entity is to be disabled.
*
* @param duration - The duration of the disable in ticks.
*/
public void onDisable(int duration);
/**
* Called to see if this tile entity is disabled.
*
* @return True if the tile entity is disabled.
*/
public boolean isDisabled();
}

View file

@ -1,16 +0,0 @@
package universalelectricity.prefab.implement;
import net.minecraftforge.common.ForgeDirection;
/**
* This should be applied on tile entities that can provide redstone power
*
* @author Calclavia
*
*/
public interface IRedstoneProvider
{
public boolean isPoweringTo(ForgeDirection side);
public boolean isIndirectlyPoweringTo(ForgeDirection side);
}

View file

@ -1,21 +0,0 @@
package universalelectricity.prefab.implement;
/**
* This interface should be applied onto all tile entities that needs to receive redstone power.
* Look at TileEntityBatteryBox for reference.
*
* @author Calclavia
*
*/
public interface IRedstoneReceptor
{
/**
* Called when the block is powered on by redstone
*/
public void onPowerOn();
/**
* Called when the block is powered off by redstone
*/
public void onPowerOff();
}

View file

@ -1,24 +0,0 @@
package universalelectricity.prefab.implement;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeDirection;
/**
* The interface is applied to Blocks and 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(World world, int x, int y, int z);
/**
* @param Sets the facing direction.
*/
public void setDirection(World world, int x, int y, int z, ForgeDirection facingDirection);
}

View file

@ -1,24 +0,0 @@
package universalelectricity.prefab.implement;
/**
* This interface should be applied to all things that has a tier/level.
*
* @author Calclavia
*
*/
public interface ITier
{
/**
* Gets the tier of this object
*
* @return - The tier
*/
public int getTier();
/**
* Sets the tier of the object
*
* @param tier - The tier to be set
*/
public void setTier(int tier);
}

View file

@ -1,33 +0,0 @@
package universalelectricity.prefab.implement;
import net.minecraft.entity.player.EntityPlayer;
/**
* Code written by Buildcraft. Applied to items that acts as a block configurator such as wrenches,
* screw drivers and such.
*
* @author Buildcraft Team
*/
public interface IToolConfigurator
{
/***
* Called to ensure that the wrench can be used. To get the ItemStack that is used, check
* player.inventory.getCurrentItem()
*
* @param player - The player doing the wrenching
* @param x ,y,z - The coordinates for the block being wrenched
*
* @return true if wrenching is allowed, false if not
*/
public boolean canWrench(EntityPlayer player, int x, int y, int z);
/***
* Callback after the wrench has been used. This can be used to decrease durability or for other
* purposes. To get the ItemStack that was used, check player.inventory.getCurrentItem()
*
* @param player - The player doing the wrenching
* @param x ,y,z - The coordinates of the block being wrenched
*/
public void wrenchUsed(EntityPlayer player, int x, int y, int z);
}

View file

@ -1,22 +0,0 @@
package universalelectricity.prefab.modifier;
import net.minecraft.item.ItemStack;
/**
* This must be applied to an item that acts as a modifier or an upgrade.
*
* @author Calclavia
*
*/
public interface IModifier
{
/**
* @return - The name of the modifier.
*/
public String getName(ItemStack itemstack);
/**
* @return - How much effect does this modifier have?
*/
public int getEffectiveness(ItemStack itemstack);
}

View file

@ -1,29 +0,0 @@
package universalelectricity.prefab.modifier;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
/**
* This slot should be used by any container that contains an item that is a modifier. An example of
* this would be upgrade slots.
*
* @author Calclavia
*
*/
public class SlotModifier extends Slot
{
public SlotModifier(IInventory par2IInventory, int par3, int par4, int par5)
{
super(par2IInventory, par3, par4, par5);
}
/**
* Check if the stack is a valid item for this slot. Always true beside for the armor slots.
*/
@Override
public boolean isItemValid(ItemStack par1ItemStack)
{
return par1ItemStack.getItem() instanceof IModifier;
}
}

View file

@ -1,101 +0,0 @@
package universalelectricity.prefab.multiblock;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.World;
import universalelectricity.core.UniversalElectricity;
import universalelectricity.core.vector.Vector3;
public class BlockMulti extends BlockContainer
{
public BlockMulti(int id)
{
super(id, UniversalElectricity.machine);
this.setHardness(0.8F);
this.setUnlocalizedName("MultiBlock");
}
public void makeFakeBlock(World worldObj, Vector3 position, Vector3 mainBlock)
{
worldObj.setBlock(position.intX(), position.intY(), position.intZ(), this.blockID, 0, 2);
((TileEntityMulti) worldObj.getBlockTileEntity(position.intX(), position.intY(), position.intZ())).setMainBlock(mainBlock);
}
@Override
public void breakBlock(World par1World, int x, int y, int z, int par5, int par6)
{
TileEntityMulti tileEntity = (TileEntityMulti) par1World.getBlockTileEntity(x, y, z);
tileEntity.onBlockRemoval();
super.breakBlock(par1World, x, y, z, par5, par6);
}
/**
* Called when the block is right clicked by the player. This modified version detects electric
* items and wrench actions on your machine block. Do not override this function. Use
* machineActivated instead! (It does the same thing)
*/
@Override
public boolean onBlockActivated(World par1World, int x, int y, int z, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9)
{
TileEntityMulti tileEntity = (TileEntityMulti) par1World.getBlockTileEntity(x, y, z);
return tileEntity.onBlockActivated(par1World, x, y, z, par5EntityPlayer);
}
/**
* Returns the quantity of items to drop on block destruction.
*/
@Override
public int quantityDropped(Random par1Random)
{
return 0;
}
@Override
public int getRenderType()
{
return -1;
}
@Override
public boolean isOpaqueCube()
{
return false;
}
@Override
public boolean renderAsNormalBlock()
{
return false;
}
@Override
public TileEntity createNewTileEntity(World var1)
{
return new TileEntityMulti();
}
@Override
public ItemStack getPickBlock(MovingObjectPosition target, World par1World, int x, int y, int z)
{
TileEntity tileEntity = par1World.getBlockTileEntity(x, y, z);
Vector3 mainBlockPosition = ((TileEntityMulti) tileEntity).mainBlockPosition;
if (mainBlockPosition != null)
{
int mainBlockID = par1World.getBlockId(mainBlockPosition.intX(), mainBlockPosition.intY(), mainBlockPosition.intZ());
if (mainBlockID > 0)
{
return Block.blocksList[mainBlockID].getPickBlock(target, par1World, mainBlockPosition.intX(), mainBlockPosition.intY(), mainBlockPosition.intZ());
}
}
return null;
}
}

View file

@ -1,17 +0,0 @@
package universalelectricity.prefab.multiblock;
import net.minecraft.entity.player.EntityPlayer;
/**
* A general interface to be implemented by anything that needs it.
*
* @author Calclavia
*
*/
public interface IBlockActivate
{
/**
* Called when activated
*/
public boolean onActivated(EntityPlayer entityPlayer);
}

View file

@ -1,28 +0,0 @@
package universalelectricity.prefab.multiblock;
import net.minecraft.tileentity.TileEntity;
import universalelectricity.core.vector.Vector3;
/**
* Interface to be applied to tile entity blocks that occupies more than one block space. Useful for
* large machines.
*
* @author Calclavia
*
*/
public interface IMultiBlock extends IBlockActivate
{
/**
* Called when this multiblock is created
*
* @param placedPosition - The position the block was placed at
*/
public void onCreate(Vector3 placedPosition);
/**
* Called when one of the multiblocks of this block is destroyed
*
* @param callingBlock - The tile entity who called the onDestroy function
*/
public void onDestroy(TileEntity callingBlock);
}

View file

@ -1,127 +0,0 @@
package universalelectricity.prefab.multiblock;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.Packet;
import net.minecraft.network.packet.Packet250CustomPayload;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import universalelectricity.core.vector.Vector3;
import universalelectricity.prefab.network.IPacketReceiver;
import universalelectricity.prefab.network.PacketManager;
import com.google.common.io.ByteArrayDataInput;
/**
* This is a multiblock to be used for blocks that are bigger than one block.
*
* @author Calclavia
*
*/
public class TileEntityMulti extends TileEntity implements IPacketReceiver
{
// The the position of the main block
public Vector3 mainBlockPosition;
public void setMainBlock(Vector3 mainBlock)
{
this.mainBlockPosition = mainBlock;
if (!this.worldObj.isRemote)
{
PacketManager.sendPacketToClients(this.getDescriptionPacket());
}
}
@Override
public Packet getDescriptionPacket()
{
if (this.mainBlockPosition != null)
{
return PacketManager.getPacket("BasicComponents", this, this.mainBlockPosition.x, this.mainBlockPosition.y, this.mainBlockPosition.z);
}
return null;
}
public void onBlockRemoval()
{
if (mainBlockPosition != null)
{
TileEntity tileEntity = this.worldObj.getBlockTileEntity((int) mainBlockPosition.x, (int) mainBlockPosition.y, (int) mainBlockPosition.z);
if (tileEntity != null && tileEntity instanceof IMultiBlock)
{
IMultiBlock mainBlock = (IMultiBlock) tileEntity;
if (mainBlock != null)
{
mainBlock.onDestroy(this);
}
}
}
}
public boolean onBlockActivated(World par1World, int x, int y, int z, EntityPlayer par5EntityPlayer)
{
if (mainBlockPosition != null)
{
TileEntity tileEntity = this.worldObj.getBlockTileEntity((int) mainBlockPosition.x, (int) mainBlockPosition.y, (int) mainBlockPosition.z);
if (tileEntity != null)
{
if (tileEntity instanceof IMultiBlock)
{
return ((IMultiBlock) tileEntity).onActivated(par5EntityPlayer);
}
}
}
return false;
}
/**
* Reads a tile entity from NBT.
*/
@Override
public void readFromNBT(NBTTagCompound nbt)
{
super.readFromNBT(nbt);
this.mainBlockPosition = Vector3.readFromNBT(nbt.getCompoundTag("mainBlockPosition"));
}
/**
* Writes a tile entity to NBT.
*/
@Override
public void writeToNBT(NBTTagCompound nbt)
{
super.writeToNBT(nbt);
nbt.setCompoundTag("mainBlockPosition", this.mainBlockPosition.writeToNBT(new NBTTagCompound()));
}
/**
* Determines if this TileEntity requires update calls.
*
* @return True if you want updateEntity() to be called, false if not
*/
public boolean canUpdate()
{
return false;
}
@Override
public void handlePacketData(INetworkManager network, int packetType, Packet250CustomPayload packet, EntityPlayer player, ByteArrayDataInput dataStream)
{
try
{
this.mainBlockPosition = new Vector3(dataStream.readDouble(), dataStream.readDouble(), dataStream.readDouble());
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

View file

@ -1,88 +0,0 @@
package universalelectricity.prefab.network;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.NetLoginHandler;
import net.minecraft.network.packet.NetHandler;
import net.minecraft.network.packet.Packet1Login;
import net.minecraft.server.MinecraftServer;
import cpw.mods.fml.common.network.IConnectionHandler;
import cpw.mods.fml.common.network.Player;
public class ConnectionHandler implements IConnectionHandler
{
private static final List<ISimpleConnectionHandler> simpleConnectionHandlers = new ArrayList<ISimpleConnectionHandler>();
public static enum ConnectionType
{
LOGIN_SERVER, LOGIN_CLIENT, RECEIVED, OPEN_REMOTE, OPEN_LOCAL, CLOSED
}
/**
* Registers a simple connection handler
*
* @param tileEntity
*/
public static void registerConnectionHandler(ISimpleConnectionHandler tileEntity)
{
simpleConnectionHandlers.add(tileEntity);
}
@Override
public void playerLoggedIn(Player player, NetHandler netHandler, INetworkManager manager)
{
for (ISimpleConnectionHandler handler : simpleConnectionHandlers)
{
handler.handelConnection(ConnectionType.LOGIN_SERVER, player, netHandler, manager);
}
}
@Override
public void clientLoggedIn(NetHandler clientHandler, INetworkManager manager, Packet1Login login)
{
for (ISimpleConnectionHandler handler : simpleConnectionHandlers)
{
handler.handelConnection(ConnectionType.LOGIN_CLIENT, clientHandler, manager, login);
}
}
@Override
public String connectionReceived(NetLoginHandler netHandler, INetworkManager manager)
{
for (ISimpleConnectionHandler handler : simpleConnectionHandlers)
{
handler.handelConnection(ConnectionType.RECEIVED, netHandler, manager);
}
return null;
}
@Override
public void connectionOpened(NetHandler netClientHandler, String server, int port, INetworkManager manager)
{
for (ISimpleConnectionHandler handler : simpleConnectionHandlers)
{
handler.handelConnection(ConnectionType.OPEN_REMOTE, netClientHandler, server, port, manager);
}
}
@Override
public void connectionOpened(NetHandler netClientHandler, MinecraftServer server, INetworkManager manager)
{
for (ISimpleConnectionHandler handler : simpleConnectionHandlers)
{
handler.handelConnection(ConnectionType.OPEN_LOCAL, netClientHandler, server, manager);
}
}
@Override
public void connectionClosed(INetworkManager manager)
{
for (ISimpleConnectionHandler handler : simpleConnectionHandlers)
{
handler.handelConnection(ConnectionType.CLOSED, manager);
}
}
}

View file

@ -1,15 +0,0 @@
package universalelectricity.prefab.network;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.Packet250CustomPayload;
import com.google.common.io.ByteArrayDataInput;
public interface IPacketReceiver
{
/**
* Sends some data to the tile entity.
*/
public void handlePacketData(INetworkManager network, int packetType, Packet250CustomPayload packet, EntityPlayer player, ByteArrayDataInput dataStream);
}

View file

@ -1,13 +0,0 @@
package universalelectricity.prefab.network;
import universalelectricity.prefab.network.ConnectionHandler.ConnectionType;
public interface ISimpleConnectionHandler
{
/**
* Called when a player logs in. Use this to reset some tile entities variables if you need to.
*
* @param player
*/
public void handelConnection(ConnectionType type, Object... data);
}

View file

@ -1,304 +0,0 @@
package universalelectricity.prefab.network;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.Packet;
import net.minecraft.network.packet.Packet250CustomPayload;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import universalelectricity.core.vector.Vector3;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteStreams;
import cpw.mods.fml.common.network.IPacketHandler;
import cpw.mods.fml.common.network.PacketDispatcher;
import cpw.mods.fml.common.network.Player;
/**
* This class is used for sending and receiving packets between the server and the client. You can
* directly use this by registering this packet manager with NetworkMod. Example:
*
* @NetworkMod(channels = { "BasicComponents" }, clientSideRequired = true, serverSideRequired =
* false, packetHandler = PacketManager.class)
*
* Check out {@link #BasicComponents} for better reference.
*
* @author Calclavia
*/
public class PacketManager implements IPacketHandler, IPacketReceiver
{
public enum PacketType
{
UNSPECIFIED, TILEENTITY;
public static PacketType get(int id)
{
if (id >= 0 && id < PacketType.values().length)
{
return PacketType.values()[id];
}
return UNSPECIFIED;
}
}
/**
* Writes a compressed NBTTagCompound to the OutputStream
*/
public static void writeNBTTagCompound(NBTTagCompound tag, DataOutputStream dataStream) throws IOException
{
if (tag == null)
{
dataStream.writeShort(-1);
}
else
{
byte[] var2 = CompressedStreamTools.compress(tag);
dataStream.writeShort((short) var2.length);
dataStream.write(var2);
}
}
/**
* Reads a compressed NBTTagCompount in a ByteStream.
*/
public static NBTTagCompound readNBTTagCompound(ByteArrayDataInput dataStream) throws IOException
{
short var1 = dataStream.readShort();
if (var1 < 0)
{
return null;
}
else
{
byte[] var2 = new byte[var1];
dataStream.readFully(var2);
return CompressedStreamTools.decompress(var2);
}
}
@SuppressWarnings("resource")
public static Packet getPacketWithID(String channelName, int id, Object... sendData)
{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
DataOutputStream data = new DataOutputStream(bytes);
try
{
data.writeInt(id);
data = encodeDataStream(data, sendData);
Packet250CustomPayload packet = new Packet250CustomPayload();
packet.channel = channelName;
packet.data = bytes.toByteArray();
packet.length = packet.data.length;
return packet;
}
catch (IOException e)
{
System.out.println("Failed to create packet.");
e.printStackTrace();
}
return null;
}
public static Packet getPacket(String channelName, Object... sendData)
{
return getPacketWithID(channelName, PacketType.UNSPECIFIED.ordinal(), sendData);
}
/**
* Gets a packet for the tile entity.
*
* @return
*/
@SuppressWarnings("resource")
public static Packet getPacket(String channelName, TileEntity sender, Object... sendData)
{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
DataOutputStream data = new DataOutputStream(bytes);
try
{
data.writeInt(PacketType.TILEENTITY.ordinal());
data.writeInt(sender.xCoord);
data.writeInt(sender.yCoord);
data.writeInt(sender.zCoord);
data = encodeDataStream(data, sendData);
Packet250CustomPayload packet = new Packet250CustomPayload();
packet.channel = channelName;
packet.data = bytes.toByteArray();
packet.length = packet.data.length;
return packet;
}
catch (IOException e)
{
System.out.println("Failed to create packet.");
e.printStackTrace();
}
return null;
}
/**
* Sends packets to clients around a specific coordinate. A wrapper using Vector3. See
* {@PacketDispatcher} for detailed information.
*/
public static void sendPacketToClients(Packet packet, World worldObj, Vector3 position, double range)
{
try
{
PacketDispatcher.sendPacketToAllAround(position.x, position.y, position.z, range, worldObj.provider.dimensionId, packet);
}
catch (Exception e)
{
System.out.println("Sending packet to client failed.");
e.printStackTrace();
}
}
/**
* Sends a packet to all the clients on this server.
*/
public static void sendPacketToClients(Packet packet, World worldObj)
{
try
{
PacketDispatcher.sendPacketToAllInDimension(packet, worldObj.provider.dimensionId);
}
catch (Exception e)
{
System.out.println("Sending packet to client failed.");
e.printStackTrace();
}
}
public static void sendPacketToClients(Packet packet)
{
try
{
PacketDispatcher.sendPacketToAllPlayers(packet);
}
catch (Exception e)
{
System.out.println("Sending packet to client failed.");
e.printStackTrace();
}
}
public static DataOutputStream encodeDataStream(DataOutputStream data, Object... sendData)
{
try
{
for (Object dataValue : sendData)
{
if (dataValue instanceof Integer)
{
data.writeInt((Integer) dataValue);
}
else if (dataValue instanceof Float)
{
data.writeFloat((Float) dataValue);
}
else if (dataValue instanceof Double)
{
data.writeDouble((Double) dataValue);
}
else if (dataValue instanceof Byte)
{
data.writeByte((Byte) dataValue);
}
else if (dataValue instanceof Boolean)
{
data.writeBoolean((Boolean) dataValue);
}
else if (dataValue instanceof String)
{
data.writeUTF((String) dataValue);
}
else if (dataValue instanceof Short)
{
data.writeShort((Short) dataValue);
}
else if (dataValue instanceof Long)
{
data.writeLong((Long) dataValue);
}
else if (dataValue instanceof NBTTagCompound)
{
writeNBTTagCompound((NBTTagCompound) dataValue, data);
}
}
return data;
}
catch (IOException e)
{
System.out.println("Packet data encoding failed.");
e.printStackTrace();
}
return data;
}
@Override
public void onPacketData(INetworkManager network, Packet250CustomPayload packet, Player player)
{
try
{
ByteArrayDataInput data = ByteStreams.newDataInput(packet.data);
int packetTypeID = data.readInt();
PacketType packetType = PacketType.get(packetTypeID);
if (packetType == PacketType.TILEENTITY)
{
int x = data.readInt();
int y = data.readInt();
int z = data.readInt();
World world = ((EntityPlayer) player).worldObj;
if (world != null)
{
TileEntity tileEntity = world.getBlockTileEntity(x, y, z);
if (tileEntity != null)
{
if (tileEntity instanceof IPacketReceiver)
{
((IPacketReceiver) tileEntity).handlePacketData(network, packetTypeID, packet, ((EntityPlayer) player), data);
}
}
}
}
else
{
this.handlePacketData(network, packetTypeID, packet, ((EntityPlayer) player), data);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
@Override
public void handlePacketData(INetworkManager network, int packetType, Packet250CustomPayload packet, EntityPlayer player, ByteArrayDataInput dataStream)
{
}
}

View file

@ -1,99 +0,0 @@
package universalelectricity.prefab.ore;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraftforge.common.Configuration;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.oredict.OreDictionary;
import cpw.mods.fml.common.FMLLog;
/**
* This class is used for storing ore generation data. If you are too lazy to generate your own
* ores, you can do {@link #OreGenerator.ORES_TO_GENERATE.add()} to add your ore to the list of ores
* to generate.
*
* @author Calclavia
*
*/
public abstract class OreGenBase
{
public String name;
public String oreDictionaryName;
public boolean shouldGenerate = false;
public int blockIndexTexture;
public ItemStack oreStack;
public int oreID;
public int oreMeta;
/**
* What harvest level does this machine need to be acquired?
*/
public int harvestLevel;
/**
* The predefined tool classes are "pickaxe", "shovel", "axe". You can add others for custom
* tools.
*/
public String harvestTool;
/**
* @param name - The name of the ore for display
* @param textureFile - The 16x16 png texture of your ore to override
* @param minGenerateLevel - The highest generation level of your ore
* @param maxGenerateLevel - The lowest generation level of your ore
* @param amountPerChunk - The amount of ores to generate per chunk
* @param amountPerBranch - The amount of ores to generate in a clutter. E.g coal generates with
* a lot of other coal next to it. How much do you want?
*/
public OreGenBase(String name, String oreDiectionaryName, ItemStack stack, String harvestTool, int harvestLevel)
{
if (stack != null)
{
this.name = name;
this.harvestTool = harvestTool;
this.harvestLevel = harvestLevel;
this.oreDictionaryName = oreDiectionaryName;
this.oreStack = stack;
this.oreID = stack.itemID;
this.oreMeta = stack.getItemDamage();
OreDictionary.registerOre(oreDictionaryName, stack);
MinecraftForge.setBlockHarvestLevel(Block.blocksList[stack.itemID], stack.getItemDamage(), harvestTool, harvestLevel);
}
else
{
FMLLog.severe("ItemStack is null while registering ore generation!");
}
}
public OreGenBase enable(Configuration config)
{
this.shouldGenerate = shouldGenerateOre(config, this.name);
return this;
}
/**
* Checks the config file and see if Universal Electricity should generate this ore
*/
private static boolean shouldGenerateOre(Configuration configuration, String oreName)
{
configuration.load();
boolean shouldGenerate = configuration.get("Ore Generation", "Generate " + oreName, true).getBoolean(true);
configuration.save();
return shouldGenerate;
}
public abstract void generate(World world, Random random, int varX, int varZ);
public abstract boolean isOreGeneratedInWorld(World world, IChunkProvider chunkGenerator);
}

View file

@ -1,152 +0,0 @@
package universalelectricity.prefab.ore;
import java.util.Random;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraft.world.gen.ChunkProviderEnd;
import net.minecraft.world.gen.ChunkProviderGenerate;
import net.minecraft.world.gen.ChunkProviderHell;
/**
* This class is used for storing ore generation data. If you are too lazy to generate your own
* ores, you can do {@link #OreGenerator.ORES_TO_GENERATE.add()} to add your ore to the list of ores
* to generate.
*
* @author Calclavia
*
*/
public class OreGenReplace extends OreGenBase
{
public int minGenerateLevel;
public int maxGenerateLevel;
public int amountPerChunk;
public int amountPerBranch;
public int replaceID;
/**
* Dimensions to ignore ore generation
*/
public boolean ignoreSurface = false;
public boolean ignoreNether = true;
public boolean ignoreEnd = true;
/**
* @param name - The name of the ore for display
* @param textureFile - The 16x16 png texture of your ore to override
* @param minGenerateLevel - The highest generation level of your ore
* @param maxGenerateLevel - The lowest generation level of your ore
* @param amountPerChunk - The amount of ores to generate per chunk
* @param amountPerBranch - The amount of ores to generate in a clutter. E.g coal generates with
* a lot of other coal next to it. How much do you want?
*/
public OreGenReplace(String name, String oreDiectionaryName, ItemStack stack, int replaceID, int minGenerateLevel, int maxGenerateLevel, int amountPerChunk, int amountPerBranch, String harvestTool, int harvestLevel)
{
super(name, oreDiectionaryName, stack, harvestTool, harvestLevel);
this.minGenerateLevel = minGenerateLevel;
this.maxGenerateLevel = maxGenerateLevel;
this.amountPerChunk = amountPerChunk;
this.amountPerBranch = amountPerBranch;
this.replaceID = replaceID;
}
public void generate(World world, Random random, int varX, int varZ)
{
try
{
for (int i = 0; i < this.amountPerChunk; i++)
{
int x = varX + random.nextInt(16);
int z = varZ + random.nextInt(16);
int y = random.nextInt(Math.max(this.maxGenerateLevel - this.minGenerateLevel, 0)) + this.minGenerateLevel;
this.generateReplace(world, random, x, y, z);
}
}
catch (Exception e)
{
System.out.println("Error generating ore: " + this.name);
e.printStackTrace();
}
}
public boolean generateReplace(World par1World, Random par2Random, int par3, int par4, int par5)
{
float var6 = par2Random.nextFloat() * (float) Math.PI;
double var7 = (double) ((float) (par3 + 8) + MathHelper.sin(var6) * (float) this.amountPerBranch / 8.0F);
double var9 = (double) ((float) (par3 + 8) - MathHelper.sin(var6) * (float) this.amountPerBranch / 8.0F);
double var11 = (double) ((float) (par5 + 8) + MathHelper.cos(var6) * (float) this.amountPerBranch / 8.0F);
double var13 = (double) ((float) (par5 + 8) - MathHelper.cos(var6) * (float) this.amountPerBranch / 8.0F);
double var15 = (double) (par4 + par2Random.nextInt(3) - 2);
double var17 = (double) (par4 + par2Random.nextInt(3) - 2);
for (int var19 = 0; var19 <= this.amountPerBranch; ++var19)
{
double var20 = var7 + (var9 - var7) * (double) var19 / (double) this.amountPerBranch;
double var22 = var15 + (var17 - var15) * (double) var19 / (double) this.amountPerBranch;
double var24 = var11 + (var13 - var11) * (double) var19 / (double) this.amountPerBranch;
double var26 = par2Random.nextDouble() * (double) this.amountPerBranch / 16.0D;
double var28 = (double) (MathHelper.sin((float) var19 * (float) Math.PI / (float) this.amountPerBranch) + 1.0F) * var26 + 1.0D;
double var30 = (double) (MathHelper.sin((float) var19 * (float) Math.PI / (float) this.amountPerBranch) + 1.0F) * var26 + 1.0D;
int var32 = MathHelper.floor_double(var20 - var28 / 2.0D);
int var33 = MathHelper.floor_double(var22 - var30 / 2.0D);
int var34 = MathHelper.floor_double(var24 - var28 / 2.0D);
int var35 = MathHelper.floor_double(var20 + var28 / 2.0D);
int var36 = MathHelper.floor_double(var22 + var30 / 2.0D);
int var37 = MathHelper.floor_double(var24 + var28 / 2.0D);
for (int var38 = var32; var38 <= var35; ++var38)
{
double var39 = ((double) var38 + 0.5D - var20) / (var28 / 2.0D);
if (var39 * var39 < 1.0D)
{
for (int var41 = var33; var41 <= var36; ++var41)
{
double var42 = ((double) var41 + 0.5D - var22) / (var30 / 2.0D);
if (var39 * var39 + var42 * var42 < 1.0D)
{
for (int var44 = var34; var44 <= var37; ++var44)
{
double var45 = ((double) var44 + 0.5D - var24) / (var28 / 2.0D);
int block = par1World.getBlockId(var38, var41, var44);
if (var39 * var39 + var42 * var42 + var45 * var45 < 1.0D && (this.replaceID == 0 || block == this.replaceID))
{
par1World.setBlock(var38, var41, var44, this.oreID, this.oreMeta, 2);
}
}
}
}
}
}
}
return true;
}
@Override
public boolean isOreGeneratedInWorld(World world, IChunkProvider chunkGenerator)
{
if (!this.shouldGenerate)
{
return false;
}
if (this.ignoreSurface && chunkGenerator instanceof ChunkProviderGenerate)
{
return false;
}
if (this.ignoreNether && chunkGenerator instanceof ChunkProviderHell)
{
return false;
}
if (this.ignoreEnd && chunkGenerator instanceof ChunkProviderEnd)
{
return false;
}
return true;
}
}

View file

@ -1,17 +0,0 @@
package universalelectricity.prefab.ore;
import net.minecraft.item.ItemStack;
public class OreGenReplaceStone extends OreGenReplace
{
public OreGenReplaceStone(String name, String oreDiectionaryName, ItemStack stack, int minGenerateLevel, int maxGenerateLevel, int amountPerChunk, int amountPerBranch, String harvestTool, int harvestLevel)
{
super(name, oreDiectionaryName, stack, 1, minGenerateLevel, maxGenerateLevel, amountPerChunk, amountPerBranch, harvestTool, harvestLevel);
}
// A simplified version of the constructor
public OreGenReplaceStone(String name, String oreDiectionaryName, ItemStack stack, int maxGenerateLevel, int amountPerChunk, int amountPerBranch)
{
this(name, oreDiectionaryName, stack, 0, maxGenerateLevel, amountPerChunk, amountPerBranch, "pickaxe", 1);
}
}

View file

@ -1,78 +0,0 @@
package universalelectricity.prefab.ore;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import net.minecraft.world.World;
import net.minecraft.world.chunk.IChunkProvider;
import cpw.mods.fml.common.IWorldGenerator;
import cpw.mods.fml.common.registry.GameRegistry;
public class OreGenerator implements IWorldGenerator
{
public static boolean isInitiated = false;
/**
* Add your ore data to this list of ores for it to automatically generate! No hassle indeed!
*/
private static final List<OreGenBase> ORES_TO_GENERATE = new ArrayList<OreGenBase>();
/**
* Adds an ore to the ore generate list. Do this in pre-init.
*/
public static void addOre(OreGenBase data)
{
if (!isInitiated)
{
GameRegistry.registerWorldGenerator(new OreGenerator());
}
ORES_TO_GENERATE.add(data);
}
/**
* Checks to see if this ore
*
* @param oreName
* @return
*/
public static boolean oreExists(String oreName)
{
for (OreGenBase ore : ORES_TO_GENERATE)
{
if (ore.oreDictionaryName == oreName)
{
return true;
}
}
return false;
}
/**
* Removes an ore to the ore generate list. Do this in init.
*/
public static void removeOre(OreGenBase data)
{
ORES_TO_GENERATE.remove(data);
}
@Override
public void generate(Random rand, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider)
{
chunkX = chunkX << 4;
chunkZ = chunkZ << 4;
// Checks to make sure this is the normal
// world
for (OreGenBase oreData : ORES_TO_GENERATE)
{
if (oreData.shouldGenerate && oreData.isOreGeneratedInWorld(world, chunkGenerator))
{
oreData.generate(world, rand, chunkX, chunkZ);
}
}
}
}

View file

@ -1,35 +0,0 @@
package universalelectricity.prefab.potion;
import net.minecraft.potion.Potion;
public abstract class CustomPotion extends Potion
{
/**
* Creates a new type of potion
*
* @param id - The ID of this potion. Make it greater than 20.
* @param isBadEffect - Is this potion a good potion or a bad one?
* @param color - The color of this potion.
* @param name - The name of this potion.
*/
public CustomPotion(int id, boolean isBadEffect, int color, String name)
{
super(id, isBadEffect, color);
this.setPotionName("potion." + name);
Potion.potionTypes[this.getId()] = this;
}
@Override
public Potion setIconIndex(int par1, int par2)
{
super.setIconIndex(par1, par2);
return this;
}
@Override
protected Potion setEffectiveness(double par1)
{
super.setEffectiveness(par1);
return this;
}
}

View file

@ -1,40 +0,0 @@
package universalelectricity.prefab.potion;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
public class CustomPotionEffect extends PotionEffect
{
public CustomPotionEffect(int potionID, int duration, int amplifier)
{
super(potionID, duration, amplifier);
}
public CustomPotionEffect(Potion potion, int duration, int amplifier)
{
this(potion.getId(), duration, amplifier);
}
/**
* Creates a potion effect with custom curable items.
*
* @param curativeItems - ItemStacks that can cure this potion effect
*/
public CustomPotionEffect(int potionID, int duration, int amplifier, List<ItemStack> curativeItems)
{
super(potionID, duration, amplifier);
if (curativeItems == null)
{
this.setCurativeItems(new ArrayList<ItemStack>());
}
else
{
this.setCurativeItems(curativeItems);
}
}
}

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,192 +0,0 @@
package universalelectricity.prefab.tile;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.Packet;
import net.minecraft.network.packet.Packet250CustomPayload;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraftforge.common.ForgeDirection;
import org.bouncycastle.util.Arrays;
import universalelectricity.core.block.IConductor;
import universalelectricity.core.block.IConnector;
import universalelectricity.core.block.INetworkProvider;
import universalelectricity.core.electricity.ElectricityNetwork;
import universalelectricity.core.electricity.IElectricityNetwork;
import universalelectricity.core.vector.Vector3;
import universalelectricity.core.vector.VectorHelper;
import universalelectricity.prefab.network.IPacketReceiver;
import universalelectricity.prefab.network.PacketManager;
import com.google.common.io.ByteArrayDataInput;
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, IPacketReceiver
{
private IElectricityNetwork network;
/**
* Used client side to render.
*/
public boolean[] visuallyConnected = { false, false, false, false, false, false };
/**
* Stores information on the blocks that this conductor is connected to.
*/
public TileEntity[] connectedBlocks = { null, null, null, null, null, null };
protected String channel = "";
public void updateConnection(TileEntity tileEntity, ForgeDirection side)
{
if (!this.worldObj.isRemote)
{
if (tileEntity instanceof IConnector)
{
if (((IConnector) tileEntity).canConnect(side.getOpposite()))
{
this.connectedBlocks[side.ordinal()] = tileEntity;
this.visuallyConnected[side.ordinal()] = true;
if (tileEntity.getClass() == this.getClass() && tileEntity instanceof INetworkProvider)
{
this.getNetwork().mergeConnection(((INetworkProvider) tileEntity).getNetwork());
}
return;
}
}
if (this.connectedBlocks[side.ordinal()] != null)
{
this.getNetwork().stopProducing(this.connectedBlocks[side.ordinal()]);
this.getNetwork().stopRequesting(this.connectedBlocks[side.ordinal()]);
}
this.connectedBlocks[side.ordinal()] = null;
this.visuallyConnected[side.ordinal()] = false;
}
}
@Override
public void handlePacketData(INetworkManager network, int type, Packet250CustomPayload packet, EntityPlayer player, ByteArrayDataInput dataStream)
{
if (this.worldObj.isRemote)
{
this.visuallyConnected[0] = dataStream.readBoolean();
this.visuallyConnected[1] = dataStream.readBoolean();
this.visuallyConnected[2] = dataStream.readBoolean();
this.visuallyConnected[3] = dataStream.readBoolean();
this.visuallyConnected[4] = dataStream.readBoolean();
this.visuallyConnected[5] = dataStream.readBoolean();
}
}
@Override
public void initiate()
{
this.updateAdjacentConnections();
}
@Override
public void invalidate()
{
if (!this.worldObj.isRemote)
{
this.getNetwork().splitNetwork(this);
}
super.invalidate();
}
@Override
public void updateEntity()
{
super.updateEntity();
if (!this.worldObj.isRemote)
{
if (this.ticks % 300 == 0)
{
this.updateAdjacentConnections();
}
}
}
@Override
public void updateAdjacentConnections()
{
if (this.worldObj != null)
{
if (!this.worldObj.isRemote)
{
boolean[] previousConnections = this.visuallyConnected.clone();
for (byte i = 0; i < 6; i++)
{
this.updateConnection(VectorHelper.getConnectorFromSide(this.worldObj, new Vector3(this), ForgeDirection.getOrientation(i)), ForgeDirection.getOrientation(i));
}
/**
* Only send packet updates if visuallyConnected changed.
*/
if (!Arrays.areEqual(previousConnections, this.visuallyConnected))
{
this.worldObj.markBlockForUpdate(this.xCoord, this.yCoord, this.zCoord);
}
}
}
}
@Override
public Packet getDescriptionPacket()
{
return PacketManager.getPacket(this.channel, this, this.visuallyConnected[0], this.visuallyConnected[1], this.visuallyConnected[2], this.visuallyConnected[3], this.visuallyConnected[4], this.visuallyConnected[5]);
}
@Override
public IElectricityNetwork getNetwork()
{
if (this.network == null)
{
this.setNetwork(new ElectricityNetwork(this));
}
return this.network;
}
@Override
public void setNetwork(IElectricityNetwork network)
{
this.network = network;
}
@Override
public TileEntity[] getAdjacentConnections()
{
return this.connectedBlocks;
}
@Override
public boolean canConnect(ForgeDirection direction)
{
return true;
}
@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,46 +0,0 @@
package universalelectricity.prefab.tile;
import universalelectricity.prefab.implement.IDisableable;
/**
* An easier way to implement the methods from IElectricityDisableable with default values set.
*
* @author Calclavia
*/
public abstract class TileEntityDisableable extends TileEntityAdvanced implements IDisableable
{
protected int disabledTicks = 0;
@Override
public void updateEntity()
{
super.updateEntity();
if (this.disabledTicks > 0)
{
this.disabledTicks--;
this.whileDisable();
return;
}
}
/**
* Called every tick while this tile entity is disabled.
*/
protected void whileDisable()
{
}
@Override
public void onDisable(int duration)
{
this.disabledTicks = duration;
}
@Override
public boolean isDisabled()
{
return this.disabledTicks > 0;
}
}

View file

@ -1,38 +0,0 @@
package universalelectricity.prefab.tile;
import universalelectricity.core.block.IConnector;
import universalelectricity.core.block.IVoltage;
import universalelectricity.core.electricity.ElectricityNetworkHelper;
/**
* Extend this if your TileEntity is electrical.
*
* @author Calclavia
*/
public abstract class TileEntityElectrical extends TileEntityDisableable implements IConnector, IVoltage
{
public TileEntityElectrical()
{
super();
}
@Override
public void updateEntity()
{
super.updateEntity();
}
@Override
public double getVoltage()
{
return 120;
}
@Override
public void invalidate()
{
ElectricityNetworkHelper.invalidate(this);
super.invalidate();
}
}

View file

@ -1,96 +0,0 @@
package universalelectricity.prefab.tile;
import java.util.EnumSet;
import net.minecraftforge.common.ForgeDirection;
import universalelectricity.core.UniversalElectricity;
import universalelectricity.core.electricity.ElectricityNetworkHelper;
import universalelectricity.core.electricity.ElectricityPack;
/**
* This class should be extended by TileEntities that run on electricity but do not store them.
* Things such as electric furnaces should extend this. Take this class mainly as an example.
*
* @author Calclavia
*
*/
public abstract class TileEntityElectricityRunnable extends TileEntityElectrical
{
/**
* The amount of watts received this tick. This variable should be deducted when used.
*/
public double prevWatts, wattsReceived = 0;
@Override
public void updateEntity()
{
super.updateEntity();
this.prevWatts = this.wattsReceived;
/**
* ElectricityManager works on server side.
*/
if (!this.worldObj.isRemote)
{
/**
* If the machine is disabled, stop requesting electricity.
*/
if (!this.isDisabled())
{
ElectricityPack electricityPack = ElectricityNetworkHelper.consumeFromMultipleSides(this, this.getConsumingSides(), this.getRequest());
this.onReceive(electricityPack);
}
else
{
ElectricityNetworkHelper.consumeFromMultipleSides(this, new ElectricityPack());
}
}
}
protected EnumSet<ForgeDirection> getConsumingSides()
{
return ElectricityNetworkHelper.getDirections(this);
}
/**
* Returns the amount of energy being requested this tick. Return an empty ElectricityPack if no
* electricity is desired.
*/
public ElectricityPack getRequest()
{
return new ElectricityPack();
}
/**
* Called right after electricity is transmitted to the TileEntity. Override this if you wish to
* have another effect for a voltage overcharge.
*
* @param electricityPack
*/
public void onReceive(ElectricityPack electricityPack)
{
/**
* Creates an explosion if the voltage is too high.
*/
if (UniversalElectricity.isVoltageSensitive)
{
if (electricityPack.voltage > this.getVoltage())
{
this.worldObj.createExplosion(null, this.xCoord, this.yCoord, this.zCoord, 1.5f, true);
return;
}
}
this.wattsReceived = Math.min(this.wattsReceived + electricityPack.getWatts(), this.getWattBuffer());
}
/**
* @return The amount of internal buffer that may be stored within this machine. This will make
* the machine run smoother as electricity might not always be consistent.
*/
public double getWattBuffer()
{
return this.getRequest().getWatts() * 2;
}
}

View file

@ -1,110 +0,0 @@
package universalelectricity.prefab.tile;
import java.util.EnumSet;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.common.ForgeDirection;
import universalelectricity.core.UniversalElectricity;
import universalelectricity.core.block.IElectricityStorage;
import universalelectricity.core.electricity.ElectricityNetworkHelper;
import universalelectricity.core.electricity.ElectricityPack;
public abstract class TileEntityElectricityStorage extends TileEntityElectrical implements IElectricityStorage
{
/**
* The amount of joules stored within this machine. Use get and set functions instead of
* referencing to this variable.
*/
private double joules = 0;
public double prevJoules = 0;
@Override
public void updateEntity()
{
super.updateEntity();
this.prevJoules = joules;
if (!this.worldObj.isRemote)
{
if (!this.isDisabled())
{
ElectricityPack electricityPack = ElectricityNetworkHelper.consumeFromMultipleSides(this, this.getConsumingSides(), this.getRequest());
this.onReceive(electricityPack);
}
else
{
ElectricityNetworkHelper.consumeFromMultipleSides(this, new ElectricityPack());
}
}
}
protected EnumSet<ForgeDirection> getConsumingSides()
{
return ElectricityNetworkHelper.getDirections(this);
}
/**
* Returns the amount of energy being requested this tick. Return an empty ElectricityPack if no
* electricity is desired.
*/
public ElectricityPack getRequest()
{
return new ElectricityPack((this.getMaxJoules() - this.getJoules()) / this.getVoltage(), this.getVoltage());
}
/**
* Called right after electricity is transmitted to the TileEntity. Override this if you wish to
* have another effect for a voltage overcharge.
*
* @param electricityPack
*/
public void onReceive(ElectricityPack electricityPack)
{
/**
* Creates an explosion if the voltage is too high.
*/
if (UniversalElectricity.isVoltageSensitive)
{
if (electricityPack.voltage > this.getVoltage())
{
this.worldObj.createExplosion(null, this.xCoord, this.yCoord, this.zCoord, 1.5f, true);
return;
}
}
this.setJoules(this.getJoules() + electricityPack.getWatts());
}
@Override
public void readFromNBT(NBTTagCompound par1NBTTagCompound)
{
super.readFromNBT(par1NBTTagCompound);
this.joules = par1NBTTagCompound.getDouble("joules");
}
/**
* Writes a tile entity to NBT.
*/
@Override
public void writeToNBT(NBTTagCompound par1NBTTagCompound)
{
super.writeToNBT(par1NBTTagCompound);
par1NBTTagCompound.setDouble("joules", this.joules);
}
@Override
public double getJoules()
{
return this.joules;
}
@Override
public void setJoules(double joules)
{
this.joules = Math.max(Math.min(joules, this.getMaxJoules()), 0);
}
}

View file

@ -1,36 +0,0 @@
package universalelectricity.prefab.vector;
import universalelectricity.core.vector.Vector2;
public class Region2
{
public Vector2 min;
public Vector2 max;
public Region2()
{
this(new Vector2(), new Vector2());
}
public Region2(Vector2 min, Vector2 max)
{
this.min = min;
this.max = max;
}
/**
* Checks if a point is located inside a region
*/
public boolean isIn(Vector2 point)
{
return (point.x > this.min.x && point.x < this.max.x) && (point.y > this.min.y && point.y < this.max.y);
}
/**
* Returns whether the given region intersects with this one.
*/
public boolean isIn(Region2 region)
{
return region.max.x > this.min.x && region.min.x < this.max.x ? (region.max.y > this.min.y && region.min.y < this.max.y ? true : false) : false;
}
}

View file

@ -1,131 +0,0 @@
package universalelectricity.prefab.vector;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.entity.Entity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.World;
import universalelectricity.core.vector.Vector3;
/**
* A cubical region class.
*
* @author Calclavia
*/
public class Region3
{
public Vector3 min;
public Vector3 max;
public Region3()
{
this(new Vector3(), new Vector3());
}
public Region3(Vector3 min, Vector3 max)
{
this.min = min;
this.max = max;
}
public Region3(AxisAlignedBB aabb)
{
this.min = new Vector3(aabb.minX, aabb.minY, aabb.minZ);
this.max = new Vector3(aabb.maxX, aabb.maxY, aabb.maxZ);
}
public AxisAlignedBB toAABB()
{
return AxisAlignedBB.getBoundingBox(this.min.x, this.min.y, this.min.z, this.max.x, this.max.y, this.max.z);
}
public Region2 toRegion2()
{
return new Region2(this.min.toVector2(), this.max.toVector2());
}
/**
* Checks if a point is located inside a region
*/
public boolean isIn(Vector3 point)
{
return (point.x > this.min.x && point.x < this.max.x) && (point.y > this.min.y && point.y < this.max.y) && (point.z > this.min.z && point.z < this.max.z);
}
/**
* Returns whether the given region intersects with this one.
*/
public boolean isIn(Region3 region)
{
return region.max.x > this.min.x && region.min.x < this.max.x ? (region.max.y > this.min.y && region.min.y < this.max.y ? region.max.z > this.min.z && region.min.z < this.max.z : false) : false;
}
public void expand(Vector3 difference)
{
this.min.subtract(difference);
this.max.add(difference);
}
/**
* @return List of vectors within this region.
*/
public List<Vector3> getVectors()
{
List<Vector3> vectors = new ArrayList<Vector3>();
for (int x = this.min.intX(); x < this.max.intX(); x++)
{
for (int y = this.min.intY(); x < this.max.intY(); y++)
{
for (int z = this.min.intZ(); x < this.max.intZ(); z++)
{
vectors.add(new Vector3(x, y, z));
}
}
}
return vectors;
}
public List<Vector3> getVectors(Vector3 center, int radius)
{
List<Vector3> vectors = new ArrayList<Vector3>();
for (int x = this.min.intX(); x < this.max.intX(); x++)
{
for (int y = this.min.intY(); x < this.max.intY(); y++)
{
for (int z = this.min.intZ(); x < this.max.intZ(); z++)
{
Vector3 vector3 = new Vector3(x, y, z);
if (center.distanceTo(vector3) <= radius)
{
vectors.add(vector3);
}
}
}
}
return vectors;
}
/**
* Returns all entities in this region.
*/
public List<Entity> getEntities(World world, Class<? extends Entity> entityClass)
{
return world.getEntitiesWithinAABB(entityClass, this.toAABB());
}
public List<Entity> getEntitiesExlude(World world, Entity entity)
{
return world.getEntitiesWithinAABBExcludingEntity(entity, this.toAABB());
}
public List<Entity> getEntities(World world)
{
return this.getEntities(world, Entity.class);
}
}