big-butt formatting changes

This commit is contained in:
xbony2 2015-05-25 08:55:25 -04:00
parent 6ea2b0e556
commit df384c778f
43 changed files with 3389 additions and 3755 deletions

View file

@ -3,14 +3,12 @@ package com.kaijin.AdvPowerMan;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
public class AdvPacket
{
public class AdvPacket{
byte[] data;
public AdvPacket () {}
public AdvPacket(byte[] packet)
{
public AdvPacket() {}
public AdvPacket(byte[] packet) {
this.data = packet.clone();
}
}
}

View file

@ -49,101 +49,125 @@ import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.relauncher.Side;
@Mod(modid = "AdvancedPowerManagement", name="Advanced Power Management", version="@VERSION@", dependencies = "required-after:IC2")
@Mod(modid = "AdvancedPowerManagement", name = "Advanced Power Management", version = "@VERSION@", dependencies = "required-after:IC2")
public class AdvancedPowerManagement // implements ICraftingHandler
{
@SidedProxy(clientSide = "com.kaijin.AdvPowerMan.ClientProxy", serverSide = "com.kaijin.AdvPowerMan.CommonProxy")
public static CommonProxy proxy; //This object will be populated with the class that you choose for the environment
public static CommonProxy proxy; // This object will be populated with the
// class that you choose for the
// environment
@Instance("AdvancedPowerManagement")
public static AdvancedPowerManagement instance; //The instance of the mod that will be defined, populated, and callable
//Channels for handling packages
public static AdvancedPowerManagement instance; // The instance of the mod
// that will be defined,
// populated, and callable
// Channels for handling packages
public static EnumMap<Side, FMLEmbeddedChannel> channels;
public static Logger logger;
public static Block blockAdvPwrMan;
public static Item itemBenchTools;
public static Item itemStorageLinkCard;
public static Item itemStorageLinkCardCreator;
@EventHandler
public static void preInit(FMLPreInitializationEvent event)
{
public static void preInit(FMLPreInitializationEvent event){
Info.isDebugging = false;
logger = event.getModLog();
try
{
try{
Configuration configuration = new Configuration(event.getSuggestedConfigurationFile());
configuration.load();
// Read or create config file properties, reusing any block and item IDs discovered in old file, if it was present
Info.isDebugging = configuration.get(configuration.CATEGORY_GENERAL, "debug", Info.isDebugging).getBoolean(Info.isDebugging);
// Read or create config file properties, reusing any block and item
// IDs discovered in old file, if it was present
Info.isDebugging = configuration.get(configuration.CATEGORY_GENERAL, "debug", Info.isDebugging).getBoolean(Info.isDebugging);
configuration.save();
}
catch (Exception e)
{
}catch(Exception e){
logger.warn("Error while trying to access configuration!", e);
throw new RuntimeException(e);
}
}
@EventHandler
public void load(FMLInitializationEvent event)
{
public void load(FMLInitializationEvent event){
logger.info("Loading.");
blockAdvPwrMan = new BlockAdvPwrMan(Material.ground);
GameRegistry.registerBlock(blockAdvPwrMan, ItemBlockAdvPwrMan.class, "blockAdvPwrMan");
// Charging Benches
GameRegistry.registerTileEntity(TEChargingBench.class, "LV Charging Bench"); // Legacy mappings for backward compatibility - we didn't know wtf we were doing when we started this mod :)
GameRegistry.registerTileEntity(TEChargingBench.class, "LV Charging Bench"); // Legacy
// mappings
// for
// backward
// compatibility
// -
// we
// didn't
// know
// wtf
// we
// were
// doing
// when
// we
// started
// this
// mod
// :)
GameRegistry.registerTileEntity(TEChargingBench.class, "MV Charging Bench"); // Legacy
GameRegistry.registerTileEntity(TEChargingBench.class, "HV Charging Bench"); // Legacy
GameRegistry.registerTileEntity(TEChargingBench.class, "kaijin.chargingBench"); // Proper mapping
GameRegistry.registerTileEntity(TEChargingBench.class, "kaijin.chargingBench"); // Proper
// mapping
// Battery Stations
GameRegistry.registerTileEntity(TEBatteryStation.class, "LV Battery Station"); // Legacy mappings
GameRegistry.registerTileEntity(TEBatteryStation.class, "LV Battery Station"); // Legacy
// mappings
GameRegistry.registerTileEntity(TEBatteryStation.class, "MV Battery Station"); // Legacy
GameRegistry.registerTileEntity(TEBatteryStation.class, "HV Battery Station"); // Legacy
GameRegistry.registerTileEntity(TEBatteryStation.class, "kaijin.batteryStation"); // Proper mapping
GameRegistry.registerTileEntity(TEBatteryStation.class, "kaijin.batteryStation"); // Proper
// mapping
// Adjustable Transformer
GameRegistry.registerTileEntity(TEAdjustableTransformer.class, "kaijin.adjTransformer");
// Storage Monitor
GameRegistry.registerTileEntity(TEStorageMonitor.class, "kaijin.storageMonitor");
// Emitters
GameRegistry.registerTileEntity(TEAdvEmitter.class, "LV Emitter"); // Legacy mappings
GameRegistry.registerTileEntity(TEAdvEmitter.class, "LV Emitter"); // Legacy
// mappings
GameRegistry.registerTileEntity(TEAdvEmitter.class, "MV Emitter"); // Legacy
GameRegistry.registerTileEntity(TEAdvEmitter.class, "HV Emitter"); // Legacy
GameRegistry.registerTileEntity(TEAdvEmitter.class, "EV Emitter"); // Legacy
GameRegistry.registerTileEntity(TEAdvEmitter.class, "kaijin.emitter"); // Now legacy as well
GameRegistry.registerTileEntity(TEAdvEmitter.class, "kaijin.advEmitter"); // Proper mapping
GameRegistry.registerTileEntity(TEAdvEmitter.class, "kaijin.emitter"); // Now
// legacy
// as
// well
GameRegistry.registerTileEntity(TEAdvEmitter.class, "kaijin.advEmitter"); // Proper
// mapping
// Items
itemBenchTools = new ItemBenchTools("benchTools.toolkit");
itemStorageLinkCard = new ItemStorageLinkCard("itemStorageLinkCard");
itemStorageLinkCardCreator = new ItemStorageLinkCardCreator("itemStorageLinkCardCreator");
//Info.registerTranslations();
//register channel handler
// Info.registerTranslations();
// register channel handler
channels = NetworkRegistry.INSTANCE.newChannel("APMKaijin", ChannelHandler.instance);
if (event.getSide().isClient())
{
if(event.getSide().isClient()){
FMLEventChannel events = NetworkRegistry.INSTANCE.newEventDrivenChannel("Test");
events.register(new ClientPacketHandler());
}
NetworkRegistry.INSTANCE.registerGuiHandler(instance, proxy);
proxy.load();
// For returning charging benches and deconstructing them
Info.componentCopperCable = IC2Items.getItem("insulatedCopperCableItem").copy();
Info.componentCopperCable.stackSize = 3;
@ -155,72 +179,101 @@ public class AdvancedPowerManagement // implements ICraftingHandler
Info.componentMFE = IC2Items.getItem("mfeUnit").copy();
Info.componentMFSU = IC2Items.getItem("mfsUnit").copy();
Info.componentCircuit = IC2Items.getItem("electronicCircuit").copy();
// For internal reference to verify items can be placed in inventory.
Info.ic2overclockerUpg = IC2Items.getItem("overclockerUpgrade").copy();
Info.ic2transformerUpg = IC2Items.getItem("transformerUpgrade").copy();
Info.ic2storageUpg = IC2Items.getItem("energyStorageUpgrade").copy();
Info.ic2WrenchID = Item.getIdFromItem(IC2Items.getItem("wrench").getItem());
Info.ic2ElectricWrenchID = Item.getIdFromItem(IC2Items.getItem("electricWrench").getItem());
if (proxy.isServer())
{
if(proxy.isServer()){
logger.info("Advanced Power Management 1.7.2.02 loaded.");
}
if (Info.isDebugging)
{
if(Info.isDebugging){
logger.info("Debugging enabled.");
}
logger.info("Done loading.");
}
@EventHandler
public void modsLoaded(FMLPostInitializationEvent event)
{
public void modsLoaded(FMLPostInitializationEvent event){
logger.info("Adding crafting recipes.");
// Charging Bench recipes
GameRegistry.addRecipe(new ItemStack(blockAdvPwrMan, 1, Info.CB_META + 0), new Object[] {"UUU", "WCW", "WBW", 'U', IC2Items.getItem("insulatedCopperCableItem"), 'W', Blocks.planks, 'C', IC2Items.getItem("electronicCircuit"), 'B', IC2Items.getItem("batBox")});
GameRegistry.addRecipe(new ItemStack(blockAdvPwrMan, 1, Info.CB_META + 1), new Object[] {"UUU", "WCW", "WBW", 'U', IC2Items.getItem("insulatedGoldCableItem"), 'W', Blocks.planks, 'C', IC2Items.getItem("electronicCircuit"), 'B', IC2Items.getItem("mfeUnit")});
GameRegistry.addRecipe(new ItemStack(blockAdvPwrMan, 1, Info.CB_META + 2), new Object[] {"UUU", "WCW", "WBW", 'U', IC2Items.getItem("insulatedIronCableItem"), 'W', Blocks.planks, 'C', IC2Items.getItem("electronicCircuit"), 'B', IC2Items.getItem("mfsUnit")});
GameRegistry.addRecipe(
new ItemStack(blockAdvPwrMan, 1, Info.CB_META + 0),
new Object[] {"UUU", "WCW", "WBW", 'U', IC2Items.getItem("insulatedCopperCableItem"), 'W', Blocks.planks, 'C',
IC2Items.getItem("electronicCircuit"), 'B', IC2Items.getItem("batBox")});
GameRegistry.addRecipe(
new ItemStack(blockAdvPwrMan, 1, Info.CB_META + 1),
new Object[] {"UUU", "WCW", "WBW", 'U', IC2Items.getItem("insulatedGoldCableItem"), 'W', Blocks.planks, 'C',
IC2Items.getItem("electronicCircuit"), 'B', IC2Items.getItem("mfeUnit")});
GameRegistry.addRecipe(
new ItemStack(blockAdvPwrMan, 1, Info.CB_META + 2),
new Object[] {"UUU", "WCW", "WBW", 'U', IC2Items.getItem("insulatedIronCableItem"), 'W', Blocks.planks, 'C',
IC2Items.getItem("electronicCircuit"), 'B', IC2Items.getItem("mfsUnit")});
// Battery Station recipes
GameRegistry.addRecipe(new ItemStack(blockAdvPwrMan, 1, Info.BS_META + 0), new Object[] {"UUU", "WCW", "WBW", 'U', IC2Items.getItem("insulatedCopperCableItem"), 'W', Blocks.planks, 'C', IC2Items.getItem("electronicCircuit"), 'B', IC2Items.getItem("lvTransformer")});
GameRegistry.addRecipe(new ItemStack(blockAdvPwrMan, 1, Info.BS_META + 1), new Object[] {"UUU", "WCW", "WBW", 'U', IC2Items.getItem("insulatedGoldCableItem"), 'W', Blocks.planks, 'C', IC2Items.getItem("electronicCircuit"), 'B', IC2Items.getItem("mvTransformer")});
GameRegistry.addRecipe(new ItemStack(blockAdvPwrMan, 1, Info.BS_META + 2), new Object[] {"UUU", "WCW", "WBW", 'U', IC2Items.getItem("insulatedIronCableItem"), 'W', Blocks.planks, 'C', IC2Items.getItem("electronicCircuit"), 'B', IC2Items.getItem("hvTransformer")});
GameRegistry.addRecipe(
new ItemStack(blockAdvPwrMan, 1, Info.BS_META + 0),
new Object[] {"UUU", "WCW", "WBW", 'U', IC2Items.getItem("insulatedCopperCableItem"), 'W', Blocks.planks, 'C',
IC2Items.getItem("electronicCircuit"), 'B', IC2Items.getItem("lvTransformer")});
GameRegistry.addRecipe(
new ItemStack(blockAdvPwrMan, 1, Info.BS_META + 1),
new Object[] {"UUU", "WCW", "WBW", 'U', IC2Items.getItem("insulatedGoldCableItem"), 'W', Blocks.planks, 'C',
IC2Items.getItem("electronicCircuit"), 'B', IC2Items.getItem("mvTransformer")});
GameRegistry.addRecipe(
new ItemStack(blockAdvPwrMan, 1, Info.BS_META + 2),
new Object[] {"UUU", "WCW", "WBW", 'U', IC2Items.getItem("insulatedIronCableItem"), 'W', Blocks.planks, 'C',
IC2Items.getItem("electronicCircuit"), 'B', IC2Items.getItem("hvTransformer")});
// Adjustable Transformer recipe
GameRegistry.addRecipe(new ItemStack(blockAdvPwrMan, 1, Info.AT_META), new Object[] {"L", "C", "H", 'L', IC2Items.getItem("lvTransformer"), 'C', IC2Items.getItem("advancedCircuit"), 'H', IC2Items.getItem("hvTransformer")});
GameRegistry.addRecipe(new ItemStack(blockAdvPwrMan, 1, Info.AT_META), new Object[] {"H", "C", "L", 'H', IC2Items.getItem("hvTransformer"), 'C', IC2Items.getItem("advancedCircuit"), 'L', IC2Items.getItem("lvTransformer")});
GameRegistry.addRecipe(new ItemStack(blockAdvPwrMan, 1, Info.AT_META), new Object[] {"L", "C", "H", 'L', IC2Items.getItem("lvTransformer"),
'C', IC2Items.getItem("advancedCircuit"), 'H', IC2Items.getItem("hvTransformer")});
GameRegistry.addRecipe(new ItemStack(blockAdvPwrMan, 1, Info.AT_META), new Object[] {"H", "C", "L", 'H', IC2Items.getItem("hvTransformer"),
'C', IC2Items.getItem("advancedCircuit"), 'L', IC2Items.getItem("lvTransformer")});
// Storage Monitor recipe
GameRegistry.addRecipe(new ItemStack(blockAdvPwrMan, 1, Info.SM_META), new Object[] {"WUW", "GCG", "WRW", 'W', Blocks.planks, 'U', IC2Items.getItem("goldCableItem"), 'G', Blocks.glass, 'C', IC2Items.getItem("electronicCircuit"), 'R', Items.redstone});
GameRegistry.addRecipe(
new ItemStack(blockAdvPwrMan, 1, Info.SM_META),
new Object[] {"WUW", "GCG", "WRW", 'W', Blocks.planks, 'U', IC2Items.getItem("goldCableItem"), 'G', Blocks.glass, 'C',
IC2Items.getItem("electronicCircuit"), 'R', Items.redstone});
// Link Card Creator recipe
GameRegistry.addRecipe(new ItemStack(itemStorageLinkCardCreator, 1, 0), new Object[] {"U ", " C ", " V", 'U', IC2Items.getItem("insulatedCopperCableItem"), 'C', IC2Items.getItem("electronicCircuit"), 'V', Items.paper});
GameRegistry.addRecipe(new ItemStack(itemStorageLinkCardCreator, 1, 0),
new Object[] {"U ", " C ", " V", 'U', IC2Items.getItem("insulatedCopperCableItem"), 'C', IC2Items.getItem("electronicCircuit"),
'V', Items.paper});
// Bench Toolkit recipe
GameRegistry.addRecipe(new ItemStack(itemBenchTools, 1, 0), new Object[] {" I ", "S S", 'I', Items.iron_ingot, 'S', Items.stick});
// LV, MV, HV Charging Bench Components recipes
GameRegistry.addShapelessRecipe(new ItemStack(itemBenchTools, 1, 1), new ItemStack(itemBenchTools, 1, 0), new ItemStack(blockAdvPwrMan, 1, 0));
GameRegistry.addShapelessRecipe(new ItemStack(itemBenchTools, 1, 2), new ItemStack(itemBenchTools, 1, 0), new ItemStack(blockAdvPwrMan, 1, 1));
GameRegistry.addShapelessRecipe(new ItemStack(itemBenchTools, 1, 3), new ItemStack(itemBenchTools, 1, 0), new ItemStack(blockAdvPwrMan, 1, 2));
GameRegistry
.addShapelessRecipe(new ItemStack(itemBenchTools, 1, 1), new ItemStack(itemBenchTools, 1, 0), new ItemStack(blockAdvPwrMan, 1, 0));
GameRegistry
.addShapelessRecipe(new ItemStack(itemBenchTools, 1, 2), new ItemStack(itemBenchTools, 1, 0), new ItemStack(blockAdvPwrMan, 1, 1));
GameRegistry
.addShapelessRecipe(new ItemStack(itemBenchTools, 1, 3), new ItemStack(itemBenchTools, 1, 0), new ItemStack(blockAdvPwrMan, 1, 2));
// LV, MV, HV Charging Bench reassembly recipes
GameRegistry.addShapelessRecipe(new ItemStack(blockAdvPwrMan, 1, 0), new ItemStack(itemBenchTools, 1, 0), new ItemStack(itemBenchTools, 1, 1));
GameRegistry.addShapelessRecipe(new ItemStack(blockAdvPwrMan, 1, 1), new ItemStack(itemBenchTools, 1, 0), new ItemStack(itemBenchTools, 1, 2));
GameRegistry.addShapelessRecipe(new ItemStack(blockAdvPwrMan, 1, 2), new ItemStack(itemBenchTools, 1, 0), new ItemStack(itemBenchTools, 1, 3));
GameRegistry
.addShapelessRecipe(new ItemStack(blockAdvPwrMan, 1, 0), new ItemStack(itemBenchTools, 1, 0), new ItemStack(itemBenchTools, 1, 1));
GameRegistry
.addShapelessRecipe(new ItemStack(blockAdvPwrMan, 1, 1), new ItemStack(itemBenchTools, 1, 0), new ItemStack(itemBenchTools, 1, 2));
GameRegistry
.addShapelessRecipe(new ItemStack(blockAdvPwrMan, 1, 2), new ItemStack(itemBenchTools, 1, 0), new ItemStack(itemBenchTools, 1, 3));
}
/*
@EventHandler
public void certificateWarning(FMLFingerprintViolationEvent event)
{
FMLLog.warning("[AdvancedPowerManagement] " + "[Certificate Error] Fingerprint does not match! This mod's jar file has been modified from the original version.");
FMLLog.warning("[AdvancedPowerManagement] " + "[Certificate Error] Expected fingerprint: " + event.expectedFingerprint);
FMLLog.warning("[AdvancedPowerManagement] " + "[Certificate Error] File: " + event.source.getAbsolutePath());
}*/
/*
* @EventHandler public void certificateWarning(FMLFingerprintViolationEvent
* event) { FMLLog.warning("[AdvancedPowerManagement] " +
* "[Certificate Error] Fingerprint does not match! This mod's jar file has been modified from the original version."
* ); FMLLog.warning("[AdvancedPowerManagement] " +
* "[Certificate Error] Expected fingerprint: " +
* event.expectedFingerprint); FMLLog.warning("[AdvancedPowerManagement] " +
* "[Certificate Error] File: " + event.source.getAbsolutePath()); }
*/
}

View file

@ -10,53 +10,47 @@ import cpw.mods.fml.relauncher.Side;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
public class ChannelHandler extends FMLIndexedMessageToMessageCodec<AdvPacket>
{
public static ChannelHandler instance = new ChannelHandler();
public ChannelHandler()
{
public class ChannelHandler extends FMLIndexedMessageToMessageCodec<AdvPacket>{
public static ChannelHandler instance = new ChannelHandler();
public ChannelHandler() {
addDiscriminator(0, AdvPacket.class);
}
}
@Override
public void encodeInto(ChannelHandlerContext ctx, AdvPacket msg, ByteBuf target) throws Exception
{
public void encodeInto(ChannelHandlerContext ctx, AdvPacket msg, ByteBuf target) throws Exception{
target.writeBytes(msg.data);
}
@Override
public void decodeInto(ChannelHandlerContext ctx, ByteBuf source, AdvPacket msg)
{
switch (FMLCommonHandler.instance().getEffectiveSide())
{
public void decodeInto(ChannelHandlerContext ctx, ByteBuf source, AdvPacket msg){
switch(FMLCommonHandler.instance().getEffectiveSide()){
case CLIENT:
AdvancedPowerManagement.instance.proxy.onPacketDataClient(source, ClientProxy.getPlayer());
break;
case SERVER:
NetHandlerPlayServer netHandler = (NetHandlerPlayServer)(ctx.channel().attr(NetworkRegistry.NET_HANDLER).get());
NetHandlerPlayServer netHandler = (NetHandlerPlayServer) (ctx.channel().attr(NetworkRegistry.NET_HANDLER).get());
AdvancedPowerManagement.instance.proxy.onPacketDataClient(source, netHandler.playerEntity);
break;
}
}
}
public static void sendToServer(AdvPacket packet)
{
public static void sendToServer(AdvPacket packet){
AdvancedPowerManagement.channels.get(Side.CLIENT).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.TOSERVER);
AdvancedPowerManagement.channels.get(Side.CLIENT).writeOutbound(packet);
}
public static void sendToPlayer(AdvPacket packet, EntityPlayer player)
{
public static void sendToPlayer(AdvPacket packet, EntityPlayer player){
AdvancedPowerManagement.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.PLAYER);
AdvancedPowerManagement.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(player);
AdvancedPowerManagement.channels.get(Side.SERVER).writeOutbound(packet);
}
/*
public static void sendToAllPlayers(Packet packet)
{
AdvancedPowerManagement.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALL);
AdvancedPowerManagement.channels.get(Side.SERVER).writeOutbound(packet);
}
*/
}
/*
* public static void sendToAllPlayers(Packet packet) {
* AdvancedPowerManagement
* .channels.get(Side.SERVER).attr(FMLOutboundHandler.
* FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALL);
* AdvancedPowerManagement.channels.get(Side.SERVER).writeOutbound(packet);
* }
*/
}

View file

@ -20,72 +20,58 @@ import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.network.FMLNetworkEvent.ClientCustomPacketEvent;
public class ClientPacketHandler
{
public class ClientPacketHandler{
/*
* Packet format:
* 0: byte Packet Type
* 1: int x location of TileEntity
* 2: int y location of TileEntity
* 3: int z location of TileEntity
*
* Packet format: 0: byte Packet Type 1: int x location of TileEntity 2: int
* y location of TileEntity 3: int z location of TileEntity
*
* Currently used packet types
*
* Server-to-Client:
* 0 = Universal description packet
* Charging Bench:
* 4: int charge level for texture
* 5: boolean activity state for texture
*
* Battery Station:
* 4: boolean activity state for texture
*
* Storage Monitor:
* 4: int charge level for texture
* 5: boolean power state for texture
* 6: boolean valid state for texture
*
* Server-to-Client: 0 = Universal description packet Charging Bench: 4: int
* charge level for texture 5: boolean activity state for texture
*
* Battery Station: 4: boolean activity state for texture
*
* Storage Monitor: 4: int charge level for texture 5: boolean power state
* for texture 6: boolean valid state for texture
*/
// @Override
// public void onPacketData(INetworkManager network, Packet250CustomPayload packet, Player player)
@SubscribeEvent
public void onClientPacket(ClientCustomPacketEvent event)
{
ByteBuf stream = event.packet.payload();
//DataInputStream stream = new DataInputStream(new ByteArrayInputStream(packet.data));
// Determine packet type and coordinates of affected tile entity
// @Override
// public void onPacketData(INetworkManager network, Packet250CustomPayload
// packet, Player player)
@SubscribeEvent
public void onClientPacket(ClientCustomPacketEvent event){
ByteBuf stream = event.packet.payload();
// DataInputStream stream = new DataInputStream(new
// ByteArrayInputStream(packet.data));
// Determine packet type and coordinates of affected tile entity
int packetType = -1;
int x = 0;
int y = 0;
int z = 0;
packetType = stream.readInt();
x = stream.readInt();
y = stream.readInt();
z = stream.readInt();
if (packetType == 0)
{
if(packetType == 0){
World world = FMLClientHandler.instance().getClient().theWorld;
TileEntity tile = world.getTileEntity(x, y, z);
Exception e;
try
{
((TECommon)tile).receiveDescriptionData(packetType, stream);
try{
((TECommon) tile).receiveDescriptionData(packetType, stream);
return;
}
catch (ClassCastException ex)
{
}catch(ClassCastException ex){
e = ex;
}catch(NullPointerException ex){
e = ex;
}
catch (NullPointerException ex)
{
e = ex;
}
FMLLog.getLogger().info("[AdvancedPowerManagement] " + "Client received description packet for " + x + ", " + y + ", " + z +
" but couldn't deliver to tile entity. (Details: " + e.toString() + ")");
FMLLog.getLogger().info(
"[AdvancedPowerManagement] " + "Client received description packet for " + x + ", " + y + ", " + z
+ " but couldn't deliver to tile entity. (Details: " + e.toString() + ")");
return;
}
}

View file

@ -21,21 +21,18 @@ import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraftforge.client.MinecraftForgeClient;
public class ClientProxy extends CommonProxy
{
public static EntityPlayer getPlayer()
{
public class ClientProxy extends CommonProxy{
public static EntityPlayer getPlayer(){
return Minecraft.getMinecraft().thePlayer;
}
/* @Override
public void load()
{
// MinecraftForgeClient.preloadTexture(Info.ITEM_PNG);
// MinecraftForgeClient.preloadTexture(Info.BLOCK_PNG);
// MinecraftForgeClient.preloadTexture(Info.GUI1_PNG);
// MinecraftForgeClient.preloadTexture(Info.GUI2_PNG);
// MinecraftForgeClient.preloadTexture(Info.GUI3_PNG);
// MinecraftForgeClient.preloadTexture(Info.GUI4_PNG);
}*/
/*
* @Override public void load() { //
* MinecraftForgeClient.preloadTexture(Info.ITEM_PNG); //
* MinecraftForgeClient.preloadTexture(Info.BLOCK_PNG); //
* MinecraftForgeClient.preloadTexture(Info.GUI1_PNG); //
* MinecraftForgeClient.preloadTexture(Info.GUI2_PNG); //
* MinecraftForgeClient.preloadTexture(Info.GUI3_PNG); //
* MinecraftForgeClient.preloadTexture(Info.GUI4_PNG); }
*/
}

View file

@ -39,137 +39,109 @@ import cpw.mods.fml.common.network.IGuiHandler;
//import cpw.mods.fml.common.network.Player;
import cpw.mods.fml.relauncher.Side;
public class CommonProxy implements IGuiHandler
{
public void load() {}
public boolean isClient()
{
public class CommonProxy implements IGuiHandler{
public void load(){}
public boolean isClient(){
return FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT;
}
public boolean isServer()
{
public boolean isServer(){
return FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER;
}
@Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z)
{
if (!world.blockExists(x, y, z)) return null;
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z){
if(!world.blockExists(x, y, z))
return null;
TileEntity tile = world.getTileEntity(x, y, z);
if (ID == 1 && tile instanceof TEChargingBench)
{
return new ContainerChargingBench(player.inventory, (TEChargingBench)tile);
if(ID == 1 && tile instanceof TEChargingBench){
return new ContainerChargingBench(player.inventory, (TEChargingBench) tile);
}else if(ID == 2 && tile instanceof TEBatteryStation){
return new ContainerBatteryStation(player.inventory, (TEBatteryStation) tile);
}else if(ID == 3 && tile instanceof TEStorageMonitor){
return new ContainerStorageMonitor(player.inventory, (TEStorageMonitor) tile);
}else if(ID == 4 && tile instanceof TEAdvEmitter){
return new ContainerAdvEmitter((TEAdvEmitter) tile);
}else if(ID == 5 && tile instanceof TEAdjustableTransformer){
return new ContainerAdjustableTransformer((TEAdjustableTransformer) tile);
}
else if (ID == 2 && tile instanceof TEBatteryStation)
{
return new ContainerBatteryStation(player.inventory, (TEBatteryStation)tile);
}
else if (ID == 3 && tile instanceof TEStorageMonitor)
{
return new ContainerStorageMonitor(player.inventory, (TEStorageMonitor)tile);
}
else if (ID == 4 && tile instanceof TEAdvEmitter)
{
return new ContainerAdvEmitter((TEAdvEmitter)tile);
}
else if (ID == 5 && tile instanceof TEAdjustableTransformer)
{
return new ContainerAdjustableTransformer((TEAdjustableTransformer)tile);
}
return null;
}
@Override
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z)
{
if (!world.blockExists(x, y, z)) return null;
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z){
if(!world.blockExists(x, y, z))
return null;
TileEntity tile = world.getTileEntity(x, y, z);
if (ID == 1 && tile instanceof TEChargingBench)
{
return new GuiChargingBench(player.inventory, (TEChargingBench)tile);
if(ID == 1 && tile instanceof TEChargingBench){
return new GuiChargingBench(player.inventory, (TEChargingBench) tile);
}else if(ID == 2 && tile instanceof TEBatteryStation){
return new GuiBatteryStation(player.inventory, (TEBatteryStation) tile);
}else if(ID == 3 && tile instanceof TEStorageMonitor){
return new GuiStorageMonitor(player.inventory, (TEStorageMonitor) tile);
}else if(ID == 4 && tile instanceof TEAdvEmitter){
return new GuiAdvEmitter((TEAdvEmitter) tile);
}else if(ID == 5 && tile instanceof TEAdjustableTransformer){
return new GuiAdjustableTransformer((TEAdjustableTransformer) tile);
}
else if (ID == 2 && tile instanceof TEBatteryStation)
{
return new GuiBatteryStation(player.inventory, (TEBatteryStation)tile);
}
else if (ID == 3 && tile instanceof TEStorageMonitor)
{
return new GuiStorageMonitor(player.inventory, (TEStorageMonitor)tile);
}
else if (ID == 4 && tile instanceof TEAdvEmitter)
{
return new GuiAdvEmitter((TEAdvEmitter)tile);
}
else if (ID == 5 && tile instanceof TEAdjustableTransformer)
{
return new GuiAdjustableTransformer((TEAdjustableTransformer)tile);
}
return null;
}
/*
* Packet format:
* 0: byte Packet Type
* 1: int x location of TileEntity
* 2: int y location of TileEntity
* 3: int z location of TileEntity
*
* Packet format: 0: byte Packet Type 1: int x location of TileEntity 2: int
* y location of TileEntity 3: int z location of TileEntity
*
* Currently used packet types
*
* Client-to-Server:
* 0 = GUI button command
* 4: int Button ID clicked
*
* Client-to-Server: 0 = GUI button command 4: int Button ID clicked
*/
public void onPacketDataClient(ByteBuf source, EntityPlayer entityPlayer)
{
public void onPacketDataClient(ByteBuf source, EntityPlayer entityPlayer){
DataInputStream stream = new DataInputStream(new ByteArrayInputStream(Arrays.copyOfRange(source.array(), 1, source.array().length)));
// Determine packet type and coordinates of affected tile entity
// Determine packet type and coordinates of affected tile entity
int packetType = -1;
int x;
int y;
int z;
try
{
try{
packetType = stream.readInt();
x = stream.readInt();
y = stream.readInt();
z = stream.readInt();
}
catch (IOException e)
{
}catch(IOException e){
FMLLog.getLogger().info("[AdvancedPowerManagement] " + "Failed to read packet from client. (Details: " + e.toString() + ")");
return;
}
if (packetType == 0)
{
if(packetType == 0){
Exception e;
try
{
try{
World world = entityPlayer.worldObj;
TileEntity tile = world.getTileEntity(x, y, z);
int buttonID = stream.readInt();
((TECommon)tile).receiveGuiButton(buttonID);
((TECommon) tile).receiveGuiButton(buttonID);
return;
}catch(ClassCastException ex){
e = ex;
}catch(NullPointerException ex){
e = ex;
}catch(IOException ex){
e = ex;
}
catch (ClassCastException ex) { e = ex; }
catch (NullPointerException ex) { e = ex; }
catch (IOException ex) { e = ex; }
FMLLog.getLogger().info("[AdvancedPowerManagement] " + "Server received GUI button packet for " + x + ", " + y + ", " + z +
" but couldn't deliver to tile entity. (Details: " + e.toString() + ")");
FMLLog.getLogger().info(
"[AdvancedPowerManagement] " + "Server received GUI button packet for " + x + ", " + y + ", " + z
+ " but couldn't deliver to tile entity. (Details: " + e.toString() + ")");
return;
}
}

View file

@ -4,14 +4,12 @@
******************************************************************************/
package com.kaijin.AdvPowerMan;
public class Coords
{
public class Coords{
public int x;
public int y;
public int z;
public Coords(int x, int y, int z)
{
public Coords(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;

View file

@ -8,26 +8,25 @@ import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import cpw.mods.fml.common.registry.LanguageRegistry;
public class Info
{
public class Info{
// Mod Info
public static final String TITLE_PACKED = "AdvancedPowerManagement";
public static final String TITLE = "Advanced Power Management";
public static final String TITLE_LOG = "[" + TITLE_PACKED + "] ";
// Textures
public static final String TEX_BASE = "textures/";
public static final String GUI_TEX_CHARGING_BENCH = TEX_BASE + "GUIChargingBench.png";
public static final String GUI_TEX_CHARGING_BENCH = TEX_BASE + "GUIChargingBench.png";
public static final String GUI_TEX_BATTERY_STATION = TEX_BASE + "GUIBatteryStation.png";
public static final String GUI_TEX_STORAGE_MONITOR = TEX_BASE + "GUIStorageMonitor.png";
public static final String GUI_TEX_EMITTER = TEX_BASE + "GUIAdvEmitter.png";
public static final String GUI_TEX_EMITTER = TEX_BASE + "GUIAdvEmitter.png";
public static final String GUI_TEX_ADJ_TRANSFORMER = TEX_BASE + "GUIAdjustableTransformer.png";
public static final String[] KEY_BLOCK_NAMES = new String[] {"blockChargingBench1", "blockChargingBench2", "blockChargingBench3",
"blockEmitterBlock1", "blockEmitterBlock2", "blockEmitterBlock3", "blockAdjustableTransformer", "blockEmitterAdjustable",
"blockBatteryStation1", "blockBatteryStation2", "blockBatteryStation3", "blockStorageMonitor"};
"blockEmitterBlock1", "blockEmitterBlock2", "blockEmitterBlock3", "blockAdjustableTransformer", "blockEmitterAdjustable",
"blockBatteryStation1", "blockBatteryStation2", "blockBatteryStation3", "blockStorageMonitor"};
public static final String KEY_NAME_SUFFIX = ".name";
// Blocks
public static final String CHARGER_NAME = "Charging Bench";
public static final String DISCHARGER_NAME = "Battery Station";
@ -35,53 +34,53 @@ public class Info
public static final String EMITTER_NAME = "Emitter";
public static final String ADV_EMITTER_NAME = "Adjustable Emitter";
public static final String ADJ_TRANSFORMER_NAME = "Adjustable Transformer";
// Items
public static final String TOOLKIT_NAME = CHARGER_NAME + " Toolkit";
public static final String COMPONENTS_NAME = CHARGER_NAME + " Components";
public static final String LINK_CARD_NAME = "Energy Link Card";
public static final String LINK_CREATOR_NAME = "Energy Link Card (Blank)";
// GUI IDs
public static final int GUI_ID_CHARGING_BENCH = 1;
public static final int GUI_ID_BATTERY_STATION = 2;
public static final int GUI_ID_STORAGE_MONITOR = 3;
public static final int GUI_ID_ADJUSTABLE_EMITTER = 4;
public static final int GUI_ID_ADJUSTABLE_TRANSFORMER = 5;
// Other constants for use in multiple classes
public static final int LAST_META_VALUE = 11;
public static final int CB_META = 0; // through 2
// 3-5 are unused
public static final int AT_META = 6;
public static final int AE_META = 7;
public static final int BS_META = 8; // through 10
public static final int SM_META = 11;
public static final int CB_SLOT_INPUT = 0;
public static final int CB_SLOT_OUTPUT = 1;
public static final int CB_SLOT_POWER_SOURCE = 2;
public static final int CB_SLOT_CHARGING = 3;
public static final int CB_SLOT_UPGRADE = 15;
public static final int BS_SLOT_INPUT = 0;
public static final int BS_SLOT_OUTPUT = 1;
public static final int BS_SLOT_POWER_START = 2;
public static final int SM_SLOT_UNIVERSAL = 0;
public static final int CB_INVENTORY_SIZE = 19;
public static final int BS_INVENTORY_SIZE = 14;
public static final int SM_INVENTORY_SIZE = 1;
public static final int AE_MIN_PACKET = 4;
public static final int AE_MAX_PACKET = 8192;
public static final int AE_MIN_OUTPUT = 1;
public static final int AE_MAX_OUTPUT = 32768;
public static final int AE_PACKETS_TICK = 64;
// GUI strings
public static final String KEY_TITLE = "AdvPwrMan.title";
public static final String KEY_EU = "AdvPwrMan.misc.EU";
@ -106,18 +105,19 @@ public class Info
public static final String KEY_STATS_DISPLAY_UNKNOWN = "AdvPwrMan.station.led.unknown";
public static final String KEY_STATS_AVERAGE_INPUT = "AdvPwrMan.station.packetIn";
public static final String KEY_EU_BUFFERED = "AdvPwrMan.station.EUbuffered";
public static final String AE_PACKET_RANGE = "[" + AE_MIN_PACKET + " - " + AE_MAX_PACKET + "]";
public static final String AE_OUTPUT_RANGE = "[" + AE_MIN_OUTPUT + " - " + AE_MAX_OUTPUT + "]";
public static final String[] KEY_DIRECTION_NAMES = {"AdvPwrMan.dir.down", "AdvPwrMan.dir.up", "AdvPwrMan.dir.north", "AdvPwrMan.dir.south", "AdvPwrMan.dir.west", "AdvPwrMan.dir.east"};
public static final String[] KEY_DIRECTION_NAMES = {"AdvPwrMan.dir.down", "AdvPwrMan.dir.up", "AdvPwrMan.dir.north", "AdvPwrMan.dir.south",
"AdvPwrMan.dir.west", "AdvPwrMan.dir.east"};
// Some global variables
public static boolean isDebugging;
public static int ic2WrenchID;
public static int ic2ElectricWrenchID;
// For returning charging benches and deconstructing them
public static ItemStack componentCopperCable;
public static ItemStack componentGoldCable;
@ -126,12 +126,12 @@ public class Info
public static ItemStack componentMFE;
public static ItemStack componentMFSU;
public static ItemStack componentCircuit;
// For internal reference to verify items can be placed in inventory.
public static ItemStack ic2overclockerUpg;
public static ItemStack ic2transformerUpg;
public static ItemStack ic2storageUpg;
// Icons for GUI slots
public static IIcon iconSlotChargeable;
public static IIcon iconSlotDrainable;
@ -141,4 +141,4 @@ public class Info
public static IIcon iconSlotLinkCard;
public static IIcon[] iconSlotPowerSource;
public static IIcon[] iconSlotPlayerArmor;
}
}

View file

@ -4,92 +4,88 @@
******************************************************************************/
package com.kaijin.AdvPowerMan;
public class MovingAverage
{
public class MovingAverage{
protected int packets[] = null;
protected int delays[] = null;
protected int position;
//protected int packetTotal;
//protected int delayTotal;
// protected int packetTotal;
// protected int delayTotal;
protected int delay;
protected int window;
protected float average;
protected float delta;
public MovingAverage(int size)
{
public MovingAverage(int size) {
packets = new int[size];
delays = new int[size];
position = 0;
//packetTotal = 0;
//delayTotal = size;
// packetTotal = 0;
// delayTotal = size;
delay = 1;
window = size;
average = 0F;
delta = 0F;
for (int i = 0; i < size; i++)
{
for(int i = 0; i < size; i++){
packets[i] = 0;
delays[i] = 600;
}
}
public void tick(int value)
{
if (value > 0 || delay >= 600) // 600 ticks (30 sec) is long enough for 1 EU/t to have triggered a 512 EU packet by now
public void tick(int value){
if(value > 0 || delay >= 600) // 600 ticks (30 sec) is long enough for 1
// EU/t to have triggered a 512 EU
// packet by now
{
position++;
if (position >= packets.length) position = 0;
//packetTotal -= packet[position];
if(position >= packets.length)
position = 0;
// packetTotal -= packet[position];
packets[position] = value;
//packetTotal += value;
//delayTotal -= time[position];
// packetTotal += value;
// delayTotal -= time[position];
delays[position] = delay;
//delayTotal += delay;
// delayTotal += delay;
delay = 1;
window = sumDelays();
final float newAvg = ((float)sumPackets()) / ((float)window);
final float newAvg = ((float) sumPackets()) / ((float) window);
delta = newAvg - average;
average = newAvg;
}
else
{
}else{
delay++;
// Estimate decline of average based on increased average delay
if (delays.length * delay > window)
{
if(delays.length * delay > window){
window++;
average = ((float)sumPackets()) / ((float)window);
average = ((float) sumPackets()) / ((float) window);
}
}
}
protected int sumDelays()
{
if (delays == null) return 1;
protected int sumDelays(){
if(delays == null)
return 1;
int delayTotal = 0;
for (int d : delays) delayTotal += d;
for(int d : delays)
delayTotal += d;
return delayTotal;
}
protected int sumPackets()
{
if (packets == null) return 0;
protected int sumPackets(){
if(packets == null)
return 0;
int packetTotal = 0;
for (int p : packets) packetTotal += p;
for(int p : packets)
packetTotal += p;
return packetTotal;
}
public float getAverage()
{
public float getAverage(){
return average;
}
public int getWindow()
{
public int getWindow(){
return window;
}
}

View file

@ -12,190 +12,198 @@ import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class Utils
{
public boolean isClient()
{
public class Utils{
public boolean isClient(){
return FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT;
}
public boolean isServer()
{
public boolean isServer(){
return FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER;
}
/**
*
* @param fr - Font Renderer handle
* @param text - Text to display
* @param xLoc - x location
* @param yLoc - y location
* @param color - Color
* @param fr
* - Font Renderer handle
* @param text
* - Text to display
* @param xLoc
* - x location
* @param yLoc
* - y location
* @param color
* - Color
*/
@SideOnly(Side.CLIENT)
public static void drawCenteredText(FontRenderer fr, String text, int xLoc, int yLoc, int color)
{
public static void drawCenteredText(FontRenderer fr, String text, int xLoc, int yLoc, int color){
fr.drawString(text, xLoc - fr.getStringWidth(text) / 2, yLoc, color);
}
/**
*
* @param fr - Font Renderer handle
* @param text - Text to display
* @param xLoc - x location
* @param yLoc - y location
* @param color - Color
* @param fr
* - Font Renderer handle
* @param text
* - Text to display
* @param xLoc
* - x location
* @param yLoc
* - y location
* @param color
* - Color
*/
@SideOnly(Side.CLIENT)
public static void drawRightAlignedText(FontRenderer fr, String text, int xLoc, int yLoc, int color)
{
public static void drawRightAlignedText(FontRenderer fr, String text, int xLoc, int yLoc, int color){
fr.drawString(text, xLoc - fr.getStringWidth(text), yLoc, color);
}
/**
*
* @param fr - Font Renderer handle
* @param text - Text to display
* @param xLoc - x location
* @param yLoc - y location
* @param color - Color
* @param fr
* - Font Renderer handle
* @param text
* - Text to display
* @param xLoc
* - x location
* @param yLoc
* - y location
* @param color
* - Color
*/
@SideOnly(Side.CLIENT)
public static void drawLeftAlignedText(FontRenderer fr, String text, int xLoc, int yLoc, int color)
{
public static void drawLeftAlignedText(FontRenderer fr, String text, int xLoc, int yLoc, int color){
fr.drawString(text, xLoc, yLoc, color);
}
private static final int MASKR = 0xFF0000;
private static final int MASKG = 0x00FF00;
private static final int MASKB = 0x0000FF;
/**
* Individually multiply R, G, B color components by scalar value to dim or brighten the color.
* Does not check for overflow. Beware when using values over 1.0F.
* @param color - original color
* @param brightnessFactor - should be positive and <> 1.0F
* Individually multiply R, G, B color components by scalar value to dim or
* brighten the color. Does not check for overflow. Beware when using values
* over 1.0F.
*
* @param color
* - original color
* @param brightnessFactor
* - should be positive and <> 1.0F
* @return - modified color
*/
public static int multiplyColorComponents(int color, float brightnessFactor)
{
return ((int)(brightnessFactor * (color & MASKR)) & MASKR)
| ((int)(brightnessFactor * (color & MASKG)) & MASKG)
| ((int)(brightnessFactor * (color & MASKB)) & MASKB);
public static int multiplyColorComponents(int color, float brightnessFactor){
return ((int) (brightnessFactor * (color & MASKR)) & MASKR) | ((int) (brightnessFactor * (color & MASKG)) & MASKG)
| ((int) (brightnessFactor * (color & MASKB)) & MASKB);
}
public static int interpolateColors(int a, int b, float lerp)
{
final int MASK1 = 0xff00ff;
final int MASK2 = 0x00ff00;
int f2 = (int)(256 * lerp);
public static int interpolateColors(int a, int b, float lerp){
final int MASK1 = 0xff00ff;
final int MASK2 = 0x00ff00;
int f2 = (int) (256 * lerp);
int f1 = 256 - f2;
return ((((( a & MASK1 ) * f1 ) + ( ( b & MASK1 ) * f2 )) >> 8 ) & MASK1 )
| ((((( a & MASK2 ) * f1 ) + ( ( b & MASK2 ) * f2 )) >> 8 ) & MASK2 );
return (((((a & MASK1) * f1) + ((b & MASK1) * f2)) >> 8) & MASK1) | (((((a & MASK2) * f1) + ((b & MASK2) * f2)) >> 8) & MASK2);
}
public static final int GUIBACKGROUNDCOLOR = 0xC6C6C6;
public static int overlayColors(int base, int over)
{
final float rDiff = 1F - ((float)(base & MASKR) / MASKR);
final float gDiff = 1F - ((float)(base & MASKG) / MASKG);
final float bDiff = 1F - ((float)(base & MASKB) / MASKB);
public static int overlayColors(int base, int over){
final float rDiff = 1F - ((float) (base & MASKR) / MASKR);
final float gDiff = 1F - ((float) (base & MASKG) / MASKG);
final float bDiff = 1F - ((float) (base & MASKB) / MASKB);
final int r2 = (over & MASKR);
final int g2 = (over & MASKG);
final int b2 = (over & MASKB);
return base + ((int)(rDiff * r2) & MASKR) + ((int)(gDiff * g2) & MASKG) + ((int)(bDiff * b2) & MASKB);
return base + ((int) (rDiff * r2) & MASKR) + ((int) (gDiff * g2) & MASKG) + ((int) (bDiff * b2) & MASKB);
}
private static final int oX[] = {0, -1, 0, 1};
private static final int oY[] = {-1, 0, 1, 0};
/**
* Draws right-aligned text with a 'glow' surrounding it.
* @param fr - Font Renderer handle
* @param text - Text to display
* @param xLoc - x location (upper right corner)
* @param yLoc - y location (upper right corner)
* @param color - Main Color
* @param glowColor - Surrounding Color
* Draws right-aligned text with a 'glow' surrounding it.
*
* @param fr
* - Font Renderer handle
* @param text
* - Text to display
* @param xLoc
* - x location (upper right corner)
* @param yLoc
* - y location (upper right corner)
* @param color
* - Main Color
* @param glowColor
* - Surrounding Color
*/
@SideOnly(Side.CLIENT)
public static void drawRightAlignedGlowingText(FontRenderer fr, String text, int xLoc, int yLoc, int color, int glowColor)
{
public static void drawRightAlignedGlowingText(FontRenderer fr, String text, int xLoc, int yLoc, int color, int glowColor){
drawGlowingText(fr, text, xLoc - fr.getStringWidth(text), yLoc, color, glowColor);
}
/**
* Draws centered text with a 'glow' surrounding it.
* @param fr - Font Renderer handle
* @param text - Text to display
* @param xLoc - x location (top center)
* @param yLoc - y location (top center)
* @param color - Main Color
* @param glowColor - Surrounding Color
* Draws centered text with a 'glow' surrounding it.
*
* @param fr
* - Font Renderer handle
* @param text
* - Text to display
* @param xLoc
* - x location (top center)
* @param yLoc
* - y location (top center)
* @param color
* - Main Color
* @param glowColor
* - Surrounding Color
*/
@SideOnly(Side.CLIENT)
public static void drawCenteredGlowingText(FontRenderer fr, String text, int xLoc, int yLoc, int color, int glowColor)
{
public static void drawCenteredGlowingText(FontRenderer fr, String text, int xLoc, int yLoc, int color, int glowColor){
drawGlowingText(fr, text, xLoc - fr.getStringWidth(text) / 2, yLoc, color, glowColor);
}
/**
* Draws left-aligned text with a 'glow' surrounding it.
* @param fr - Font Renderer handle
* @param text - Text to display
* @param xLoc - x location (upper left corner)
* @param yLoc - y location (upper left corner)
* @param color - Main Color
* @param glowColor - Surrounding Color
* Draws left-aligned text with a 'glow' surrounding it.
*
* @param fr
* - Font Renderer handle
* @param text
* - Text to display
* @param xLoc
* - x location (upper left corner)
* @param yLoc
* - y location (upper left corner)
* @param color
* - Main Color
* @param glowColor
* - Surrounding Color
*/
@SideOnly(Side.CLIENT)
public static void drawGlowingText(FontRenderer fr, String text, int xLoc, int yLoc, int color, int glowColor)
{
for (int i = 0; i < 4; i++)
{
public static void drawGlowingText(FontRenderer fr, String text, int xLoc, int yLoc, int color, int glowColor){
for(int i = 0; i < 4; i++){
fr.drawString(text, xLoc + oX[i], yLoc + oY[i], glowColor);
}
fr.drawString(text, xLoc, yLoc, color);
}
/*
* Convert desired side to actual side based on orientation of block
* I Meta
* D U N S W E 0 1 2 3 4 5
* 0 F K T T T T 0 0 1 2 2 2 2
* 1 K F B B B B 1 1 0 3 3 3 3
* 2 T B F K L R 2 2 3 0 1 5 4
* 3 B T K F R L 3 3 2 1 0 4 5
* 4 L L L R F K 4 5 5 5 4 0 1
* 5 R R R L K F 5 4 4 4 5 1 0
*
* Convert desired side to actual side based on orientation of block I Meta
* D U N S W E 0 1 2 3 4 5 0 F K T T T T 0 0 1 2 2 2 2 1 K F B B B B 1 1 0 3
* 3 3 3 2 T B F K L R 2 2 3 0 1 5 4 3 B T K F R L 3 3 2 1 0 4 5 4 L L L R F
* K 4 5 5 5 4 0 1 5 R R R L K F 5 4 4 4 5 1 0
*/
public static int lookupRotatedSide(int side, int orientation)
{
final int table[][] =
{
{0, 1, 2, 2, 2, 2},
{1, 0, 3, 3, 3, 3},
{2, 3, 0, 1, 5, 4},
{3, 2, 1, 0, 4, 5},
{5, 5, 5, 4, 0, 1},
{4, 4, 4, 5, 1, 0}
};
public static int lookupRotatedSide(int side, int orientation){
final int table[][] = { {0, 1, 2, 2, 2, 2}, {1, 0, 3, 3, 3, 3}, {2, 3, 0, 1, 5, 4}, {3, 2, 1, 0, 4, 5}, {5, 5, 5, 4, 0, 1},
{4, 4, 4, 5, 1, 0}};
return table[side][orientation];
}
public static NBTTagCompound getOrCreateStackTag(ItemStack itemStack)
{
if (itemStack != null)
{
public static NBTTagCompound getOrCreateStackTag(ItemStack itemStack){
if(itemStack != null){
NBTTagCompound tag = itemStack.getTagCompound();
if (tag == null)
{
if(tag == null){
tag = new NBTTagCompound();
itemStack.setTagCompound(tag);
}
@ -203,25 +211,23 @@ public class Utils
}
return null;
}
public static boolean isItemChargeable(ItemStack stack, int tier)
{
public static boolean isItemChargeable(ItemStack stack, int tier){
// Decide if the item is a valid IC2 electrical item
if (stack != null && stack.getItem() instanceof IElectricItem)
{
IElectricItem item = (IElectricItem)(stack.getItem());
if (item.getTier(stack) <= tier) return true;
if(stack != null && stack.getItem() instanceof IElectricItem){
IElectricItem item = (IElectricItem) (stack.getItem());
if(item.getTier(stack) <= tier)
return true;
}
return false;
}
public static boolean isItemDrainable(ItemStack stack, int tier)
{
public static boolean isItemDrainable(ItemStack stack, int tier){
// Decide if the item is a valid IC2 power source
if (stack != null && stack.getItem() instanceof IElectricItem)
{
IElectricItem item = (IElectricItem)(stack.getItem());
if (item.canProvideEnergy(stack) && item.getTier(stack) <= tier) return true;
if(stack != null && stack.getItem() instanceof IElectricItem){
IElectricItem item = (IElectricItem) (stack.getItem());
if(item.canProvideEnergy(stack) && item.getTier(stack) <= tier)
return true;
}
return false;
}

View file

@ -34,360 +34,319 @@ import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class BlockAdvPwrMan extends BlockContainer
{
static final String[] tierPrefix = {"LV", "MV", "HV", "EV"};
public class BlockAdvPwrMan extends BlockContainer{
static final String[] tierPrefix = {"LV", "MV", "HV", "EV"};
protected IIcon benchBottom;
protected IIcon smTop;
protected IIcon smBottom;
protected IIcon smInvalid;
protected IIcon emitter;
protected IIcon atOut;
protected IIcon atInput;
protected IIcon atInput;
protected IIcon[] atOutput;
protected IIcon[] benchTop;
protected IIcon[][][] cbSides;
protected IIcon[][] bsSides;
protected IIcon[][] bsSides;
protected IIcon[][] smSides;
public BlockAdvPwrMan( Material material)
{
public BlockAdvPwrMan(Material material) {
super(material);
setHardness(0.75F);
setResistance(5F);
setStepSound(soundTypeStone);
//setUnlocalizedName("AdvPwrMan");
// setUnlocalizedName("AdvPwrMan");
setCreativeTab(CreativeTabs.tabDecorations);
}
@SideOnly(Side.CLIENT)
@Override
public void getSubBlocks(Item block, CreativeTabs creativetabs, List list)
{
for (int i = 0; i <= Info.LAST_META_VALUE; ++i)
{
if (i >= 3 && i <= 5) continue; // Don't add legacy emitters to creative inventory
@SideOnly(Side.CLIENT)
@Override
public void getSubBlocks(Item block, CreativeTabs creativetabs, List list){
for(int i = 0; i <= Info.LAST_META_VALUE; ++i){
if(i >= 3 && i <= 5)
continue; // Don't add legacy emitters to creative inventory
list.add(new ItemStack(block, 1, i));
}
}
@Override
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer entityplayer, int par6, float par7, float par8, float par9)
{
//int currentEquippedItemID = 0; //TODO We're not currently responding to wrenches
//if (entityplayer.getCurrentEquippedItem() != null)
//{
// currentEquippedItemID = entityplayer.getCurrentEquippedItem().itemID;
//}
//if (entityplayer.isSneaking() || currentEquippedItemID == Info.ic2WrenchID || currentEquippedItemID == Info.ic2ElectricWrenchID)
if (entityplayer.isSneaking())
{
// Prevent GUI popup when sneaking - this allows you to place things directly on blocks
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer entityplayer, int par6, float par7, float par8, float par9){
// int currentEquippedItemID = 0; //TODO We're not currently responding
// to wrenches
// if (entityplayer.getCurrentEquippedItem() != null)
// {
// currentEquippedItemID = entityplayer.getCurrentEquippedItem().itemID;
// }
// if (entityplayer.isSneaking() || currentEquippedItemID ==
// Info.ic2WrenchID || currentEquippedItemID ==
// Info.ic2ElectricWrenchID)
if(entityplayer.isSneaking()){
// Prevent GUI popup when sneaking - this allows you to place things
// directly on blocks
return false;
}
TileEntity tile = world.getTileEntity(x, y, z);
if (tile instanceof TECommon)
{
final int id = ((TECommon)tile).getGuiID();
if (id < 1) return false;
if (AdvancedPowerManagement.proxy.isServer())
{
if(tile instanceof TECommon){
final int id = ((TECommon) tile).getGuiID();
if(id < 1)
return false;
if(AdvancedPowerManagement.proxy.isServer()){
entityplayer.openGui(AdvancedPowerManagement.instance, id, world, x, y, z);
}
}
return true;
}
@Override
public void registerBlockIcons(IIconRegister iconRegister)
{
public void registerBlockIcons(IIconRegister iconRegister){
cbSides = new IIcon[3][2][13];
bsSides = new IIcon[3][2];
smSides = new IIcon[2][13];
benchTop = new IIcon[3];
atOutput = new IIcon[4];
benchBottom = iconRegister.registerIcon(Info.TITLE_PACKED + ":BenchBottom");
smTop = iconRegister.registerIcon(Info.TITLE_PACKED + ":StorageMonitorTop");
smBottom = iconRegister.registerIcon(Info.TITLE_PACKED + ":StorageMonitorBottom");
smInvalid = iconRegister.registerIcon(Info.TITLE_PACKED + ":StorageMonitorInvalid");
emitter = iconRegister.registerIcon(Info.TITLE_PACKED + ":Emitter");
atInput = iconRegister.registerIcon(Info.TITLE_PACKED + ":TransformerInput");
int i, j;
for (i = 0; i < 13; i++)
{
for(i = 0; i < 13; i++){
String temp = Integer.toString(i);
for (j = 0; j < 3; j++)
{
for(j = 0; j < 3; j++){
cbSides[j][0][i] = iconRegister.registerIcon(Info.TITLE_PACKED + ":" + tierPrefix[j] + "ChargingBenchOff" + temp);
cbSides[j][1][i] = iconRegister.registerIcon(Info.TITLE_PACKED + ":" + tierPrefix[j] + "ChargingBenchOn" + temp);
}
smSides[0][i] = iconRegister.registerIcon(Info.TITLE_PACKED + ":StorageMonitorOff" + temp);
smSides[1][i] = iconRegister.registerIcon(Info.TITLE_PACKED + ":StorageMonitorOn" + temp);
}
for (i = 0; i < 3; i++)
{
for(i = 0; i < 3; i++){
benchTop[i] = iconRegister.registerIcon(Info.TITLE_PACKED + ":" + tierPrefix[i] + "BenchTop");
bsSides[i][0] = iconRegister.registerIcon(Info.TITLE_PACKED + ":" + tierPrefix[i] + "BatteryStationOff");
bsSides[i][1] = iconRegister.registerIcon(Info.TITLE_PACKED + ":" + tierPrefix[i] + "BatteryStationOn");
}
for (i = 0; i < 4; i++)
{
for(i = 0; i < 4; i++){
atOutput[i] = iconRegister.registerIcon(Info.TITLE_PACKED + ":TransformerOutput1" + tierPrefix[i]);
}
}
//Textures in the world
// Textures in the world
@SideOnly(Side.CLIENT)
@Override
public IIcon getIcon(IBlockAccess blocks, int x, int y, int z, int side)
{
public IIcon getIcon(IBlockAccess blocks, int x, int y, int z, int side){
final int meta = blocks.getBlockMetadata(x, y, z);
TileEntity tile = blocks.getTileEntity(x, y, z);
if (tile instanceof TEChargingBench)
{
switch (side)
{
if(tile instanceof TEChargingBench){
switch(side){
case 0: // bottom
return benchBottom;
case 1: // top
return benchTop[meta - Info.CB_META];
default:
return cbSides[meta - Info.CB_META][((TEChargingBench)tile).doingWork ? 1 : 0][((TEChargingBench)tile).chargeLevel];
return cbSides[meta - Info.CB_META][((TEChargingBench) tile).doingWork ? 1 : 0][((TEChargingBench) tile).chargeLevel];
}
}
else if (tile instanceof TEAdvEmitter)
{
}else if(tile instanceof TEAdvEmitter){
return emitter;
}
else if (tile instanceof TEAdjustableTransformer)
{
final byte flags = ((TEAdjustableTransformer)tile).sideSettings[side];
if ((flags & 1) == 0) return atInput;
}else if(tile instanceof TEAdjustableTransformer){
final byte flags = ((TEAdjustableTransformer) tile).sideSettings[side];
if((flags & 1) == 0)
return atInput;
return atOutput[(flags >>> 1) & 3];
}
else if (tile instanceof TEBatteryStation)
{
switch (side)
{
}else if(tile instanceof TEBatteryStation){
switch(side){
case 0: // bottom
return benchBottom;
case 1: // top
return benchTop[meta - Info.BS_META];
default:
return bsSides[meta - Info.BS_META][((TEBatteryStation)tile).doingWork ? 1 : 0];
return bsSides[meta - Info.BS_META][((TEBatteryStation) tile).doingWork ? 1 : 0];
}
}
else if (tile instanceof TEStorageMonitor)
{
switch (side)
{
}else if(tile instanceof TEStorageMonitor){
switch(side){
case 0: // bottom
return smBottom;
case 1: // top
return smTop;
default:
if (((TEStorageMonitor)tile).blockState)
{
return smSides[((TEStorageMonitor)tile).isPowering ? 1 : 0][((TEStorageMonitor)tile).chargeLevel];
}
else return smInvalid;
if(((TEStorageMonitor) tile).blockState){
return smSides[((TEStorageMonitor) tile).isPowering ? 1 : 0][((TEStorageMonitor) tile).chargeLevel];
}else
return smInvalid;
}
}
//If we're here, something is wrong
// If we're here, something is wrong
return benchBottom;
}
//Textures in your inventory
// Textures in your inventory
@Override
public IIcon getIcon(int side, int meta)
{
if (meta == Info.AE_META)
{
public IIcon getIcon(int side, int meta){
if(meta == Info.AE_META){
return emitter;
}
if (meta == Info.AT_META)
{
if(meta == Info.AT_META){
// TODO: Give transformer better textures
return atInput;
}
switch (side)
{
switch(side){
case 0: // bottom
return meta == Info.SM_META ? smBottom : benchBottom;
case 1: // top
if (meta < 3) // CB tops
if(meta < 3) // CB tops
{
return benchTop[meta - Info.CB_META];
}
else if (meta < 11) // Battery Station top
return benchTop[meta - Info.CB_META];
}else if(meta < 11) // Battery Station top
{
return benchTop[meta - Info.BS_META];
}
else
{
}else{
return smTop;
}
default: // side
if (meta < 3) // Charging Bench
if(meta < 3) // Charging Bench
{
return cbSides[meta - Info.CB_META][0][0];
}
else if (meta < 11) // Battery Station
}else if(meta < 11) // Battery Station
{
return bsSides[meta - Info.BS_META][0];
}
else
{
}else{
return smInvalid;
}
}
}
@Override
public int isProvidingWeakPower(IBlockAccess block, int x, int y, int z, int side)
{
public int isProvidingWeakPower(IBlockAccess block, int x, int y, int z, int side){
TileEntity tile = block.getTileEntity(x, y, z);
return tile instanceof TEStorageMonitor && ((TEStorageMonitor)tile).isPowering ? 15 : 0; // TODO Verify this works properly
return tile instanceof TEStorageMonitor && ((TEStorageMonitor) tile).isPowering ? 15 : 0; // TODO
// Verify
// this
// works
// properly
}
@Override
public int isProvidingStrongPower(IBlockAccess block, int x, int y, int z, int side)
{
public int isProvidingStrongPower(IBlockAccess block, int x, int y, int z, int side){
return 0;
}
@Override
public boolean canProvidePower()
{
public boolean canProvidePower(){
return false; // Old means of causing visual RedPower wire connections.
}
@Override
public boolean canConnectRedstone(IBlockAccess world, int x, int y, int z, int direction)
{
public boolean canConnectRedstone(IBlockAccess world, int x, int y, int z, int direction){
return true;
}
@Override
public boolean isBlockNormalCube()
{
public boolean isBlockNormalCube(){
return false;
}
@Override
public boolean isSideSolid(IBlockAccess world, int x, int y, int z, ForgeDirection side)
{
public boolean isSideSolid(IBlockAccess world, int x, int y, int z, ForgeDirection side){
return true;
}
@Override
public TileEntity createNewTileEntity(World world, int i)
{
public TileEntity createNewTileEntity(World world, int i){
return null;
}
@Override
public TileEntity createTileEntity(World world, int metadata)
{
//if (ChargingBench.isDebugging) System.out.println("BlockAdvPwrMan.createTileEntity");
switch (metadata)
{
public TileEntity createTileEntity(World world, int metadata){
// if (ChargingBench.isDebugging)
// System.out.println("BlockAdvPwrMan.createTileEntity");
switch(metadata){
case 0:
return new TEChargingBench(1);
case 1:
return new TEChargingBench(2);
case 2:
return new TEChargingBench(3);
case 3:
return new TEAdvEmitter(1); // Update old emitter tier 1
case 4:
return new TEAdvEmitter(2); // Update old emitter tier 2
case 5:
return new TEAdvEmitter(3); // Update old emitter tier 3
case 6:
return new TEAdjustableTransformer();
case 7:
return new TEAdvEmitter();
case 8:
return new TEBatteryStation(1);
case 9:
return new TEBatteryStation(2);
case 10:
return new TEBatteryStation(3);
case 11:
return new TEStorageMonitor();
default:
return null;
}
}
@Override
public boolean hasTileEntity(int metadata)
{
public boolean hasTileEntity(int metadata){
return metadata >= 0 && metadata <= Info.LAST_META_VALUE;
}
/*
/*
* @Override public Item getItemDropped(int var1, Random var2, int var3) {
* //if (ChargingBench.isDebugging)
* System.out.println("BlockAdvPwrMan.idDropped"); return blockID; }
*/
@Override
public Item getItemDropped(int var1, Random var2, int var3)
{
//if (ChargingBench.isDebugging) System.out.println("BlockAdvPwrMan.idDropped");
return blockID;
}
*/
@Override
public int damageDropped(int meta)
{
//if (ChargingBench.isDebugging) System.out.println("BlockAdvPwrMan.damageDropped");
public int damageDropped(int meta){
// if (ChargingBench.isDebugging)
// System.out.println("BlockAdvPwrMan.damageDropped");
return meta;
}
@Override
public void breakBlock(World world, int x, int y, int z, Block block, int meta)
{
public void breakBlock(World world, int x, int y, int z, Block block, int meta){
preDestroyBlock(world, x, y, z);
}
public static void preDestroyBlock(World world, int i, int j, int k)
{
if (!AdvancedPowerManagement.proxy.isClient())
{
public static void preDestroyBlock(World world, int i, int j, int k){
if(!AdvancedPowerManagement.proxy.isClient()){
TileEntity tile = world.getTileEntity(i, j, k);
if (tile == null) return;
try
{
((TECommon)tile).dropContents();
}
catch (ClassCastException e)
{
FMLLog.warning("[AdvancedPowerManagement] " + "Attempted to destroy APM block with non-APM tile entity at: " + i + ", " + j + ", " + k);
if(tile == null)
return;
try{
((TECommon) tile).dropContents();
}catch(ClassCastException e){
FMLLog.warning("[AdvancedPowerManagement] " + "Attempted to destroy APM block with non-APM tile entity at: " + i + ", " + j + ", "
+ k);
}
tile.invalidate();
}

View file

@ -12,153 +12,141 @@ import net.minecraft.inventory.ICrafting;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ContainerAdjustableTransformer extends Container
{
public class ContainerAdjustableTransformer extends Container{
private final int playerInventoryStartSlot = 1;
public TEAdjustableTransformer tile;
public int outputRate;
public int packetSize;
public byte[] sideSettings = {0, 0, 0, 0, 0, 0}; // DOWN, UP, NORTH, SOUTH, WEST, EAST
public byte[] sideSettings = {0, 0, 0, 0, 0, 0}; // DOWN, UP, NORTH, SOUTH,
// WEST, EAST
public int outputAvg;
public int inputAvg;
public int energyBuffer;
public ContainerAdjustableTransformer(TEAdjustableTransformer tileentity)
{
//if (Info.isDebugging) System.out.println("ContainerAdjustableTransformer");
public ContainerAdjustableTransformer(TEAdjustableTransformer tileentity) {
// if (Info.isDebugging)
// System.out.println("ContainerAdjustableTransformer");
tile = tileentity;
outputRate = -1;
packetSize = -1;
for (int i : sideSettings)
i = (byte)255;
for(int i : sideSettings)
i = (byte) 255;
outputAvg = -1;
inputAvg = -1;
energyBuffer = -1;
}
@Override
public void detectAndSendChanges()
{
final int syncOutAvg = (int)(tile.outputTracker.getAverage() * 100);
final int syncInAvg = (int)(tile.inputTracker.getAverage() * 100);
for (int crafterIndex = 0; crafterIndex < crafters.size(); ++crafterIndex)
{
ICrafting crafter = (ICrafting)crafters.get(crafterIndex);
if (this.outputRate != tile.outputRate)
{
public void detectAndSendChanges(){
final int syncOutAvg = (int) (tile.outputTracker.getAverage() * 100);
final int syncInAvg = (int) (tile.inputTracker.getAverage() * 100);
for(int crafterIndex = 0; crafterIndex < crafters.size(); ++crafterIndex){
ICrafting crafter = (ICrafting) crafters.get(crafterIndex);
if(this.outputRate != tile.outputRate){
crafter.sendProgressBarUpdate(this, 0, tile.outputRate & 65535);
crafter.sendProgressBarUpdate(this, 1, tile.outputRate >>> 16);
}
if (this.packetSize != tile.packetSize)
{
if(this.packetSize != tile.packetSize){
crafter.sendProgressBarUpdate(this, 2, tile.packetSize & 65535);
crafter.sendProgressBarUpdate(this, 3, tile.packetSize >>> 16);
}
for (int i = 0; i < 6; i++)
if (this.sideSettings[i] != tile.sideSettings[i])
{
crafter.sendProgressBarUpdate(this, 4 + i, tile.sideSettings[i]);
}
if (outputAvg != syncOutAvg)
{
for(int i = 0; i < 6; i++)
if(this.sideSettings[i] != tile.sideSettings[i]){
crafter.sendProgressBarUpdate(this, 4 + i, tile.sideSettings[i]);
}
if(outputAvg != syncOutAvg){
crafter.sendProgressBarUpdate(this, 10, syncOutAvg & 65535);
crafter.sendProgressBarUpdate(this, 11, syncOutAvg >>> 16);
}
if (inputAvg != syncInAvg)
{
if(inputAvg != syncInAvg){
crafter.sendProgressBarUpdate(this, 12, syncInAvg & 65535);
crafter.sendProgressBarUpdate(this, 13, syncInAvg >>> 16);
}
if (this.energyBuffer != tile.energyBuffer)
{
if(this.energyBuffer != tile.energyBuffer){
crafter.sendProgressBarUpdate(this, 14, tile.energyBuffer & 65535);
crafter.sendProgressBarUpdate(this, 15, tile.energyBuffer >>> 16);
}
}
// Done sending updates, record the new current values
this.outputRate = tile.outputRate;
this.packetSize = tile.packetSize;
for (int i = 0; i < 6; i++)
{
for(int i = 0; i < 6; i++){
this.sideSettings[i] = tile.sideSettings[i];
}
outputAvg = syncOutAvg;
inputAvg = syncInAvg;
this.energyBuffer = tile.energyBuffer;
}
@SideOnly(Side.CLIENT)
@Override
public void updateProgressBar(int param, int value)
{
switch (param)
{
public void updateProgressBar(int param, int value){
switch(param){
case 0:
tile.outputRate = tile.outputRate & -65536 | value;
break;
case 1:
tile.outputRate = tile.outputRate & 65535 | (value << 16);
break;
case 2:
tile.packetSize = tile.packetSize & -65536 | value;
break;
case 3:
tile.packetSize = tile.packetSize & 65535 | (value << 16);
break;
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
tile.sideSettings[param - 4] = (byte)value;
tile.sideSettings[param - 4] = (byte) value;
break;
case 10:
outputAvg = outputAvg & -65536 | value;
break;
case 11:
outputAvg = outputAvg & 65535 | (value << 16);
break;
case 12:
inputAvg = inputAvg & -65536 | value;
break;
case 13:
inputAvg = inputAvg & 65535 | (value << 16);
break;
case 14:
tile.energyBuffer = tile.energyBuffer & -65536 | value;
break;
case 15:
tile.energyBuffer = tile.energyBuffer & 65535 | (value << 16);
break;
default:
System.out.println("ContainerAdvEmitter.updateProgressBar - Warning: default case!");
}
}
@Override
public boolean canInteractWith(EntityPlayer var1)
{
public boolean canInteractWith(EntityPlayer var1){
return tile.isUseableByPlayer(var1);
}
}

View file

@ -12,38 +12,33 @@ import net.minecraft.inventory.ICrafting;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ContainerAdvEmitter extends Container
{
public class ContainerAdvEmitter extends Container{
private final int playerInventoryStartSlot = 1;
public TEAdvEmitter te;
public int outputRate;
public int packetSize;
public ContainerAdvEmitter(TEAdvEmitter tile)
{
//if (Info.isDebugging) System.out.println("ContainerAdvEmitter");
public ContainerAdvEmitter(TEAdvEmitter tile) {
// if (Info.isDebugging) System.out.println("ContainerAdvEmitter");
te = tile;
outputRate = -1;
packetSize = -1;
}
@Override
public void detectAndSendChanges()
{
// if (ChargingBench.isDebugging) System.out.println("ContainerChargingBench.updateCraftingResults");
for (int crafterIndex = 0; crafterIndex < crafters.size(); ++crafterIndex)
{
ICrafting crafter = (ICrafting)crafters.get(crafterIndex);
if (this.outputRate != te.outputRate)
{
public void detectAndSendChanges(){
// if (ChargingBench.isDebugging)
// System.out.println("ContainerChargingBench.updateCraftingResults");
for(int crafterIndex = 0; crafterIndex < crafters.size(); ++crafterIndex){
ICrafting crafter = (ICrafting) crafters.get(crafterIndex);
if(this.outputRate != te.outputRate){
crafter.sendProgressBarUpdate(this, 0, te.outputRate & 65535);
crafter.sendProgressBarUpdate(this, 1, te.outputRate >>> 16);
}
if (this.packetSize != te.packetSize)
{
if(this.packetSize != te.packetSize){
crafter.sendProgressBarUpdate(this, 2, te.packetSize & 65535);
crafter.sendProgressBarUpdate(this, 3, te.packetSize >>> 16);
}
@ -56,38 +51,45 @@ public class ContainerAdvEmitter extends Container
@SideOnly(Side.CLIENT)
@Override
public void updateProgressBar(int param, int value)
{
switch (param)
{
public void updateProgressBar(int param, int value){
switch(param){
case 0:
//if (ChargingBench.isDebugging) System.out.println("ContainerChargingBench.updateProgressBar case 0 tileentity.currentEnergy = " + (this.tileentity.currentEnergy & -65536) + " | " + value);
// if (ChargingBench.isDebugging)
// System.out.println("ContainerChargingBench.updateProgressBar case 0 tileentity.currentEnergy = "
// + (this.tileentity.currentEnergy & -65536) + " | " + value);
te.outputRate = te.outputRate & -65536 | value;
break;
case 1:
//if (ChargingBench.isDebugging) System.out.println("ContainerChargingBench.updateProgressBar case 1 tileentity.currentEnergy = " + (this.tileentity.currentEnergy & 65535) + " | " + (value << 16));
// if (ChargingBench.isDebugging)
// System.out.println("ContainerChargingBench.updateProgressBar case 1 tileentity.currentEnergy = "
// + (this.tileentity.currentEnergy & 65535) + " | " + (value <<
// 16));
te.outputRate = te.outputRate & 65535 | (value << 16);
break;
case 2:
//if (ChargingBench.isDebugging) System.out.println("ContainerChargingBench.updateProgressBar case 3 tileentity.adjustedStorage = " + (this.tileentity.adjustedStorage & -65536) + " | " + value);
// if (ChargingBench.isDebugging)
// System.out.println("ContainerChargingBench.updateProgressBar case 3 tileentity.adjustedStorage = "
// + (this.tileentity.adjustedStorage & -65536) + " | " + value);
te.packetSize = te.packetSize & -65536 | value;
break;
case 3:
//if (ChargingBench.isDebugging) System.out.println("ContainerChargingBench.updateProgressBar case 4 tileentity.adjustedStorage = " + (this.tileentity.adjustedStorage & 65535) + " | " + (value << 16));
// if (ChargingBench.isDebugging)
// System.out.println("ContainerChargingBench.updateProgressBar case 4 tileentity.adjustedStorage = "
// + (this.tileentity.adjustedStorage & 65535) + " | " + (value <<
// 16));
te.packetSize = te.packetSize & 65535 | (value << 16);
break;
default:
System.out.println("ContainerAdvEmitter.updateProgressBar - Warning: default case!");
}
}
@Override
public boolean canInteractWith(EntityPlayer var1)
{
public boolean canInteractWith(EntityPlayer var1){
return te.isUseableByPlayer(var1);
}
}

View file

@ -19,85 +19,84 @@ import net.minecraft.item.ItemStack;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ContainerBatteryStation extends Container
{
public class ContainerBatteryStation extends Container{
private static final int shiftClickRange = 13;
private static final int playerInventoryStartSlot = 14;
public TEBatteryStation tileentity;
public int opMode;
public int average;
public int itemsEnergyTotal;
public ContainerBatteryStation(InventoryPlayer player, TEBatteryStation tile)
{
public ContainerBatteryStation(InventoryPlayer player, TEBatteryStation tile) {
tileentity = tile;
opMode = -1;
average = -1;
itemsEnergyTotal = -1;
final int topOffset = 24; // Got tired of forgetting to manually alter ALL of the constants. (This won't affect the energy bar!)
final int topOffset = 24; // Got tired of forgetting to manually alter
// ALL of the constants. (This won't affect
// the energy bar!)
int xCol;
int yRow;
// Discharging slots, in reverse order
for (yRow = 3; yRow >= 0; yRow--) // 4 rows high
for(yRow = 3; yRow >= 0; yRow--) // 4 rows high
{
for (xCol = 2; xCol >= 0; xCol--) // 3 columns across
for(xCol = 2; xCol >= 0; xCol--) // 3 columns across
{
this.addSlotToContainer(new SlotDrainable(tile, 2 + 11 - xCol - 3 * yRow, 62 + xCol * 18, topOffset + yRow * 18, tile.powerTier)); // 52, 32 is upper left input slot
this.addSlotToContainer(new SlotDrainable(tile, 2 + 11 - xCol - 3 * yRow, 62 + xCol * 18, topOffset + yRow * 18, tile.powerTier)); // 52,
// 32
// is
// upper
// left
// input
// slot
}
}
// Input Slot
this.addSlotToContainer(new SlotPowerSource(tile, 0, 17, topOffset, tile.powerTier));
// Output slot
this.addSlotToContainer(new SlotOutput(tile, 1, 143, topOffset + 54));
// Player inventory
for (yRow = 0; yRow < 3; ++yRow)
{
for (xCol = 0; xCol < 9; ++xCol)
{
for(yRow = 0; yRow < 3; ++yRow){
for(xCol = 0; xCol < 9; ++xCol){
this.addSlotToContainer(new Slot(player, xCol + yRow * 9 + 9, 8 + xCol * 18, topOffset + 76 + yRow * 18));
}
}
// Player hot bar
for (yRow = 0; yRow < 9; ++yRow)
{
for(yRow = 0; yRow < 9; ++yRow){
this.addSlotToContainer(new Slot(player, yRow, 8 + yRow * 18, topOffset + 134));
}
}
@Override
public void detectAndSendChanges()
{
// if (ChargingBench.isDebugging) System.out.println("ContainerChargingBench.updateCraftingResults");
public void detectAndSendChanges(){
// if (ChargingBench.isDebugging)
// System.out.println("ContainerChargingBench.updateCraftingResults");
super.detectAndSendChanges();
final int syncAvg = (int)(tileentity.outputTracker.getAverage() * 100);
final int syncAvg = (int) (tileentity.outputTracker.getAverage() * 100);
final int energy = tileentity.getTotalEnergy();
for (int crafterIndex = 0; crafterIndex < crafters.size(); ++crafterIndex)
{
ICrafting crafter = (ICrafting)this.crafters.get(crafterIndex);
if (average != syncAvg)
{
for(int crafterIndex = 0; crafterIndex < crafters.size(); ++crafterIndex){
ICrafting crafter = (ICrafting) this.crafters.get(crafterIndex);
if(average != syncAvg){
crafter.sendProgressBarUpdate(this, 0, syncAvg & 65535);
crafter.sendProgressBarUpdate(this, 1, syncAvg >>> 16);
}
if (itemsEnergyTotal != energy)
{
if(itemsEnergyTotal != energy){
crafter.sendProgressBarUpdate(this, 2, energy & 65535);
crafter.sendProgressBarUpdate(this, 3, energy >>> 16);
}
if (opMode != tileentity.opMode)
{
if(opMode != tileentity.opMode){
crafter.sendProgressBarUpdate(this, 4, tileentity.opMode);
}
}
@ -105,80 +104,70 @@ public class ContainerBatteryStation extends Container
average = syncAvg;
itemsEnergyTotal = energy;
}
@SideOnly(Side.CLIENT)
@Override
public void updateProgressBar(int param, int value)
{
public void updateProgressBar(int param, int value){
super.updateProgressBar(param, value);
switch (param)
{
switch(param){
case 0:
average = average & -65536 | value;
break;
case 1:
average = average & 65535 | (value << 16);
break;
case 2:
itemsEnergyTotal = itemsEnergyTotal & -65536 | value;
break;
case 3:
itemsEnergyTotal = itemsEnergyTotal & 65535 | (value << 16);
break;
case 4:
this.opMode = value;
break;
default:
System.out.println("ContainerBatteryStation.updateProgressBar - Warning: default case!");
}
}
/**
* Merges provided ItemStack with the first available one in the container/player inventory
* Merges provided ItemStack with the first available one in the
* container/player inventory
*/
@Override
protected boolean mergeItemStack(ItemStack stack, int startSlot, int endSlot, boolean reverseOrder)
{
protected boolean mergeItemStack(ItemStack stack, int startSlot, int endSlot, boolean reverseOrder){
boolean result = false;
int slotID = startSlot;
if (reverseOrder)
{
if(reverseOrder){
slotID = endSlot - 1;
}
Slot currentSlot;
ItemStack currentStack;
if (stack.isStackable())
{
while (stack.stackSize > 0 && (!reverseOrder && slotID < endSlot || reverseOrder && slotID >= startSlot))
{
currentSlot = (Slot)inventorySlots.get(slotID);
if(stack.isStackable()){
while(stack.stackSize > 0 && (!reverseOrder && slotID < endSlot || reverseOrder && slotID >= startSlot)){
currentSlot = (Slot) inventorySlots.get(slotID);
currentStack = currentSlot.getStack();
if (currentStack != null && Item.getIdFromItem(currentStack.getItem()) == Item.getIdFromItem(stack.getItem())
if(currentStack != null && Item.getIdFromItem(currentStack.getItem()) == Item.getIdFromItem(stack.getItem())
&& (!stack.getHasSubtypes() || stack.getItemDamage() == currentStack.getItemDamage())
&& ItemStack.areItemStackTagsEqual(stack, currentStack)
&& currentSlot.isItemValid(stack))
{
&& ItemStack.areItemStackTagsEqual(stack, currentStack) && currentSlot.isItemValid(stack)){
int limit = Math.min(stack.getMaxStackSize(), currentSlot.getSlotStackLimit());
int sum = currentStack.stackSize + stack.stackSize;
if (sum <= limit)
{
if(sum <= limit){
stack.stackSize = 0;
currentStack.stackSize = sum;
currentSlot.onSlotChanged();
result = true;
}
else if (currentStack.stackSize < limit)
{
}else if(currentStack.stackSize < limit){
int diff = limit - currentStack.stackSize;
stack.stackSize -= diff;
currentStack.stackSize = limit;
@ -186,279 +175,195 @@ public class ContainerBatteryStation extends Container
result = true;
}
}
if (reverseOrder)
{
if(reverseOrder){
--slotID;
}
else
{
}else{
++slotID;
}
}
}
if (stack.stackSize > 0)
{
if (reverseOrder)
{
if(stack.stackSize > 0){
if(reverseOrder){
slotID = endSlot - 1;
}
else
{
}else{
slotID = startSlot;
}
while (!reverseOrder && slotID < endSlot || reverseOrder && slotID >= startSlot)
{
currentSlot = (Slot)inventorySlots.get(slotID);
while(!reverseOrder && slotID < endSlot || reverseOrder && slotID >= startSlot){
currentSlot = (Slot) inventorySlots.get(slotID);
currentStack = currentSlot.getStack();
if (currentStack == null && currentSlot.isItemValid(stack))
{
if(currentStack == null && currentSlot.isItemValid(stack)){
int limit = currentSlot.getSlotStackLimit();
if (stack.stackSize <= limit)
{
if(stack.stackSize <= limit){
currentSlot.putStack(stack.copy());
currentSlot.onSlotChanged();
stack.stackSize = 0;
result = true;
break;
}
else
{
}else{
currentSlot.putStack(stack.splitStack(limit));
currentSlot.onSlotChanged();
result = true;
}
}
if (reverseOrder)
{
if(reverseOrder){
--slotID;
}
else
{
}else{
++slotID;
}
}
}
return result;
}
/**
* transferStackInSlot with a new signature, not yet mapped to the proper method name
* transferStackInSlot with a new signature, not yet mapped to the proper
* method name
*/
@Override
public ItemStack transferStackInSlot(EntityPlayer p, int slotID)
{
public ItemStack transferStackInSlot(EntityPlayer p, int slotID){
ItemStack original = null;
Slot slotclicked = (Slot)inventorySlots.get(slotID);
if (slotclicked != null && slotclicked.getHasStack())
{
Slot slotclicked = (Slot) inventorySlots.get(slotID);
if(slotclicked != null && slotclicked.getHasStack()){
ItemStack sourceStack = slotclicked.getStack();
original = sourceStack.copy();
if (slotID < playerInventoryStartSlot)
{
if(slotID < playerInventoryStartSlot){
// Move stuff to the player's inventory
if (!this.mergeItemStack(sourceStack, playerInventoryStartSlot, inventorySlots.size(), true))
{
if(!this.mergeItemStack(sourceStack, playerInventoryStartSlot, inventorySlots.size(), true)){
return null;
}
}
else
{
}else{
// Move stuff to the battery station's inventory
if (!this.mergeItemStack(sourceStack, 0, shiftClickRange, false))
{
if(!this.mergeItemStack(sourceStack, 0, shiftClickRange, false)){
return null;
}
}
if (sourceStack.stackSize == 0)
{
slotclicked.putStack((ItemStack)null);
}
else
{
if(sourceStack.stackSize == 0){
slotclicked.putStack((ItemStack) null);
}else{
slotclicked.onSlotChanged();
}
}
return original;
}
/* @Override
public ItemStack slotClick(int slotID, int button, int shiftclick, EntityPlayer par4EntityPlayer)
{
ItemStack result = null;
//if (ChargingBench.isDebugging && ChargingBench.proxy.isServer()) System.out.println("ContainerBatteryStation.slotClick(slotID=" + slotID + ", button=" + button + ", shift=" + shiftclick + ");");
if (button > 1)
{
return null;
}
else
{
if (button == 0 || button == 1)
{
InventoryPlayer invPlayer = par4EntityPlayer.inventory;
if (slotID == -999) // Dropping items outside GUI, identical to vanilla behavior
{
if (invPlayer.getItemStack() != null && slotID == -999)
{
if (button == 0)
{
par4EntityPlayer.dropPlayerItem(invPlayer.getItemStack());
invPlayer.setItemStack((ItemStack)null);
}
if (button == 1)
{
par4EntityPlayer.dropPlayerItem(invPlayer.getItemStack().splitStack(1));
if (invPlayer.getItemStack().stackSize == 0)
{
invPlayer.setItemStack((ItemStack)null);
}
}
}
}
else if (shiftclick == 1)
{
ItemStack original = this.transferStackInSlot(par4EntityPlayer, slotID);
// For crafting and other situations where a new stack could appear in the slot after each click; may be useful for output slot
if (original != null)
{
int originalID = original.itemID;
result = original.copy();
Slot slot = (Slot)inventorySlots.get(slotID);
if (slot != null && slot.getStack() != null && slot.getStack().itemID == originalID)
{
this.retrySlotClick(slotID, button, true, par4EntityPlayer);
}
}
}
else
{
if (slotID < 0)
{
return null;
}
Slot slot = (Slot)inventorySlots.get(slotID);
if (slot != null)
{
ItemStack clickedStack = slot.getStack();
ItemStack mouseStack = invPlayer.getItemStack();
if (clickedStack != null)
{
//if (ChargingBench.isDebugging) System.out.println("Clicked stack tag: " + clickedStack.stackTagCompound + " / Item ID: " + clickedStack.itemID);
result = clickedStack.copy();
}
int quantity;
if (clickedStack == null)
{ // There's nothing in the slot, place the held item there if possible
if (mouseStack != null && slot.isItemValid(mouseStack))
{
quantity = button == 0 ? mouseStack.stackSize : 1;
if (quantity > slot.getSlotStackLimit()) quantity = slot.getSlotStackLimit();
ItemStack temp = mouseStack.splitStack(quantity);
slot.putStack(temp);
if (mouseStack.stackSize == 0)
{
invPlayer.setItemStack((ItemStack)null);
}
}
}
else if (mouseStack == null)
{ // Pick up what's in the slot
quantity = button == 0 ? clickedStack.stackSize : (clickedStack.stackSize + 1) / 2;
ItemStack remainder = slot.decrStackSize(quantity);
invPlayer.setItemStack(remainder);
if (clickedStack.stackSize == 0)
{
slot.putStack((ItemStack)null);
}
slot.onPickupFromSlot(par4EntityPlayer, invPlayer.getItemStack());
}
else if (slot.isItemValid(mouseStack))
{ // Both the mouse and the slot contain items, run this code if the item can be placed here
if (clickedStack.itemID == mouseStack.itemID && (!clickedStack.getHasSubtypes() || clickedStack.getItemDamage() == mouseStack.getItemDamage()) && ItemStack.areItemStackTagsEqual(clickedStack, mouseStack))
{
quantity = button == 0 ? mouseStack.stackSize : 1;
if (quantity > slot.getSlotStackLimit() - clickedStack.stackSize)
{
quantity = slot.getSlotStackLimit() - clickedStack.stackSize;
}
if (quantity > mouseStack.getMaxStackSize() - clickedStack.stackSize)
{
quantity = mouseStack.getMaxStackSize() - clickedStack.stackSize;
}
mouseStack.splitStack(quantity);
if (mouseStack.stackSize == 0)
{
invPlayer.setItemStack((ItemStack)null);
}
clickedStack.stackSize += quantity;
}
else if (mouseStack.stackSize <= slot.getSlotStackLimit())
{ // Exchange the items since they don't match
slot.putStack(mouseStack);
invPlayer.setItemStack(clickedStack);
}
}
else if (clickedStack.itemID == mouseStack.itemID && mouseStack.getMaxStackSize() > 1 && (!clickedStack.getHasSubtypes() || clickedStack.getItemDamage() == mouseStack.getItemDamage()) && ItemStack.areItemStackTagsEqual(clickedStack, mouseStack))
{ // Both the mouse and the slot contain items, run this code if they match
quantity = clickedStack.stackSize;
if (quantity > 0 && quantity + mouseStack.stackSize <= mouseStack.getMaxStackSize())
{
mouseStack.stackSize += quantity;
clickedStack = slot.decrStackSize(quantity);
if (clickedStack.stackSize == 0)
{
slot.putStack((ItemStack)null);
}
slot.onPickupFromSlot(par4EntityPlayer, invPlayer.getItemStack());
}
}
slot.onSlotChanged();
}
}
}
return result;
}
}
*/
public boolean canInteractWith(EntityPlayer var1)
{
// if (ChargingBench.isDebugging) System.out.println("ContainerChargingBench.canInteractWith");
/*
* @Override public ItemStack slotClick(int slotID, int button, int
* shiftclick, EntityPlayer par4EntityPlayer) { ItemStack result = null;
*
* //if (ChargingBench.isDebugging && ChargingBench.proxy.isServer())
* System.out.println("ContainerBatteryStation.slotClick(slotID=" + slotID +
* ", button=" + button + ", shift=" + shiftclick + ");");
*
* if (button > 1) { return null; } else { if (button == 0 || button == 1) {
* InventoryPlayer invPlayer = par4EntityPlayer.inventory;
*
* if (slotID == -999) // Dropping items outside GUI, identical to vanilla
* behavior { if (invPlayer.getItemStack() != null && slotID == -999) { if
* (button == 0) {
* par4EntityPlayer.dropPlayerItem(invPlayer.getItemStack());
* invPlayer.setItemStack((ItemStack)null); }
*
* if (button == 1) {
* par4EntityPlayer.dropPlayerItem(invPlayer.getItemStack().splitStack(1));
*
* if (invPlayer.getItemStack().stackSize == 0) {
* invPlayer.setItemStack((ItemStack)null); } } } } else if (shiftclick ==
* 1) { ItemStack original = this.transferStackInSlot(par4EntityPlayer,
* slotID);
*
* // For crafting and other situations where a new stack could appear in
* the slot after each click; may be useful for output slot if (original !=
* null) { int originalID = original.itemID; result = original.copy(); Slot
* slot = (Slot)inventorySlots.get(slotID);
*
* if (slot != null && slot.getStack() != null && slot.getStack().itemID ==
* originalID) { this.retrySlotClick(slotID, button, true,
* par4EntityPlayer); } } } else { if (slotID < 0) { return null; }
*
* Slot slot = (Slot)inventorySlots.get(slotID);
*
* if (slot != null) { ItemStack clickedStack = slot.getStack(); ItemStack
* mouseStack = invPlayer.getItemStack();
*
* if (clickedStack != null) { //if (ChargingBench.isDebugging)
* System.out.println("Clicked stack tag: " + clickedStack.stackTagCompound
* + " / Item ID: " + clickedStack.itemID); result = clickedStack.copy(); }
*
* int quantity;
*
* if (clickedStack == null) { // There's nothing in the slot, place the
* held item there if possible if (mouseStack != null &&
* slot.isItemValid(mouseStack)) { quantity = button == 0 ?
* mouseStack.stackSize : 1; if (quantity > slot.getSlotStackLimit())
* quantity = slot.getSlotStackLimit();
*
* ItemStack temp = mouseStack.splitStack(quantity); slot.putStack(temp);
*
* if (mouseStack.stackSize == 0) { invPlayer.setItemStack((ItemStack)null);
* } } } else if (mouseStack == null) { // Pick up what's in the slot
* quantity = button == 0 ? clickedStack.stackSize : (clickedStack.stackSize
* + 1) / 2; ItemStack remainder = slot.decrStackSize(quantity);
* invPlayer.setItemStack(remainder);
*
* if (clickedStack.stackSize == 0) { slot.putStack((ItemStack)null); }
*
* slot.onPickupFromSlot(par4EntityPlayer, invPlayer.getItemStack()); } else
* if (slot.isItemValid(mouseStack)) { // Both the mouse and the slot
* contain items, run this code if the item can be placed here if
* (clickedStack.itemID == mouseStack.itemID &&
* (!clickedStack.getHasSubtypes() || clickedStack.getItemDamage() ==
* mouseStack.getItemDamage()) &&
* ItemStack.areItemStackTagsEqual(clickedStack, mouseStack)) { quantity =
* button == 0 ? mouseStack.stackSize : 1;
*
* if (quantity > slot.getSlotStackLimit() - clickedStack.stackSize) {
* quantity = slot.getSlotStackLimit() - clickedStack.stackSize; }
*
* if (quantity > mouseStack.getMaxStackSize() - clickedStack.stackSize) {
* quantity = mouseStack.getMaxStackSize() - clickedStack.stackSize; }
*
* mouseStack.splitStack(quantity);
*
* if (mouseStack.stackSize == 0) { invPlayer.setItemStack((ItemStack)null);
* }
*
* clickedStack.stackSize += quantity; } else if (mouseStack.stackSize <=
* slot.getSlotStackLimit()) { // Exchange the items since they don't match
* slot.putStack(mouseStack); invPlayer.setItemStack(clickedStack); } } else
* if (clickedStack.itemID == mouseStack.itemID &&
* mouseStack.getMaxStackSize() > 1 && (!clickedStack.getHasSubtypes() ||
* clickedStack.getItemDamage() == mouseStack.getItemDamage()) &&
* ItemStack.areItemStackTagsEqual(clickedStack, mouseStack)) { // Both the
* mouse and the slot contain items, run this code if they match quantity =
* clickedStack.stackSize;
*
* if (quantity > 0 && quantity + mouseStack.stackSize <=
* mouseStack.getMaxStackSize()) { mouseStack.stackSize += quantity;
* clickedStack = slot.decrStackSize(quantity);
*
* if (clickedStack.stackSize == 0) { slot.putStack((ItemStack)null); }
*
* slot.onPickupFromSlot(par4EntityPlayer, invPlayer.getItemStack()); } }
*
* slot.onSlotChanged();
*
* } } }
*
* return result; } }
*/
public boolean canInteractWith(EntityPlayer var1){
// if (ChargingBench.isDebugging)
// System.out.println("ContainerChargingBench.canInteractWith");
return tileentity.isUseableByPlayer(var1);
}
}

View file

@ -25,14 +25,16 @@ import net.minecraft.item.Item;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
public class ContainerChargingBench extends Container
{
private static final int topOffset = 68; // Got tired of forgetting to manually alter ALL of the constants. (This won't affect the energy bar!)
public class ContainerChargingBench extends Container{
private static final int topOffset = 68; // Got tired of forgetting to
// manually alter ALL of the
// constants. (This won't affect
// the energy bar!)
protected final int benchShiftClickRange = 17;
protected final int playerInventoryStartSlot = 19;
protected final int playerArmorStartSlot = 55;
protected TEChargingBench tileentity;
protected int currentEnergy;
protected int adjustedStorage;
@ -42,10 +44,10 @@ public class ContainerChargingBench extends Container
protected int ticksRequired;
public int averageInput;
protected SlotPowerSource powerSlot;
public ContainerChargingBench(InventoryPlayer player, TEChargingBench tile)
{
//if (ChargingBench.isDebugging) System.out.println("ContainerChargingBench");
public ContainerChargingBench(InventoryPlayer player, TEChargingBench tile) {
// if (ChargingBench.isDebugging)
// System.out.println("ContainerChargingBench");
tileentity = tile;
currentEnergy = -1;
adjustedMaxInput = -1;
@ -54,219 +56,203 @@ public class ContainerChargingBench extends Container
energyRequired = -1;
ticksRequired = -1;
averageInput = -1;
int xCol;
int yRow;
// Input charging slots
for (yRow = 0; yRow < 4; ++yRow) // 4 rows high
for(yRow = 0; yRow < 4; ++yRow) // 4 rows high
{
for (xCol = 0; xCol < 3; ++xCol) // 3 columns across
for(xCol = 0; xCol < 3; ++xCol) // 3 columns across
{
this.addSlotToContainer(new SlotChargeable(tile, 3 + xCol + 3 * yRow, 52 + xCol * 18, topOffset + yRow * 18, tile.baseTier)); // 52, 32 is upper left input slot
this.addSlotToContainer(new SlotChargeable(tile, 3 + xCol + 3 * yRow, 52 + xCol * 18, topOffset + yRow * 18, tile.baseTier)); // 52,
// 32
// is
// upper
// left
// input
// slot
}
}
// Upgrade slots (Overclocker, storage)
for (yRow = 0; yRow < 4; ++yRow) // 4 rows high
for(yRow = 0; yRow < 4; ++yRow) // 4 rows high
{
this.addSlotToContainer(new SlotMachineUpgrade(tile, 15 + yRow, 152, topOffset + yRow * 18));
}
// Input Slot
this.addSlotToContainer(new SlotInput(tile, 0, 130, topOffset, tile.baseTier));
// Output slot
this.addSlotToContainer(new SlotOutput(tile, 1, 130, topOffset + 54));
// Power source slot
powerSlot = new SlotPowerSource(tile, Info.CB_SLOT_POWER_SOURCE, 130, topOffset + 27, tile.powerTier);
this.addSlotToContainer(powerSlot);
// Player inventory
for (yRow = 0; yRow < 3; ++yRow)
{
for (xCol = 0; xCol < 9; ++xCol)
{
for(yRow = 0; yRow < 3; ++yRow){
for(xCol = 0; xCol < 9; ++xCol){
this.addSlotToContainer(new Slot(player, xCol + yRow * 9 + 9, 8 + xCol * 18, topOffset + 76 + yRow * 18));
}
}
// Player hot bar
for (yRow = 0; yRow < 9; ++yRow)
{
for(yRow = 0; yRow < 9; ++yRow){
this.addSlotToContainer(new Slot(player, yRow, 8 + yRow * 18, topOffset + 134));
}
// Player armor
for (yRow = 0; yRow < 4; ++yRow)
{
for(yRow = 0; yRow < 4; ++yRow){
this.addSlotToContainer(new SlotPlayerArmor(player, player.getSizeInventory() - 1 - yRow, 8, topOffset + yRow * 18, yRow));
}
}
@Override
public void detectAndSendChanges()
{
// if (ChargingBench.isDebugging) System.out.println("ContainerChargingBench.updateCraftingResults");
public void detectAndSendChanges(){
// if (ChargingBench.isDebugging)
// System.out.println("ContainerChargingBench.updateCraftingResults");
super.detectAndSendChanges();
final int syncAvg = (int)(tileentity.inputTracker.getAverage() * 100);
for (int crafterIndex = 0; crafterIndex < crafters.size(); ++crafterIndex)
{
ICrafting crafter = (ICrafting)crafters.get(crafterIndex);
if (this.currentEnergy != tileentity.currentEnergy)
{
final int syncAvg = (int) (tileentity.inputTracker.getAverage() * 100);
for(int crafterIndex = 0; crafterIndex < crafters.size(); ++crafterIndex){
ICrafting crafter = (ICrafting) crafters.get(crafterIndex);
if(this.currentEnergy != tileentity.currentEnergy){
crafter.sendProgressBarUpdate(this, 0, tileentity.currentEnergy & 65535);
crafter.sendProgressBarUpdate(this, 1, tileentity.currentEnergy >>> 16);
}
if (this.adjustedMaxInput != tileentity.adjustedMaxInput)
{
if(this.adjustedMaxInput != tileentity.adjustedMaxInput){
crafter.sendProgressBarUpdate(this, 2, tileentity.adjustedMaxInput);
}
if (this.adjustedStorage != tileentity.adjustedStorage)
{
if(this.adjustedStorage != tileentity.adjustedStorage){
crafter.sendProgressBarUpdate(this, 3, tileentity.adjustedStorage & 65535);
crafter.sendProgressBarUpdate(this, 4, tileentity.adjustedStorage >>> 16);
}
if (this.powerTier != tileentity.powerTier)
{
if(this.powerTier != tileentity.powerTier){
crafter.sendProgressBarUpdate(this, 5, tileentity.powerTier);
}
if (this.energyRequired != tileentity.energyRequired)
{
if(this.energyRequired != tileentity.energyRequired){
crafter.sendProgressBarUpdate(this, 6, tileentity.energyRequired & 65535);
crafter.sendProgressBarUpdate(this, 7, tileentity.energyRequired >>> 16);
}
if (this.ticksRequired != tileentity.ticksRequired)
{
if(this.ticksRequired != tileentity.ticksRequired){
crafter.sendProgressBarUpdate(this, 8, tileentity.ticksRequired & 65535);
crafter.sendProgressBarUpdate(this, 9, tileentity.ticksRequired >>> 16);
}
if (averageInput != syncAvg)
{
if(averageInput != syncAvg){
crafter.sendProgressBarUpdate(this, 10, syncAvg & 65535);
crafter.sendProgressBarUpdate(this, 11, syncAvg >>> 16);
}
}
this.currentEnergy = tileentity.currentEnergy;
this.adjustedStorage = tileentity.adjustedStorage;
this.adjustedMaxInput = (short)tileentity.adjustedMaxInput;
this.powerTier = (short)tileentity.powerTier;
this.adjustedMaxInput = (short) tileentity.adjustedMaxInput;
this.powerTier = (short) tileentity.powerTier;
this.energyRequired = tileentity.energyRequired;
this.ticksRequired = tileentity.ticksRequired;
this.averageInput = syncAvg;
powerSlot.setTier(powerTier);
}
@SideOnly(Side.CLIENT)
@Override
public void updateProgressBar(int param, int value)
{
//super.updateProgressBar(param, value);
switch (param)
{
public void updateProgressBar(int param, int value){
// super.updateProgressBar(param, value);
switch(param){
case 0:
tileentity.currentEnergy = tileentity.currentEnergy & -65536 | value;
break;
case 1:
tileentity.currentEnergy = tileentity.currentEnergy & 65535 | (value << 16);
break;
case 2:
tileentity.adjustedMaxInput = value;
break;
case 3:
tileentity.adjustedStorage = tileentity.adjustedStorage & -65536 | value;
break;
case 4:
tileentity.adjustedStorage = tileentity.adjustedStorage & 65535 | (value << 16);
break;
case 5:
tileentity.powerTier = value;
powerSlot.setTier(value);
break;
case 6:
tileentity.energyRequired = tileentity.energyRequired & -65536 | value;
break;
case 7:
tileentity.energyRequired = tileentity.energyRequired & 65535 | (value << 16);
break;
case 8:
tileentity.ticksRequired = tileentity.ticksRequired & -65536 | value;
break;
case 9:
tileentity.ticksRequired = tileentity.ticksRequired & 65535 | (value << 16);
break;
case 10:
averageInput = averageInput & -65536 | value;
break;
case 11:
averageInput = averageInput & 65535 | (value << 16);
break;
default:
System.out.println("ContainerChargingBench.updateProgressBar - Warning: default case!");
}
}
/**
* Merges provided ItemStack with the first available one in the container/player inventory
* Merges provided ItemStack with the first available one in the
* container/player inventory
*/
@Override
protected boolean mergeItemStack(ItemStack stack, int startSlot, int endSlot, boolean reverseOrder)
{
protected boolean mergeItemStack(ItemStack stack, int startSlot, int endSlot, boolean reverseOrder){
boolean result = false;
int slotID = startSlot;
if (reverseOrder)
{
if(reverseOrder){
slotID = endSlot - 1;
}
Slot currentSlot;
ItemStack currentStack;
if (stack.isStackable())
{
while (stack.stackSize > 0 && (!reverseOrder && slotID < endSlot || reverseOrder && slotID >= startSlot))
{
currentSlot = (Slot)inventorySlots.get(slotID);
if(stack.isStackable()){
while(stack.stackSize > 0 && (!reverseOrder && slotID < endSlot || reverseOrder && slotID >= startSlot)){
currentSlot = (Slot) inventorySlots.get(slotID);
currentStack = currentSlot.getStack();
if (currentStack != null && Item.getIdFromItem(currentStack.getItem()) == Item.getIdFromItem(stack.getItem())
if(currentStack != null && Item.getIdFromItem(currentStack.getItem()) == Item.getIdFromItem(stack.getItem())
&& (!stack.getHasSubtypes() || stack.getItemDamage() == currentStack.getItemDamage())
&& ItemStack.areItemStackTagsEqual(stack, currentStack)
&& currentSlot.isItemValid(stack))
{
&& ItemStack.areItemStackTagsEqual(stack, currentStack) && currentSlot.isItemValid(stack)){
int limit = Math.min(stack.getMaxStackSize(), currentSlot.getSlotStackLimit());
int sum = currentStack.stackSize + stack.stackSize;
if (sum <= limit)
{
if(sum <= limit){
stack.stackSize = 0;
currentStack.stackSize = sum;
currentSlot.onSlotChanged();
result = true;
}
else if (currentStack.stackSize < limit)
{
}else if(currentStack.stackSize < limit){
int diff = limit - currentStack.stackSize;
stack.stackSize -= diff;
currentStack.stackSize = limit;
@ -274,327 +260,265 @@ public class ContainerChargingBench extends Container
result = true;
}
}
if (reverseOrder)
{
if(reverseOrder){
--slotID;
}
else
{
}else{
++slotID;
}
}
}
if (stack.stackSize > 0)
{
if (reverseOrder)
{
if(stack.stackSize > 0){
if(reverseOrder){
slotID = endSlot - 1;
}
else
{
}else{
slotID = startSlot;
}
while (!reverseOrder && slotID < endSlot || reverseOrder && slotID >= startSlot)
{
currentSlot = (Slot)inventorySlots.get(slotID);
while(!reverseOrder && slotID < endSlot || reverseOrder && slotID >= startSlot){
currentSlot = (Slot) inventorySlots.get(slotID);
currentStack = currentSlot.getStack();
if (currentStack == null && currentSlot.isItemValid(stack))
{
if(currentStack == null && currentSlot.isItemValid(stack)){
int limit = currentSlot.getSlotStackLimit();
if (stack.stackSize <= limit)
{
if(stack.stackSize <= limit){
currentSlot.putStack(stack.copy());
currentSlot.onSlotChanged();
stack.stackSize = 0;
result = true;
break;
}
else
{
}else{
currentSlot.putStack(stack.splitStack(limit));
currentSlot.onSlotChanged();
result = true;
}
}
if (reverseOrder)
{
if(reverseOrder){
--slotID;
}
else
{
}else{
++slotID;
}
}
}
return result;
}
@Override
public ItemStack transferStackInSlot(EntityPlayer p, int slotID)
{
public ItemStack transferStackInSlot(EntityPlayer p, int slotID){
ItemStack original = null;
Slot slotclicked = (Slot)inventorySlots.get(slotID);
if (slotclicked != null && slotclicked.getHasStack())
{
Slot slotclicked = (Slot) inventorySlots.get(slotID);
if(slotclicked != null && slotclicked.getHasStack()){
ItemStack sourceStack = slotclicked.getStack();
original = sourceStack.copy();
// Charging Bench Slots
if (slotID < playerInventoryStartSlot)
{
// Look for electric armor to move into armor equipped slots from inside our charging bench
if (original.getItem() instanceof ItemArmor && original.getItem() instanceof IElectricItem && !((Slot)inventorySlots.get(55 + ((ItemArmor)original.getItem()).armorType)).getHasStack())
{
int armorType = 55 + ((ItemArmor)original.getItem()).armorType;
if (!this.mergeItemStack(sourceStack, armorType, armorType + 1, false))
{
if(slotID < playerInventoryStartSlot){
// Look for electric armor to move into armor equipped slots
// from inside our charging bench
if(original.getItem() instanceof ItemArmor && original.getItem() instanceof IElectricItem
&& !((Slot) inventorySlots.get(55 + ((ItemArmor) original.getItem()).armorType)).getHasStack()){
int armorType = 55 + ((ItemArmor) original.getItem()).armorType;
if(!this.mergeItemStack(sourceStack, armorType, armorType + 1, false)){
return null;
}
}
// If there wasn't room, or it isn't armor, toss it into the player inventory
else if (!this.mergeItemStack(sourceStack, playerInventoryStartSlot, inventorySlots.size(), false)) // False to not use the stupid reverse order item placement
// If there wasn't room, or it isn't armor, toss it into the
// player inventory
else if(!this.mergeItemStack(sourceStack, playerInventoryStartSlot, inventorySlots.size(), false)) // False
// to
// not
// use
// the
// stupid
// reverse
// order
// item
// placement
{
return null;
}
}
else if (slotID >= playerArmorStartSlot && slotID < playerArmorStartSlot + 4)
{
}else if(slotID >= playerArmorStartSlot && slotID < playerArmorStartSlot + 4){
// Player Armor Slots
if ((original.getItem() instanceof ItemArmor) && !(original.getItem() instanceof IElectricItem))
{
if((original.getItem() instanceof ItemArmor) && !(original.getItem() instanceof IElectricItem)){
// Move regular armor from armor slots into main inventory
if (!this.mergeItemStack(sourceStack, playerInventoryStartSlot, inventorySlots.size(), false)) // False to not use the stupid reverse order item placement
if(!this.mergeItemStack(sourceStack, playerInventoryStartSlot, inventorySlots.size(), false)) // False
// to
// not
// use
// the
// stupid
// reverse
// order
// item
// placement
{
return null;
}
}
else if (!this.mergeItemStack(sourceStack, 0, benchShiftClickRange, false))
{
}
}else if(!this.mergeItemStack(sourceStack, 0, benchShiftClickRange, false)){
// Put electrical armor items from armor slots into bench
// if that fails, try to put them into our main inventory instead
if (!this.mergeItemStack(sourceStack, playerInventoryStartSlot, inventorySlots.size(), false)) // False to not use the stupid reverse order item placement)
// if that fails, try to put them into our main inventory
// instead
if(!this.mergeItemStack(sourceStack, playerInventoryStartSlot, inventorySlots.size(), false)) // False
// to
// not
// use
// the
// stupid
// reverse
// order
// item
// placement)
{
return null;
}
}
}
else if ((original.getItem() instanceof ItemArmor) && !(original.getItem() instanceof IElectricItem) && !((Slot)inventorySlots.get(55 + ((ItemArmor)original.getItem()).armorType)).getHasStack())
{
}else if((original.getItem() instanceof ItemArmor) && !(original.getItem() instanceof IElectricItem)
&& !((Slot) inventorySlots.get(55 + ((ItemArmor) original.getItem()).armorType)).getHasStack()){
// Move regular armor from main inventory into armor slots
int armorType = 55 + ((ItemArmor)original.getItem()).armorType;
if (!this.mergeItemStack(sourceStack, armorType, armorType + 1, false))
{
int armorType = 55 + ((ItemArmor) original.getItem()).armorType;
if(!this.mergeItemStack(sourceStack, armorType, armorType + 1, false)){
return null;
}
}
else
{
// Move stuff from anywhere not caught above to our charging bench inventory
if (!this.mergeItemStack(sourceStack, 0, benchShiftClickRange, false))
{
if (original.getItem() instanceof ItemArmor && original.getItem() instanceof IElectricItem && !((Slot)inventorySlots.get(55 + ((ItemArmor)original.getItem()).armorType)).getHasStack())
{
// Move electric armor from main inventory into armor slots
int armorType = 55 + ((ItemArmor)original.getItem()).armorType;
if (!this.mergeItemStack(sourceStack, armorType, armorType + 1, false))
{
}else{
// Move stuff from anywhere not caught above to our charging
// bench inventory
if(!this.mergeItemStack(sourceStack, 0, benchShiftClickRange, false)){
if(original.getItem() instanceof ItemArmor && original.getItem() instanceof IElectricItem
&& !((Slot) inventorySlots.get(55 + ((ItemArmor) original.getItem()).armorType)).getHasStack()){
// Move electric armor from main inventory into armor
// slots
int armorType = 55 + ((ItemArmor) original.getItem()).armorType;
if(!this.mergeItemStack(sourceStack, armorType, armorType + 1, false)){
return null;
}
}
else
{
}else{
return null;
}
}
}
if (sourceStack.stackSize == 0)
{
slotclicked.putStack((ItemStack)null);
}
else
{
if(sourceStack.stackSize == 0){
slotclicked.putStack((ItemStack) null);
}else{
slotclicked.onSlotChanged();
}
}
return original;
}
/* @Override
public ItemStack slotClick(int slotID, int button, int shiftclick, EntityPlayer par4EntityPlayer)
{
ItemStack result = null;
if (Info.isDebugging) System.out.println("ContainerChargingBench.slotClick(slotID=" + slotID + ", button=" + button + ", shift=" + shiftclick + ") by " + (AdvancedPowerManagement.proxy.isClient() ? "client" : "server"));
if (button > 1)
{
return null;
}
else
{
if (button == 0 || button == 1)
{
InventoryPlayer invPlayer = par4EntityPlayer.inventory;
if (slotID == -999) // Dropping items outside GUI, identical to vanilla behavior
{
if (invPlayer.getItemStack() != null && slotID == -999)
{
if (button == 0)
{
par4EntityPlayer.dropPlayerItem(invPlayer.getItemStack());
invPlayer.setItemStack((ItemStack)null);
}
if (button == 1)
{
par4EntityPlayer.dropPlayerItem(invPlayer.getItemStack().splitStack(1));
if (invPlayer.getItemStack().stackSize == 0)
{
invPlayer.setItemStack((ItemStack)null);
}
}
}
}
else if (shiftclick == 1)
{
ItemStack original = this.transferStackInSlot(par4EntityPlayer, slotID);
// For crafting and other situations where a new stack could appear in the slot after each click; may be useful for output slot
if (original != null)
{
int originalID = original.itemID;
result = original.copy();
Slot slot = (Slot)inventorySlots.get(slotID);
if (slot != null && slot.getStack() != null && slot.getStack().itemID == originalID)
{
this.retrySlotClick(slotID, button, true, par4EntityPlayer);
}
}
}
else
{
if (slotID < 0)
{
return null;
}
Slot slot = (Slot)inventorySlots.get(slotID);
if (slot != null)
{
ItemStack clickedStack = slot.getStack();
ItemStack mouseStack = invPlayer.getItemStack();
if (clickedStack != null)
{
//if (ChargingBench.isDebugging) System.out.println("Clicked stack tag: " + clickedStack.stackTagCompound + " / Item ID: " + clickedStack.itemID);
result = clickedStack.copy();
}
int quantity;
if (clickedStack == null)
{ // There's nothing in the slot, place the held item there if possible
if (mouseStack != null && slot.isItemValid(mouseStack))
{
quantity = button == 0 ? mouseStack.stackSize : 1;
if (quantity > slot.getSlotStackLimit()) quantity = slot.getSlotStackLimit();
ItemStack temp = mouseStack.splitStack(quantity);
slot.putStack(temp);
if (mouseStack.stackSize == 0)
{
invPlayer.setItemStack((ItemStack)null);
}
}
}
else if (mouseStack == null)
{ // Pick up what's in the slot
quantity = button == 0 ? clickedStack.stackSize : (clickedStack.stackSize + 1) / 2;
ItemStack remainder = slot.decrStackSize(quantity);
invPlayer.setItemStack(remainder);
if (clickedStack.stackSize == 0)
{
slot.putStack((ItemStack)null);
}
slot.onPickupFromSlot(par4EntityPlayer, invPlayer.getItemStack());
}
else if (slot.isItemValid(mouseStack))
{ // Both the mouse and the slot contain items, run this code if the item can be placed here
if (clickedStack.itemID == mouseStack.itemID && (!clickedStack.getHasSubtypes() || clickedStack.getItemDamage() == mouseStack.getItemDamage()) && ItemStack.areItemStackTagsEqual(clickedStack, mouseStack))
{
quantity = button == 0 ? mouseStack.stackSize : 1;
if (quantity > slot.getSlotStackLimit() - clickedStack.stackSize)
{
quantity = slot.getSlotStackLimit() - clickedStack.stackSize;
}
if (quantity > mouseStack.getMaxStackSize() - clickedStack.stackSize)
{
quantity = mouseStack.getMaxStackSize() - clickedStack.stackSize;
}
mouseStack.splitStack(quantity);
if (mouseStack.stackSize == 0)
{
invPlayer.setItemStack((ItemStack)null);
}
clickedStack.stackSize += quantity;
}
else if (mouseStack.stackSize <= slot.getSlotStackLimit())
{ // Exchange the items since they don't match
slot.putStack(mouseStack);
invPlayer.setItemStack(clickedStack);
}
}
else if (clickedStack.itemID == mouseStack.itemID && mouseStack.getMaxStackSize() > 1 && (!clickedStack.getHasSubtypes() || clickedStack.getItemDamage() == mouseStack.getItemDamage()) && ItemStack.areItemStackTagsEqual(clickedStack, mouseStack))
{ // Both the mouse and the slot contain items, run this code if they match
quantity = clickedStack.stackSize;
if (quantity > 0 && quantity + mouseStack.stackSize <= mouseStack.getMaxStackSize())
{
mouseStack.stackSize += quantity;
clickedStack = slot.decrStackSize(quantity);
if (clickedStack.stackSize == 0)
{
slot.putStack((ItemStack)null);
}
slot.onPickupFromSlot(par4EntityPlayer, invPlayer.getItemStack());
}
}
slot.onSlotChanged();
}
}
}
return result;
}
}
*/
public boolean canInteractWith(EntityPlayer var1)
{
// if (ChargingBench.isDebugging) System.out.println("ContainerChargingBench.canInteractWith");
/*
* @Override public ItemStack slotClick(int slotID, int button, int
* shiftclick, EntityPlayer par4EntityPlayer) { ItemStack result = null;
*
* if (Info.isDebugging)
* System.out.println("ContainerChargingBench.slotClick(slotID=" + slotID +
* ", button=" + button + ", shift=" + shiftclick + ") by " +
* (AdvancedPowerManagement.proxy.isClient() ? "client" : "server"));
*
* if (button > 1) { return null; } else { if (button == 0 || button == 1) {
* InventoryPlayer invPlayer = par4EntityPlayer.inventory;
*
* if (slotID == -999) // Dropping items outside GUI, identical to vanilla
* behavior { if (invPlayer.getItemStack() != null && slotID == -999) { if
* (button == 0) {
* par4EntityPlayer.dropPlayerItem(invPlayer.getItemStack());
* invPlayer.setItemStack((ItemStack)null); }
*
* if (button == 1) {
* par4EntityPlayer.dropPlayerItem(invPlayer.getItemStack().splitStack(1));
*
* if (invPlayer.getItemStack().stackSize == 0) {
* invPlayer.setItemStack((ItemStack)null); } } } } else if (shiftclick ==
* 1) { ItemStack original = this.transferStackInSlot(par4EntityPlayer,
* slotID);
*
* // For crafting and other situations where a new stack could appear in
* the slot after each click; may be useful for output slot if (original !=
* null) { int originalID = original.itemID; result = original.copy(); Slot
* slot = (Slot)inventorySlots.get(slotID);
*
* if (slot != null && slot.getStack() != null && slot.getStack().itemID ==
* originalID) { this.retrySlotClick(slotID, button, true,
* par4EntityPlayer); } } } else { if (slotID < 0) { return null; }
*
* Slot slot = (Slot)inventorySlots.get(slotID);
*
* if (slot != null) { ItemStack clickedStack = slot.getStack(); ItemStack
* mouseStack = invPlayer.getItemStack();
*
* if (clickedStack != null) { //if (ChargingBench.isDebugging)
* System.out.println("Clicked stack tag: " + clickedStack.stackTagCompound
* + " / Item ID: " + clickedStack.itemID); result = clickedStack.copy(); }
*
* int quantity;
*
* if (clickedStack == null) { // There's nothing in the slot, place the
* held item there if possible if (mouseStack != null &&
* slot.isItemValid(mouseStack)) { quantity = button == 0 ?
* mouseStack.stackSize : 1; if (quantity > slot.getSlotStackLimit())
* quantity = slot.getSlotStackLimit();
*
* ItemStack temp = mouseStack.splitStack(quantity); slot.putStack(temp);
*
* if (mouseStack.stackSize == 0) { invPlayer.setItemStack((ItemStack)null);
* } } } else if (mouseStack == null) { // Pick up what's in the slot
* quantity = button == 0 ? clickedStack.stackSize : (clickedStack.stackSize
* + 1) / 2; ItemStack remainder = slot.decrStackSize(quantity);
* invPlayer.setItemStack(remainder);
*
* if (clickedStack.stackSize == 0) { slot.putStack((ItemStack)null); }
*
* slot.onPickupFromSlot(par4EntityPlayer, invPlayer.getItemStack()); } else
* if (slot.isItemValid(mouseStack)) { // Both the mouse and the slot
* contain items, run this code if the item can be placed here if
* (clickedStack.itemID == mouseStack.itemID &&
* (!clickedStack.getHasSubtypes() || clickedStack.getItemDamage() ==
* mouseStack.getItemDamage()) &&
* ItemStack.areItemStackTagsEqual(clickedStack, mouseStack)) { quantity =
* button == 0 ? mouseStack.stackSize : 1;
*
* if (quantity > slot.getSlotStackLimit() - clickedStack.stackSize) {
* quantity = slot.getSlotStackLimit() - clickedStack.stackSize; }
*
* if (quantity > mouseStack.getMaxStackSize() - clickedStack.stackSize) {
* quantity = mouseStack.getMaxStackSize() - clickedStack.stackSize; }
*
* mouseStack.splitStack(quantity);
*
* if (mouseStack.stackSize == 0) { invPlayer.setItemStack((ItemStack)null);
* }
*
* clickedStack.stackSize += quantity; } else if (mouseStack.stackSize <=
* slot.getSlotStackLimit()) { // Exchange the items since they don't match
* slot.putStack(mouseStack); invPlayer.setItemStack(clickedStack); } } else
* if (clickedStack.itemID == mouseStack.itemID &&
* mouseStack.getMaxStackSize() > 1 && (!clickedStack.getHasSubtypes() ||
* clickedStack.getItemDamage() == mouseStack.getItemDamage()) &&
* ItemStack.areItemStackTagsEqual(clickedStack, mouseStack)) { // Both the
* mouse and the slot contain items, run this code if they match quantity =
* clickedStack.stackSize;
*
* if (quantity > 0 && quantity + mouseStack.stackSize <=
* mouseStack.getMaxStackSize()) { mouseStack.stackSize += quantity;
* clickedStack = slot.decrStackSize(quantity);
*
* if (clickedStack.stackSize == 0) { slot.putStack((ItemStack)null); }
*
* slot.onPickupFromSlot(par4EntityPlayer, invPlayer.getItemStack()); } }
*
* slot.onSlotChanged();
*
* } } }
*
* return result; } }
*/
public boolean canInteractWith(EntityPlayer var1){
// if (ChargingBench.isDebugging)
// System.out.println("ContainerChargingBench.canInteractWith");
return tileentity.isUseableByPlayer(var1);
}
}

View file

@ -18,78 +18,71 @@ import net.minecraft.item.ItemStack;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ContainerStorageMonitor extends Container
{
public class ContainerStorageMonitor extends Container{
private final int playerInventoryStartSlot = 1;
public TEStorageMonitor te;
public int energyStored;
public int energyCapacity;
public int lowerBoundary;
public int upperBoundary;
public ContainerStorageMonitor(InventoryPlayer player, TEStorageMonitor tile)
{
if (Info.isDebugging) System.out.println("ContainerStorageMonitor");
public ContainerStorageMonitor(InventoryPlayer player, TEStorageMonitor tile) {
if(Info.isDebugging)
System.out.println("ContainerStorageMonitor");
this.te = tile;
this.energyStored = -1;
this.energyCapacity = -1;
this.lowerBoundary = -1;
this.upperBoundary = -1;
final int topOffset = 32; // Got tired of forgetting to manually alter ALL of the constants. (This won't affect the energy bar!)
final int topOffset = 32; // Got tired of forgetting to manually alter
// ALL of the constants. (This won't affect
// the energy bar!)
int xCol;
int yRow;
// Link Card slot
this.addSlotToContainer(new SlotLinkCard(tile, Info.SM_SLOT_UNIVERSAL, 8, 9));
// Player inventory
for (yRow = 0; yRow < 3; ++yRow)
{
for (xCol = 0; xCol < 9; ++xCol)
{
for(yRow = 0; yRow < 3; ++yRow){
for(xCol = 0; xCol < 9; ++xCol){
this.addSlotToContainer(new Slot(player, xCol + yRow * 9 + 9, 8 + xCol * 18, topOffset + 76 + yRow * 18));
}
}
// Player hot bar
for (yRow = 0; yRow < 9; ++yRow)
{
for(yRow = 0; yRow < 9; ++yRow){
this.addSlotToContainer(new Slot(player, yRow, 8 + yRow * 18, topOffset + 134));
}
}
@Override
public void detectAndSendChanges()
{
// if (ChargingBench.isDebugging) System.out.println("ContainerChargingBench.updateCraftingResults");
public void detectAndSendChanges(){
// if (ChargingBench.isDebugging)
// System.out.println("ContainerChargingBench.updateCraftingResults");
super.detectAndSendChanges();
for (int crafterIndex = 0; crafterIndex < crafters.size(); ++crafterIndex)
{
ICrafting crafter = (ICrafting)crafters.get(crafterIndex);
if (this.energyStored != te.energyStored)
{
for(int crafterIndex = 0; crafterIndex < crafters.size(); ++crafterIndex){
ICrafting crafter = (ICrafting) crafters.get(crafterIndex);
if(this.energyStored != te.energyStored){
crafter.sendProgressBarUpdate(this, 0, te.energyStored & 65535);
crafter.sendProgressBarUpdate(this, 1, te.energyStored >>> 16);
}
if (this.energyCapacity != te.energyCapacity)
{
if(this.energyCapacity != te.energyCapacity){
crafter.sendProgressBarUpdate(this, 2, te.energyCapacity & 65535);
crafter.sendProgressBarUpdate(this, 3, te.energyCapacity >>> 16);
}
if (this.lowerBoundary != te.lowerBoundary)
{
if(this.lowerBoundary != te.lowerBoundary){
crafter.sendProgressBarUpdate(this, 4, te.lowerBoundary);
}
if (this.upperBoundary != te.upperBoundary)
{
if(this.upperBoundary != te.upperBoundary){
crafter.sendProgressBarUpdate(this, 5, te.upperBoundary);
}
}
@ -101,81 +94,71 @@ public class ContainerStorageMonitor extends Container
@SideOnly(Side.CLIENT)
@Override
public void updateProgressBar(int param, int value)
{
public void updateProgressBar(int param, int value){
super.updateProgressBar(param, value);
switch (param)
{
switch(param){
case 0:
te.energyStored = te.energyStored & -65536 | value;
break;
case 1:
te.energyStored = te.energyStored & 65535 | (value << 16);
break;
case 2:
te.energyCapacity = te.energyCapacity & -65536 | value;
break;
case 3:
te.energyCapacity = te.energyCapacity & 65535 | (value << 16);
break;
case 4:
te.lowerBoundary = value;
break;
case 5:
te.upperBoundary = value;
break;
default:
System.out.println("ContainerStorageMonitor.updateProgressBar - Warning: default case!");
}
}
/**
* Merges provided ItemStack with the first available one in the container/player inventory
* Merges provided ItemStack with the first available one in the
* container/player inventory
*/
@Override
protected boolean mergeItemStack(ItemStack stack, int startSlot, int endSlot, boolean reverseOrder)
{
protected boolean mergeItemStack(ItemStack stack, int startSlot, int endSlot, boolean reverseOrder){
boolean result = false;
int slotID = startSlot;
if (reverseOrder)
{
if(reverseOrder){
slotID = endSlot - 1;
}
Slot currentSlot;
ItemStack currentStack;
if (stack.isStackable())
{
while (stack.stackSize > 0 && (!reverseOrder && slotID < endSlot || reverseOrder && slotID >= startSlot))
{
currentSlot = (Slot)inventorySlots.get(slotID);
if(stack.isStackable()){
while(stack.stackSize > 0 && (!reverseOrder && slotID < endSlot || reverseOrder && slotID >= startSlot)){
currentSlot = (Slot) inventorySlots.get(slotID);
currentStack = currentSlot.getStack();
if (currentStack != null && Item.getIdFromItem(currentStack.getItem()) == Item.getIdFromItem(stack.getItem())
if(currentStack != null && Item.getIdFromItem(currentStack.getItem()) == Item.getIdFromItem(stack.getItem())
&& (!stack.getHasSubtypes() || stack.getItemDamage() == currentStack.getItemDamage())
&& ItemStack.areItemStackTagsEqual(stack, currentStack)
&& currentSlot.isItemValid(stack))
{
&& ItemStack.areItemStackTagsEqual(stack, currentStack) && currentSlot.isItemValid(stack)){
int limit = Math.min(stack.getMaxStackSize(), currentSlot.getSlotStackLimit());
int sum = currentStack.stackSize + stack.stackSize;
if (sum <= limit)
{
if(sum <= limit){
stack.stackSize = 0;
currentStack.stackSize = sum;
currentSlot.onSlotChanged();
result = true;
}
else if (currentStack.stackSize < limit)
{
}else if(currentStack.stackSize < limit){
int diff = limit - currentStack.stackSize;
stack.stackSize -= diff;
currentStack.stackSize = limit;
@ -183,269 +166,183 @@ public class ContainerStorageMonitor extends Container
result = true;
}
}
if (reverseOrder)
{
if(reverseOrder){
--slotID;
}
else
{
}else{
++slotID;
}
}
}
if (stack.stackSize > 0)
{
if (reverseOrder)
{
if(stack.stackSize > 0){
if(reverseOrder){
slotID = endSlot - 1;
}
else
{
}else{
slotID = startSlot;
}
while (!reverseOrder && slotID < endSlot || reverseOrder && slotID >= startSlot)
{
currentSlot = (Slot)inventorySlots.get(slotID);
while(!reverseOrder && slotID < endSlot || reverseOrder && slotID >= startSlot){
currentSlot = (Slot) inventorySlots.get(slotID);
currentStack = currentSlot.getStack();
if (currentStack == null && currentSlot.isItemValid(stack))
{
if(currentStack == null && currentSlot.isItemValid(stack)){
int limit = currentSlot.getSlotStackLimit();
if (stack.stackSize <= limit)
{
if(stack.stackSize <= limit){
currentSlot.putStack(stack.copy());
currentSlot.onSlotChanged();
stack.stackSize = 0;
result = true;
break;
}
else
{
}else{
currentSlot.putStack(stack.splitStack(limit));
currentSlot.onSlotChanged();
result = true;
}
}
if (reverseOrder)
{
if(reverseOrder){
--slotID;
}
else
{
}else{
++slotID;
}
}
}
return result;
}
@Override
public ItemStack transferStackInSlot(EntityPlayer p, int par1)
{
public ItemStack transferStackInSlot(EntityPlayer p, int par1){
ItemStack original = null;
Slot slotclicked = (Slot)inventorySlots.get(par1);
if (slotclicked != null && slotclicked.getHasStack())
{
Slot slotclicked = (Slot) inventorySlots.get(par1);
if(slotclicked != null && slotclicked.getHasStack()){
ItemStack sourceStack = slotclicked.getStack();
original = sourceStack.copy();
if (par1 < playerInventoryStartSlot)
{
if (!this.mergeItemStack(sourceStack, playerInventoryStartSlot, inventorySlots.size(), true))
{
if(par1 < playerInventoryStartSlot){
if(!this.mergeItemStack(sourceStack, playerInventoryStartSlot, inventorySlots.size(), true)){
return null;
}
}
else if (!this.mergeItemStack(sourceStack, 0, playerInventoryStartSlot, false))
{
}else if(!this.mergeItemStack(sourceStack, 0, playerInventoryStartSlot, false)){
return null;
}
if (sourceStack.stackSize == 0)
{
slotclicked.putStack((ItemStack)null);
}
else
{
if(sourceStack.stackSize == 0){
slotclicked.putStack((ItemStack) null);
}else{
slotclicked.onSlotChanged();
}
}
return original;
}
/* @Override
public ItemStack slotClick(int slotID, int button, int shiftclick, EntityPlayer par4EntityPlayer)
{
ItemStack result = null;
if (Info.isDebugging && AdvancedPowerManagement.proxy.isServer()) System.out.println("ContainerChargingBench.slotClick(slotID=" + slotID + ", button=" + button + ", shift=" + shiftclick + ");");
if (button > 1)
{
return null;
}
else
{
if (button == 0 || button == 1)
{
InventoryPlayer invPlayer = par4EntityPlayer.inventory;
if (slotID == -999) // Dropping items outside GUI, identical to vanilla behavior
{
if (invPlayer.getItemStack() != null && slotID == -999)
{
if (button == 0)
{
par4EntityPlayer.dropPlayerItem(invPlayer.getItemStack());
invPlayer.setItemStack((ItemStack)null);
}
if (button == 1)
{
par4EntityPlayer.dropPlayerItem(invPlayer.getItemStack().splitStack(1));
if (invPlayer.getItemStack().stackSize == 0)
{
invPlayer.setItemStack((ItemStack)null);
}
}
}
}
else if (shiftclick == 1)
{
ItemStack original = this.transferStackInSlot(par4EntityPlayer, slotID);
// For crafting and other situations where a new stack could appear in the slot after each click; may be useful for output slot
if (original != null)
{
int originalID = original.itemID;
result = original.copy();
Slot slot = (Slot)inventorySlots.get(slotID);
if (slot != null && slot.getStack() != null && slot.getStack().itemID == originalID)
{
this.retrySlotClick(slotID, button, true, par4EntityPlayer);
}
}
}
else
{
if (slotID < 0)
{
return null;
}
Slot slot = (Slot)this.inventorySlots.get(slotID);
if (slot != null)
{
ItemStack clickedStack = slot.getStack();
ItemStack mouseStack = invPlayer.getItemStack();
if (clickedStack != null)
{
if (Info.isDebugging) System.out.println("Clicked stack tag: " + clickedStack.stackTagCompound + " / Item ID: " + clickedStack.itemID);
result = clickedStack.copy();
}
int quantity;
if (clickedStack == null)
{ // There's nothing in the slot, place the held item there if possible
if (mouseStack != null && slot.isItemValid(mouseStack))
{
quantity = button == 0 ? mouseStack.stackSize : 1;
if (quantity > slot.getSlotStackLimit()) quantity = slot.getSlotStackLimit();
ItemStack temp = mouseStack.splitStack(quantity);
slot.putStack(temp);
if (mouseStack.stackSize == 0)
{
invPlayer.setItemStack((ItemStack)null);
}
}
}
else if (mouseStack == null)
{ // Pick up what's in the slot
quantity = button == 0 ? clickedStack.stackSize : (clickedStack.stackSize + 1) / 2;
ItemStack remainder = slot.decrStackSize(quantity);
invPlayer.setItemStack(remainder);
if (clickedStack.stackSize == 0)
{
slot.putStack((ItemStack)null);
}
slot.onPickupFromSlot(par4EntityPlayer, invPlayer.getItemStack());
}
else if (slot.isItemValid(mouseStack))
{ // Both the mouse and the slot contain items, run this code if the item can be placed here
if (clickedStack.itemID == mouseStack.itemID && (!clickedStack.getHasSubtypes() || clickedStack.getItemDamage() == mouseStack.getItemDamage()) && ItemStack.areItemStackTagsEqual(clickedStack, mouseStack))
{
quantity = button == 0 ? mouseStack.stackSize : 1;
if (quantity > slot.getSlotStackLimit() - clickedStack.stackSize)
{
quantity = slot.getSlotStackLimit() - clickedStack.stackSize;
}
if (quantity > mouseStack.getMaxStackSize() - clickedStack.stackSize)
{
quantity = mouseStack.getMaxStackSize() - clickedStack.stackSize;
}
mouseStack.splitStack(quantity);
if (mouseStack.stackSize == 0)
{
invPlayer.setItemStack((ItemStack)null);
}
clickedStack.stackSize += quantity;
}
else if (mouseStack.stackSize <= slot.getSlotStackLimit())
{ // Exchange the items since they don't match
slot.putStack(mouseStack);
invPlayer.setItemStack(clickedStack);
}
}
else if (clickedStack.itemID == mouseStack.itemID && mouseStack.getMaxStackSize() > 1 && (!clickedStack.getHasSubtypes() || clickedStack.getItemDamage() == mouseStack.getItemDamage()) && ItemStack.areItemStackTagsEqual(clickedStack, mouseStack))
{ // Both the mouse and the slot contain items, run this code if they match
quantity = clickedStack.stackSize;
if (quantity > 0 && quantity + mouseStack.stackSize <= mouseStack.getMaxStackSize())
{
mouseStack.stackSize += quantity;
clickedStack = slot.decrStackSize(quantity);
if (clickedStack.stackSize == 0)
{
slot.putStack((ItemStack)null);
}
slot.onPickupFromSlot(par4EntityPlayer, invPlayer.getItemStack());
}
}
slot.onSlotChanged();
}
}
}
return result;
}
}
*/
public boolean canInteractWith(EntityPlayer var1)
{
// if (ChargingBench.isDebugging) System.out.println("ContainerChargingBench.canInteractWith");
/*
* @Override public ItemStack slotClick(int slotID, int button, int
* shiftclick, EntityPlayer par4EntityPlayer) { ItemStack result = null;
*
* if (Info.isDebugging && AdvancedPowerManagement.proxy.isServer())
* System.out.println("ContainerChargingBench.slotClick(slotID=" + slotID +
* ", button=" + button + ", shift=" + shiftclick + ");");
*
* if (button > 1) { return null; } else { if (button == 0 || button == 1) {
* InventoryPlayer invPlayer = par4EntityPlayer.inventory;
*
* if (slotID == -999) // Dropping items outside GUI, identical to vanilla
* behavior { if (invPlayer.getItemStack() != null && slotID == -999) { if
* (button == 0) {
* par4EntityPlayer.dropPlayerItem(invPlayer.getItemStack());
* invPlayer.setItemStack((ItemStack)null); }
*
* if (button == 1) {
* par4EntityPlayer.dropPlayerItem(invPlayer.getItemStack().splitStack(1));
*
* if (invPlayer.getItemStack().stackSize == 0) {
* invPlayer.setItemStack((ItemStack)null); } } } } else if (shiftclick ==
* 1) { ItemStack original = this.transferStackInSlot(par4EntityPlayer,
* slotID);
*
* // For crafting and other situations where a new stack could appear in
* the slot after each click; may be useful for output slot if (original !=
* null) { int originalID = original.itemID; result = original.copy(); Slot
* slot = (Slot)inventorySlots.get(slotID);
*
* if (slot != null && slot.getStack() != null && slot.getStack().itemID ==
* originalID) { this.retrySlotClick(slotID, button, true,
* par4EntityPlayer); } } } else { if (slotID < 0) { return null; }
*
* Slot slot = (Slot)this.inventorySlots.get(slotID);
*
* if (slot != null) { ItemStack clickedStack = slot.getStack(); ItemStack
* mouseStack = invPlayer.getItemStack();
*
* if (clickedStack != null) { if (Info.isDebugging)
* System.out.println("Clicked stack tag: " + clickedStack.stackTagCompound
* + " / Item ID: " + clickedStack.itemID); result = clickedStack.copy(); }
*
* int quantity;
*
* if (clickedStack == null) { // There's nothing in the slot, place the
* held item there if possible if (mouseStack != null &&
* slot.isItemValid(mouseStack)) { quantity = button == 0 ?
* mouseStack.stackSize : 1; if (quantity > slot.getSlotStackLimit())
* quantity = slot.getSlotStackLimit();
*
* ItemStack temp = mouseStack.splitStack(quantity); slot.putStack(temp);
*
* if (mouseStack.stackSize == 0) { invPlayer.setItemStack((ItemStack)null);
* } } } else if (mouseStack == null) { // Pick up what's in the slot
* quantity = button == 0 ? clickedStack.stackSize : (clickedStack.stackSize
* + 1) / 2; ItemStack remainder = slot.decrStackSize(quantity);
* invPlayer.setItemStack(remainder);
*
* if (clickedStack.stackSize == 0) { slot.putStack((ItemStack)null); }
*
* slot.onPickupFromSlot(par4EntityPlayer, invPlayer.getItemStack()); } else
* if (slot.isItemValid(mouseStack)) { // Both the mouse and the slot
* contain items, run this code if the item can be placed here if
* (clickedStack.itemID == mouseStack.itemID &&
* (!clickedStack.getHasSubtypes() || clickedStack.getItemDamage() ==
* mouseStack.getItemDamage()) &&
* ItemStack.areItemStackTagsEqual(clickedStack, mouseStack)) { quantity =
* button == 0 ? mouseStack.stackSize : 1;
*
* if (quantity > slot.getSlotStackLimit() - clickedStack.stackSize) {
* quantity = slot.getSlotStackLimit() - clickedStack.stackSize; }
*
* if (quantity > mouseStack.getMaxStackSize() - clickedStack.stackSize) {
* quantity = mouseStack.getMaxStackSize() - clickedStack.stackSize; }
*
* mouseStack.splitStack(quantity);
*
* if (mouseStack.stackSize == 0) { invPlayer.setItemStack((ItemStack)null);
* }
*
* clickedStack.stackSize += quantity; } else if (mouseStack.stackSize <=
* slot.getSlotStackLimit()) { // Exchange the items since they don't match
* slot.putStack(mouseStack); invPlayer.setItemStack(clickedStack); } } else
* if (clickedStack.itemID == mouseStack.itemID &&
* mouseStack.getMaxStackSize() > 1 && (!clickedStack.getHasSubtypes() ||
* clickedStack.getItemDamage() == mouseStack.getItemDamage()) &&
* ItemStack.areItemStackTagsEqual(clickedStack, mouseStack)) { // Both the
* mouse and the slot contain items, run this code if they match quantity =
* clickedStack.stackSize;
*
* if (quantity > 0 && quantity + mouseStack.stackSize <=
* mouseStack.getMaxStackSize()) { mouseStack.stackSize += quantity;
* clickedStack = slot.decrStackSize(quantity);
*
* if (clickedStack.stackSize == 0) { slot.putStack((ItemStack)null); }
*
* slot.onPickupFromSlot(par4EntityPlayer, invPlayer.getItemStack()); } }
*
* slot.onSlotChanged(); } } } return result; } }
*/
public boolean canInteractWith(EntityPlayer var1){
// if (ChargingBench.isDebugging)
// System.out.println("ContainerChargingBench.canInteractWith");
return this.te.isUseableByPlayer(var1);
}
}

View file

@ -17,11 +17,10 @@ import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class CButton extends GuiButton
{
public class CButton extends GuiButton{
/** Path to custom texture for button */
protected String texture;
protected int uLoc;
protected int vLoc;
protected int uHoverLoc;
@ -29,25 +28,42 @@ public class CButton extends GuiButton
protected int color;
protected int hoverColor;
protected boolean isHovering;
/** CButton will assume the texture size is equal to the width and height of the button
/**
* CButton will assume the texture size is equal to the width and height of
* the button
*
* @param id - ID of button
* @param xLoc - x location of button on screen
* @param yLoc - y location of button on screen
* @param width - width of button
* @param height - height of button
* @param uLoc - x location of start of texture in texture file
* @param vLoc - y location of start of texture in texture file
* @param uHoverLoc - x location of start of texture for mouse over in texture file
* @param vHoverLoc - x location of start of texture for mouse over in texture file
* @param text - text to display on button
* @param color - color for the text
* @param hoverColor - color for the text while hovering
* @param texture - path to texture file
* @param id
* - ID of button
* @param xLoc
* - x location of button on screen
* @param yLoc
* - y location of button on screen
* @param width
* - width of button
* @param height
* - height of button
* @param uLoc
* - x location of start of texture in texture file
* @param vLoc
* - y location of start of texture in texture file
* @param uHoverLoc
* - x location of start of texture for mouse over in texture
* file
* @param vHoverLoc
* - x location of start of texture for mouse over in texture
* file
* @param text
* - text to display on button
* @param color
* - color for the text
* @param hoverColor
* - color for the text while hovering
* @param texture
* - path to texture file
*/
public CButton(int id, int xLoc, int yLoc, int width, int height, int uLoc, int vLoc, int uHoverLoc, int vHoverLoc, String text, int color, int hoverColor, String texture)
{
public CButton(int id, int xLoc, int yLoc, int width, int height, int uLoc, int vLoc, int uHoverLoc, int vHoverLoc, String text, int color,
int hoverColor, String texture) {
super(id, xLoc, yLoc, width, height, text);
this.enabled = true;
this.visible = true;
@ -65,48 +81,39 @@ public class CButton extends GuiButton
this.hoverColor = hoverColor;
this.texture = texture;
}
/**
* Draws this button to the screen.
*/
@Override
public void drawButton(Minecraft mc, int xLoc, int yLoc)
{
if (visible)
{
public void drawButton(Minecraft mc, int xLoc, int yLoc){
if(visible){
FontRenderer fr = mc.fontRenderer;
if (texture != null)
{
if(texture != null){
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
mc.renderEngine.bindTexture(new ResourceLocation(Info.TITLE_PACKED.toLowerCase(), texture));
}
isHovering = xLoc >= xPosition && yLoc >= yPosition && xLoc < xPosition + width && yLoc < yPosition + height;
int hoverState = this.getHoverState(isHovering);
if (hoverState == 2)
{
if(hoverState == 2){
this.drawTexturedModalRect(xPosition, yPosition, uHoverLoc, vHoverLoc, width, height);
}
else
{
}else{
this.drawTexturedModalRect(xPosition, yPosition, uLoc, vLoc, width, height);
}
int defaultColor = color;
int renderColor = defaultColor;
if (!enabled)
{
renderColor = -6250336;
if(!enabled){
renderColor = -6250336;
}else if(isHovering){
renderColor = hoverColor;
}
else if (isHovering)
{
renderColor = hoverColor;
}
fr.drawString(displayString, xPosition + (width - fr.getStringWidth(displayString)) / 2, yPosition + (height - 7) / 2, renderColor);
}
}
}
}

View file

@ -22,138 +22,147 @@ import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class GuiAdjustableTransformer extends GuiContainer
{
public class GuiAdjustableTransformer extends GuiContainer{
IInventory playerInventory;
public TEAdjustableTransformer tile;
private CButton buttons[] = new CButton[16];
private CButton dirButtons[] = new CButton[6];
private int xLoc;
private int yLoc;
private final int yOff = 30;
private static final String displayStrings[] = {"+1", "+10", "+64", "x2", "-1", "-10", "-64", "/2"};
private static final int GREEN = 0x55FF55;
private static final int GREENGLOW = Utils.multiplyColorComponents(GREEN, 0.16F);
private DecimalFormat fraction = new DecimalFormat("##0.00");
public GuiAdjustableTransformer(TEAdjustableTransformer tileentity)
{
public GuiAdjustableTransformer(TEAdjustableTransformer tileentity) {
super(new ContainerAdjustableTransformer(tileentity));
tile = tileentity;
xSize = 240; // The X size of the GUI window in pixels.
ySize = 140; // The Y size of the GUI window in pixels.
//Button definition - mouse over CButton for details
for (int i = 0; i < buttons.length; i++)
{
//16777120 old highlight color code, saved here for reference
// Button definition - mouse over CButton for details
for(int i = 0; i < buttons.length; i++){
// 16777120 old highlight color code, saved here for reference
buttons[i] = new CButton(i, 0, 0, 24, 13, 1, 192, 1, 207, displayStrings[i % 8], 4210752, 16777120, Info.GUI_TEX_ADJ_TRANSFORMER);
}
for (int i = 0; i < dirButtons.length; i++)
{
dirButtons[i] = new CButton(i + 16, 0, 0, 32, 13, 27, 192, 27, 207, I18n.format(Info.KEY_DIRECTION_NAMES[i]), 4210752, 16777120, Info.GUI_TEX_ADJ_TRANSFORMER);
for(int i = 0; i < dirButtons.length; i++){
dirButtons[i] = new CButton(i + 16, 0, 0, 32, 13, 27, 192, 27, 207, I18n.format(Info.KEY_DIRECTION_NAMES[i]), 4210752, 16777120,
Info.GUI_TEX_ADJ_TRANSFORMER);
}
}
@Override
public void initGui()
{
public void initGui(){
super.initGui(); // Don't forget this or MC will crash
// Upper left corner of GUI panel
xLoc = (width - xSize) / 2; // Half the difference between screen width and GUI width
yLoc = (height - ySize) / 2; // Half the difference between screen height and GUI height
for (int i = 0; i < 16; i++)
{
buttons[i].xPosition = xLoc + 8 + 24 * (i % 4);
xLoc = (width - xSize) / 2; // Half the difference between screen width
// and GUI width
yLoc = (height - ySize) / 2; // Half the difference between screen
// height and GUI height
for(int i = 0; i < 16; i++){
buttons[i].xPosition = xLoc + 8 + 24 * (i % 4);
buttons[i].yPosition = yLoc + yOff + 33 + 13 * (i / 4) + 17 * (i / 8);
}
for (int i = 0; i < 6; i++)
{
for(int i = 0; i < 6; i++){
dirButtons[i].xPosition = xLoc + 173;
dirButtons[i].yPosition = yLoc + yOff + 24 + 13 * i;
}
}
@Override
protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY)
{
protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY){
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
mc.renderEngine.bindTexture(new ResourceLocation(Info.TITLE_PACKED.toLowerCase(), Info.GUI_TEX_ADJ_TRANSFORMER));
// Draw GUI background graphic
drawTexturedModalRect(xLoc, yLoc, 0, 0, xSize, ySize);
// Draw title text
Utils.drawCenteredText(fontRendererObj, I18n.format(tile.getInvName()), width / 2, yLoc + 6, 4210752);
// Draw stats text
Utils.drawRightAlignedText(fontRendererObj, I18n.format(Info.KEY_STATS_AVERAGE_EU), xLoc + 180, yLoc + 26, 4210752);
Utils.drawRightAlignedText(fontRendererObj, I18n.format(Info.KEY_STATS_AVERAGE_INPUT), xLoc + 180, yLoc + 36, 4210752);
Utils.drawLeftAlignedText(fontRendererObj, I18n.format(Info.KEY_EU_BUFFERED), xLoc + 49, yLoc + 26, 4210752);
Utils.drawRightAlignedGlowingText(fontRendererObj, Integer.toString(tile.energyBuffer), xLoc + 44, yLoc + 26, GREEN, GREENGLOW);
// Factor of 100 because data is in fixed point (x100)
final float outAvg = (float)(((ContainerAdjustableTransformer)inventorySlots).outputAvg) / 100F;
final float inAvg = (float)(((ContainerAdjustableTransformer)inventorySlots).inputAvg) / 100F;
final float outAvg = (float) (((ContainerAdjustableTransformer) inventorySlots).outputAvg) / 100F;
final float inAvg = (float) (((ContainerAdjustableTransformer) inventorySlots).inputAvg) / 100F;
Utils.drawRightAlignedGlowingText(fontRendererObj, fraction.format(outAvg), xLoc + 230, yLoc + 26, GREEN, GREENGLOW);
Utils.drawRightAlignedGlowingText(fontRendererObj, fraction.format(inAvg), xLoc + 230, yLoc + 36, GREEN, GREENGLOW);
// Packet size section text
Utils.drawCenteredText(fontRendererObj, I18n.format(Info.KEY_EMITTER_PACKET), xLoc + 88, yLoc + yOff + 21, 0xB00000);
Utils.drawRightAlignedGlowingText(fontRendererObj, Integer.toString(tile.packetSize), xLoc + 146, yLoc + yOff + 49, GREEN, GREENGLOW);
fontRendererObj.drawString(Info.AE_PACKET_RANGE, xLoc + 110, yLoc + yOff + 35, 4210752);
fontRendererObj.drawString(I18n.format(Info.KEY_EU), xLoc + 152, yLoc + yOff + 49, 4210752);
// Transfer rate section text
Utils.drawCenteredText(fontRendererObj, I18n.format(Info.KEY_TRANSFORMER_OUTPUT), xLoc + 88, yLoc + yOff + 64, 0xB00000);
Utils.drawRightAlignedGlowingText(fontRendererObj, Integer.toString(tile.outputRate), xLoc + 146, yLoc + yOff + 92, GREEN, GREENGLOW);
fontRendererObj.drawString(Info.AE_OUTPUT_RANGE, xLoc + 110, yLoc + yOff + 78, 4210752);
fontRendererObj.drawString(I18n.format(Info.KEY_EU), xLoc + 152, yLoc + yOff + 92, 4210752);
// Side input/output settings text
for (int i = 0; i < 6; i++)
{
Utils.drawGlowingText(fontRendererObj, I18n.format((tile.sideSettings[i] & 1) == 0 ? Info.KEY_IN : Info.KEY_OUT), xLoc + 214, yLoc + yOff + 27 + 13 * i, GREEN, GREENGLOW);
for(int i = 0; i < 6; i++){
Utils.drawGlowingText(fontRendererObj, I18n.format((tile.sideSettings[i] & 1) == 0 ? Info.KEY_IN : Info.KEY_OUT), xLoc + 214, yLoc + yOff
+ 27 + 13 * i, GREEN, GREENGLOW);
}
//Buttons MUST be drawn after other texture stuff or it will not draw the battery meter correctly
for (CButton button : buttons)
{
// Buttons MUST be drawn after other texture stuff or it will not draw
// the battery meter correctly
for(CButton button : buttons){
button.drawButton(mc, mouseX, mouseY);
}
for (CButton button : dirButtons)
{
for(CButton button : dirButtons){
button.drawButton(mc, mouseX, mouseY);
}
}
@Override
protected void mouseClicked(int par1, int par2, int par3)
{
if (par3 == 0) // On a left click,
protected void mouseClicked(int par1, int par2, int par3){
if(par3 == 0) // On a left click,
{
for (CButton b : buttons) // For each item in buttons,
for(CButton b : buttons) // For each item in buttons,
{
if (b.enabled && b.mousePressed(this.mc, par1, par2)) // if it's enabled and was under the pointer,
if(b.enabled && b.mousePressed(this.mc, par1, par2)) // if it's
// enabled
// and
// was
// under
// the
// pointer,
{
//mc.sndManager.playSoundFX("random.click", 1.0F, 1.0F); // provide audio feedback,
tile.sendGuiButton(b.id); // and inform the server of the button click.
// mc.sndManager.playSoundFX("random.click", 1.0F, 1.0F); //
// provide audio feedback,
tile.sendGuiButton(b.id); // and inform the server of the
// button click.
}
}
for (CButton b : dirButtons)
{
if (b.enabled && b.mousePressed(this.mc, par1, par2)) // if it's enabled and was under the pointer,
for(CButton b : dirButtons){
if(b.enabled && b.mousePressed(this.mc, par1, par2)) // if it's
// enabled
// and
// was
// under
// the
// pointer,
{
//mc.sndManager.playSoundFX("random.click", 1.0F, 1.0F); // provide audio feedback,
tile.sendGuiButton(b.id); // and inform the server of the button click.
// mc.sndManager.playSoundFX("random.click", 1.0F, 1.0F); //
// provide audio feedback,
tile.sendGuiButton(b.id); // and inform the server of the
// button click.
}
}
}
super.mouseClicked(par1, par2, par3); // Finally, do all that other normal stuff.
super.mouseClicked(par1, par2, par3); // Finally, do all that other
// normal stuff.
}
}

View file

@ -20,96 +20,100 @@ import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class GuiAdvEmitter extends GuiContainer
{
public class GuiAdvEmitter extends GuiContainer{
IInventory playerInventory;
public TEAdvEmitter tile;
private CButton buttons[] = new CButton[16];
private int xLoc;
private int yLoc;
private static final String displayStrings[] = {"+1", "+10", "+64", "x2", "-1", "-10", "-64", "/2"};
private static final int GREEN = 0x55FF55;
private static final int GREENGLOW = Utils.multiplyColorComponents(GREEN, 0.16F);
public GuiAdvEmitter(TEAdvEmitter tileentity)
{
public GuiAdvEmitter(TEAdvEmitter tileentity) {
super(new ContainerAdvEmitter(tileentity));
tile = tileentity;
xSize = 176; // The X size of the GUI window in pixels.
ySize = 110; // The Y size of the GUI window in pixels.
//Button definition - mouse over CButton for details
for (int i = 0; i < buttons.length; i++)
{
//16777120 old highlight color code, saved here for reference
// Button definition - mouse over CButton for details
for(int i = 0; i < buttons.length; i++){
// 16777120 old highlight color code, saved here for reference
buttons[i] = new CButton(i, 0, 0, 24, 13, 1, 192, 1, 207, displayStrings[i % 8], 4210752, 16777120, Info.GUI_TEX_EMITTER);
}
}
@Override
public void initGui()
{
public void initGui(){
super.initGui(); // Don't forget this or MC will crash
// Upper left corner of GUI panel
xLoc = (width - xSize) / 2; // Half the difference between screen width and GUI width
yLoc = (height - ySize) / 2; // Half the difference between screen height and GUI height
for (int i = 0; i < 16; i++)
{
buttons[i].xPosition = xLoc + 8 + 24 * (i % 4);
xLoc = (width - xSize) / 2; // Half the difference between screen width
// and GUI width
yLoc = (height - ySize) / 2; // Half the difference between screen
// height and GUI height
for(int i = 0; i < 16; i++){
buttons[i].xPosition = xLoc + 8 + 24 * (i % 4);
buttons[i].yPosition = yLoc + 33 + 13 * (i / 4) + 17 * (i / 8);
}
}
@Override
protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY)
{
protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY){
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
mc.renderEngine.bindTexture(new ResourceLocation(Info.TITLE_PACKED.toLowerCase(), Info.GUI_TEX_EMITTER));
// Draw GUI background graphic
drawTexturedModalRect(xLoc, yLoc, 0, 0, xSize, ySize);
// Draw title text
Utils.drawCenteredText(fontRendererObj, I18n.format(tile.getInvName()), width / 2, yLoc + 7, 4210752);
// Packet size section text
Utils.drawCenteredText(fontRendererObj, I18n.format(Info.KEY_EMITTER_PACKET), width / 2, yLoc + 21, 0xB00000);
Utils.drawRightAlignedGlowingText(fontRendererObj, Integer.toString(tile.packetSize), xLoc + 146, yLoc + 49, GREEN, GREENGLOW);
fontRendererObj.drawString(Info.AE_PACKET_RANGE, xLoc + 110, yLoc + 35, 4210752);
fontRendererObj.drawString(I18n.format(Info.KEY_EU), xLoc + 152, yLoc + 49, 4210752);
// Output rate section text
Utils.drawCenteredText(fontRendererObj, I18n.format(Info.KEY_EMITTER_OUTPUT), width / 2, yLoc + 64, 0xB00000);
Utils.drawRightAlignedGlowingText(fontRendererObj, Integer.toString(tile.outputRate), xLoc + 146, yLoc + 92, GREEN, GREENGLOW);
fontRendererObj.drawString(Info.AE_OUTPUT_RANGE, xLoc + 110, yLoc + 78, 4210752);
fontRendererObj.drawString(I18n.format(Info.KEY_EU), xLoc + 152, yLoc + 92, 4210752);
//Buttons MUST be drawn after other texture stuff or it will not draw the battery meter correctly
for (CButton button : buttons)
{
// Buttons MUST be drawn after other texture stuff or it will not draw
// the battery meter correctly
for(CButton button : buttons){
button.drawButton(mc, mouseX, mouseY);
}
}
@Override
protected void mouseClicked(int par1, int par2, int par3)
{
if (par3 == 0) // On a left click,
protected void mouseClicked(int par1, int par2, int par3){
if(par3 == 0) // On a left click,
{
for (CButton b : buttons) // For each item in buttons,
for(CButton b : buttons) // For each item in buttons,
{
if (b.enabled && b.mousePressed(this.mc, par1, par2)) // if it's enabled and was under the pointer,
if(b.enabled && b.mousePressed(this.mc, par1, par2)) // if it's
// enabled
// and
// was
// under
// the
// pointer,
{
//mc.sndManager.playSoundFX("random.click", 1.0F, 1.0F); // provide audio feedback,
tile.sendGuiButton(b.id); // and inform the server of the button click.
// mc.sndManager.playSoundFX("random.click", 1.0F, 1.0F); //
// provide audio feedback,
tile.sendGuiButton(b.id); // and inform the server of the
// button click.
}
}
}
super.mouseClicked(par1, par2, par3); // Finally, do all that other normal stuff.
super.mouseClicked(par1, par2, par3); // Finally, do all that other
// normal stuff.
}
}

View file

@ -23,120 +23,123 @@ import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class GuiBatteryStation extends GuiContainer
{
public class GuiBatteryStation extends GuiContainer{
IInventory playerInventory;
public TEBatteryStation tile;
private CButton button;
private int mode = -1;
private int xLoc;
private int yLoc;
private int xCenter;
private DecimalFormat fraction = new DecimalFormat("##0.00");
private DecimalFormat time = new DecimalFormat("00");
private DecimalFormat days = new DecimalFormat("#0");
private DecimalFormat dayFrac = new DecimalFormat("0.#");
private static final int GREEN = 0x55FF55;
private static final int GREENGLOW = Utils.multiplyColorComponents(GREEN, 0.16F);
public GuiBatteryStation(InventoryPlayer player, TEBatteryStation tileentity)
{
public GuiBatteryStation(InventoryPlayer player, TEBatteryStation tileentity) {
super(new ContainerBatteryStation(player, tileentity));
tile = tileentity;
xSize = 176; // The X size of the GUI window in pixels.
ySize = 182; // The Y size of the GUI window in pixels.
button = new CButton(0, 0, 0, 18, 12, 30, 200, 30, 200, "", 4210752, 16777120, Info.GUI_TEX_BATTERY_STATION);
}
@Override
public void initGui()
{
public void initGui(){
super.initGui(); // Don't forget this or MC will crash
// Upper left corner of GUI panel
xLoc = (width - xSize) / 2; // Half the difference between screen width and GUI width
yLoc = (height - ySize) / 2; // Half the difference between screen height and GUI height
xLoc = (width - xSize) / 2; // Half the difference between screen width
// and GUI width
yLoc = (height - ySize) / 2; // Half the difference between screen
// height and GUI height
xCenter = width / 2;
button.xPosition = xLoc + 16;
button.yPosition = yLoc + 44;
mode = -1;
}
@Override
protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY)
{
protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY){
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
mc.renderEngine.bindTexture(new ResourceLocation(Info.TITLE_PACKED.toLowerCase(), Info.GUI_TEX_BATTERY_STATION));
this.drawTexturedModalRect(xLoc, yLoc, 0, 0, xSize, ySize);
// Draw title text
Utils.drawCenteredText(fontRendererObj, I18n.format(tile.getInventoryName()), xCenter, yLoc + 8, 4210752);
if (mode != ((ContainerBatteryStation)inventorySlots).opMode)
{
mode = ((ContainerBatteryStation)inventorySlots).opMode;
if (mode == 0)
{
if(mode != ((ContainerBatteryStation) inventorySlots).opMode){
mode = ((ContainerBatteryStation) inventorySlots).opMode;
if(mode == 0){
button.vLoc = 200;
button.vHoverLoc = 200;
}
else
{
}else{
button.vLoc = 185;
button.vHoverLoc = 185;
}
}
Utils.drawLeftAlignedText(fontRendererObj, I18n.format(Info.KEY_DISCHARGER_MODE_LINE1), xLoc + 7, yLoc + 59, 4210752);
Utils.drawLeftAlignedText(fontRendererObj, I18n.format(Info.KEY_DISCHARGER_MODE_LINE2), xLoc + 7, yLoc + 70, 4210752);
Utils.drawCenteredText(fontRendererObj, I18n.format(Info.KEY_STATS_AVERAGE_EU), xLoc + 144, yLoc + 27, 4210752);
Utils.drawCenteredText(fontRendererObj, I18n.format(Info.KEY_STATS_TIME_REMAINING), xLoc + 144, yLoc + 65, 4210752);
// Factor of 100 because data is in fixed point (x100)
final float rate = (float)(((ContainerBatteryStation)inventorySlots).average) / 100F;
final float rate = (float) (((ContainerBatteryStation) inventorySlots).average) / 100F;
Utils.drawRightAlignedGlowingText(fontRendererObj, fraction.format(rate), xLoc + 166, yLoc + 41, GREEN, GREENGLOW);
String clock;
if (rate > 0)
{
if(rate > 0){
// Rate * 20 to convert per tick to per second
int timeScratch = (int)((float)(((ContainerBatteryStation)inventorySlots).itemsEnergyTotal) / (rate * 20));
if (timeScratch <= 345600) // 60 * 60 * 96 or 4 days
int timeScratch = (int) ((float) (((ContainerBatteryStation) inventorySlots).itemsEnergyTotal) / (rate * 20));
if(timeScratch <= 345600) // 60 * 60 * 96 or 4 days
{
final int sec = timeScratch % 60;
timeScratch /= 60;
final int min = timeScratch % 60;
timeScratch /= 60;
clock = time.format(timeScratch) + ":" + time.format(min) + ":" + time.format(sec);
}else{
float dayScratch = ((float) timeScratch) / 86400F; // 60 * 60 *
// 24 or 1
// day
clock = (dayScratch < 10F ? dayFrac.format(dayScratch) : dayScratch < 100 ? days.format((int) dayScratch) : "??")
+ I18n.format(Info.KEY_STATS_DISPLAY_DAYS);
}
else
{
float dayScratch = ((float)timeScratch) / 86400F; // 60 * 60 * 24 or 1 day
clock = (dayScratch < 10F ? dayFrac.format(dayScratch) : dayScratch < 100 ? days.format((int)dayScratch) : "??") + I18n.format(Info.KEY_STATS_DISPLAY_DAYS);
}
}
else clock = I18n.format(Info.KEY_STATS_DISPLAY_UNKNOWN);
}else
clock = I18n.format(Info.KEY_STATS_DISPLAY_UNKNOWN);
Utils.drawRightAlignedGlowingText(fontRendererObj, clock, xLoc + 166, yLoc + 51, GREEN, GREENGLOW);
button.drawButton(mc, mouseX, mouseY);
}
@Override
protected void mouseClicked(int par1, int par2, int par3)
{
if (par3 == 0) // On a left click,
protected void mouseClicked(int par1, int par2, int par3){
if(par3 == 0) // On a left click,
{
if (button.enabled && button.mousePressed(this.mc, par1, par2)) // if it's enabled and was under the pointer,
if(button.enabled && button.mousePressed(this.mc, par1, par2)) // if
// it's
// enabled
// and
// was
// under
// the
// pointer,
{
//mc.sndManager.playSoundFX("random.click", 1.0F, 1.0F); // provide audio feedback,
tile.sendGuiButton(button.id); // and inform the server of the button click.
// mc.sndManager.playSoundFX("random.click", 1.0F, 1.0F); //
// provide audio feedback,
tile.sendGuiButton(button.id); // and inform the server of the
// button click.
}
}
super.mouseClicked(par1, par2, par3); // Finally, do all that other normal stuff.
super.mouseClicked(par1, par2, par3); // Finally, do all that other
// normal stuff.
}
}

View file

@ -23,106 +23,106 @@ import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class GuiChargingBench extends GuiContainer
{
public class GuiChargingBench extends GuiContainer{
IInventory playerInventory;
public TEChargingBench tile;
private int xLoc;
private int yLoc;
private int xCenter;
private DecimalFormat fraction = new DecimalFormat("##0.00");
private DecimalFormat time = new DecimalFormat("00");
private DecimalFormat days = new DecimalFormat("#0");
private DecimalFormat dayFrac = new DecimalFormat("0.#");
private static final int GREEN = 0x55FF55;
private static final int GREENGLOW = Utils.multiplyColorComponents(GREEN, 0.16F);
public GuiChargingBench(InventoryPlayer player, TEChargingBench tileentity)
{
public GuiChargingBench(InventoryPlayer player, TEChargingBench tileentity) {
super(new ContainerChargingBench(player, tileentity));
tile = tileentity;
xSize = 176; // The X size of the GUI window in pixels.
ySize = 226; // The Y size of the GUI window in pixels.
}
@Override
public void initGui()
{
public void initGui(){
super.initGui(); // Don't forget this or MC will crash
// Upper left corner of GUI panel
xLoc = (width - xSize) / 2; // Half the difference between screen width and GUI width
yLoc = (height - ySize) / 2; // Half the difference between screen height and GUI height
xLoc = (width - xSize) / 2; // Half the difference between screen width
// and GUI width
yLoc = (height - ySize) / 2; // Half the difference between screen
// height and GUI height
xCenter = width / 2;
}
@Override
protected void drawGuiContainerBackgroundLayer(float var1, int var2, int var3)
{
protected void drawGuiContainerBackgroundLayer(float var1, int var2, int var3){
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
mc.renderEngine.bindTexture(new ResourceLocation(Info.TITLE_PACKED.toLowerCase(), Info.GUI_TEX_CHARGING_BENCH));
// Draw GUI background
drawTexturedModalRect(xLoc, yLoc, 0, 0, xSize, ySize);
// Energy bar
if (tile.currentEnergy > 0)
{
// Make each box light up all at once like a LED instead of gradually using barLength = tile.gaugeEnergyScaled(66);
if(tile.currentEnergy > 0){
// Make each box light up all at once like a LED instead of
// gradually using barLength = tile.gaugeEnergyScaled(66);
int barLength = 5 * tile.gaugeEnergyScaled(13);
if (barLength > 0) barLength++;
if(barLength > 0)
barLength++;
drawTexturedModalRect(xLoc + 32, yLoc + 136 - barLength, 176, 66 - barLength, 12, barLength);
}
// Redstone power indicator
drawTexturedModalRect(xLoc + 129, yLoc + 48, tile.receivingRedstoneSignal() ? 188 : 206, 0, 18, 15);
// Draw labels
Utils.drawCenteredText(fontRendererObj, I18n.format(tile.getInventoryName()), xCenter, yLoc + 7, 4210752);
Utils.drawRightAlignedText(fontRendererObj, I18n.format(Info.KEY_EU), xLoc + 25, yLoc + 23, 4210752);
Utils.drawLeftAlignedText(fontRendererObj, I18n.format(Info.KEY_CHARGER_MAX), xLoc + 151, yLoc + 23, 4210752);
Utils.drawRightAlignedText(fontRendererObj, I18n.format(Info.KEY_CHARGER_REQ), xLoc + 25, yLoc + 33, 4210752);
Utils.drawLeftAlignedText(fontRendererObj, I18n.format(Info.KEY_CHARGER_ETC), xLoc + 151, yLoc + 33, 4210752);
Utils.drawRightAlignedText(fontRendererObj, I18n.format(Info.KEY_CHARGER_AVG), xLoc + 70, yLoc + 52, 4210752);
Utils.drawLeftAlignedText(fontRendererObj, I18n.format(Info.KEY_CHARGER_PWR), xLoc + 151, yLoc + 52, 4210752);
// Draw current and max storage
Utils.drawRightAlignedGlowingText(fontRendererObj, Integer.toString(tile.currentEnergy), xCenter - 7, yLoc + 23, GREEN, GREENGLOW);
Utils.drawGlowingText(fontRendererObj, " / " + Integer.toString(tile.adjustedStorage), xCenter - 7, yLoc + 23, GREEN, GREENGLOW);
// Factor of 100 because data is in fixed point (x100)
final float rate = (float)(((ContainerChargingBench)inventorySlots).averageInput) / 100F;
final float rate = (float) (((ContainerChargingBench) inventorySlots).averageInput) / 100F;
Utils.drawRightAlignedGlowingText(fontRendererObj, fraction.format(rate), xLoc + 122, yLoc + 52, GREEN, GREENGLOW);
// Charging stats (only displayed while charging items)
if (tile.energyRequired > 0)
{
if(tile.energyRequired > 0){
final String clock;
if (tile.ticksRequired > 0)
{
if(tile.ticksRequired > 0){
int timeScratch = tile.ticksRequired / 20;
if (timeScratch <= 345600) // 60 * 60 * 96 or 4 days
if(timeScratch <= 345600) // 60 * 60 * 96 or 4 days
{
final int sec = timeScratch % 60;
timeScratch /= 60;
final int min = timeScratch % 60;
timeScratch /= 60;
clock = time.format(timeScratch) + ":" + time.format(min) + ":" + time.format(sec);
}else{
float dayScratch = ((float) timeScratch) / 86400F; // 60 *
// 60 *
// 24 or
// 1 day
clock = (dayScratch < 10F ? dayFrac.format(dayScratch) : dayScratch < 100 ? days.format((int) dayScratch) : "??")
+ I18n.format(Info.KEY_STATS_DISPLAY_DAYS);
}
else
{
float dayScratch = ((float)timeScratch) / 86400F; // 60 * 60 * 24 or 1 day
clock = (dayScratch < 10F ? dayFrac.format(dayScratch) : dayScratch < 100 ? days.format((int)dayScratch) : "??") + I18n.format(Info.KEY_STATS_DISPLAY_DAYS);
}
}
else clock = I18n.format(Info.KEY_STATS_DISPLAY_UNKNOWN);
final String energyReq = tile.energyRequired > 9999999 ? dayFrac.format(((float)tile.energyRequired) / 1000000F) + "M" : Integer.toString(tile.energyRequired);
}else
clock = I18n.format(Info.KEY_STATS_DISPLAY_UNKNOWN);
final String energyReq = tile.energyRequired > 9999999 ? dayFrac.format(((float) tile.energyRequired) / 1000000F) + "M" : Integer
.toString(tile.energyRequired);
Utils.drawRightAlignedGlowingText(fontRendererObj, energyReq, xCenter - 7, yLoc + 33, GREEN, GREENGLOW);
Utils.drawRightAlignedGlowingText(fontRendererObj, clock, xLoc + 144, yLoc + 33, GREEN, GREENGLOW);
}

View file

@ -21,126 +21,130 @@ import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class GuiStorageMonitor extends GuiContainer
{
public class GuiStorageMonitor extends GuiContainer{
IInventory playerInventory;
public TEStorageMonitor tile;
private CButton buttons[] = new CButton[8];
private int xLoc;
private int yLoc;
private static final String DISPLAYSTRINGS[] = {"-10", "-1", "+1", "+10"};
private static final int HORIZONTALOFFSETS[] = {-57, -33, 25, 49};
private static final int RED = 0xFF5555;
private static final int GREEN = 0x55FF55;
private static final int REDGLOW = Utils.multiplyColorComponents(RED, 0.16F);
private static final int GREENGLOW = Utils.multiplyColorComponents(GREEN, 0.16F);
public GuiStorageMonitor(InventoryPlayer player, TEStorageMonitor tileentity)
{
public GuiStorageMonitor(InventoryPlayer player, TEStorageMonitor tileentity) {
super(new ContainerStorageMonitor(player, tileentity));
tile = tileentity;
xSize = 176; // The X size of the GUI window in pixels.
ySize = 190; // The Y size of the GUI window in pixels.
//Button definition - mouse over CButton for details
for (int i = 0; i < buttons.length; i++)
{
//16777120 old highlight color code, saved here for reference
// Button definition - mouse over CButton for details
for(int i = 0; i < buttons.length; i++){
// 16777120 old highlight color code, saved here for reference
buttons[i] = new CButton(i, 0, 0, 24, 13, 1, 192, 1, 207, DISPLAYSTRINGS[i % 4], 4210752, 0xFFFFAF, Info.GUI_TEX_STORAGE_MONITOR);
}
}
@Override
public void initGui()
{
public void initGui(){
super.initGui(); // Don't forget this or MC will crash
// Upper left corner of GUI panel
xLoc = (width - xSize) / 2; // Half the difference between screen width and GUI width
yLoc = (height - ySize) / 2; // Half the difference between screen height and GUI height
xLoc = (width - xSize) / 2; // Half the difference between screen width
// and GUI width
yLoc = (height - ySize) / 2; // Half the difference between screen
// height and GUI height
// Reposition buttons
for (int i = 0; i < 8; i++)
{
for(int i = 0; i < 8; i++){
buttons[i].xPosition = width / 2 + HORIZONTALOFFSETS[i % 4];
buttons[i].yPosition = yLoc + 60 + 29 * (i / 4);
}
}
@Override
protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY)
{
protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY){
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
mc.renderEngine.bindTexture(new ResourceLocation(Info.TITLE_PACKED.toLowerCase(), Info.GUI_TEX_STORAGE_MONITOR));
// Draw GUI background
drawTexturedModalRect(xLoc, yLoc, 0, 0, xSize, ySize);
// Draw energy meter
if (tile.energyStored > 0)
{
if(tile.energyStored > 0){
// Which color energy meter should be used?
final int offset = tile.isPowering ? 12 : 0;
// Make each box light up all at once like a LED instead of gradually using barLength = this.tile.gaugeEnergyScaled(66);
// Make each box light up all at once like a LED instead of
// gradually using barLength = this.tile.gaugeEnergyScaled(66);
int barLength = 5 * tile.gaugeEnergyScaled(13);
if (barLength > 0) barLength++;
if(barLength > 0)
barLength++;
drawTexturedModalRect(xLoc + 10, yLoc + 100 - barLength, 176 + offset, 66 - barLength, 12, barLength);
}
// Draw title text
Utils.drawCenteredText(fontRendererObj, I18n.format(tile.getInventoryName()), xLoc + 96, yLoc + 12, 4210752);
if (tile.energyCapacity <= 0)
{
if(tile.energyCapacity <= 0){
// Error message: No card or storage unit not found
Utils.drawCenteredGlowingText(fontRendererObj, I18n.format(Info.KEY_MONITOR_INVALID), xLoc + 96, yLoc + 35, RED, REDGLOW);
}
else
{
}else{
// Draw right-aligned current energy number
Utils.drawRightAlignedGlowingText(fontRendererObj, Integer.toString(tile.energyStored), xLoc + 90, yLoc + 35, GREEN, GREENGLOW);
// Draw separator and left-aligned max energy number
Utils.drawGlowingText(fontRendererObj, " / " + Integer.toString(tile.energyCapacity), xLoc + 90, yLoc + 35, GREEN, GREENGLOW);
// Test strings
//Utils.drawCenteredGlowingText(fontRenderer, " / ", xLoc + 96, yLoc + 35, 0x55FF55, glowFactor);
//Utils.drawRightAlignedGlowingText(fontRenderer, "123456789", xLoc + 90, yLoc + 35, 0x55FF55, 0.15F);
//Utils.drawGlowingText(fontRenderer, " / 123456789", xLoc + 90, yLoc + 35, 0x55FF55, 0.15F);
// Utils.drawCenteredGlowingText(fontRenderer, " / ", xLoc + 96,
// yLoc + 35, 0x55FF55, glowFactor);
// Utils.drawRightAlignedGlowingText(fontRenderer, "123456789", xLoc
// + 90, yLoc + 35, 0x55FF55, 0.15F);
// Utils.drawGlowingText(fontRenderer, " / 123456789", xLoc + 90,
// yLoc + 35, 0x55FF55, 0.15F);
}
// Draw control section labels and readouts
Utils.drawCenteredText(fontRendererObj, I18n.format(Info.KEY_MONITOR_UPPER), xLoc + 96, yLoc + 49, 0xB00000);
Utils.drawRightAlignedGlowingText(fontRendererObj, Integer.toString(tile.upperBoundary) + "%", xLoc + 109, yLoc + 63, GREEN, GREENGLOW);
Utils.drawCenteredText(fontRendererObj, I18n.format(Info.KEY_MONITOR_LOWER), xLoc + 96, yLoc + 78, 0xB00000);
Utils.drawRightAlignedGlowingText(fontRendererObj, Integer.toString(tile.lowerBoundary) + "%", xLoc + 109, yLoc + 92, GREEN, GREENGLOW);
for (CButton button : /* Who's got the */ buttons)
{
for(CButton button : /* Who's got the */buttons){
// Draw ALL of the things?! :o
button.drawButton(mc, mouseX, mouseY);
}
}
@Override
protected void mouseClicked(int par1, int par2, int par3)
{
if (par3 == 0) // On a left click,
protected void mouseClicked(int par1, int par2, int par3){
if(par3 == 0) // On a left click,
{
for (CButton b : buttons) // For each item in buttons,
for(CButton b : buttons) // For each item in buttons,
{
if (b.enabled && b.mousePressed(this.mc, par1, par2)) // if it's enabled and was under the pointer,
if(b.enabled && b.mousePressed(this.mc, par1, par2)) // if it's
// enabled
// and
// was
// under
// the
// pointer,
{
//mc.sndManager.playSoundFX("random.click", 1.0F, 1.0F); // provide audio feedback,
tile.sendGuiButton(b.id); // and inform the server of the button click.
// mc.sndManager.playSoundFX("random.click", 1.0F, 1.0F); //
// provide audio feedback,
tile.sendGuiButton(b.id); // and inform the server of the
// button click.
}
}
}
super.mouseClicked(par1, par2, par3); // Finally, do all that other normal stuff.
super.mouseClicked(par1, par2, par3); // Finally, do all that other
// normal stuff.
}
}

View file

@ -24,13 +24,11 @@ import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ItemBenchTools extends Item
{
public class ItemBenchTools extends Item{
public static final String[] benchToolsNames = new String[] {"toolkit", "LV-kit", "MV-kit", "HV-kit"};
protected IIcon[] itemIcons;
public ItemBenchTools(String name)
{
public ItemBenchTools(String name) {
super();
this.setHasSubtypes(true);
this.setMaxDamage(0);
@ -38,27 +36,25 @@ public class ItemBenchTools extends Item
this.setCreativeTab(CreativeTabs.tabMisc);
GameRegistry.registerItem(this, name);
}
/**
* Gets an icon based on an item's damage value
*/
@Override
@SideOnly(Side.CLIENT)
public IIcon getIconFromDamage(int par1)
{
public IIcon getIconFromDamage(int par1){
return itemIcons[MathHelper.clamp_int(par1, 0, 3)];
}
@Override
public void registerIcons(IIconRegister iconRegister)
{
@Override
public void registerIcons(IIconRegister iconRegister){
itemIcons = new IIcon[benchToolsNames.length];
for (int i = 0; i < itemIcons.length; i++)
{
for(int i = 0; i < itemIcons.length; i++){
itemIcons[i] = iconRegister.registerIcon(Info.TITLE_PACKED + ":" + benchToolsNames[i]);
}
// Until/unless a better way is found, register GUI slot backgrounds here.
// Until/unless a better way is found, register GUI slot backgrounds
// here.
Info.iconSlotChargeable = iconRegister.registerIcon(Info.TITLE_PACKED + ":SlotChargeable");
Info.iconSlotDrainable = iconRegister.registerIcon(Info.TITLE_PACKED + ":SlotDrainable");
Info.iconSlotInput = iconRegister.registerIcon(Info.TITLE_PACKED + ":SlotInput");
@ -67,75 +63,78 @@ public class ItemBenchTools extends Item
Info.iconSlotLinkCard = iconRegister.registerIcon(Info.TITLE_PACKED + ":SlotLinkCard");
Info.iconSlotPowerSource = new IIcon[3];
Info.iconSlotPlayerArmor = new IIcon[4];
for (int i = 0; i < 3; i++)
for(int i = 0; i < 3; i++)
Info.iconSlotPowerSource[i] = iconRegister.registerIcon(Info.TITLE_PACKED + ":SlotPowerSource" + Integer.toString(i));
for (int i = 0; i < 4; i++)
for(int i = 0; i < 4; i++)
Info.iconSlotPlayerArmor[i] = iconRegister.registerIcon(Info.TITLE_PACKED + ":SlotPlayerArmor" + Integer.toString(i));
}
}
@Override
public boolean isRepairable()
{
public boolean isRepairable(){
return false;
}
@Override
public String getUnlocalizedName(ItemStack par1ItemStack)
{
public String getUnlocalizedName(ItemStack par1ItemStack){
int meta = MathHelper.clamp_int(par1ItemStack.getItemDamage(), 0, 3);
return "item.benchTools." + benchToolsNames[meta];
}
protected void generateItemStack(ItemStack stack, EntityPlayer player)
{
protected void generateItemStack(ItemStack stack, EntityPlayer player){
EntityItem entityitem = player.dropPlayerItemWithRandomChoice(stack, false);
entityitem.delayBeforeCanPickup = 0;
}
/**
* This is called when the item is used, before the block is activated.
* @param stack The Item Stack
* @param player The Player that used the item
* @param world The Current World
* @param x Target X Position
* @param y Target Y Position
* @param z Target Z Position
* @param side The side of the target hit
*
* @param stack
* The Item Stack
* @param player
* The Player that used the item
* @param world
* The Current World
* @param x
* Target X Position
* @param y
* Target Y Position
* @param z
* Target Z Position
* @param side
* The side of the target hit
* @return Return true to prevent any further processing.
*/
@Override
public boolean onItemUseFirst(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ)
{
if (AdvancedPowerManagement.proxy.isClient()) return false;
// Test if the target is a charging bench and the item is a component kit. If so, do the upgrade and return true.
if (world.getBlock(x, y, z) != AdvancedPowerManagement.blockAdvPwrMan || stack.getItemDamage() < 1 || stack.getItemDamage() > 3 || player == null)
{
public boolean onItemUseFirst(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ){
if(AdvancedPowerManagement.proxy.isClient())
return false;
// Test if the target is a charging bench and the item is a component
// kit. If so, do the upgrade and return true.
if(world.getBlock(x, y, z) != AdvancedPowerManagement.blockAdvPwrMan || stack.getItemDamage() < 1 || stack.getItemDamage() > 3
|| player == null){
return false;
}
TileEntity tile = world.getTileEntity(x, y, z);
if (!(tile instanceof TEChargingBench))
{
if(!(tile instanceof TEChargingBench)){
return false;
}
int recoveredTier = ((TEChargingBench)tile).swapBenchComponents(stack.getItemDamage());
int recoveredTier = ((TEChargingBench) tile).swapBenchComponents(stack.getItemDamage());
generateItemStack(new ItemStack(AdvancedPowerManagement.itemBenchTools, 1, recoveredTier), player);
stack.stackSize--;
return true;
}
/**
* Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer
* Called whenever this item is equipped and the right mouse button is
* pressed. Args: itemStack, world, entityPlayer
*/
@Override
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player)
{
if (player.isSneaking() && stack.getItemDamage() > 0 && stack.getItemDamage() < 4)
{
switch (stack.getItemDamage())
{
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player){
if(player.isSneaking() && stack.getItemDamage() > 0 && stack.getItemDamage() < 4){
switch(stack.getItemDamage()){
case 1:
generateItemStack(Info.componentCopperCable.copy(), player);
generateItemStack(Info.componentBatBox.copy(), player);
@ -154,16 +153,15 @@ public class ItemBenchTools extends Item
}
return stack;
}
/**
* returns a list of items with the same ID, but different meta (eg: dye returns 16 items)
* returns a list of items with the same ID, but different meta (eg: dye
* returns 16 items)
*/
@Override
@SideOnly(Side.CLIENT)
public void getSubItems(Item par1, CreativeTabs par2CreativeTabs, List par3List)
{
for (int meta = 0; meta < 4; ++meta)
{
public void getSubItems(Item par1, CreativeTabs par2CreativeTabs, List par3List){
for(int meta = 0; meta < 4; ++meta){
par3List.add(new ItemStack(par1, 1, meta));
}
}

View file

@ -4,35 +4,31 @@
******************************************************************************/
package com.kaijin.AdvPowerMan.items;
import com.kaijin.AdvPowerMan.Info;
import net.minecraft.block.Block;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
public class ItemBlockAdvPwrMan extends ItemBlock
{
public ItemBlockAdvPwrMan(Block block)
{
public class ItemBlockAdvPwrMan extends ItemBlock{
public ItemBlockAdvPwrMan(Block block) {
super(block);
this.setMaxDamage(0);
this.setHasSubtypes(true);
}
public int getMetadata(int meta)
{
//if (meta >= 3 && meta <= 6) return 7;
public int getMetadata(int meta){
// if (meta >= 3 && meta <= 6) return 7;
return meta;
}
@Override
public String getUnlocalizedName(ItemStack var1)
{
public String getUnlocalizedName(ItemStack var1){
int var2 = var1.getItemDamage();
if (var2 >= 0 && var2 <= Info.LAST_META_VALUE) return Info.KEY_BLOCK_NAMES[var2];
if(var2 >= 0 && var2 <= Info.LAST_META_VALUE)
return Info.KEY_BLOCK_NAMES[var2];
return null;
}
}

View file

@ -11,71 +11,57 @@ import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
public class ItemCardBase extends Item
{
protected ItemCardBase(String name)
{
public class ItemCardBase extends Item{
protected ItemCardBase(String name) {
super();
setUnlocalizedName(name);
GameRegistry.registerItem(this, name);
}
@Override
public boolean isRepairable()
{
public boolean isRepairable(){
return false;
}
public static int[] getCoordinates(ItemStack itemStack)
{
if (!(itemStack.getItem() instanceof ItemStorageLinkCard))
public static int[] getCoordinates(ItemStack itemStack){
if(!(itemStack.getItem() instanceof ItemStorageLinkCard))
return null;
NBTTagCompound nbtTagCompound = itemStack.getTagCompound();
if (nbtTagCompound == null)
{
if(nbtTagCompound == null){
return null;
}
int[] coordinates = new int[]{
nbtTagCompound.getInteger("x"),
nbtTagCompound.getInteger("y"),
nbtTagCompound.getInteger("z"),
nbtTagCompound.getInteger("dim")
};
int[] coordinates = new int[] {nbtTagCompound.getInteger("x"), nbtTagCompound.getInteger("y"), nbtTagCompound.getInteger("z"),
nbtTagCompound.getInteger("dim")};
return coordinates;
}
public static void setCoordinates(ItemStack itemStack, int[] coords)
{
public static void setCoordinates(ItemStack itemStack, int[] coords){
final String tags[] = {"x", "y", "z", "dim"};
NBTTagCompound nbtTagCompound = Utils.getOrCreateStackTag(itemStack);
for (int i = 0; i < coords.length && i < 4; i++)
{
for(int i = 0; i < coords.length && i < 4; i++){
nbtTagCompound.setInteger(tags[i], coords[i]);
}
}
public static void setCoordinates(ItemStack itemStack, int x, int y, int z, int dim)
{
public static void setCoordinates(ItemStack itemStack, int x, int y, int z, int dim){
NBTTagCompound nbtTagCompound = Utils.getOrCreateStackTag(itemStack);
nbtTagCompound.setInteger("x", x);
nbtTagCompound.setInteger("y", y);
nbtTagCompound.setInteger("z", z);
nbtTagCompound.setInteger("dim", dim);
}
public String getTitle(ItemStack stack)
{
if (!(stack.getItem() instanceof ItemStorageLinkCard))
public String getTitle(ItemStack stack){
if(!(stack.getItem() instanceof ItemStorageLinkCard))
return "";
NBTTagCompound nbtTagCompound = stack.getTagCompound();
if (nbtTagCompound == null)
if(nbtTagCompound == null)
return "";
return nbtTagCompound.getString("title");
}
public void setTitle(ItemStack stack, String title)
{
public void setTitle(ItemStack stack, String title){
Utils.getOrCreateStackTag(stack).setString("title", title);
}
}

View file

@ -17,58 +17,50 @@ import net.minecraft.world.World;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ItemStorageLinkCard extends ItemCardBase
{
public class ItemStorageLinkCard extends ItemCardBase{
private static final String HINT_TEMPLATE = "X: %d, Y: %d, Z: %d, Dim: %d";
public ItemStorageLinkCard(String name)
{
public ItemStorageLinkCard(String name) {
super(name);
setMaxStackSize(1);
setTextureName(Info.TITLE_PACKED + ":LinkCard");
// This shouldn't be easily spawnable, so don't show in creative tabs
// setTabToDisplayOn(CreativeTabs.tabMisc);
}
@Override
@SideOnly(Side.SERVER)
public boolean getShareTag()
{
public boolean getShareTag(){
return true;
}
}
@Override
@SideOnly(Side.CLIENT)
@SuppressWarnings({ "rawtypes", "unchecked" })
public void addInformation(ItemStack itemStack, EntityPlayer player, List info, boolean bool)
{
@SuppressWarnings({"rawtypes", "unchecked"})
public void addInformation(ItemStack itemStack, EntityPlayer player, List info, boolean bool){
int[] coordinates = getCoordinates(itemStack);
if (coordinates != null)
{
if(coordinates != null){
NBTTagCompound nbtTagCompound = itemStack.getTagCompound();
String title = nbtTagCompound.getString("title");
if (title != null && !title.isEmpty())
{
if(title != null && !title.isEmpty()){
info.add(title);
}
String hint = String.format(HINT_TEMPLATE, coordinates[0], coordinates[1], coordinates[2], coordinates [3]);
String hint = String.format(HINT_TEMPLATE, coordinates[0], coordinates[1], coordinates[2], coordinates[3]);
info.add(hint);
}
}
/**
* Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer
* Called whenever this item is equipped and the right mouse button is
* pressed. Args: itemStack, world, entityPlayer
*
* @return The ItemStack to replace it with.
*/
@Override
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player)
{
if (player.isSneaking())
{
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player){
if(player.isSneaking()){
return new ItemStack(AdvancedPowerManagement.itemStorageLinkCardCreator);
}
else
{
}else{
return stack;
}
}

View file

@ -16,24 +16,22 @@ import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
public class ItemStorageLinkCardCreator extends ItemCardBase
{
public ItemStorageLinkCardCreator(String name)
{
public class ItemStorageLinkCardCreator extends ItemCardBase{
public ItemStorageLinkCardCreator(String name) {
super(name);
setMaxStackSize(1);
setCreativeTab(CreativeTabs.tabMisc);
setTextureName(Info.TITLE_PACKED + ":LinkCardCreator");
}
@Override
public boolean onItemUseFirst(ItemStack itemstack, EntityPlayer entityplayer, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ)
{
public boolean onItemUseFirst(ItemStack itemstack, EntityPlayer entityplayer, World world, int x, int y, int z, int side, float hitX, float hitY,
float hitZ){
TileEntity tile = world.getTileEntity(x, y, z);
if (entityplayer instanceof EntityPlayerMP && tile instanceof IEnergyStorage)
{
//if (Info.isDebugging) System.out.println("Clicked on X:" + x + " Y:" + y + " Z:" + z + " Dim:" + world.provider.dimensionId);
if(entityplayer instanceof EntityPlayerMP && tile instanceof IEnergyStorage){
// if (Info.isDebugging) System.out.println("Clicked on X:" + x +
// " Y:" + y + " Z:" + z + " Dim:" + world.provider.dimensionId);
ItemStack newcard = new ItemStack(AdvancedPowerManagement.itemStorageLinkCard);
setCoordinates(newcard, x, y, z, world.provider.dimensionId);
entityplayer.inventory.mainInventory[entityplayer.inventory.currentItem] = newcard;

View file

@ -11,34 +11,28 @@ import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
public class SlotChargeable extends SlotCustom
{
public class SlotChargeable extends SlotCustom{
public int chargeTier;
public SlotChargeable(IInventory inv, int index, int xpos, int ypos, int tier)
{
public SlotChargeable(IInventory inv, int index, int xpos, int ypos, int tier) {
super(inv, index, xpos, ypos);
chargeTier = tier;
}
@Override
public boolean isItemValid(ItemStack stack)
{
public boolean isItemValid(ItemStack stack){
// Decide if the item is a valid IC2 electrical item
return Utils.isItemChargeable(stack, chargeTier);
}
@Override
public int getSlotStackLimit()
{
public int getSlotStackLimit(){
return 1;
}
@Override
public IIcon getBackgroundIconIndex()
{
public IIcon getBackgroundIconIndex(){
return Info.iconSlotChargeable;
//return 247;
// return 247;
}
}

View file

@ -9,22 +9,16 @@ import com.kaijin.AdvPowerMan.tileentities.TECommon;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
public class SlotCustom extends Slot
{
public SlotCustom(IInventory inv, int index, int xpos, int ypos)
{
public class SlotCustom extends Slot{
public SlotCustom(IInventory inv, int index, int xpos, int ypos) {
super(inv, index, xpos, ypos);
}
@Override
public void onSlotChanged()
{
if (inventory instanceof TECommon)
{
((TECommon)inventory).markDirty(this.getSlotIndex());
}
else
{
public void onSlotChanged(){
if(inventory instanceof TECommon){
((TECommon) inventory).markDirty(this.getSlotIndex());
}else{
inventory.markDirty();
}
}

View file

@ -11,35 +11,30 @@ import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
public class SlotDrainable extends SlotCustom
{
public class SlotDrainable extends SlotCustom{
protected int powerTier;
public SlotDrainable(IInventory inv, int index, int xpos, int ypos, int tier)
{
public SlotDrainable(IInventory inv, int index, int xpos, int ypos, int tier) {
super(inv, index, xpos, ypos);
powerTier = tier;
}
/**
* Check if the stack is a valid item for this slot.
*/
@Override
public boolean isItemValid(ItemStack stack)
{
public boolean isItemValid(ItemStack stack){
// Decide if the item is a valid IC2 power source
return Utils.isItemDrainable(stack, powerTier);
}
@Override
public int getSlotStackLimit()
{
public int getSlotStackLimit(){
return 1;
}
@Override
public IIcon getBackgroundIconIndex()
{
public IIcon getBackgroundIconIndex(){
return Info.iconSlotDrainable;
// return -1; // 232;
}

View file

@ -11,26 +11,22 @@ import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
public class SlotInput extends SlotCustom
{
public class SlotInput extends SlotCustom{
public int chargeTier;
public SlotInput(IInventory inv, int index, int xpos, int ypos, int tier)
{
public SlotInput(IInventory inv, int index, int xpos, int ypos, int tier) {
super(inv, index, xpos, ypos);
chargeTier = tier;
}
@Override
public boolean isItemValid(ItemStack stack)
{
public boolean isItemValid(ItemStack stack){
// Decide if the item is a valid IC2 electrical item
return Utils.isItemChargeable(stack, chargeTier);
}
@Override
public IIcon getBackgroundIconIndex()
{
public IIcon getBackgroundIconIndex(){
return Info.iconSlotInput;
// return 249;
}

View file

@ -13,49 +13,39 @@ import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
public class SlotLinkCard extends Slot
{
public SlotLinkCard(IInventory inv, int index, int xpos, int ypos)
{
public class SlotLinkCard extends Slot{
public SlotLinkCard(IInventory inv, int index, int xpos, int ypos) {
super(inv, index, xpos, ypos);
}
/**
* Check if the stack is a valid item for this slot.
*/
@Override
public boolean isItemValid(ItemStack stack)
{
public boolean isItemValid(ItemStack stack){
// Decide if the item is a link card
if (stack != null && stack.getItem() instanceof ItemStorageLinkCard)
{
if(stack != null && stack.getItem() instanceof ItemStorageLinkCard){
return true;
}
return false;
}
@Override
public int getSlotStackLimit()
{
public int getSlotStackLimit(){
return 1;
}
@Override
public IIcon getBackgroundIconIndex()
{
public IIcon getBackgroundIconIndex(){
return Info.iconSlotLinkCard;
// return 246;
}
@Override
public void onSlotChanged()
{
if (this.inventory instanceof TECommon)
{
((TECommon)inventory).markDirty(this.getSlotIndex());
}
else
{
public void onSlotChanged(){
if(this.inventory instanceof TECommon){
((TECommon) inventory).markDirty(this.getSlotIndex());
}else{
inventory.markDirty();
}
}

View file

@ -10,31 +10,27 @@ import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
public class SlotMachineUpgrade extends SlotCustom
{
public SlotMachineUpgrade(IInventory inv, int index, int xpos, int ypos)
{
public class SlotMachineUpgrade extends SlotCustom{
public SlotMachineUpgrade(IInventory inv, int index, int xpos, int ypos) {
super(inv, index, xpos, ypos);
}
/**
* Check if the stack is a valid item for this slot.
*/
/**
* Check if the stack is a valid item for this slot.
*/
@Override
public boolean isItemValid(ItemStack stack)
{
// Decide if the item is a valid IC2 machine upgrade
if (stack == null) return false;
if (stack.isItemEqual(Info.ic2overclockerUpg) || stack.isItemEqual(Info.ic2transformerUpg) || stack.isItemEqual(Info.ic2storageUpg))
{
return true;
}
return false;
}
public boolean isItemValid(ItemStack stack){
// Decide if the item is a valid IC2 machine upgrade
if(stack == null)
return false;
if(stack.isItemEqual(Info.ic2overclockerUpg) || stack.isItemEqual(Info.ic2transformerUpg) || stack.isItemEqual(Info.ic2storageUpg)){
return true;
}
return false;
}
@Override
public IIcon getBackgroundIconIndex()
{
public IIcon getBackgroundIconIndex(){
return Info.iconSlotMachineUpgrade;
// return 245;
}

View file

@ -10,26 +10,22 @@ import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
public class SlotOutput extends SlotCustom
{
public SlotOutput(IInventory inv, int index, int xpos, int ypos)
{
public class SlotOutput extends SlotCustom{
public SlotOutput(IInventory inv, int index, int xpos, int ypos) {
super(inv, index, xpos, ypos);
}
/**
* Check if the stack is a valid item for this slot.
*/
@Override
public boolean isItemValid(ItemStack stack)
{
// No items may be placed here, parameter is ignored
return false;
public boolean isItemValid(ItemStack stack){
// No items may be placed here, parameter is ignored
return false;
}
@Override
public IIcon getBackgroundIconIndex()
{
public IIcon getBackgroundIconIndex(){
return Info.iconSlotOutput;
// return -1; // 250
}

View file

@ -14,33 +14,31 @@ import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
public class SlotPlayerArmor extends SlotCustom
{
// The armor type that can be placed on that slot, it uses the same values of armorType field on ItemArmor.
public class SlotPlayerArmor extends SlotCustom{
// The armor type that can be placed on that slot, it uses the same values
// of armorType field on ItemArmor.
final int armorType;
public SlotPlayerArmor(IInventory inv, int index, int xpos, int ypos, int armorType)
{
public SlotPlayerArmor(IInventory inv, int index, int xpos, int ypos, int armorType) {
super(inv, index, xpos, ypos);
this.armorType = armorType;
}
@Override
public int getSlotStackLimit()
{
public int getSlotStackLimit(){
return 1;
}
@Override
public boolean isItemValid(ItemStack stack)
{
if (stack == null) return false;
return stack.getItem() instanceof ItemArmor ? ((ItemArmor)stack.getItem()).armorType == this.armorType : (Item.getIdFromItem(stack.getItem()) == Item.getIdFromItem(Item.getItemFromBlock(Blocks.pumpkin)) ? this.armorType == 0 : false);
public boolean isItemValid(ItemStack stack){
if(stack == null)
return false;
return stack.getItem() instanceof ItemArmor ? ((ItemArmor) stack.getItem()).armorType == this.armorType : (Item
.getIdFromItem(stack.getItem()) == Item.getIdFromItem(Item.getItemFromBlock(Blocks.pumpkin)) ? this.armorType == 0 : false);
}
@Override
public IIcon getBackgroundIconIndex()
{
public IIcon getBackgroundIconIndex(){
return Info.iconSlotPlayerArmor[armorType];
// return 240 + armorType;
}

View file

@ -11,44 +11,41 @@ import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
public class SlotPowerSource extends SlotCustom
{
public class SlotPowerSource extends SlotCustom{
private int powerTier;
//private int iconIndex;
public SlotPowerSource(IInventory inv, int index, int xpos, int ypos, int tier)
{
// private int iconIndex;
public SlotPowerSource(IInventory inv, int index, int xpos, int ypos, int tier) {
super(inv, index, xpos, ypos);
setTier(tier);
}
public void setTier(int tier)
{
if (tier < 1) tier = 1;
if (tier > 3) tier = 3;
public void setTier(int tier){
if(tier < 1)
tier = 1;
if(tier > 3)
tier = 3;
powerTier = tier;
//iconIndex = 223 + tier;
// iconIndex = 223 + tier;
}
/**
* Check if the stack is a valid item for this slot.
*/
@Override
public boolean isItemValid(ItemStack stack)
{
public boolean isItemValid(ItemStack stack){
// Decide if the item is a valid IC2 power source
return Utils.isItemDrainable(stack, powerTier);
}
@Override
public int getSlotStackLimit()
{
public int getSlotStackLimit(){
return 1;
}
@Override
public IIcon getBackgroundIconIndex()
{
public IIcon getBackgroundIconIndex(){
return Info.iconSlotPowerSource[powerTier - 1];
// return iconIndex;
}

View file

@ -34,353 +34,361 @@ import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class TEAdjustableTransformer extends TECommon implements IEnergySource, IEnergySink
{
public class TEAdjustableTransformer extends TECommon implements IEnergySource, IEnergySink{
protected boolean initialized = false;
public MovingAverage outputTracker = new MovingAverage(12);
public MovingAverage inputTracker = new MovingAverage(12);
protected int maxInput = 8192;
public int energyBuffer = 0;
public int energyReceived = 0;
public int outputRate = 32;
public int packetSize = 32;
public int energyCap = 32;
public byte[] sideSettings = {0, 0, 0, 0, 0, 0}; // DOWN, UP, NORTH, SOUTH, WEST, EAST
public TEAdjustableTransformer() // Constructor used when placing a new tile entity, to set up correct parameters
public int energyCap = 32;
public byte[] sideSettings = {0, 0, 0, 0, 0, 0}; // DOWN, UP, NORTH, SOUTH,
// WEST, EAST
public TEAdjustableTransformer() // Constructor used when placing a new tile
// entity, to set up correct parameters
{
super();
}
/**
* Reads a tile entity from NBT.
*/
@Override
public void readFromNBT(NBTTagCompound nbttagcompound)
{
public void readFromNBT(NBTTagCompound nbttagcompound){
super.readFromNBT(nbttagcompound);
outputRate = nbttagcompound.getInteger("outputRate");
packetSize = nbttagcompound.getInteger("packetSize");
energyBuffer = nbttagcompound.getInteger("energyBuffer");
if (packetSize > Info.AE_MAX_PACKET) packetSize = Info.AE_MAX_PACKET;
if (packetSize < Info.AE_MIN_PACKET) packetSize = Info.AE_MIN_PACKET;
if (outputRate > packetSize * Info.AE_PACKETS_TICK) outputRate = packetSize * Info.AE_PACKETS_TICK;
if (outputRate > Info.AE_MAX_OUTPUT) outputRate = Info.AE_MAX_OUTPUT;
if (outputRate < Info.AE_MIN_OUTPUT) outputRate = Info.AE_MIN_OUTPUT;
if (energyBuffer > packetSize * Info.AE_PACKETS_TICK) energyBuffer = packetSize * Info.AE_PACKETS_TICK;
if(packetSize > Info.AE_MAX_PACKET)
packetSize = Info.AE_MAX_PACKET;
if(packetSize < Info.AE_MIN_PACKET)
packetSize = Info.AE_MIN_PACKET;
if(outputRate > packetSize * Info.AE_PACKETS_TICK)
outputRate = packetSize * Info.AE_PACKETS_TICK;
if(outputRate > Info.AE_MAX_OUTPUT)
outputRate = Info.AE_MAX_OUTPUT;
if(outputRate < Info.AE_MIN_OUTPUT)
outputRate = Info.AE_MIN_OUTPUT;
if(energyBuffer > packetSize * Info.AE_PACKETS_TICK)
energyBuffer = packetSize * Info.AE_PACKETS_TICK;
energyCap = Math.max(packetSize, outputRate);
NBTTagList nbttaglist = nbttagcompound.getTagList("SideSettings", Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < nbttaglist.tagCount(); ++i)
{
NBTTagCompound entry = (NBTTagCompound)nbttaglist.getCompoundTagAt(i);
if (i >= 0 && i < sideSettings.length)
{
sideSettings[i] = (byte)(entry.getByte("Flags") & 255);
for(int i = 0; i < nbttaglist.tagCount(); ++i){
NBTTagCompound entry = (NBTTagCompound) nbttaglist.getCompoundTagAt(i);
if(i >= 0 && i < sideSettings.length){
sideSettings[i] = (byte) (entry.getByte("Flags") & 255);
}
}
}
/**
* Writes a tile entity to NBT.
*/
@Override
public void writeToNBT(NBTTagCompound nbttagcompound)
{
public void writeToNBT(NBTTagCompound nbttagcompound){
super.writeToNBT(nbttagcompound);
nbttagcompound.setInteger("outputRate", outputRate);
nbttagcompound.setInteger("packetSize", packetSize);
nbttagcompound.setInteger("energyBuffer", energyBuffer);
NBTTagList nbttaglist = new NBTTagList();
for (int i = 0; i < sideSettings.length; ++i)
{
for(int i = 0; i < sideSettings.length; ++i){
NBTTagCompound entry = new NBTTagCompound();
entry.setByte("Flags", sideSettings[i]);
nbttaglist.appendTag(entry);
}
nbttagcompound.setTag("SideSettings", nbttaglist);
}
@Override
public void invalidate()
{
if (worldObj != null && initialized)
{
public void invalidate(){
if(worldObj != null && initialized){
EnergyTileUnloadEvent unloadEvent = new EnergyTileUnloadEvent(this);
MinecraftForge.EVENT_BUS.post(unloadEvent);
}
super.invalidate();
}
@Override
public int getGuiID()
{
public int getGuiID(){
return Info.GUI_ID_ADJUSTABLE_TRANSFORMER;
}
@Override
public void updateEntity()
{
if (AdvancedPowerManagement.proxy.isClient()) return;
if (!initialized)
{
if (worldObj == null) return;
public void updateEntity(){
if(AdvancedPowerManagement.proxy.isClient())
return;
if(!initialized){
if(worldObj == null)
return;
MinecraftForge.EVENT_BUS.post(new EnergyTileLoadEvent(this));
initialized = true;
}
}
protected boolean receivingRedstoneSignal()
{
protected boolean receivingRedstoneSignal(){
return worldObj.isBlockIndirectlyGettingPowered(xCoord, yCoord, zCoord);
}
public String getInvName()
{
public String getInvName(){
return Info.KEY_BLOCK_NAMES[6] + Info.KEY_NAME_SUFFIX;
}
public boolean isUseableByPlayer(EntityPlayer entityplayer)
{
if (worldObj.getTileEntity(xCoord, yCoord, zCoord) != this)
{
public boolean isUseableByPlayer(EntityPlayer entityplayer){
if(worldObj.getTileEntity(xCoord, yCoord, zCoord) != this){
return false;
}
return entityplayer.getDistanceSq((double)xCoord + 0.5D, (double)yCoord + 0.5D, (double)zCoord + 0.5D) <= 64D;
return entityplayer.getDistanceSq((double) xCoord + 0.5D, (double) yCoord + 0.5D, (double) zCoord + 0.5D) <= 64D;
}
protected void selfDestroy()
{
//dropContents();
protected void selfDestroy(){
// dropContents();
ItemStack stack = new ItemStack(AdvancedPowerManagement.blockAdvPwrMan, 1, Info.AT_META);
worldObj.setBlockToAir(xCoord, yCoord, zCoord);
this.invalidate();
}
// IC2 API stuff
//@Override - this method doesn't exist anymore
public boolean isAddedToEnergyNet()
{
// @Override - this method doesn't exist anymore
public boolean isAddedToEnergyNet(){
return initialized;
}
@Override
public boolean emitsEnergyTo(TileEntity receiver, ForgeDirection direction)
{
public boolean emitsEnergyTo(TileEntity receiver, ForgeDirection direction){
// TODO Side I/O
//System.out.println("emit - direction.toSideValue() = " + direction.toSideValue() + " setting = " + ((sideSettings[direction.toSideValue()] & 1) == 1));
// System.out.println("emit - direction.toSideValue() = " +
// direction.toSideValue() + " setting = " +
// ((sideSettings[direction.toSideValue()] & 1) == 1));
return (sideSettings[direction.ordinal()] & 1) == 1;
}
@Override
public double getOfferedEnergy()
{
public double getOfferedEnergy(){
return (!receivingRedstoneSignal()) ? Math.min(energyBuffer, outputRate) : 0;
}
@Override
public void drawEnergy(double amount)
{
if (!receivingRedstoneSignal())
{
public void drawEnergy(double amount){
if(!receivingRedstoneSignal()){
// Reset input limiter
if (energyReceived > outputRate) energyReceived -= outputRate;
else energyReceived = 0;
if(energyReceived > outputRate)
energyReceived -= outputRate;
else
energyReceived = 0;
energyBuffer -= amount;
outputTracker.tick((int)amount);
outputTracker.tick((int) amount);
}
}
@Override
public int getSinkTier()
{
public int getSinkTier(){
return maxInput;
}
@Override
public int getSourceTier() {
public int getSourceTier(){
return maxInput;
}
@Override
public boolean acceptsEnergyFrom(TileEntity emitter, ForgeDirection direction)
{
public boolean acceptsEnergyFrom(TileEntity emitter, ForgeDirection direction){
// TODO Side I/O
//System.out.println("accept - direction.toSideValue() = " + direction.toSideValue() + " setting = " + ((sideSettings[direction.toSideValue()] & 1) == 0));
// System.out.println("accept - direction.toSideValue() = " +
// direction.toSideValue() + " setting = " +
// ((sideSettings[direction.toSideValue()] & 1) == 0));
return (sideSettings[direction.ordinal()] & 1) == 0;
}
@Override
public double getDemandedEnergy(){
if(!receivingRedstoneSignal()){
final int tickAmt = Math.max(outputRate - energyReceived, 0);
final int capAmt = Math.max(energyCap - energyBuffer, 0);
//System.out.println("demandsEnergy: " + amt);
// System.out.println("demandsEnergy: " + amt);
return Math.min(tickAmt, capAmt);
}
return 0;
}
@Override
public double injectEnergy(ForgeDirection directionFrom, double amount, double voltage) {
//System.out.println("energyBuffer: " + energyBuffer);
if (AdvancedPowerManagement.proxy.isServer())
{
public double injectEnergy(ForgeDirection directionFrom, double amount, double voltage){
// System.out.println("energyBuffer: " + energyBuffer);
if(AdvancedPowerManagement.proxy.isServer()){
// if supply is greater than the max we can take per tick
if (amount > maxInput)
{
//If the supplied EU is over the baseMaxInput, we're getting
//supplied higher than acceptable current. Pop ourselves off
//into the world and return all but 1 EU, or if the supply
//somehow was 1EU, return zero to keep IC2 from spitting out
//massive errors in the log
if(amount > maxInput){
// If the supplied EU is over the baseMaxInput, we're getting
// supplied higher than acceptable current. Pop ourselves off
// into the world and return all but 1 EU, or if the supply
// somehow was 1EU, return zero to keep IC2 from spitting out
// massive errors in the log
selfDestroy();
if (amount <= 1)
if(amount <= 1)
return 0;
else
return amount - 1;
}
else
{
}else{
energyReceived += amount;
energyBuffer += amount;
inputTracker.tick((int)amount);
inputTracker.tick((int) amount);
}
}
return 0;
}
// Networking stuff
@SideOnly(Side.CLIENT)
@Override
public void receiveDescriptionData(int packetID, ByteBuf stream)
{
//try
//{
for (int i = 0; i < 6; i++)
{
sideSettings[i] = stream.readByte();
}
/*}
catch (IOException e)
{
logDescPacketError(e);
return;
}*/
public void receiveDescriptionData(int packetID, ByteBuf stream){
// try
// {
for(int i = 0; i < 6; i++){
sideSettings[i] = stream.readByte();
}
/*
* } catch (IOException e) { logDescPacketError(e); return; }
*/
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
@Override
public Packet getDescriptionPacket()
{
public Packet getDescriptionPacket(){
createDescPacket();
return null;
}
@Override
protected void addUniqueDescriptionData(ByteBuf data) throws IOException
{
for (int i = 0; i < 6; i++)
{
protected void addUniqueDescriptionData(ByteBuf data) throws IOException{
for(int i = 0; i < 6; i++){
data.writeByte(sideSettings[i]);
}
}
/**
* Packet reception by server of what button was clicked on the client's GUI.
* @param id = the button ID
* Packet reception by server of what button was clicked on the client's
* GUI.
*
* @param id
* = the button ID
*/
@Override
public void receiveGuiButton(int id)
{
switch (id)
{
public void receiveGuiButton(int id){
switch(id){
case 0:
packetSize += 1;
if (packetSize > Info.AE_MAX_PACKET) packetSize = Info.AE_MAX_PACKET;
if(packetSize > Info.AE_MAX_PACKET)
packetSize = Info.AE_MAX_PACKET;
break;
case 1:
packetSize += 10;
if (packetSize > Info.AE_MAX_PACKET) packetSize = Info.AE_MAX_PACKET;
if(packetSize > Info.AE_MAX_PACKET)
packetSize = Info.AE_MAX_PACKET;
break;
case 2:
packetSize += 64;
if (packetSize == 68) packetSize = 64;
if (packetSize > Info.AE_MAX_PACKET) packetSize = Info.AE_MAX_PACKET;
if(packetSize == 68)
packetSize = 64;
if(packetSize > Info.AE_MAX_PACKET)
packetSize = Info.AE_MAX_PACKET;
break;
case 3:
packetSize *= 2;
if (packetSize > Info.AE_MAX_PACKET) packetSize = Info.AE_MAX_PACKET;
if(packetSize > Info.AE_MAX_PACKET)
packetSize = Info.AE_MAX_PACKET;
break;
case 4:
packetSize -= 1;
if (packetSize < Info.AE_MIN_PACKET) packetSize = Info.AE_MIN_PACKET;
if (outputRate > packetSize * Info.AE_PACKETS_TICK) outputRate = packetSize * Info.AE_PACKETS_TICK;
if(packetSize < Info.AE_MIN_PACKET)
packetSize = Info.AE_MIN_PACKET;
if(outputRate > packetSize * Info.AE_PACKETS_TICK)
outputRate = packetSize * Info.AE_PACKETS_TICK;
break;
case 5:
packetSize -= 10;
if (packetSize < Info.AE_MIN_PACKET) packetSize = Info.AE_MIN_PACKET;
if (outputRate > packetSize * Info.AE_PACKETS_TICK) outputRate = packetSize * Info.AE_PACKETS_TICK;
if(packetSize < Info.AE_MIN_PACKET)
packetSize = Info.AE_MIN_PACKET;
if(outputRate > packetSize * Info.AE_PACKETS_TICK)
outputRate = packetSize * Info.AE_PACKETS_TICK;
break;
case 6:
packetSize -= 64;
if (packetSize < Info.AE_MIN_PACKET) packetSize = Info.AE_MIN_PACKET;
if (outputRate > packetSize * Info.AE_PACKETS_TICK) outputRate = packetSize * Info.AE_PACKETS_TICK;
if(packetSize < Info.AE_MIN_PACKET)
packetSize = Info.AE_MIN_PACKET;
if(outputRate > packetSize * Info.AE_PACKETS_TICK)
outputRate = packetSize * Info.AE_PACKETS_TICK;
break;
case 7:
packetSize /= 2;
if (packetSize < Info.AE_MIN_PACKET) packetSize = Info.AE_MIN_PACKET;
if (outputRate > packetSize * Info.AE_PACKETS_TICK) outputRate = packetSize * Info.AE_PACKETS_TICK;
if(packetSize < Info.AE_MIN_PACKET)
packetSize = Info.AE_MIN_PACKET;
if(outputRate > packetSize * Info.AE_PACKETS_TICK)
outputRate = packetSize * Info.AE_PACKETS_TICK;
break;
case 8:
outputRate += 1;
if (outputRate > packetSize * Info.AE_PACKETS_TICK) outputRate = packetSize * Info.AE_PACKETS_TICK;
if (outputRate > Info.AE_MAX_OUTPUT) outputRate = Info.AE_MAX_OUTPUT;
if(outputRate > packetSize * Info.AE_PACKETS_TICK)
outputRate = packetSize * Info.AE_PACKETS_TICK;
if(outputRate > Info.AE_MAX_OUTPUT)
outputRate = Info.AE_MAX_OUTPUT;
break;
case 9:
outputRate += 10;
if (outputRate > packetSize * Info.AE_PACKETS_TICK) outputRate = packetSize * Info.AE_PACKETS_TICK;
if (outputRate > Info.AE_MAX_OUTPUT) outputRate = Info.AE_MAX_OUTPUT;
if(outputRate > packetSize * Info.AE_PACKETS_TICK)
outputRate = packetSize * Info.AE_PACKETS_TICK;
if(outputRate > Info.AE_MAX_OUTPUT)
outputRate = Info.AE_MAX_OUTPUT;
break;
case 10:
outputRate += 64;
if (outputRate == 65) outputRate = 64;
if (outputRate > packetSize * Info.AE_PACKETS_TICK) outputRate = packetSize * Info.AE_PACKETS_TICK;
if (outputRate > Info.AE_MAX_OUTPUT) outputRate = Info.AE_MAX_OUTPUT;
if(outputRate == 65)
outputRate = 64;
if(outputRate > packetSize * Info.AE_PACKETS_TICK)
outputRate = packetSize * Info.AE_PACKETS_TICK;
if(outputRate > Info.AE_MAX_OUTPUT)
outputRate = Info.AE_MAX_OUTPUT;
break;
case 11:
outputRate *= 2;
if (outputRate > packetSize * Info.AE_PACKETS_TICK) outputRate = packetSize * Info.AE_PACKETS_TICK;
if (outputRate > Info.AE_MAX_OUTPUT) outputRate = Info.AE_MAX_OUTPUT;
if(outputRate > packetSize * Info.AE_PACKETS_TICK)
outputRate = packetSize * Info.AE_PACKETS_TICK;
if(outputRate > Info.AE_MAX_OUTPUT)
outputRate = Info.AE_MAX_OUTPUT;
break;
case 12:
outputRate -= 1;
if (outputRate < Info.AE_MIN_OUTPUT) outputRate = Info.AE_MIN_OUTPUT;
if(outputRate < Info.AE_MIN_OUTPUT)
outputRate = Info.AE_MIN_OUTPUT;
break;
case 13:
outputRate -= 10;
if (outputRate < Info.AE_MIN_OUTPUT) outputRate = Info.AE_MIN_OUTPUT;
if(outputRate < Info.AE_MIN_OUTPUT)
outputRate = Info.AE_MIN_OUTPUT;
break;
case 14:
outputRate -= 64;
if (outputRate < Info.AE_MIN_OUTPUT) outputRate = Info.AE_MIN_OUTPUT;
if(outputRate < Info.AE_MIN_OUTPUT)
outputRate = Info.AE_MIN_OUTPUT;
break;
case 15:
outputRate /= 2;
if (outputRate < Info.AE_MIN_OUTPUT) outputRate = Info.AE_MIN_OUTPUT;
if(outputRate < Info.AE_MIN_OUTPUT)
outputRate = Info.AE_MIN_OUTPUT;
break;
case 16:
case 17:
@ -388,19 +396,21 @@ public class TEAdjustableTransformer extends TECommon implements IEnergySource,
case 19:
case 20:
case 21:
//TODO How can we make IC2 check the new emit/accept values without doing a reload?
if (initialized) MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this));
// TODO How can we make IC2 check the new emit/accept values without
// doing a reload?
if(initialized)
MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this));
initialized = false;
sideSettings[id - 16] ^= 1;
MinecraftForge.EVENT_BUS.post(new EnergyTileLoadEvent(this));
initialized = true;
//worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
// worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
break;
}
energyCap = Math.max(packetSize, outputRate);
final byte voltLevel = (byte)(packetSize <= 32 ? 0 : packetSize <= 128 ? 2 : packetSize <= 512 ? 4 : 6);
for (int i = 0; i < 6; i++)
sideSettings[i] = (byte)(sideSettings[i] & 249 | voltLevel);
final byte voltLevel = (byte) (packetSize <= 32 ? 0 : packetSize <= 128 ? 2 : packetSize <= 512 ? 4 : 6);
for(int i = 0; i < 6; i++)
sideSettings[i] = (byte) (sideSettings[i] & 249 | voltLevel);
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
}

View file

@ -20,106 +20,106 @@ import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.util.ForgeDirection;
import cpw.mods.fml.common.FMLLog;
public class TEAdvEmitter extends TECommon implements IEnergySource
{
public class TEAdvEmitter extends TECommon implements IEnergySource{
protected boolean initialized;
public int outputRate = 32;
public int packetSize = 32;
private int energyBuffer = 0;
public TEAdvEmitter() // Constructor used when placing a new tile entity, to set up correct parameters
public TEAdvEmitter() // Constructor used when placing a new tile entity, to
// set up correct parameters
{
super();
}
public TEAdvEmitter(int i) // Constructor used when placing a new tile entity, to set up correct parameters
public TEAdvEmitter(int i) // Constructor used when placing a new tile
// entity, to set up correct parameters
{
super();
packetSize = outputRate = (int)Math.pow(2.0D, (double)(2 * i + 3));
packetSize = outputRate = (int) Math.pow(2.0D, (double) (2 * i + 3));
FMLLog.info("[AdvancedPowerManagement] " + "Updating old Emitter block of tier " + i);
}
/**
* Reads a tile entity from NBT.
*/
@Override
public void readFromNBT(NBTTagCompound nbttagcompound)
{
public void readFromNBT(NBTTagCompound nbttagcompound){
super.readFromNBT(nbttagcompound);
// Test if block used to be an old style emitter and if so use appropriate settings
// Test if block used to be an old style emitter and if so use
// appropriate settings
int baseTier = nbttagcompound.getInteger("baseTier");
if (baseTier > 0)
{
packetSize = outputRate = (int)Math.pow(2.0D, (double)(2 * baseTier + 3));
FMLLog.info("[AdvancedPowerManagement] " + "Loading NBT data for old Emitter block with baseTier of " + baseTier + " and setting output to " + packetSize);
}
else
{
if(baseTier > 0){
packetSize = outputRate = (int) Math.pow(2.0D, (double) (2 * baseTier + 3));
FMLLog.info("[AdvancedPowerManagement] " + "Loading NBT data for old Emitter block with baseTier of " + baseTier
+ " and setting output to " + packetSize);
}else{
// Normal load
outputRate = nbttagcompound.getInteger("outputRate");
packetSize = nbttagcompound.getInteger("packetSize");
energyBuffer = nbttagcompound.getInteger("energyBuffer");
if (packetSize > Info.AE_MAX_PACKET) packetSize = Info.AE_MAX_PACKET;
if (packetSize < Info.AE_MIN_PACKET) packetSize = Info.AE_MIN_PACKET;
if (outputRate > packetSize * Info.AE_PACKETS_TICK) outputRate = packetSize * Info.AE_PACKETS_TICK;
if (outputRate > Info.AE_MAX_OUTPUT) outputRate = Info.AE_MAX_OUTPUT;
if (outputRate < Info.AE_MIN_OUTPUT) outputRate = Info.AE_MIN_OUTPUT;
if (energyBuffer > packetSize * Info.AE_PACKETS_TICK) energyBuffer = packetSize * Info.AE_PACKETS_TICK;
if(packetSize > Info.AE_MAX_PACKET)
packetSize = Info.AE_MAX_PACKET;
if(packetSize < Info.AE_MIN_PACKET)
packetSize = Info.AE_MIN_PACKET;
if(outputRate > packetSize * Info.AE_PACKETS_TICK)
outputRate = packetSize * Info.AE_PACKETS_TICK;
if(outputRate > Info.AE_MAX_OUTPUT)
outputRate = Info.AE_MAX_OUTPUT;
if(outputRate < Info.AE_MIN_OUTPUT)
outputRate = Info.AE_MIN_OUTPUT;
if(energyBuffer > packetSize * Info.AE_PACKETS_TICK)
energyBuffer = packetSize * Info.AE_PACKETS_TICK;
}
}
/**
* Writes a tile entity to NBT.
*/
@Override
public void writeToNBT(NBTTagCompound nbttagcompound)
{
public void writeToNBT(NBTTagCompound nbttagcompound){
super.writeToNBT(nbttagcompound);
nbttagcompound.setInteger("outputRate", outputRate);
nbttagcompound.setInteger("packetSize", packetSize);
nbttagcompound.setInteger("energyBuffer", energyBuffer);
}
@Override
public void invalidate()
{
if (worldObj != null && initialized)
{
public void invalidate(){
if(worldObj != null && initialized){
EnergyTileUnloadEvent unloadEvent = new EnergyTileUnloadEvent(this);
MinecraftForge.EVENT_BUS.post(unloadEvent);
// EnergyNet.getForWorld(worldObj).removeTileEntity(this);
// EnergyNet.getForWorld(worldObj).removeTileEntity(this);
}
super.invalidate();
}
@Override
public boolean canUpdate()
{
public boolean canUpdate(){
return true;
}
@Override
public int getGuiID()
{
public int getGuiID(){
return Info.GUI_ID_ADJUSTABLE_EMITTER;
}
@Override
public void updateEntity()
{
if (AdvancedPowerManagement.proxy.isClient()) return;
if (!initialized)
{
if (worldObj == null) return;
// Test if this is an old emitter block and needs its meta value adjusted
public void updateEntity(){
if(AdvancedPowerManagement.proxy.isClient())
return;
if(!initialized){
if(worldObj == null)
return;
// Test if this is an old emitter block and needs its meta value
// adjusted
final int meta = worldObj.getBlockMetadata(xCoord, yCoord, zCoord);
if (meta != 7)
{
if(meta != 7){
FMLLog.info("[AdvancedPowerManagement] " + "Resetting Emitter block meta value from " + meta + " to 7");
worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 7, 3);
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
@ -127,163 +127,178 @@ public class TEAdvEmitter extends TECommon implements IEnergySource
}
EnergyTileLoadEvent loadEvent = new EnergyTileLoadEvent(this);
MinecraftForge.EVENT_BUS.post(loadEvent);
// EnergyNet.getForWorld(worldObj).addTileEntity(this);
// EnergyNet.getForWorld(worldObj).addTileEntity(this);
initialized = true;
}
/* if (receivingRedstoneSignal())
{
energyBuffer += outputRate;
EnergyNet net = EnergyNet.getForWorld(worldObj);
while (energyBuffer >= packetSize)
{
EnergyTileSourceEvent sourceEvent = new EnergyTileSourceEvent(this, packetSize);
MinecraftForge.EVENT_BUS.post(sourceEvent);
// net.emitEnergyFrom(this, packetSize); // No reason to save any surplus. Output is always the same.
energyBuffer -= packetSize;
}
}*/
/*
* if (receivingRedstoneSignal()) { energyBuffer += outputRate;
* EnergyNet net = EnergyNet.getForWorld(worldObj); while (energyBuffer
* >= packetSize) { EnergyTileSourceEvent sourceEvent = new
* EnergyTileSourceEvent(this, packetSize);
* MinecraftForge.EVENT_BUS.post(sourceEvent); //
* net.emitEnergyFrom(this, packetSize); // No reason to save any
* surplus. Output is always the same. energyBuffer -= packetSize; } }
*/
}
protected boolean receivingRedstoneSignal()
{
protected boolean receivingRedstoneSignal(){
return worldObj.isBlockIndirectlyGettingPowered(xCoord, yCoord, zCoord);
}
public String getInvName()
{
public String getInvName(){
return Info.KEY_BLOCK_NAMES[7] + Info.KEY_NAME_SUFFIX;
}
public boolean isUseableByPlayer(EntityPlayer entityplayer)
{
if (worldObj.getTileEntity(xCoord, yCoord, zCoord) != this)
{
public boolean isUseableByPlayer(EntityPlayer entityplayer){
if(worldObj.getTileEntity(xCoord, yCoord, zCoord) != this){
return false;
}
return entityplayer.getDistanceSq((double)xCoord + 0.5D, (double)yCoord + 0.5D, (double)zCoord + 0.5D) <= 64D;
return entityplayer.getDistanceSq((double) xCoord + 0.5D, (double) yCoord + 0.5D, (double) zCoord + 0.5D) <= 64D;
}
// IC2 API stuff
//@Override - this method doesn't exist anymore
public boolean isAddedToEnergyNet()
{
// @Override - this method doesn't exist anymore
public boolean isAddedToEnergyNet(){
return initialized;
}
@Override
public boolean emitsEnergyTo(TileEntity receiver, ForgeDirection direction)
{
public boolean emitsEnergyTo(TileEntity receiver, ForgeDirection direction){
return true;
}
@Override
public double getOfferedEnergy()
{
public double getOfferedEnergy(){
return Math.min(packetSize, outputRate);
}
@Override
public void drawEnergy(double amount)
{
if (receivingRedstoneSignal())
{
public void drawEnergy(double amount){
if(receivingRedstoneSignal()){
energyBuffer += outputRate;
energyBuffer -= packetSize;
}
}
@Override
public int getSourceTier() {
return 4; //XXX: cause I dunno what to put...
public int getSourceTier(){
return 4; // XXX: cause I dunno what to put...
}
// Networking stuff
/**
* Packet reception by server of what button was clicked on the client's GUI.
* @param id = the button ID
* Packet reception by server of what button was clicked on the client's
* GUI.
*
* @param id
* = the button ID
*/
@Override
public void receiveGuiButton(int id)
{
switch (id)
{
public void receiveGuiButton(int id){
switch(id){
case 0:
packetSize += 1;
if (packetSize > Info.AE_MAX_PACKET) packetSize = Info.AE_MAX_PACKET;
if(packetSize > Info.AE_MAX_PACKET)
packetSize = Info.AE_MAX_PACKET;
break;
case 1:
packetSize += 10;
if (packetSize > Info.AE_MAX_PACKET) packetSize = Info.AE_MAX_PACKET;
if(packetSize > Info.AE_MAX_PACKET)
packetSize = Info.AE_MAX_PACKET;
break;
case 2:
packetSize += 64;
if (packetSize == 68) packetSize = 64;
if (packetSize > Info.AE_MAX_PACKET) packetSize = Info.AE_MAX_PACKET;
if(packetSize == 68)
packetSize = 64;
if(packetSize > Info.AE_MAX_PACKET)
packetSize = Info.AE_MAX_PACKET;
break;
case 3:
packetSize *= 2;
if (packetSize > Info.AE_MAX_PACKET) packetSize = Info.AE_MAX_PACKET;
if(packetSize > Info.AE_MAX_PACKET)
packetSize = Info.AE_MAX_PACKET;
break;
case 4:
packetSize -= 1;
if (packetSize < Info.AE_MIN_PACKET) packetSize = Info.AE_MIN_PACKET;
if (outputRate > packetSize * Info.AE_PACKETS_TICK) outputRate = packetSize * Info.AE_PACKETS_TICK;
if(packetSize < Info.AE_MIN_PACKET)
packetSize = Info.AE_MIN_PACKET;
if(outputRate > packetSize * Info.AE_PACKETS_TICK)
outputRate = packetSize * Info.AE_PACKETS_TICK;
break;
case 5:
packetSize -= 10;
if (packetSize < Info.AE_MIN_PACKET) packetSize = Info.AE_MIN_PACKET;
if (outputRate > packetSize * Info.AE_PACKETS_TICK) outputRate = packetSize * Info.AE_PACKETS_TICK;
if(packetSize < Info.AE_MIN_PACKET)
packetSize = Info.AE_MIN_PACKET;
if(outputRate > packetSize * Info.AE_PACKETS_TICK)
outputRate = packetSize * Info.AE_PACKETS_TICK;
break;
case 6:
packetSize -= 64;
if (packetSize < Info.AE_MIN_PACKET) packetSize = Info.AE_MIN_PACKET;
if (outputRate > packetSize * Info.AE_PACKETS_TICK) outputRate = packetSize * Info.AE_PACKETS_TICK;
if(packetSize < Info.AE_MIN_PACKET)
packetSize = Info.AE_MIN_PACKET;
if(outputRate > packetSize * Info.AE_PACKETS_TICK)
outputRate = packetSize * Info.AE_PACKETS_TICK;
break;
case 7:
packetSize /= 2;
if (packetSize < Info.AE_MIN_PACKET) packetSize = Info.AE_MIN_PACKET;
if (outputRate > packetSize * Info.AE_PACKETS_TICK) outputRate = packetSize * Info.AE_PACKETS_TICK;
if(packetSize < Info.AE_MIN_PACKET)
packetSize = Info.AE_MIN_PACKET;
if(outputRate > packetSize * Info.AE_PACKETS_TICK)
outputRate = packetSize * Info.AE_PACKETS_TICK;
break;
case 8:
outputRate += 1;
if (outputRate > packetSize * Info.AE_PACKETS_TICK) outputRate = packetSize * Info.AE_PACKETS_TICK;
if (outputRate > Info.AE_MAX_OUTPUT) outputRate = Info.AE_MAX_OUTPUT;
if(outputRate > packetSize * Info.AE_PACKETS_TICK)
outputRate = packetSize * Info.AE_PACKETS_TICK;
if(outputRate > Info.AE_MAX_OUTPUT)
outputRate = Info.AE_MAX_OUTPUT;
break;
case 9:
outputRate += 10;
if (outputRate > packetSize * Info.AE_PACKETS_TICK) outputRate = packetSize * Info.AE_PACKETS_TICK;
if (outputRate > Info.AE_MAX_OUTPUT) outputRate = Info.AE_MAX_OUTPUT;
if(outputRate > packetSize * Info.AE_PACKETS_TICK)
outputRate = packetSize * Info.AE_PACKETS_TICK;
if(outputRate > Info.AE_MAX_OUTPUT)
outputRate = Info.AE_MAX_OUTPUT;
break;
case 10:
outputRate += 64;
if (outputRate == 65) outputRate = 64;
if (outputRate > packetSize * Info.AE_PACKETS_TICK) outputRate = packetSize * Info.AE_PACKETS_TICK;
if (outputRate > Info.AE_MAX_OUTPUT) outputRate = Info.AE_MAX_OUTPUT;
if(outputRate == 65)
outputRate = 64;
if(outputRate > packetSize * Info.AE_PACKETS_TICK)
outputRate = packetSize * Info.AE_PACKETS_TICK;
if(outputRate > Info.AE_MAX_OUTPUT)
outputRate = Info.AE_MAX_OUTPUT;
break;
case 11:
outputRate *= 2;
if (outputRate > packetSize * Info.AE_PACKETS_TICK) outputRate = packetSize * Info.AE_PACKETS_TICK;
if (outputRate > Info.AE_MAX_OUTPUT) outputRate = Info.AE_MAX_OUTPUT;
if(outputRate > packetSize * Info.AE_PACKETS_TICK)
outputRate = packetSize * Info.AE_PACKETS_TICK;
if(outputRate > Info.AE_MAX_OUTPUT)
outputRate = Info.AE_MAX_OUTPUT;
break;
case 12:
outputRate -= 1;
if (outputRate < Info.AE_MIN_OUTPUT) outputRate = Info.AE_MIN_OUTPUT;
if(outputRate < Info.AE_MIN_OUTPUT)
outputRate = Info.AE_MIN_OUTPUT;
break;
case 13:
outputRate -= 10;
if (outputRate < Info.AE_MIN_OUTPUT) outputRate = Info.AE_MIN_OUTPUT;
if(outputRate < Info.AE_MIN_OUTPUT)
outputRate = Info.AE_MIN_OUTPUT;
break;
case 14:
outputRate -= 64;
if (outputRate < Info.AE_MIN_OUTPUT) outputRate = Info.AE_MIN_OUTPUT;
if(outputRate < Info.AE_MIN_OUTPUT)
outputRate = Info.AE_MIN_OUTPUT;
break;
case 15:
outputRate /= 2;
if (outputRate < Info.AE_MIN_OUTPUT) outputRate = Info.AE_MIN_OUTPUT;
if(outputRate < Info.AE_MIN_OUTPUT)
outputRate = Info.AE_MIN_OUTPUT;
break;
}
}

View file

@ -37,66 +37,66 @@ import cpw.mods.fml.relauncher.SideOnly;
public class TEBatteryStation extends TECommonBench implements IEnergySource, IInventory, ISidedInventory{
public int opMode;
// Base values
public int packetSize;
public int currentEnergy = 0;
private boolean invChanged = false;
private boolean hasEnoughItems = false;
//For outside texture display
// For outside texture display
public boolean doingWork;
private int energyOut = 0;
public MovingAverage outputTracker = new MovingAverage(12);
private static final int[] BatteryStationSideInput = {Info.BS_SLOT_INPUT};
private static final int[] BatteryStationSideOutput = {Info.BS_SLOT_OUTPUT};
private static final int[] BatteryStationSideInOut = {Info.BS_SLOT_INPUT, Info.BS_SLOT_OUTPUT};
public TEBatteryStation() // Default constructor used only when loading tile entity from world save
public TEBatteryStation() // Default constructor used only when loading tile
// entity from world save
{
super();
// Do nothing else; Creating the inventory array and loading previous values will be handled in NBT read method momentarily.
// Do nothing else; Creating the inventory array and loading previous
// values will be handled in NBT read method momentarily.
}
public TEBatteryStation(int i) // Constructor used when placing a new tile entity, to set up correct parameters
public TEBatteryStation(int i) // Constructor used when placing a new tile
// entity, to set up correct parameters
{
super();
contents = new ItemStack[14];
//base tier = what we're passed, so 1, 2 or 3
// base tier = what we're passed, so 1, 2 or 3
baseTier = i;
opMode = 1;
initializeValues();
}
private void initializeValues()
{
private void initializeValues(){
powerTier = baseTier;
//Output math = 32 for tier 1, 128 for tier 2, 512 for tier 3
packetSize = (int)Math.pow(2.0D, (double)(2 * baseTier + 3));
// Output math = 32 for tier 1, 128 for tier 2, 512 for tier 3
packetSize = (int) Math.pow(2.0D, (double) (2 * baseTier + 3));
}
// IC2 API functions
@Override
public boolean emitsEnergyTo(TileEntity receiver, ForgeDirection direction)
{
public boolean emitsEnergyTo(TileEntity receiver, ForgeDirection direction){
return true;
}
@Override
public double getOfferedEnergy() {
public double getOfferedEnergy(){
return (!receivingRedstoneSignal()) ? Math.min(currentEnergy, packetSize) : 0;
}
@Override
public void drawEnergy(double amount) {
if (!receivingRedstoneSignal())
{
public void drawEnergy(double amount){
if(!receivingRedstoneSignal()){
drainPowerSource();
outputTracker.tick((int) amount);
currentEnergy -= amount;
@ -104,131 +104,125 @@ public class TEBatteryStation extends TECommonBench implements IEnergySource, II
}
@Override
public int getSourceTier() {
return 4; //XXX: cause I dunno what to put...
public int getSourceTier(){
return 4; // XXX: cause I dunno what to put...
}
// End IC2 API
@Override
public int getGuiID()
{
public int getGuiID(){
return Info.GUI_ID_BATTERY_STATION;
}
/**
* This will cause the block to drop anything inside it, create a new item in the
* world of its type, invalidate the tile entity, remove itself from the IC2
* EnergyNet and clear the block space (set it to air)
* This will cause the block to drop anything inside it, create a new item
* in the world of its type, invalidate the tile entity, remove itself from
* the IC2 EnergyNet and clear the block space (set it to air)
*/
@Override
protected void selfDestroy()
{
protected void selfDestroy(){
dropContents();
ItemStack stack = new ItemStack(AdvancedPowerManagement.blockAdvPwrMan, 1, Info.BS_META + baseTier - 1);
dropItem(stack);
worldObj.setBlockToAir(xCoord, yCoord, zCoord);
this.invalidate();
}
public boolean isItemValid(int slot, ItemStack stack)
{
public boolean isItemValid(int slot, ItemStack stack){
// Decide if the item is a valid IC2 electrical item
if (stack != null && stack.getItem() instanceof IElectricItem)
{
IElectricItem item = (IElectricItem)(stack.getItem());
if(stack != null && stack.getItem() instanceof IElectricItem){
IElectricItem item = (IElectricItem) (stack.getItem());
// Is the item appropriate for this slot?
if (slot == Info.BS_SLOT_OUTPUT) return true; // GUI won't allow placement of items here, but if the bench or an external machine does, it should at least let it sit there as long as it's an electrical item.
if (item.canProvideEnergy(stack) && item.getTier(stack) <= powerTier)
{
if ((slot >= Info.BS_SLOT_POWER_START && slot < Info.BS_SLOT_POWER_START + 12) || slot == Info.BS_SLOT_INPUT) return true;
if(slot == Info.BS_SLOT_OUTPUT)
return true; // GUI won't allow placement of items here, but if
// the bench or an external machine does, it
// should at least let it sit there as long as
// it's an electrical item.
if(item.canProvideEnergy(stack) && item.getTier(stack) <= powerTier){
if((slot >= Info.BS_SLOT_POWER_START && slot < Info.BS_SLOT_POWER_START + 12) || slot == Info.BS_SLOT_INPUT)
return true;
}
}
return false;
return false;
}
/**
* Reads a tile entity from NBT.
*/
@Override
public void readFromNBT(NBTTagCompound nbttagcompound)
{
public void readFromNBT(NBTTagCompound nbttagcompound){
super.readFromNBT(nbttagcompound);
if (Info.isDebugging) System.out.println("BS ID: " + nbttagcompound.getString("id"));
if(Info.isDebugging)
System.out.println("BS ID: " + nbttagcompound.getString("id"));
baseTier = nbttagcompound.getInteger("baseTier");
opMode = nbttagcompound.getInteger("opMode");
currentEnergy = nbttagcompound.getInteger("currentEnergy");
// Our inventory
contents = new ItemStack[Info.BS_INVENTORY_SIZE];
NBTTagList nbttaglist = nbttagcompound.getTagList("Items", Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < nbttaglist.tagCount(); ++i)
{
NBTTagCompound nbttagcompound1 = (NBTTagCompound)nbttaglist.getCompoundTagAt(i);
for(int i = 0; i < nbttaglist.tagCount(); ++i){
NBTTagCompound nbttagcompound1 = (NBTTagCompound) nbttaglist.getCompoundTagAt(i);
int j = nbttagcompound1.getByte("Slot") & 255;
if (j >= 0 && j < contents.length)
{
if(j >= 0 && j < contents.length){
contents[j] = ItemStack.loadItemStackFromNBT(nbttagcompound1);
}
}
// We can calculate these, no need to save/load them.
initializeValues();
}
/**
* Writes a tile entity to NBT.
*/
@Override
public void writeToNBT(NBTTagCompound nbttagcompound)
{
public void writeToNBT(NBTTagCompound nbttagcompound){
super.writeToNBT(nbttagcompound);
nbttagcompound.setInteger("baseTier", baseTier);
nbttagcompound.setInteger("opMode", opMode);
nbttagcompound.setInteger("currentEnergy", currentEnergy);
// Our inventory
NBTTagList nbttaglist = new NBTTagList();
for (int i = 0; i < contents.length; ++i)
{
if (contents[i] != null)
{
//if (ChargingBench.isDebugging) System.out.println("WriteNBT contents[" + i + "] stack tag: " + contents[i].stackTagCompound);
for(int i = 0; i < contents.length; ++i){
if(contents[i] != null){
// if (ChargingBench.isDebugging)
// System.out.println("WriteNBT contents[" + i + "] stack tag: "
// + contents[i].stackTagCompound);
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
nbttagcompound1.setByte("Slot", (byte)i);
nbttagcompound1.setByte("Slot", (byte) i);
contents[i].writeToNBT(nbttagcompound1);
nbttaglist.appendTag(nbttagcompound1);
}
}
nbttagcompound.setTag("Items", nbttaglist);
}
@Override
public void updateEntity()
{
if (AdvancedPowerManagement.proxy.isClient()) return;
if (!initialized && worldObj != null)
{
public void updateEntity(){
if(AdvancedPowerManagement.proxy.isClient())
return;
if(!initialized && worldObj != null){
EnergyTileLoadEvent loadEvent = new EnergyTileLoadEvent(this);
MinecraftForge.EVENT_BUS.post(loadEvent);
// EnergyNet.getForWorld(worldObj).addTileEntity(this);
// EnergyNet.getForWorld(worldObj).addTileEntity(this);
initialized = true;
}
boolean lastWorkState = doingWork;
doingWork = false;
invChanged = false;
hasEnoughItems = true;
if (!receivingRedstoneSignal())
{
// Work done only when not redstone powered
if(!receivingRedstoneSignal()){
// Work done only when not redstone powered
drainPowerSource();
}
@ -237,52 +231,65 @@ public class TEBatteryStation extends TECommonBench implements IEnergySource, II
repositionItems();
acceptInputItems();
if (invChanged)
{
this.markDirty(); // This doesn't need to be called multiple times, so it gets flagged to happen here if needed.
if(invChanged){
this.markDirty(); // This doesn't need to be called multiple times,
// so it gets flagged to happen here if needed.
}
// Trigger this only when it would need to update the client texture
if (lastWorkState != doingWork)
{
//if (ChargingBench.isDebugging) System.out.println("TE oldChargeLevel: " + oldChargeLevel + " chargeLevel: " + chargeLevel);
if(lastWorkState != doingWork){
// if (ChargingBench.isDebugging)
// System.out.println("TE oldChargeLevel: " + oldChargeLevel +
// " chargeLevel: " + chargeLevel);
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
}
private void drainPowerSource(){
hasEnoughItems = false;
for (int i = Info.BS_SLOT_POWER_START; i < Info.BS_SLOT_POWER_START + 12; i++){
//if (ChargingBench.isDebugging) System.out.println("currentEnergy: " + currentEnergy + " baseMaxOutput: " + baseMaxOutput);
if (currentEnergy >= packetSize){
for(int i = Info.BS_SLOT_POWER_START; i < Info.BS_SLOT_POWER_START + 12; i++){
// if (ChargingBench.isDebugging)
// System.out.println("currentEnergy: " + currentEnergy +
// " baseMaxOutput: " + baseMaxOutput);
if(currentEnergy >= packetSize){
hasEnoughItems = true;
break;
}
ItemStack stack = contents[i];
if (stack != null && stack.getItem() instanceof IElectricItem && stack.stackSize == 1){
IElectricItem item = (IElectricItem)(stack.getItem());
if (item.getTier(stack) <= powerTier && item.canProvideEnergy(stack)){
if(stack != null && stack.getItem() instanceof IElectricItem && stack.stackSize == 1){
IElectricItem item = (IElectricItem) (stack.getItem());
if(item.getTier(stack) <= powerTier && item.canProvideEnergy(stack)){
Item emptyItem = item.getEmptyItem(stack);
int chargedItemID = Item.getIdFromItem(item.getChargedItem(stack));
if (Item.getIdFromItem(stack.getItem()) == chargedItemID){
if(Item.getIdFromItem(stack.getItem()) == chargedItemID){
double transferLimit = item.getTransferLimit(stack);
//int amountNeeded = baseMaxOutput - currentEnergy;
if (transferLimit == 0) transferLimit = packetSize;
//if (transferLimit > amountNeeded) transferLimit = amountNeeded;
// int amountNeeded = baseMaxOutput - currentEnergy;
if(transferLimit == 0)
transferLimit = packetSize;
// if (transferLimit > amountNeeded) transferLimit =
// amountNeeded;
double chargeReturned = ElectricItem.manager.discharge(stack, transferLimit, powerTier, false, false, false);
if (chargeReturned > 0){
// Add the energy we received to our current energy level
if(chargeReturned > 0){
// Add the energy we received to our current energy
// level
currentEnergy += chargeReturned;
doingWork = true;
}
// Workaround for buggy IC2 API .discharge that automatically switches stack to emptyItemID but leaves a stackTagCompound on it, so it can't be stacked with never-used empties
if (chargedItemID != Item.getIdFromItem(emptyItem) && (chargeReturned < transferLimit || ElectricItem.manager.discharge(stack, 1, powerTier, false, true, false) == 0)){
//if (ChargingBench.isDebugging) System.out.println("Switching to emptyItemID: " + emptyItemID + " from stack.itemID: " + stack.itemID + " - chargedItemID: " + chargedItemID);
// Workaround for buggy IC2 API .discharge that
// automatically switches stack to emptyItemID but
// leaves a stackTagCompound on it, so it can't be
// stacked with never-used empties
if(chargedItemID != Item.getIdFromItem(emptyItem)
&& (chargeReturned < transferLimit || ElectricItem.manager.discharge(stack, 1, powerTier, false, true, false) == 0)){
// if (ChargingBench.isDebugging)
// System.out.println("Switching to emptyItemID: " +
// emptyItemID + " from stack.itemID: " +
// stack.itemID + " - chargedItemID: " +
// chargedItemID);
setInventorySlotContents(i, new ItemStack(emptyItem, 1, 0));
}
}
@ -290,58 +297,51 @@ public class TEBatteryStation extends TECommonBench implements IEnergySource, II
}
}
}
/**
* First, check the output slot to see if it's empty. If so, look to see if there are any fully
* DIScharged items in the main inventory. Move the first empty item to the output slot.
* If output slot contains stackable empties, check for matching empties to add to that stack.
* First, check the output slot to see if it's empty. If so, look to see if
* there are any fully DIScharged items in the main inventory. Move the
* first empty item to the output slot. If output slot contains stackable
* empties, check for matching empties to add to that stack.
*/
private void moveOutputItems()
{
private void moveOutputItems(){
rejectInvalidInput();
ItemStack outputStack = contents[Info.BS_SLOT_OUTPUT];
if (outputStack == null || (outputStack.isStackable() && outputStack.stackSize < outputStack.getMaxStackSize()))
{
// Output slot could receive item(s). Try to find something to move there.
for (int slot = 0; slot < contents.length; ++slot)
{
if (slot == Info.BS_SLOT_OUTPUT) continue;
if(outputStack == null || (outputStack.isStackable() && outputStack.stackSize < outputStack.getMaxStackSize())){
// Output slot could receive item(s). Try to find something to move
// there.
for(int slot = 0; slot < contents.length; ++slot){
if(slot == Info.BS_SLOT_OUTPUT)
continue;
ItemStack currentStack = contents[slot];
if (currentStack != null && currentStack.getItem() instanceof IElectricItem)
{
IElectricItem powerSource = (IElectricItem)(currentStack.getItem());
if (powerSource.getTier(currentStack) <= powerTier) // && powerSource.canProvideEnergy()
if(currentStack != null && currentStack.getItem() instanceof IElectricItem){
IElectricItem powerSource = (IElectricItem) (currentStack.getItem());
if(powerSource.getTier(currentStack) <= powerTier) // &&
// powerSource.canProvideEnergy()
{
int emptyItemID = Item.getIdFromItem(powerSource.getEmptyItem(currentStack));
int chargedItemID = Item.getIdFromItem(powerSource.getChargedItem(currentStack));
if (emptyItemID != chargedItemID)
{
if (Item.getIdFromItem(currentStack.getItem()) == emptyItemID)
{
if(emptyItemID != chargedItemID){
if(Item.getIdFromItem(currentStack.getItem()) == emptyItemID){
// Pick Me
if (outputStack == null)
{
if(outputStack == null){
contents[Info.BS_SLOT_OUTPUT] = currentStack;
contents[slot] = null;
}
else
{
}else{
// We already know the stack isn't full yet
contents[Info.BS_SLOT_OUTPUT].stackSize++;
contents[slot].stackSize--;
if (contents[slot].stackSize < 1) contents[slot] = null;
if(contents[slot].stackSize < 1)
contents[slot] = null;
}
invChanged = true;
break;
}
}
else if (outputStack == null)
{
}else if(outputStack == null){
boolean empty = ElectricItem.manager.discharge(currentStack, 1, powerTier, true, true, false) == 0;
if (empty)
{
if(empty){
// Pick Me
contents[Info.BS_SLOT_OUTPUT] = currentStack;
contents[slot] = null;
@ -354,23 +354,24 @@ public class TEBatteryStation extends TECommonBench implements IEnergySource, II
}
}
}
/**
* Adjust positions of items in inventory to preserve FIFO order where possible.
* Adjust positions of items in inventory to preserve FIFO order where
* possible.
*/
private void repositionItems()
{
private void repositionItems(){
final int lastIndex = Info.BS_SLOT_POWER_START + 11;
int vacancy = Info.BS_SLOT_POWER_START;
while (vacancy < lastIndex && contents[vacancy] != null)
{
while(vacancy < lastIndex && contents[vacancy] != null){
vacancy++;
}
int hunt = vacancy + 1;
while (vacancy < lastIndex && hunt <= lastIndex) // Mix of < and <= is not an error: Avoids needing +1 or -1 added to something.
while(vacancy < lastIndex && hunt <= lastIndex) // Mix of < and <= is
// not an error: Avoids
// needing +1 or -1
// added to something.
{
if (contents[vacancy] == null && contents[hunt] != null)
{
if(contents[vacancy] == null && contents[hunt] != null){
contents[vacancy] = contents[hunt];
contents[hunt] = null;
invChanged = true;
@ -379,65 +380,62 @@ public class TEBatteryStation extends TECommonBench implements IEnergySource, II
hunt++;
}
}
/**
* Check to see if there are any items in the input slot. If so, check to see if there are any
* free discharging slots. If so, move one from the input slot to a free discharging slot.
* Check to see if there are any items in the input slot. If so, check to
* see if there are any free discharging slots. If so, move one from the
* input slot to a free discharging slot.
*/
private void acceptInputItems()
{
//System.out.println("aII: opMode " + opMode);
private void acceptInputItems(){
// System.out.println("aII: opMode " + opMode);
ItemStack stack = contents[Info.BS_SLOT_INPUT];
if (stack == null || !(stack.getItem() instanceof IElectricItem) || (opMode == 1 && hasEnoughItems)) return;
IElectricItem item = (IElectricItem)stack.getItem();
if (item.canProvideEnergy(stack))
{
// Input slot contains a power source. If possible, move one of it into the discharging area.
for (int slot = Info.BS_SLOT_POWER_START; slot < Info.BS_SLOT_POWER_START + 12; ++slot)
{
if (contents[slot] == null)
{
// Grab one unit from input and move it to the selected slot.
if(stack == null || !(stack.getItem() instanceof IElectricItem) || (opMode == 1 && hasEnoughItems))
return;
IElectricItem item = (IElectricItem) stack.getItem();
if(item.canProvideEnergy(stack)){
// Input slot contains a power source. If possible, move one of it
// into the discharging area.
for(int slot = Info.BS_SLOT_POWER_START; slot < Info.BS_SLOT_POWER_START + 12; ++slot){
if(contents[slot] == null){
// Grab one unit from input and move it to the selected
// slot.
contents[slot] = decrStackSize(Info.BS_SLOT_INPUT, 1);
break;
}
}
}
}
private void rejectInvalidInput()
{
// Move item from input to output if not valid. (Wrong tier or not electric item.)
if (contents[Info.BS_SLOT_INPUT] != null && contents[Info.BS_SLOT_OUTPUT] == null)
{
if (!isItemValid(Info.BS_SLOT_INPUT, contents[Info.BS_SLOT_INPUT]))
{
private void rejectInvalidInput(){
// Move item from input to output if not valid. (Wrong tier or not
// electric item.)
if(contents[Info.BS_SLOT_INPUT] != null && contents[Info.BS_SLOT_OUTPUT] == null){
if(!isItemValid(Info.BS_SLOT_INPUT, contents[Info.BS_SLOT_INPUT])){
contents[Info.BS_SLOT_OUTPUT] = contents[Info.BS_SLOT_INPUT];
contents[Info.BS_SLOT_INPUT] = null;
invChanged = true;
}
}
}
// Add up amount of energy stored in items in all slots except output and return that value
public int getTotalEnergy()
{
// Add up amount of energy stored in items in all slots except output and
// return that value
public int getTotalEnergy(){
int energySum = 0;
for (int i = 0; i < Info.BS_SLOT_POWER_START + 12; i++)
{
if (i == Info.BS_SLOT_OUTPUT) continue;
for(int i = 0; i < Info.BS_SLOT_POWER_START + 12; i++){
if(i == Info.BS_SLOT_OUTPUT)
continue;
final ItemStack stack = contents[i];
if (stack != null && stack.getItem() instanceof IElectricItem && stack.stackSize == 1)
{
final IElectricItem item = (IElectricItem)(stack.getItem());
if (item.getTier(stack) <= powerTier && item.canProvideEnergy(stack) && Item.getIdFromItem(stack.getItem()) == Item.getIdFromItem(item.getChargedItem(stack)))
{
if(stack != null && stack.getItem() instanceof IElectricItem && stack.stackSize == 1){
final IElectricItem item = (IElectricItem) (stack.getItem());
if(item.getTier(stack) <= powerTier && item.canProvideEnergy(stack)
&& Item.getIdFromItem(stack.getItem()) == Item.getIdFromItem(item.getChargedItem(stack))){
final double chargeReturned = ElectricItem.manager.discharge(stack, Integer.MAX_VALUE, powerTier, true, true, false);
if (chargeReturned > 0)
{
// Add the energy we received to our current energy level
if(chargeReturned > 0){
// Add the energy we received to our current energy
// level
energySum += chargeReturned;
}
}
@ -445,12 +443,11 @@ public class TEBatteryStation extends TECommonBench implements IEnergySource, II
}
return energySum;
}
//Networking stuff
// Networking stuff
@Override
public Packet getDescriptionPacket()
{
public Packet getDescriptionPacket(){
return createDescPacket();
}
@ -458,96 +455,82 @@ public class TEBatteryStation extends TECommonBench implements IEnergySource, II
protected void addUniqueDescriptionData(ByteBuf data) throws IOException{
data.writeBoolean(doingWork);
}
@SideOnly(Side.CLIENT)
@Override
public void receiveDescriptionData(int packetID, ByteBuf stream){
boolean b = doingWork;
//try
//{
b = stream.readBoolean();
/*}
catch (IOException e)
{
logDescPacketError(e);
return;
}*/
// try
// {
b = stream.readBoolean();
/*
* } catch (IOException e) { logDescPacketError(e); return; }
*/
doingWork = b;
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
@Override
public void receiveGuiButton(int buttonID)
{
if (buttonID == 0)
{
public void receiveGuiButton(int buttonID){
if(buttonID == 0){
opMode ^= 1;
}
}
// ISidedInventory
/*
* @Override public int getStartInventorySide(ForgeDirection side) { switch
* (side) { case UP: case DOWN: return Info.BS_SLOT_INPUT; default: return
* Info.BS_SLOT_OUTPUT; } }
*
* @Override public int getSizeInventorySide(ForgeDirection side) { // Each
* side accesses a single slot return 1; }
*/
@Override
public int getStartInventorySide(ForgeDirection side)
{
switch (side)
{
case UP:
case DOWN:
return Info.BS_SLOT_INPUT;
default:
return Info.BS_SLOT_OUTPUT;
}
public int[] getAccessibleSlotsFromSide(int side){
return BatteryStationSideInOut; // Testing I/O constraint methods
// func_102007_a, func_102008_b
}
@Override
public int getSizeInventorySide(ForgeDirection side)
{
// Each side accesses a single slot
return 1;
}
*/
@Override
public int[] getAccessibleSlotsFromSide(int side)
{
return BatteryStationSideInOut; // Testing I/O constraint methods func_102007_a, func_102008_b
}
@Override
public boolean isItemValidForSlot(int i, ItemStack stack)
{
if (i == Info.BS_SLOT_INPUT) return Utils.isItemDrainable(stack, powerTier);
public boolean isItemValidForSlot(int i, ItemStack stack){
if(i == Info.BS_SLOT_INPUT)
return Utils.isItemDrainable(stack, powerTier);
return false;
}
// Returns true if automation can insert the given item in the given slot from the given side. Args: Slot, item, side
// Returns true if automation can insert the given item in the given slot
// from the given side. Args: Slot, item, side
@Override
public boolean canInsertItem(int i, ItemStack itemstack, int j) // canInsertItem
{
if (i == Info.BS_SLOT_INPUT) return true;
if(i == Info.BS_SLOT_INPUT)
return true;
return false;
}
// Returns true if automation can extract the given item in the given slot from the given side. Args: Slot, item, side
// Returns true if automation can extract the given item in the given slot
// from the given side. Args: Slot, item, side
@Override
public boolean canExtractItem(int i, ItemStack itemstack, int j){ // canExtractItem
if (i == Info.BS_SLOT_OUTPUT) return true;
if(i == Info.BS_SLOT_OUTPUT)
return true;
return false;
}
// IInventory
@Override
public int getSizeInventory(){
// Only input/output slots are accessible to machines
return 2;
}
@Override
public String getInventoryName(){
switch (baseTier){
switch(baseTier){
case 1:
return Info.KEY_BLOCK_NAMES[8] + Info.KEY_NAME_SUFFIX;
case 2:
@ -557,10 +540,10 @@ public class TEBatteryStation extends TECommonBench implements IEnergySource, II
}
return "";
}
@Override
public void markDirty(int slot){
if (slot == Info.BS_SLOT_INPUT || slot == Info.BS_SLOT_OUTPUT){
if(slot == Info.BS_SLOT_INPUT || slot == Info.BS_SLOT_OUTPUT){
rejectInvalidInput();
}
super.markDirty();

View file

@ -23,112 +23,128 @@ import net.minecraft.tileentity.TileEntity;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.FMLLog;
public abstract class TECommon extends TileEntity
{
public abstract class TECommon extends TileEntity{
@Override
public boolean canUpdate()
{
public boolean canUpdate(){
return true;
}
/**
* TileEntities override this to select a GUI to open on block activation
*
* @return int guiID
*/
public int getGuiID()
{
public int getGuiID(){
return -1;
}
/**
* TileEntites implement this to receive packet data, they are then responsible
* in their own code to handle the packet.
* @param packetID The first value from the packet, in case it's needed again
* @param stream The remaining unread packet data for the tile entity to handle
* TileEntites implement this to receive packet data, they are then
* responsible in their own code to handle the packet.
*
* @param packetID
* The first value from the packet, in case it's needed again
* @param stream
* The remaining unread packet data for the tile entity to handle
*/
public void receiveDescriptionData(int packetID, ByteBuf stream) {} // Stub for classes that need no desc data
public void receiveGuiButton(int buttonID) {} // Stub for classes with no buttons
public void receiveGuiControl(int controlID, int state) {} // Stub for classes with no other controls
public void receiveGuiText(int fieldID, String text) {} // Stub for classes with no text fields
public void receiveDescriptionData(int packetID, ByteBuf stream){} // Stub
// for
// classes
// that
// need
// no
// desc
// data
public void receiveGuiButton(int buttonID){} // Stub for classes with no
// buttons
public void receiveGuiControl(int controlID, int state){} // Stub for
// classes with
// no other
// controls
public void receiveGuiText(int fieldID, String text){} // Stub for classes
// with no text
// fields
/**
* Packet transmission from client to server of what button was clicked on the GUI.
* @param id = the button ID
* Packet transmission from client to server of what button was clicked on
* the GUI.
*
* @param id
* = the button ID
*/
public void sendGuiButton(int id)
{
public void sendGuiButton(int id){
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
DataOutputStream data = new DataOutputStream(bytes);
try
{
try{
data.writeInt(0); // Packet ID for GUI button clicks
data.writeInt(xCoord);
data.writeInt(yCoord);
data.writeInt(zCoord);
data.writeInt(id);
}
catch (IOException e)
{
}catch(IOException e){
FMLLog.getLogger().info("[AdvancedPowerManagement] " + "Client failed to create packet. (Details: " + e.toString() + ")");
return;
}
//AdvancedPowerManagement.proxy.sendPacketToServer(new Packet250CustomPayload(Info.PACKET_CHANNEL, bytes.toByteArray()));
// AdvancedPowerManagement.proxy.sendPacketToServer(new
// Packet250CustomPayload(Info.PACKET_CHANNEL, bytes.toByteArray()));
ChannelHandler.instance.sendToServer(new AdvPacket(bytes.toByteArray()));
}
/**
* Does the bulk of the work of creating the description packet.
* Performs a callback to addUniqueDescriptionData. That method must be overridden.
* We're not overriding getDescriptionPacket in this class because not all of our tile entities need such packets.
* Does the bulk of the work of creating the description packet. Performs a
* callback to addUniqueDescriptionData. That method must be overridden.
* We're not overriding getDescriptionPacket in this class because not all
* of our tile entities need such packets.
*
* @return The completed Packet250.
*/
protected Packet createDescPacket()
{
//if (ChargingBench.isDebugging) System.out.println("TE getAuxillaryInfoPacket()");
//ByteArrayOutputStream bytes = new ByteArrayOutputStream();
//DataOutputStream data = new DataOutputStream(bytes);
protected Packet createDescPacket(){
// if (ChargingBench.isDebugging)
// System.out.println("TE getAuxillaryInfoPacket()");
// ByteArrayOutputStream bytes = new ByteArrayOutputStream();
// DataOutputStream data = new DataOutputStream(bytes);
ByteBuf data = Unpooled.buffer();
try
{
try{
data.writeInt(0);
data.writeInt(xCoord);
data.writeInt(yCoord);
data.writeInt(zCoord);
addUniqueDescriptionData(data);
}
catch (IOException e)
{
}catch(IOException e){
FMLLog.getLogger().info("[AdvancedPowerManagement] " + "Server failed to create description packet. (Details: " + e.toString() + ")");
}
//ChannelHandler.instance.sendToPlayer(new AdvPacket(bytes.toByteArray()), player);
// ChannelHandler.instance.sendToPlayer(new
// AdvPacket(bytes.toByteArray()), player);
return new S3FPacketCustomPayload("Test", data);
}
/**
* Tile Entities that use description packets must override this to write whatever
* information they require into 'data'
* @param data - Base packet data with packet ID and coordinates already written
* Tile Entities that use description packets must override this to write
* whatever information they require into 'data'
*
* @param data
* - Base packet data with packet ID and coordinates already
* written
*/
protected void addUniqueDescriptionData(ByteBuf data) throws IOException
{
// Why can't I throw something that I WANT to be uncaught so it stops the program??
// Piggy-backing on IOException is stupid, but hopefully this will never end up happening anyway.
protected void addUniqueDescriptionData(ByteBuf data) throws IOException{
// Why can't I throw something that I WANT to be uncaught so it stops
// the program??
// Piggy-backing on IOException is stupid, but hopefully this will never
// end up happening anyway.
throw new IOException("This tile entity must override addUniqueDescriptionData to pass its description correctly! " + this.getClass());
}
protected void logDescPacketError(Exception e)
{
protected void logDescPacketError(Exception e){
FMLLog.getLogger().info("[AdvancedPowerManagement] " + "Client received invalid description packet. (Details: " + e.toString() + ")");
}
public void dropContents() {} // Stub for block destroyed event
public void markDirty(int slot)
{
public void dropContents(){} // Stub for block destroyed event
public void markDirty(int slot){
markDirty();
}
}

View file

@ -12,164 +12,141 @@ import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
public abstract class TECommonBench extends TECommon implements IInventory
{
public abstract class TECommonBench extends TECommon implements IInventory{
protected ItemStack[] contents;
protected boolean initialized = false;
public int baseTier;
public int powerTier; // Transformer upgrades allow charging from energy crystals and lapotrons
//For outside texture display
public int powerTier; // Transformer upgrades allow charging from energy
// crystals and lapotrons
// For outside texture display
public boolean doingWork;
public boolean receivingRedstoneSignal()
{
public boolean receivingRedstoneSignal(){
return worldObj.isBlockIndirectlyGettingPowered(xCoord, yCoord, zCoord);
}
@Override
public void invalidate()
{
if (worldObj != null && initialized)
{
EnergyTileUnloadEvent unloadEvent = new EnergyTileUnloadEvent((IEnergyTile)this);
public void invalidate(){
if(worldObj != null && initialized){
EnergyTileUnloadEvent unloadEvent = new EnergyTileUnloadEvent((IEnergyTile) this);
MinecraftForge.EVENT_BUS.post(unloadEvent);
}
super.invalidate();
}
// Common IC2 API function
public boolean isAddedToEnergyNet()
{
public boolean isAddedToEnergyNet(){
return initialized;
}
/**
* This will cause the block to drop anything inside it, create a new item in the
* world of its type, invalidate the tile entity, remove itself from the IC2
* EnergyNet and clear the block space (set it to air)
* This will cause the block to drop anything inside it, create a new item
* in the world of its type, invalidate the tile entity, remove itself from
* the IC2 EnergyNet and clear the block space (set it to air)
*/
protected abstract void selfDestroy();
public void dropItem(ItemStack item)
{
EntityItem entityitem = new EntityItem(worldObj, (double)xCoord + 0.5D, (double)yCoord + 0.5D, (double)zCoord + 0.5D, item);
public void dropItem(ItemStack item){
EntityItem entityitem = new EntityItem(worldObj, (double) xCoord + 0.5D, (double) yCoord + 0.5D, (double) zCoord + 0.5D, item);
entityitem.delayBeforeCanPickup = 10;
worldObj.spawnEntityInWorld(entityitem);
}
@Override
public void dropContents()
{
public void dropContents(){
ItemStack item;
for (int i = 0; i < contents.length; ++i)
{
for(int i = 0; i < contents.length; ++i){
item = contents[i];
contents[i] = null;
if (item != null && item.stackSize > 0) dropItem(item);
if(item != null && item.stackSize > 0)
dropItem(item);
}
}
public abstract int getSizeInventory();
public abstract int getSizeInventory();
@Override
public ItemStack getStackInSlot(int i)
{
public ItemStack getStackInSlot(int i){
return contents[i];
}
@Override
public ItemStack decrStackSize(int slot, int amount)
{
if (this.contents[slot] != null)
{
public ItemStack decrStackSize(int slot, int amount){
if(this.contents[slot] != null){
ItemStack output;
if (this.contents[slot].stackSize <= amount)
{
if(this.contents[slot].stackSize <= amount){
output = this.contents[slot];
this.contents[slot] = null;
this.markDirty(slot);
return output;
}
else
{
}else{
output = this.contents[slot].splitStack(amount);
if (this.contents[slot].stackSize <= 0)
{
if(this.contents[slot].stackSize <= 0){
this.contents[slot] = null;
}
this.markDirty(slot);
return output;
}
}
else
{
}else{
return null;
}
}
@Override
public ItemStack getStackInSlotOnClosing(int slot)
{
if (this.contents[slot] == null)
{
public ItemStack getStackInSlotOnClosing(int slot){
if(this.contents[slot] == null){
return null;
}
ItemStack stack = this.contents[slot];
this.contents[slot] = null;
return stack;
}
@Override
public void setInventorySlotContents(int slot, ItemStack itemstack)
{
public void setInventorySlotContents(int slot, ItemStack itemstack){
this.contents[slot] = itemstack;
if (itemstack != null && itemstack.stackSize > getInventoryStackLimit())
{
if(itemstack != null && itemstack.stackSize > getInventoryStackLimit()){
itemstack.stackSize = getInventoryStackLimit();
}
this.markDirty(slot);
}
/**
* Returns the name of the inventory.
*/
/**
* Returns the name of the inventory.
*/
@Override
public abstract String getInventoryName();
public abstract String getInventoryName();
@Override
public boolean hasCustomInventoryName()
{
public boolean hasCustomInventoryName(){
return false;
}
@Override
public int getInventoryStackLimit()
{
public int getInventoryStackLimit(){
return 64;
}
@Override
public boolean isUseableByPlayer(EntityPlayer entityplayer)
{
if (worldObj.getTileEntity(xCoord, yCoord, zCoord) != this)
{
public boolean isUseableByPlayer(EntityPlayer entityplayer){
if(worldObj.getTileEntity(xCoord, yCoord, zCoord) != this){
return false;
}
return entityplayer.getDistanceSq((double)xCoord + 0.5D, (double)yCoord + 0.5D, (double)zCoord + 0.5D) <= 64D;
return entityplayer.getDistanceSq((double) xCoord + 0.5D, (double) yCoord + 0.5D, (double) zCoord + 0.5D) <= 64D;
}
@Override
public void openInventory() {}
public void openInventory(){}
@Override
public void closeInventory() {}
public void closeInventory(){}
}

View file

@ -31,174 +31,158 @@ import net.minecraftforge.common.util.ForgeDirection;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class TEStorageMonitor extends TECommon implements ISidedInventory
{
public class TEStorageMonitor extends TECommon implements ISidedInventory{
private ItemStack[] contents;
private int tickTime = 0;
private int tickDelay = 5;
public int lowerBoundary = 60;
public int upperBoundary = 90;
private boolean tileLoaded = false;
public int energyStored = 0;
public int energyCapacity = 0;
public int chargeLevel = 0;
public boolean isPowering = false;
public boolean blockState = false;
public int[] targetCoords;
private static final int[] storageMonitorSideUniversal = {Info.SM_SLOT_UNIVERSAL};
public TEStorageMonitor()
{
public TEStorageMonitor() {
super();
contents = new ItemStack[Info.SM_INVENTORY_SIZE];
}
/**
* Reads a tile entity from NBT.
*/
@Override
public void readFromNBT(NBTTagCompound nbttagcompound)
{
public void readFromNBT(NBTTagCompound nbttagcompound){
super.readFromNBT(nbttagcompound);
// State info to remember
isPowering = nbttagcompound.getBoolean("isPowering");
upperBoundary = nbttagcompound.getInteger("upperBoundary");
lowerBoundary = nbttagcompound.getInteger("lowerBoundary");
// Our inventory
NBTTagList nbttaglist = nbttagcompound.getTagList("Items", Constants.NBT.TAG_COMPOUND);
//Redundant: contents = new ItemStack[Info.SM_INVENTORY_SIZE];
for (int i = 0; i < nbttaglist.tagCount(); ++i)
{
NBTTagCompound nbttagcompound1 = (NBTTagCompound)nbttaglist.getCompoundTagAt(i);
// Redundant: contents = new ItemStack[Info.SM_INVENTORY_SIZE];
for(int i = 0; i < nbttaglist.tagCount(); ++i){
NBTTagCompound nbttagcompound1 = (NBTTagCompound) nbttaglist.getCompoundTagAt(i);
int j = nbttagcompound1.getByte("Slot") & 255;
if (j >= 0 && j < contents.length)
{
if(j >= 0 && j < contents.length){
contents[j] = ItemStack.loadItemStackFromNBT(nbttagcompound1);
}
}
}
/**
* Writes a tile entity to NBT.
*/
@Override
public void writeToNBT(NBTTagCompound nbttagcompound)
{
public void writeToNBT(NBTTagCompound nbttagcompound){
super.writeToNBT(nbttagcompound);
// State info to remember
nbttagcompound.setBoolean("isPowering", isPowering);
nbttagcompound.setInteger("upperBoundary", upperBoundary);
nbttagcompound.setInteger("lowerBoundary", lowerBoundary);
// Our inventory
NBTTagList nbttaglist = new NBTTagList();
for (int i = 0; i < contents.length; ++i)
{
if (contents[i] != null)
{
//if (ChargingBench.isDebugging) System.out.println("WriteNBT contents[" + i + "] stack tag: " + contents[i].stackTagCompound);
for(int i = 0; i < contents.length; ++i){
if(contents[i] != null){
// if (ChargingBench.isDebugging)
// System.out.println("WriteNBT contents[" + i + "] stack tag: "
// + contents[i].stackTagCompound);
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
nbttagcompound1.setByte("Slot", (byte)i);
nbttagcompound1.setByte("Slot", (byte) i);
contents[i].writeToNBT(nbttagcompound1);
nbttaglist.appendTag(nbttagcompound1);
}
}
nbttagcompound.setTag("Items", nbttaglist);
}
@Override
public int getGuiID()
{
public int getGuiID(){
return Info.GUI_ID_STORAGE_MONITOR;
}
/**
* This will cause the block to drop anything inside it, create a new item in the
* world of its type, invalidate the tile entity, remove itself from the IC2
* EnergyNet and clear the block space (set it to air)
* This will cause the block to drop anything inside it, create a new item
* in the world of its type, invalidate the tile entity, remove itself from
* the IC2 EnergyNet and clear the block space (set it to air)
*/
private void selfDestroy()
{
private void selfDestroy(){
dropContents();
ItemStack stack = new ItemStack(AdvancedPowerManagement.blockAdvPwrMan, 1, 11);
dropItem(stack);
worldObj.setBlockToAir(xCoord, yCoord, zCoord);
this.invalidate();
}
public void dropItem(ItemStack item)
{
EntityItem entityitem = new EntityItem(worldObj, (double)xCoord + 0.5D, (double)yCoord + 0.5D, (double)zCoord + 0.5D, item);
public void dropItem(ItemStack item){
EntityItem entityitem = new EntityItem(worldObj, (double) xCoord + 0.5D, (double) yCoord + 0.5D, (double) zCoord + 0.5D, item);
entityitem.delayBeforeCanPickup = 10;
worldObj.spawnEntityInWorld(entityitem);
}
@Override
public void dropContents()
{
public void dropContents(){
ItemStack item;
int i;
for (i = 0; i < contents.length; ++i)
{
for(i = 0; i < contents.length; ++i){
item = contents[i];
if (item != null && item.stackSize > 0) dropItem(item);
if(item != null && item.stackSize > 0)
dropItem(item);
}
}
public boolean isItemValid(int slot, ItemStack stack)
{
// Decide if the item is valid to place in a slot
return stack != null && stack.getItem() instanceof ItemStorageLinkCard;
public boolean isItemValid(int slot, ItemStack stack){
// Decide if the item is valid to place in a slot
return stack != null && stack.getItem() instanceof ItemStorageLinkCard;
}
/**
* Runs once on tile entity load to make sure all of our internals are setup correctly
* Runs once on tile entity load to make sure all of our internals are setup
* correctly
*/
private void onLoad()
{
if (!AdvancedPowerManagement.proxy.isClient())
{
private void onLoad(){
if(!AdvancedPowerManagement.proxy.isClient()){
tileLoaded = true;
checkInventory();
if (targetCoords != null)
{
if(targetCoords != null){
TileEntity tile = null;
if (targetCoords[3] == worldObj.provider.dimensionId)
{
if(targetCoords[3] == worldObj.provider.dimensionId){
tile = worldObj.getTileEntity(targetCoords[0], targetCoords[1], targetCoords[2]);
}
if (tile instanceof IEnergyStorage)
{
energyStored = ((IEnergyStorage)tile).getStored();
energyCapacity = ((IEnergyStorage)tile).getCapacity();
if(tile instanceof IEnergyStorage){
energyStored = ((IEnergyStorage) tile).getStored();
energyCapacity = ((IEnergyStorage) tile).getCapacity();
blockState = true;
}
else
{
}else{
energyStored = 0;
energyCapacity = 0;
blockState = false;
}
}
chargeLevel = gaugeEnergyScaled(12);
if (energyCapacity > 0) // Avoid divide by zero and also test if the remote energy storage is valid
if(energyCapacity > 0) // Avoid divide by zero and also test if the
// remote energy storage is valid
{
updateRedstone();
}
else if (isPowering) // If we're emitting redstone at this point, we need to shut it off
}else if(isPowering) // If we're emitting redstone at this point, we
// need to shut it off
{
isPowering = false;
worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, worldObj.getBlock(xCoord, yCoord, zCoord));
@ -206,390 +190,364 @@ public class TEStorageMonitor extends TECommon implements ISidedInventory
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
}
@Override
public void updateEntity() //TODO Marked for easy access
public void updateEntity() // TODO Marked for easy access
{
if (AdvancedPowerManagement.proxy.isClient()) return;
if (!tileLoaded)
{
if(AdvancedPowerManagement.proxy.isClient())
return;
if(!tileLoaded){
onLoad();
}
// Delayed work
if (tickTime > 0)
{
if(tickTime > 0){
tickTime--;
}
else
{
}else{
tickTime = tickDelay;
if (targetCoords != null)
{
if(targetCoords != null){
TileEntity tile = null;
if (targetCoords[3] == worldObj.provider.dimensionId)
{
if(targetCoords[3] == worldObj.provider.dimensionId){
tile = worldObj.getTileEntity(targetCoords[0], targetCoords[1], targetCoords[2]);
}
if (tile instanceof IEnergyStorage)
{
//if (ChargingBench.isDebugging) System.out.println("updateEntity - check energy level of remote block");
energyStored = ((IEnergyStorage)tile).getStored();
energyCapacity = ((IEnergyStorage)tile).getCapacity();
if (!blockState)
{
if(tile instanceof IEnergyStorage){
// if (ChargingBench.isDebugging)
// System.out.println("updateEntity - check energy level of remote block");
energyStored = ((IEnergyStorage) tile).getStored();
energyCapacity = ((IEnergyStorage) tile).getCapacity();
if(!blockState){
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
blockState = true;
}
else
{
}else{
energyStored = 0;
energyCapacity = 0;
if (blockState)
{
if(blockState){
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
blockState = false;
}
}
if (energyCapacity > 0) // Avoid divide by zero and also test if the remote energy storage is valid
if(energyCapacity > 0) // Avoid divide by zero and also test if the
// remote energy storage is valid
{
updateRedstone();
}
else if (isPowering) // If we're emitting redstone at this point, we need to shut it off
}else if(isPowering) // If we're emitting redstone at this point, we
// need to shut it off
{
isPowering = false;
worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, worldObj.getBlock(xCoord, yCoord, zCoord));
}
// Trigger this only when charge level passes where it would need to update the client texture
// Trigger this only when charge level passes where it would need to
// update the client texture
int oldChargeLevel = chargeLevel;
chargeLevel = gaugeEnergyScaled(12);
if (oldChargeLevel != chargeLevel)
{
//if (ChargingBench.isDebugging) System.out.println("TE oldChargeLevel: " + oldChargeLevel + " chargeLevel: " + chargeLevel);
if(oldChargeLevel != chargeLevel){
// if (ChargingBench.isDebugging)
// System.out.println("TE oldChargeLevel: " + oldChargeLevel +
// " chargeLevel: " + chargeLevel);
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
}
}
private void updateRedstone()
{
float chargePercent = ((float)energyStored * 100.0F) / (float)energyCapacity;
if ((isPowering == false && chargePercent < lowerBoundary) || (isPowering == true && chargePercent >= upperBoundary))
{
if (Info.isDebugging) System.out.println("Storage Monitor toggling redstone. chargePercent:" + chargePercent);
private void updateRedstone(){
float chargePercent = ((float) energyStored * 100.0F) / (float) energyCapacity;
if((isPowering == false && chargePercent < lowerBoundary) || (isPowering == true && chargePercent >= upperBoundary)){
if(Info.isDebugging)
System.out.println("Storage Monitor toggling redstone. chargePercent:" + chargePercent);
isPowering = !isPowering;
worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, worldObj.getBlock(xCoord, yCoord, zCoord));
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
}
private void checkInventory()
{
private void checkInventory(){
ItemStack item = getStackInSlot(Info.SM_SLOT_UNIVERSAL);
if (item == null || !(item.getItem() instanceof ItemStorageLinkCard))
{
if(item == null || !(item.getItem() instanceof ItemStorageLinkCard)){
targetCoords = null;
energyCapacity = 0;
energyStored = 0;
blockState = false;
}
else
{
}else{
targetCoords = ItemCardBase.getCoordinates(item);
ItemCardBase.setCoordinates(item, targetCoords); // Make sure old cards have a dimension number
ItemCardBase.setCoordinates(item, targetCoords); // Make sure old
// cards have a
// dimension
// number
}
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
boolean receivingRedstoneSignal()
{
boolean receivingRedstoneSignal(){
return worldObj.isBlockIndirectlyGettingPowered(xCoord, yCoord, zCoord);
}
public int gaugeEnergyScaled(int gaugeSize)
{
if (energyStored <= 0 || energyCapacity <= 0)
{
public int gaugeEnergyScaled(int gaugeSize){
if(energyStored <= 0 || energyCapacity <= 0){
return 0;
}
int result = energyStored * gaugeSize / energyCapacity;
if (result > gaugeSize) result = gaugeSize;
if(result > gaugeSize)
result = gaugeSize;
return result;
}
//Networking stuff
// Networking stuff
/**
* Packet reception by server of what button was clicked on the client's GUI.
* @param id = the button ID
* Packet reception by server of what button was clicked on the client's
* GUI.
*
* @param id
* = the button ID
*/
@Override
public void receiveGuiButton(int id)
{
switch (id)
{
public void receiveGuiButton(int id){
switch(id){
case 0:
upperBoundary -= 10;
if (upperBoundary < 1) upperBoundary = 1;
if (upperBoundary < lowerBoundary) lowerBoundary = upperBoundary;
if(upperBoundary < 1)
upperBoundary = 1;
if(upperBoundary < lowerBoundary)
lowerBoundary = upperBoundary;
break;
case 1:
upperBoundary -= 1;
if (upperBoundary < 1) upperBoundary = 1;
if (upperBoundary < lowerBoundary) lowerBoundary = upperBoundary;
if(upperBoundary < 1)
upperBoundary = 1;
if(upperBoundary < lowerBoundary)
lowerBoundary = upperBoundary;
break;
case 2:
upperBoundary += 1;
if (upperBoundary > 100) upperBoundary = 100;
if(upperBoundary > 100)
upperBoundary = 100;
break;
case 3:
upperBoundary += 10;
if (upperBoundary == 11) upperBoundary = 10;
if (upperBoundary > 100) upperBoundary = 100;
if(upperBoundary == 11)
upperBoundary = 10;
if(upperBoundary > 100)
upperBoundary = 100;
break;
case 4:
lowerBoundary -= 10;
if (lowerBoundary < 1) lowerBoundary = 1;
if(lowerBoundary < 1)
lowerBoundary = 1;
break;
case 5:
lowerBoundary -= 1;
if (lowerBoundary < 1) lowerBoundary = 1;
if(lowerBoundary < 1)
lowerBoundary = 1;
break;
case 6:
lowerBoundary += 1;
if (lowerBoundary > 100) lowerBoundary = 100;
if (lowerBoundary > upperBoundary) upperBoundary = lowerBoundary;
if(lowerBoundary > 100)
lowerBoundary = 100;
if(lowerBoundary > upperBoundary)
upperBoundary = lowerBoundary;
break;
case 7:
lowerBoundary += 10;
if (lowerBoundary == 11) lowerBoundary = 10;
if (lowerBoundary > 100) lowerBoundary = 100;
if (lowerBoundary > upperBoundary) upperBoundary = lowerBoundary;
if(lowerBoundary == 11)
lowerBoundary = 10;
if(lowerBoundary > 100)
lowerBoundary = 100;
if(lowerBoundary > upperBoundary)
upperBoundary = lowerBoundary;
break;
}
}
@Override
public Packet getDescriptionPacket()
{
public Packet getDescriptionPacket(){
return createDescPacket();
}
@Override
protected void addUniqueDescriptionData(ByteBuf data) throws IOException
{
protected void addUniqueDescriptionData(ByteBuf data) throws IOException{
data.writeInt(chargeLevel);
data.writeBoolean(isPowering);
data.writeBoolean(blockState);
}
@SideOnly(Side.CLIENT)
@Override
public void receiveDescriptionData(int packetID, ByteBuf stream)
{
public void receiveDescriptionData(int packetID, ByteBuf stream){
final int a;
final boolean b;
final boolean c;
//try
//{
a = stream.readInt();
b = stream.readBoolean();
c = stream.readBoolean();
/*}
catch (IOException e)
{
logDescPacketError(e);
return;
}*/
// try
// {
a = stream.readInt();
b = stream.readBoolean();
c = stream.readBoolean();
/*
* } catch (IOException e) { logDescPacketError(e); return; }
*/
chargeLevel = a;
isPowering = b;
blockState = c;
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
// ISidedInventory
/* @Override
public int getStartInventorySide(ForgeDirection side)
{
return Info.SM_SLOT_UNIVERSAL;
}
/*
* @Override public int getStartInventorySide(ForgeDirection side) { return
* Info.SM_SLOT_UNIVERSAL; }
*
* @Override public int getSizeInventorySide(int side) { // Each side
* accesses a single slot return 1; }
*/
@Override
public int getSizeInventorySide(int side)
{
// Each side accesses a single slot
return 1;
}
*/
@Override
public int[] getAccessibleSlotsFromSide(int side)
{
public int[] getAccessibleSlotsFromSide(int side){
return storageMonitorSideUniversal;
}
@Override
public boolean isItemValidForSlot(int i, ItemStack stack)
{
public boolean isItemValidForSlot(int i, ItemStack stack){
// Decide if the item is a link card
return (i == Info.SM_SLOT_UNIVERSAL && stack != null && stack.getItem() instanceof ItemStorageLinkCard);
return (i == Info.SM_SLOT_UNIVERSAL && stack != null && stack.getItem() instanceof ItemStorageLinkCard);
}
// Returns true if automation can insert the given item in the given slot from the given side. Args: Slot, item, side
// Returns true if automation can insert the given item in the given slot
// from the given side. Args: Slot, item, side
@Override
public boolean canInsertItem(int i, ItemStack itemstack, int j) // canInsertItem
{
return true;
}
// Returns true if automation can extract the given item in the given slot from the given side. Args: Slot, item, side
// Returns true if automation can extract the given item in the given slot
// from the given side. Args: Slot, item, side
@Override
public boolean canExtractItem(int i, ItemStack itemstack, int j) // canExtractItem
{
return true;
}
// IInventory
@Override
public boolean hasCustomInventoryName()
{
public boolean hasCustomInventoryName(){
return false;
}
@Override
public int getSizeInventory()
{
public int getSizeInventory(){
// Only input/output slots are accessible to machines
return 1;
}
@Override
public ItemStack getStackInSlot(int i)
{
public ItemStack getStackInSlot(int i){
return contents[i];
}
@Override
public ItemStack decrStackSize(int slot, int amount)
{
if (contents[slot] != null)
{
public ItemStack decrStackSize(int slot, int amount){
if(contents[slot] != null){
ItemStack output;
if (contents[slot].stackSize <= amount)
{
if(contents[slot].stackSize <= amount){
output = contents[slot];
contents[slot] = null;
this.markDirty(slot);
return output;
}
else
{
}else{
output = contents[slot].splitStack(amount);
if (contents[slot].stackSize == 0)
{
if(contents[slot].stackSize == 0){
contents[slot] = null;
}
this.markDirty(slot);
return output;
}
}
else
{
}else{
return null;
}
}
@Override
public ItemStack getStackInSlotOnClosing(int slot)
{
if (contents[slot] == null)
{
public ItemStack getStackInSlotOnClosing(int slot){
if(contents[slot] == null){
return null;
}
ItemStack stack = contents[slot];
contents[slot] = null;
return stack;
}
@Override
public void setInventorySlotContents(int slot, ItemStack itemstack)
{
public void setInventorySlotContents(int slot, ItemStack itemstack){
contents[slot] = itemstack;
if (Info.isDebugging && itemstack != null)
{
if (AdvancedPowerManagement.proxy.isServer())
{
if(Info.isDebugging && itemstack != null){
if(AdvancedPowerManagement.proxy.isServer()){
System.out.println("Server assigned stack tag: " + itemstack.stackTagCompound);
// if (itemstack.stackTagCompound != null) System.out.println(" " + itemstack.stackTagCompound.getTags().toString());
// if (itemstack.stackTagCompound != null)
// System.out.println(" " +
// itemstack.stackTagCompound.getTags().toString());
}
if (AdvancedPowerManagement.proxy.isClient())
{
if(AdvancedPowerManagement.proxy.isClient()){
System.out.println("Client assigned stack tag: " + itemstack.stackTagCompound);
// if (itemstack.stackTagCompound != null) System.out.println(" " + itemstack.stackTagCompound.getTags().toString());
// if (itemstack.stackTagCompound != null)
// System.out.println(" " +
// itemstack.stackTagCompound.getTags().toString());
}
}
if (itemstack != null && itemstack.stackSize > getInventoryStackLimit())
{
if(itemstack != null && itemstack.stackSize > getInventoryStackLimit()){
itemstack.stackSize = getInventoryStackLimit();
}
this.markDirty(slot);
}
@Override
public void markDirty(int slot)
{
public void markDirty(int slot){
this.markDirty();
}
@Override
public void markDirty()
{
if (Info.isDebugging) System.out.println("TEStorageMonitor.onInventoryChanged");
public void markDirty(){
if(Info.isDebugging)
System.out.println("TEStorageMonitor.onInventoryChanged");
checkInventory();
super.markDirty();
}
@Override
public String getInventoryName()
{
public String getInventoryName(){
return Info.KEY_BLOCK_NAMES[11] + Info.KEY_NAME_SUFFIX;
}
@Override
public int getInventoryStackLimit()
{
public int getInventoryStackLimit(){
return 64;
}
@Override
public boolean isUseableByPlayer(EntityPlayer entityplayer)
{
if (worldObj.getTileEntity(xCoord, yCoord, zCoord) != this)
{
public boolean isUseableByPlayer(EntityPlayer entityplayer){
if(worldObj.getTileEntity(xCoord, yCoord, zCoord) != this){
return false;
}
return entityplayer.getDistanceSq((double)xCoord + 0.5D, (double)yCoord + 0.5D, (double)zCoord + 0.5D) <= 64D;
return entityplayer.getDistanceSq((double) xCoord + 0.5D, (double) yCoord + 0.5D, (double) zCoord + 0.5D) <= 64D;
}
@Override
public void openInventory() {}
public void openInventory(){}
@Override
public void closeInventory() {}
public void closeInventory(){}
}