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.ByteBuf;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
public class AdvPacket public class AdvPacket{
{
byte[] data; byte[] data;
public AdvPacket () {} public AdvPacket() {}
public AdvPacket(byte[] packet) public AdvPacket(byte[] packet) {
{
this.data = packet.clone(); 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.common.registry.GameRegistry;
import cpw.mods.fml.relauncher.Side; 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 public class AdvancedPowerManagement // implements ICraftingHandler
{ {
@SidedProxy(clientSide = "com.kaijin.AdvPowerMan.ClientProxy", serverSide = "com.kaijin.AdvPowerMan.CommonProxy") @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") @Instance("AdvancedPowerManagement")
public static AdvancedPowerManagement instance; //The instance of the mod that will be defined, populated, and callable public static AdvancedPowerManagement instance; // The instance of the mod
// that will be defined,
//Channels for handling packages // populated, and callable
// Channels for handling packages
public static EnumMap<Side, FMLEmbeddedChannel> channels; public static EnumMap<Side, FMLEmbeddedChannel> channels;
public static Logger logger; public static Logger logger;
public static Block blockAdvPwrMan; public static Block blockAdvPwrMan;
public static Item itemBenchTools; public static Item itemBenchTools;
public static Item itemStorageLinkCard; public static Item itemStorageLinkCard;
public static Item itemStorageLinkCardCreator; public static Item itemStorageLinkCardCreator;
@EventHandler @EventHandler
public static void preInit(FMLPreInitializationEvent event) public static void preInit(FMLPreInitializationEvent event){
{
Info.isDebugging = false; Info.isDebugging = false;
logger = event.getModLog(); logger = event.getModLog();
try try{
{
Configuration configuration = new Configuration(event.getSuggestedConfigurationFile()); Configuration configuration = new Configuration(event.getSuggestedConfigurationFile());
configuration.load(); configuration.load();
// Read or create config file properties, reusing any block and item IDs discovered in old file, if it was present // Read or create config file properties, reusing any block and item
Info.isDebugging = configuration.get(configuration.CATEGORY_GENERAL, "debug", Info.isDebugging).getBoolean(Info.isDebugging); // IDs discovered in old file, if it was present
Info.isDebugging = configuration.get(configuration.CATEGORY_GENERAL, "debug", Info.isDebugging).getBoolean(Info.isDebugging);
configuration.save(); configuration.save();
} }catch(Exception e){
catch (Exception e)
{
logger.warn("Error while trying to access configuration!", e); logger.warn("Error while trying to access configuration!", e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@EventHandler @EventHandler
public void load(FMLInitializationEvent event) public void load(FMLInitializationEvent event){
{
logger.info("Loading."); logger.info("Loading.");
blockAdvPwrMan = new BlockAdvPwrMan(Material.ground); blockAdvPwrMan = new BlockAdvPwrMan(Material.ground);
GameRegistry.registerBlock(blockAdvPwrMan, ItemBlockAdvPwrMan.class, "blockAdvPwrMan"); GameRegistry.registerBlock(blockAdvPwrMan, ItemBlockAdvPwrMan.class, "blockAdvPwrMan");
// Charging Benches // 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, "MV Charging Bench"); // Legacy
GameRegistry.registerTileEntity(TEChargingBench.class, "HV 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 // 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, "MV Battery Station"); // Legacy
GameRegistry.registerTileEntity(TEBatteryStation.class, "HV 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 // Adjustable Transformer
GameRegistry.registerTileEntity(TEAdjustableTransformer.class, "kaijin.adjTransformer"); GameRegistry.registerTileEntity(TEAdjustableTransformer.class, "kaijin.adjTransformer");
// Storage Monitor // Storage Monitor
GameRegistry.registerTileEntity(TEStorageMonitor.class, "kaijin.storageMonitor"); GameRegistry.registerTileEntity(TEStorageMonitor.class, "kaijin.storageMonitor");
// Emitters // 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, "MV Emitter"); // Legacy
GameRegistry.registerTileEntity(TEAdvEmitter.class, "HV Emitter"); // Legacy GameRegistry.registerTileEntity(TEAdvEmitter.class, "HV Emitter"); // Legacy
GameRegistry.registerTileEntity(TEAdvEmitter.class, "EV Emitter"); // Legacy GameRegistry.registerTileEntity(TEAdvEmitter.class, "EV Emitter"); // Legacy
GameRegistry.registerTileEntity(TEAdvEmitter.class, "kaijin.emitter"); // Now legacy as well GameRegistry.registerTileEntity(TEAdvEmitter.class, "kaijin.emitter"); // Now
GameRegistry.registerTileEntity(TEAdvEmitter.class, "kaijin.advEmitter"); // Proper mapping // legacy
// as
// well
GameRegistry.registerTileEntity(TEAdvEmitter.class, "kaijin.advEmitter"); // Proper
// mapping
// Items // Items
itemBenchTools = new ItemBenchTools("benchTools.toolkit"); itemBenchTools = new ItemBenchTools("benchTools.toolkit");
itemStorageLinkCard = new ItemStorageLinkCard("itemStorageLinkCard"); itemStorageLinkCard = new ItemStorageLinkCard("itemStorageLinkCard");
itemStorageLinkCardCreator = new ItemStorageLinkCardCreator("itemStorageLinkCardCreator"); itemStorageLinkCardCreator = new ItemStorageLinkCardCreator("itemStorageLinkCardCreator");
//Info.registerTranslations(); // Info.registerTranslations();
//register channel handler // register channel handler
channels = NetworkRegistry.INSTANCE.newChannel("APMKaijin", ChannelHandler.instance); channels = NetworkRegistry.INSTANCE.newChannel("APMKaijin", ChannelHandler.instance);
if (event.getSide().isClient()) if(event.getSide().isClient()){
{
FMLEventChannel events = NetworkRegistry.INSTANCE.newEventDrivenChannel("Test"); FMLEventChannel events = NetworkRegistry.INSTANCE.newEventDrivenChannel("Test");
events.register(new ClientPacketHandler()); events.register(new ClientPacketHandler());
} }
NetworkRegistry.INSTANCE.registerGuiHandler(instance, proxy); NetworkRegistry.INSTANCE.registerGuiHandler(instance, proxy);
proxy.load(); proxy.load();
// For returning charging benches and deconstructing them // For returning charging benches and deconstructing them
Info.componentCopperCable = IC2Items.getItem("insulatedCopperCableItem").copy(); Info.componentCopperCable = IC2Items.getItem("insulatedCopperCableItem").copy();
Info.componentCopperCable.stackSize = 3; Info.componentCopperCable.stackSize = 3;
@ -155,72 +179,101 @@ public class AdvancedPowerManagement // implements ICraftingHandler
Info.componentMFE = IC2Items.getItem("mfeUnit").copy(); Info.componentMFE = IC2Items.getItem("mfeUnit").copy();
Info.componentMFSU = IC2Items.getItem("mfsUnit").copy(); Info.componentMFSU = IC2Items.getItem("mfsUnit").copy();
Info.componentCircuit = IC2Items.getItem("electronicCircuit").copy(); Info.componentCircuit = IC2Items.getItem("electronicCircuit").copy();
// For internal reference to verify items can be placed in inventory. // For internal reference to verify items can be placed in inventory.
Info.ic2overclockerUpg = IC2Items.getItem("overclockerUpgrade").copy(); Info.ic2overclockerUpg = IC2Items.getItem("overclockerUpgrade").copy();
Info.ic2transformerUpg = IC2Items.getItem("transformerUpgrade").copy(); Info.ic2transformerUpg = IC2Items.getItem("transformerUpgrade").copy();
Info.ic2storageUpg = IC2Items.getItem("energyStorageUpgrade").copy(); Info.ic2storageUpg = IC2Items.getItem("energyStorageUpgrade").copy();
Info.ic2WrenchID = Item.getIdFromItem(IC2Items.getItem("wrench").getItem()); Info.ic2WrenchID = Item.getIdFromItem(IC2Items.getItem("wrench").getItem());
Info.ic2ElectricWrenchID = Item.getIdFromItem(IC2Items.getItem("electricWrench").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."); logger.info("Advanced Power Management 1.7.2.02 loaded.");
} }
if (Info.isDebugging) if(Info.isDebugging){
{
logger.info("Debugging enabled."); logger.info("Debugging enabled.");
} }
logger.info("Done loading."); logger.info("Done loading.");
} }
@EventHandler @EventHandler
public void modsLoaded(FMLPostInitializationEvent event) public void modsLoaded(FMLPostInitializationEvent event){
{
logger.info("Adding crafting recipes."); logger.info("Adding crafting recipes.");
// Charging Bench 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(
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")}); new ItemStack(blockAdvPwrMan, 1, Info.CB_META + 0),
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")}); 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 // 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(
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")}); new ItemStack(blockAdvPwrMan, 1, Info.BS_META + 0),
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")}); 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 // 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[] {"L", "C", "H", 'L', IC2Items.getItem("lvTransformer"),
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")}); '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 // 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 // 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 // Bench Toolkit recipe
GameRegistry.addRecipe(new ItemStack(itemBenchTools, 1, 0), new Object[] {" I ", "S S", 'I', Items.iron_ingot, 'S', Items.stick}); 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 // 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
GameRegistry.addShapelessRecipe(new ItemStack(itemBenchTools, 1, 2), new ItemStack(itemBenchTools, 1, 0), new ItemStack(blockAdvPwrMan, 1, 1)); .addShapelessRecipe(new ItemStack(itemBenchTools, 1, 1), new ItemStack(itemBenchTools, 1, 0), new ItemStack(blockAdvPwrMan, 1, 0));
GameRegistry.addShapelessRecipe(new ItemStack(itemBenchTools, 1, 3), new ItemStack(itemBenchTools, 1, 0), new ItemStack(blockAdvPwrMan, 1, 2)); 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 // 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
GameRegistry.addShapelessRecipe(new ItemStack(blockAdvPwrMan, 1, 1), new ItemStack(itemBenchTools, 1, 0), new ItemStack(itemBenchTools, 1, 2)); .addShapelessRecipe(new ItemStack(blockAdvPwrMan, 1, 0), new ItemStack(itemBenchTools, 1, 0), new ItemStack(itemBenchTools, 1, 1));
GameRegistry.addShapelessRecipe(new ItemStack(blockAdvPwrMan, 1, 2), new ItemStack(itemBenchTools, 1, 0), new ItemStack(itemBenchTools, 1, 3)); 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 * @EventHandler public void certificateWarning(FMLFingerprintViolationEvent
public void certificateWarning(FMLFingerprintViolationEvent event) * 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] Fingerprint does not match! This mod's jar file has been modified from the original version."); * ); FMLLog.warning("[AdvancedPowerManagement] " +
FMLLog.warning("[AdvancedPowerManagement] " + "[Certificate Error] Expected fingerprint: " + event.expectedFingerprint); * "[Certificate Error] Expected fingerprint: " +
FMLLog.warning("[AdvancedPowerManagement] " + "[Certificate Error] File: " + event.source.getAbsolutePath()); * 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.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
public class ChannelHandler extends FMLIndexedMessageToMessageCodec<AdvPacket> public class ChannelHandler extends FMLIndexedMessageToMessageCodec<AdvPacket>{
{ public static ChannelHandler instance = new ChannelHandler();
public static ChannelHandler instance = new ChannelHandler();
public ChannelHandler() {
public ChannelHandler()
{
addDiscriminator(0, AdvPacket.class); addDiscriminator(0, AdvPacket.class);
} }
@Override @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); target.writeBytes(msg.data);
} }
@Override @Override
public void decodeInto(ChannelHandlerContext ctx, ByteBuf source, AdvPacket msg) public void decodeInto(ChannelHandlerContext ctx, ByteBuf source, AdvPacket msg){
{ switch(FMLCommonHandler.instance().getEffectiveSide()){
switch (FMLCommonHandler.instance().getEffectiveSide())
{
case CLIENT: case CLIENT:
AdvancedPowerManagement.instance.proxy.onPacketDataClient(source, ClientProxy.getPlayer()); AdvancedPowerManagement.instance.proxy.onPacketDataClient(source, ClientProxy.getPlayer());
break; break;
case SERVER: 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); AdvancedPowerManagement.instance.proxy.onPacketDataClient(source, netHandler.playerEntity);
break; 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).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.TOSERVER);
AdvancedPowerManagement.channels.get(Side.CLIENT).writeOutbound(packet); 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_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.PLAYER);
AdvancedPowerManagement.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(player); AdvancedPowerManagement.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(player);
AdvancedPowerManagement.channels.get(Side.SERVER).writeOutbound(packet); AdvancedPowerManagement.channels.get(Side.SERVER).writeOutbound(packet);
} }
/* /*
public static void sendToAllPlayers(Packet packet) * public static void sendToAllPlayers(Packet packet) {
{ * AdvancedPowerManagement
AdvancedPowerManagement.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALL); * .channels.get(Side.SERVER).attr(FMLOutboundHandler.
AdvancedPowerManagement.channels.get(Side.SERVER).writeOutbound(packet); * 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.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.network.FMLNetworkEvent.ClientCustomPacketEvent; import cpw.mods.fml.common.network.FMLNetworkEvent.ClientCustomPacketEvent;
public class ClientPacketHandler public class ClientPacketHandler{
{
/* /*
* Packet format: * Packet format: 0: byte Packet Type 1: int x location of TileEntity 2: int
* 0: byte Packet Type * y location of TileEntity 3: int z location of TileEntity
* 1: int x location of TileEntity *
* 2: int y location of TileEntity
* 3: int z location of TileEntity
*
* Currently used packet types * Currently used packet types
* *
* Server-to-Client: * Server-to-Client: 0 = Universal description packet Charging Bench: 4: int
* 0 = Universal description packet * charge level for texture 5: boolean activity state for texture
* Charging Bench: *
* 4: int charge level for texture * Battery Station: 4: boolean activity state for texture
* 5: boolean activity state for texture *
* * Storage Monitor: 4: int charge level for texture 5: boolean power state
* Battery Station: * for texture 6: boolean valid state for texture
* 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 // @Override
// public void onPacketData(INetworkManager network, Packet250CustomPayload packet, Player player) // public void onPacketData(INetworkManager network, Packet250CustomPayload
@SubscribeEvent // packet, Player player)
public void onClientPacket(ClientCustomPacketEvent event) @SubscribeEvent
{ public void onClientPacket(ClientCustomPacketEvent event){
ByteBuf stream = event.packet.payload(); ByteBuf stream = event.packet.payload();
//DataInputStream stream = new DataInputStream(new ByteArrayInputStream(packet.data)); // DataInputStream stream = new DataInputStream(new
// ByteArrayInputStream(packet.data));
// Determine packet type and coordinates of affected tile entity
// Determine packet type and coordinates of affected tile entity
int packetType = -1; int packetType = -1;
int x = 0; int x = 0;
int y = 0; int y = 0;
int z = 0; int z = 0;
packetType = stream.readInt(); packetType = stream.readInt();
x = stream.readInt(); x = stream.readInt();
y = stream.readInt(); y = stream.readInt();
z = stream.readInt(); z = stream.readInt();
if (packetType == 0) if(packetType == 0){
{
World world = FMLClientHandler.instance().getClient().theWorld; World world = FMLClientHandler.instance().getClient().theWorld;
TileEntity tile = world.getTileEntity(x, y, z); TileEntity tile = world.getTileEntity(x, y, z);
Exception e; Exception e;
try try{
{ ((TECommon) tile).receiveDescriptionData(packetType, stream);
((TECommon)tile).receiveDescriptionData(packetType, stream);
return; return;
} }catch(ClassCastException ex){
catch (ClassCastException ex) e = ex;
{ }catch(NullPointerException ex){
e = ex; e = ex;
} }
catch (NullPointerException ex) FMLLog.getLogger().info(
{ "[AdvancedPowerManagement] " + "Client received description packet for " + x + ", " + y + ", " + z
e = ex; + " 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; return;
} }
} }

View file

@ -21,21 +21,18 @@ import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World; import net.minecraft.world.World;
import net.minecraftforge.client.MinecraftForgeClient; import net.minecraftforge.client.MinecraftForgeClient;
public class ClientProxy extends CommonProxy public class ClientProxy extends CommonProxy{
{
public static EntityPlayer getPlayer(){
public static EntityPlayer getPlayer()
{
return Minecraft.getMinecraft().thePlayer; return Minecraft.getMinecraft().thePlayer;
} }
/* @Override /*
public void load() * @Override public void load() { //
{ * MinecraftForgeClient.preloadTexture(Info.ITEM_PNG); //
// MinecraftForgeClient.preloadTexture(Info.ITEM_PNG); * MinecraftForgeClient.preloadTexture(Info.BLOCK_PNG); //
// MinecraftForgeClient.preloadTexture(Info.BLOCK_PNG); * MinecraftForgeClient.preloadTexture(Info.GUI1_PNG); //
// MinecraftForgeClient.preloadTexture(Info.GUI1_PNG); * MinecraftForgeClient.preloadTexture(Info.GUI2_PNG); //
// MinecraftForgeClient.preloadTexture(Info.GUI2_PNG); * MinecraftForgeClient.preloadTexture(Info.GUI3_PNG); //
// MinecraftForgeClient.preloadTexture(Info.GUI3_PNG); * MinecraftForgeClient.preloadTexture(Info.GUI4_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.common.network.Player;
import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.Side;
public class CommonProxy implements IGuiHandler public class CommonProxy implements IGuiHandler{
{ public void load(){}
public void load() {}
public boolean isClient(){
public boolean isClient()
{
return FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT; return FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT;
} }
public boolean isServer() public boolean isServer(){
{
return FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER; return FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER;
} }
@Override @Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z){
{ if(!world.blockExists(x, y, z))
if (!world.blockExists(x, y, z)) return null; return null;
TileEntity tile = world.getTileEntity(x, y, z); TileEntity tile = world.getTileEntity(x, y, z);
if (ID == 1 && tile instanceof TEChargingBench) if(ID == 1 && tile instanceof TEChargingBench){
{ return new ContainerChargingBench(player.inventory, (TEChargingBench) tile);
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; return null;
} }
@Override @Override
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z){
{ if(!world.blockExists(x, y, z))
if (!world.blockExists(x, y, z)) return null; return null;
TileEntity tile = world.getTileEntity(x, y, z); TileEntity tile = world.getTileEntity(x, y, z);
if (ID == 1 && tile instanceof TEChargingBench) if(ID == 1 && tile instanceof TEChargingBench){
{ return new GuiChargingBench(player.inventory, (TEChargingBench) tile);
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; return null;
} }
/* /*
* Packet format: * Packet format: 0: byte Packet Type 1: int x location of TileEntity 2: int
* 0: byte Packet Type * y location of TileEntity 3: int z location of TileEntity
* 1: int x location of TileEntity *
* 2: int y location of TileEntity
* 3: int z location of TileEntity
*
* Currently used packet types * Currently used packet types
* *
* Client-to-Server: * Client-to-Server: 0 = GUI button command 4: int Button ID clicked
* 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))); 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 packetType = -1;
int x; int x;
int y; int y;
int z; int z;
try try{
{
packetType = stream.readInt(); packetType = stream.readInt();
x = stream.readInt(); x = stream.readInt();
y = stream.readInt(); y = stream.readInt();
z = stream.readInt(); z = stream.readInt();
} }catch(IOException e){
catch (IOException e)
{
FMLLog.getLogger().info("[AdvancedPowerManagement] " + "Failed to read packet from client. (Details: " + e.toString() + ")"); FMLLog.getLogger().info("[AdvancedPowerManagement] " + "Failed to read packet from client. (Details: " + e.toString() + ")");
return; return;
} }
if (packetType == 0) if(packetType == 0){
{
Exception e; Exception e;
try try{
{
World world = entityPlayer.worldObj; World world = entityPlayer.worldObj;
TileEntity tile = world.getTileEntity(x, y, z); TileEntity tile = world.getTileEntity(x, y, z);
int buttonID = stream.readInt(); int buttonID = stream.readInt();
((TECommon)tile).receiveGuiButton(buttonID); ((TECommon) tile).receiveGuiButton(buttonID);
return; 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; } FMLLog.getLogger().info(
catch (IOException ex) { e = ex; } "[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; return;
} }
} }

View file

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

View file

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

View file

@ -4,92 +4,88 @@
******************************************************************************/ ******************************************************************************/
package com.kaijin.AdvPowerMan; package com.kaijin.AdvPowerMan;
public class MovingAverage public class MovingAverage{
{
protected int packets[] = null; protected int packets[] = null;
protected int delays[] = null; protected int delays[] = null;
protected int position; protected int position;
//protected int packetTotal; // protected int packetTotal;
//protected int delayTotal; // protected int delayTotal;
protected int delay; protected int delay;
protected int window; protected int window;
protected float average; protected float average;
protected float delta; protected float delta;
public MovingAverage(int size) public MovingAverage(int size) {
{
packets = new int[size]; packets = new int[size];
delays = new int[size]; delays = new int[size];
position = 0; position = 0;
//packetTotal = 0; // packetTotal = 0;
//delayTotal = size; // delayTotal = size;
delay = 1; delay = 1;
window = size; window = size;
average = 0F; average = 0F;
delta = 0F; delta = 0F;
for (int i = 0; i < size; i++) for(int i = 0; i < size; i++){
{
packets[i] = 0; packets[i] = 0;
delays[i] = 600; delays[i] = 600;
} }
} }
public void tick(int value) public void tick(int value){
{ if(value > 0 || delay >= 600) // 600 ticks (30 sec) is long enough for 1
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 // EU/t to have triggered a 512 EU
// packet by now
{ {
position++; position++;
if (position >= packets.length) position = 0; if(position >= packets.length)
position = 0;
//packetTotal -= packet[position];
// packetTotal -= packet[position];
packets[position] = value; packets[position] = value;
//packetTotal += value; // packetTotal += value;
//delayTotal -= time[position]; // delayTotal -= time[position];
delays[position] = delay; delays[position] = delay;
//delayTotal += delay; // delayTotal += delay;
delay = 1; delay = 1;
window = sumDelays(); window = sumDelays();
final float newAvg = ((float)sumPackets()) / ((float)window); final float newAvg = ((float) sumPackets()) / ((float) window);
delta = newAvg - average; delta = newAvg - average;
average = newAvg; average = newAvg;
} }else{
else
{
delay++; delay++;
// Estimate decline of average based on increased average delay // Estimate decline of average based on increased average delay
if (delays.length * delay > window) if(delays.length * delay > window){
{
window++; window++;
average = ((float)sumPackets()) / ((float)window); average = ((float) sumPackets()) / ((float) window);
} }
} }
} }
protected int sumDelays() protected int sumDelays(){
{ if(delays == null)
if (delays == null) return 1; return 1;
int delayTotal = 0; int delayTotal = 0;
for (int d : delays) delayTotal += d; for(int d : delays)
delayTotal += d;
return delayTotal; return delayTotal;
} }
protected int sumPackets() protected int sumPackets(){
{ if(packets == null)
if (packets == null) return 0; return 0;
int packetTotal = 0; int packetTotal = 0;
for (int p : packets) packetTotal += p; for(int p : packets)
packetTotal += p;
return packetTotal; return packetTotal;
} }
public float getAverage() public float getAverage(){
{
return average; return average;
} }
public int getWindow() public int getWindow(){
{
return window; 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.Side;
import cpw.mods.fml.relauncher.SideOnly; import cpw.mods.fml.relauncher.SideOnly;
public class Utils public class Utils{
{ public boolean isClient(){
public boolean isClient()
{
return FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT; return FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT;
} }
public boolean isServer() public boolean isServer(){
{
return FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER; return FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER;
} }
/** /**
* *
* @param fr - Font Renderer handle * @param fr
* @param text - Text to display * - Font Renderer handle
* @param xLoc - x location * @param text
* @param yLoc - y location * - Text to display
* @param color - Color * @param xLoc
* - x location
* @param yLoc
* - y location
* @param color
* - Color
*/ */
@SideOnly(Side.CLIENT) @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); fr.drawString(text, xLoc - fr.getStringWidth(text) / 2, yLoc, color);
} }
/** /**
* *
* @param fr - Font Renderer handle * @param fr
* @param text - Text to display * - Font Renderer handle
* @param xLoc - x location * @param text
* @param yLoc - y location * - Text to display
* @param color - Color * @param xLoc
* - x location
* @param yLoc
* - y location
* @param color
* - Color
*/ */
@SideOnly(Side.CLIENT) @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); fr.drawString(text, xLoc - fr.getStringWidth(text), yLoc, color);
} }
/** /**
* *
* @param fr - Font Renderer handle * @param fr
* @param text - Text to display * - Font Renderer handle
* @param xLoc - x location * @param text
* @param yLoc - y location * - Text to display
* @param color - Color * @param xLoc
* - x location
* @param yLoc
* - y location
* @param color
* - Color
*/ */
@SideOnly(Side.CLIENT) @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); fr.drawString(text, xLoc, yLoc, color);
} }
private static final int MASKR = 0xFF0000; private static final int MASKR = 0xFF0000;
private static final int MASKG = 0x00FF00; private static final int MASKG = 0x00FF00;
private static final int MASKB = 0x0000FF; private static final int MASKB = 0x0000FF;
/** /**
* Individually multiply R, G, B color components by scalar value to dim or brighten the color. * Individually multiply R, G, B color components by scalar value to dim or
* Does not check for overflow. Beware when using values over 1.0F. * brighten the color. Does not check for overflow. Beware when using values
* @param color - original color * over 1.0F.
* @param brightnessFactor - should be positive and <> 1.0F *
* @param color
* - original color
* @param brightnessFactor
* - should be positive and <> 1.0F
* @return - modified color * @return - modified color
*/ */
public static int multiplyColorComponents(int color, float brightnessFactor) public static int multiplyColorComponents(int color, float brightnessFactor){
{ return ((int) (brightnessFactor * (color & MASKR)) & MASKR) | ((int) (brightnessFactor * (color & MASKG)) & MASKG)
return ((int)(brightnessFactor * (color & MASKR)) & MASKR) | ((int) (brightnessFactor * (color & MASKB)) & MASKB);
| ((int)(brightnessFactor * (color & MASKG)) & MASKG)
| ((int)(brightnessFactor * (color & MASKB)) & MASKB);
} }
public static int interpolateColors(int a, int b, float lerp) public static int interpolateColors(int a, int b, float lerp){
{ final int MASK1 = 0xff00ff;
final int MASK1 = 0xff00ff; final int MASK2 = 0x00ff00;
final int MASK2 = 0x00ff00;
int f2 = (int) (256 * lerp);
int f2 = (int)(256 * lerp);
int f1 = 256 - f2; int f1 = 256 - f2;
return ((((( a & MASK1 ) * f1 ) + ( ( b & MASK1 ) * f2 )) >> 8 ) & MASK1 ) return (((((a & MASK1) * f1) + ((b & MASK1) * f2)) >> 8) & MASK1) | (((((a & MASK2) * f1) + ((b & MASK2) * f2)) >> 8) & MASK2);
| ((((( a & MASK2 ) * f1 ) + ( ( b & MASK2 ) * f2 )) >> 8 ) & MASK2 );
} }
public static final int GUIBACKGROUNDCOLOR = 0xC6C6C6; public static final int GUIBACKGROUNDCOLOR = 0xC6C6C6;
public static int overlayColors(int base, int over) public static int overlayColors(int base, int over){
{ final float rDiff = 1F - ((float) (base & MASKR) / MASKR);
final float rDiff = 1F - ((float)(base & MASKR) / MASKR); final float gDiff = 1F - ((float) (base & MASKG) / MASKG);
final float gDiff = 1F - ((float)(base & MASKG) / MASKG); final float bDiff = 1F - ((float) (base & MASKB) / MASKB);
final float bDiff = 1F - ((float)(base & MASKB) / MASKB);
final int r2 = (over & MASKR); final int r2 = (over & MASKR);
final int g2 = (over & MASKG); final int g2 = (over & MASKG);
final int b2 = (over & MASKB); 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 oX[] = {0, -1, 0, 1};
private static final int oY[] = {-1, 0, 1, 0}; private static final int oY[] = {-1, 0, 1, 0};
/** /**
* Draws right-aligned text with a 'glow' surrounding it. * Draws right-aligned text with a 'glow' surrounding it.
* @param fr - Font Renderer handle *
* @param text - Text to display * @param fr
* @param xLoc - x location (upper right corner) * - Font Renderer handle
* @param yLoc - y location (upper right corner) * @param text
* @param color - Main Color * - Text to display
* @param glowColor - Surrounding Color * @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) @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); drawGlowingText(fr, text, xLoc - fr.getStringWidth(text), yLoc, color, glowColor);
} }
/** /**
* Draws centered text with a 'glow' surrounding it. * Draws centered text with a 'glow' surrounding it.
* @param fr - Font Renderer handle *
* @param text - Text to display * @param fr
* @param xLoc - x location (top center) * - Font Renderer handle
* @param yLoc - y location (top center) * @param text
* @param color - Main Color * - Text to display
* @param glowColor - Surrounding Color * @param xLoc
* - x location (top center)
* @param yLoc
* - y location (top center)
* @param color
* - Main Color
* @param glowColor
* - Surrounding Color
*/ */
@SideOnly(Side.CLIENT) @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); drawGlowingText(fr, text, xLoc - fr.getStringWidth(text) / 2, yLoc, color, glowColor);
} }
/** /**
* Draws left-aligned text with a 'glow' surrounding it. * Draws left-aligned text with a 'glow' surrounding it.
* @param fr - Font Renderer handle *
* @param text - Text to display * @param fr
* @param xLoc - x location (upper left corner) * - Font Renderer handle
* @param yLoc - y location (upper left corner) * @param text
* @param color - Main Color * - Text to display
* @param glowColor - Surrounding Color * @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) @SideOnly(Side.CLIENT)
public static void drawGlowingText(FontRenderer fr, String text, int xLoc, int yLoc, int color, int glowColor) public static void drawGlowingText(FontRenderer fr, String text, int xLoc, int yLoc, int color, int glowColor){
{ for(int i = 0; i < 4; i++){
for (int i = 0; i < 4; i++)
{
fr.drawString(text, xLoc + oX[i], yLoc + oY[i], glowColor); fr.drawString(text, xLoc + oX[i], yLoc + oY[i], glowColor);
} }
fr.drawString(text, xLoc, yLoc, color); fr.drawString(text, xLoc, yLoc, color);
} }
/* /*
* Convert desired side to actual side based on orientation of block * Convert desired side to actual side based on orientation of block I Meta
* 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
* D U N S W E 0 1 2 3 4 5 * 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
* 0 F K T T T T 0 0 1 2 2 2 2 * K 4 5 5 5 4 0 1 5 R R R L K F 5 4 4 4 5 1 0
* 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) 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},
final int table[][] = {4, 4, 4, 5, 1, 0}};
{
{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]; return table[side][orientation];
} }
public static NBTTagCompound getOrCreateStackTag(ItemStack itemStack) public static NBTTagCompound getOrCreateStackTag(ItemStack itemStack){
{ if(itemStack != null){
if (itemStack != null)
{
NBTTagCompound tag = itemStack.getTagCompound(); NBTTagCompound tag = itemStack.getTagCompound();
if (tag == null) if(tag == null){
{
tag = new NBTTagCompound(); tag = new NBTTagCompound();
itemStack.setTagCompound(tag); itemStack.setTagCompound(tag);
} }
@ -203,25 +211,23 @@ public class Utils
} }
return null; 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 // Decide if the item is a valid IC2 electrical item
if (stack != null && stack.getItem() instanceof IElectricItem) if(stack != null && stack.getItem() instanceof IElectricItem){
{ IElectricItem item = (IElectricItem) (stack.getItem());
IElectricItem item = (IElectricItem)(stack.getItem()); if(item.getTier(stack) <= tier)
if (item.getTier(stack) <= tier) return true; return true;
} }
return false; 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 // Decide if the item is a valid IC2 power source
if (stack != null && stack.getItem() instanceof IElectricItem) if(stack != null && stack.getItem() instanceof IElectricItem){
{ IElectricItem item = (IElectricItem) (stack.getItem());
IElectricItem item = (IElectricItem)(stack.getItem()); if(item.canProvideEnergy(stack) && item.getTier(stack) <= tier)
if (item.canProvideEnergy(stack) && item.getTier(stack) <= tier) return true; return true;
} }
return false; 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.Side;
import cpw.mods.fml.relauncher.SideOnly; import cpw.mods.fml.relauncher.SideOnly;
public class BlockAdvPwrMan extends BlockContainer public class BlockAdvPwrMan extends BlockContainer{
{ static final String[] tierPrefix = {"LV", "MV", "HV", "EV"};
static final String[] tierPrefix = {"LV", "MV", "HV", "EV"};
protected IIcon benchBottom; protected IIcon benchBottom;
protected IIcon smTop; protected IIcon smTop;
protected IIcon smBottom; protected IIcon smBottom;
protected IIcon smInvalid; protected IIcon smInvalid;
protected IIcon emitter; protected IIcon emitter;
protected IIcon atOut; protected IIcon atOut;
protected IIcon atInput; protected IIcon atInput;
protected IIcon[] atOutput; protected IIcon[] atOutput;
protected IIcon[] benchTop; protected IIcon[] benchTop;
protected IIcon[][][] cbSides; protected IIcon[][][] cbSides;
protected IIcon[][] bsSides; protected IIcon[][] bsSides;
protected IIcon[][] smSides; protected IIcon[][] smSides;
public BlockAdvPwrMan( Material material) public BlockAdvPwrMan(Material material) {
{
super(material); super(material);
setHardness(0.75F); setHardness(0.75F);
setResistance(5F); setResistance(5F);
setStepSound(soundTypeStone); setStepSound(soundTypeStone);
//setUnlocalizedName("AdvPwrMan"); // setUnlocalizedName("AdvPwrMan");
setCreativeTab(CreativeTabs.tabDecorations); setCreativeTab(CreativeTabs.tabDecorations);
} }
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
@Override @Override
public void getSubBlocks(Item block, CreativeTabs creativetabs, List list) public void getSubBlocks(Item block, CreativeTabs creativetabs, List list){
{ for(int i = 0; i <= Info.LAST_META_VALUE; ++i){
for (int i = 0; i <= Info.LAST_META_VALUE; ++i) if(i >= 3 && i <= 5)
{ continue; // Don't add legacy emitters to creative inventory
if (i >= 3 && i <= 5) continue; // Don't add legacy emitters to creative inventory
list.add(new ItemStack(block, 1, i)); list.add(new ItemStack(block, 1, i));
} }
} }
@Override @Override
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer entityplayer, int par6, float par7, float par8, float par9) 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
//int currentEquippedItemID = 0; //TODO We're not currently responding to wrenches // to wrenches
//if (entityplayer.getCurrentEquippedItem() != null) // if (entityplayer.getCurrentEquippedItem() != null)
//{ // {
// currentEquippedItemID = entityplayer.getCurrentEquippedItem().itemID; // currentEquippedItemID = entityplayer.getCurrentEquippedItem().itemID;
//} // }
//if (entityplayer.isSneaking() || currentEquippedItemID == Info.ic2WrenchID || currentEquippedItemID == Info.ic2ElectricWrenchID) // if (entityplayer.isSneaking() || currentEquippedItemID ==
if (entityplayer.isSneaking()) // Info.ic2WrenchID || currentEquippedItemID ==
{ // Info.ic2ElectricWrenchID)
// Prevent GUI popup when sneaking - this allows you to place things directly on blocks if(entityplayer.isSneaking()){
// Prevent GUI popup when sneaking - this allows you to place things
// directly on blocks
return false; return false;
} }
TileEntity tile = world.getTileEntity(x, y, z); TileEntity tile = world.getTileEntity(x, y, z);
if (tile instanceof TECommon) if(tile instanceof TECommon){
{ final int id = ((TECommon) tile).getGuiID();
final int id = ((TECommon)tile).getGuiID(); if(id < 1)
if (id < 1) return false; return false;
if (AdvancedPowerManagement.proxy.isServer()) if(AdvancedPowerManagement.proxy.isServer()){
{
entityplayer.openGui(AdvancedPowerManagement.instance, id, world, x, y, z); entityplayer.openGui(AdvancedPowerManagement.instance, id, world, x, y, z);
} }
} }
return true; return true;
} }
@Override @Override
public void registerBlockIcons(IIconRegister iconRegister) public void registerBlockIcons(IIconRegister iconRegister){
{
cbSides = new IIcon[3][2][13]; cbSides = new IIcon[3][2][13];
bsSides = new IIcon[3][2]; bsSides = new IIcon[3][2];
smSides = new IIcon[2][13]; smSides = new IIcon[2][13];
benchTop = new IIcon[3]; benchTop = new IIcon[3];
atOutput = new IIcon[4]; atOutput = new IIcon[4];
benchBottom = iconRegister.registerIcon(Info.TITLE_PACKED + ":BenchBottom"); benchBottom = iconRegister.registerIcon(Info.TITLE_PACKED + ":BenchBottom");
smTop = iconRegister.registerIcon(Info.TITLE_PACKED + ":StorageMonitorTop"); smTop = iconRegister.registerIcon(Info.TITLE_PACKED + ":StorageMonitorTop");
smBottom = iconRegister.registerIcon(Info.TITLE_PACKED + ":StorageMonitorBottom"); smBottom = iconRegister.registerIcon(Info.TITLE_PACKED + ":StorageMonitorBottom");
smInvalid = iconRegister.registerIcon(Info.TITLE_PACKED + ":StorageMonitorInvalid"); smInvalid = iconRegister.registerIcon(Info.TITLE_PACKED + ":StorageMonitorInvalid");
emitter = iconRegister.registerIcon(Info.TITLE_PACKED + ":Emitter"); emitter = iconRegister.registerIcon(Info.TITLE_PACKED + ":Emitter");
atInput = iconRegister.registerIcon(Info.TITLE_PACKED + ":TransformerInput"); atInput = iconRegister.registerIcon(Info.TITLE_PACKED + ":TransformerInput");
int i, j; int i, j;
for (i = 0; i < 13; i++) for(i = 0; i < 13; i++){
{
String temp = Integer.toString(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][0][i] = iconRegister.registerIcon(Info.TITLE_PACKED + ":" + tierPrefix[j] + "ChargingBenchOff" + temp);
cbSides[j][1][i] = iconRegister.registerIcon(Info.TITLE_PACKED + ":" + tierPrefix[j] + "ChargingBenchOn" + 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[0][i] = iconRegister.registerIcon(Info.TITLE_PACKED + ":StorageMonitorOff" + temp);
smSides[1][i] = iconRegister.registerIcon(Info.TITLE_PACKED + ":StorageMonitorOn" + 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"); benchTop[i] = iconRegister.registerIcon(Info.TITLE_PACKED + ":" + tierPrefix[i] + "BenchTop");
bsSides[i][0] = iconRegister.registerIcon(Info.TITLE_PACKED + ":" + tierPrefix[i] + "BatteryStationOff"); bsSides[i][0] = iconRegister.registerIcon(Info.TITLE_PACKED + ":" + tierPrefix[i] + "BatteryStationOff");
bsSides[i][1] = iconRegister.registerIcon(Info.TITLE_PACKED + ":" + tierPrefix[i] + "BatteryStationOn"); 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]); atOutput[i] = iconRegister.registerIcon(Info.TITLE_PACKED + ":TransformerOutput1" + tierPrefix[i]);
} }
} }
//Textures in the world // Textures in the world
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
@Override @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); final int meta = blocks.getBlockMetadata(x, y, z);
TileEntity tile = blocks.getTileEntity(x, y, z); TileEntity tile = blocks.getTileEntity(x, y, z);
if (tile instanceof TEChargingBench) if(tile instanceof TEChargingBench){
{ switch(side){
switch (side)
{
case 0: // bottom case 0: // bottom
return benchBottom; return benchBottom;
case 1: // top case 1: // top
return benchTop[meta - Info.CB_META]; return benchTop[meta - Info.CB_META];
default: 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; return emitter;
} }else if(tile instanceof TEAdjustableTransformer){
else if (tile instanceof TEAdjustableTransformer) final byte flags = ((TEAdjustableTransformer) tile).sideSettings[side];
{ if((flags & 1) == 0)
final byte flags = ((TEAdjustableTransformer)tile).sideSettings[side]; return atInput;
if ((flags & 1) == 0) return atInput;
return atOutput[(flags >>> 1) & 3]; return atOutput[(flags >>> 1) & 3];
} }else if(tile instanceof TEBatteryStation){
else if (tile instanceof TEBatteryStation) switch(side){
{
switch (side)
{
case 0: // bottom case 0: // bottom
return benchBottom; return benchBottom;
case 1: // top case 1: // top
return benchTop[meta - Info.BS_META]; return benchTop[meta - Info.BS_META];
default: 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){
else if (tile instanceof TEStorageMonitor) switch(side){
{
switch (side)
{
case 0: // bottom case 0: // bottom
return smBottom; return smBottom;
case 1: // top case 1: // top
return smTop; return smTop;
default: default:
if (((TEStorageMonitor)tile).blockState) if(((TEStorageMonitor) tile).blockState){
{ return smSides[((TEStorageMonitor) tile).isPowering ? 1 : 0][((TEStorageMonitor) tile).chargeLevel];
return smSides[((TEStorageMonitor)tile).isPowering ? 1 : 0][((TEStorageMonitor)tile).chargeLevel]; }else
} return smInvalid;
else return smInvalid;
} }
} }
//If we're here, something is wrong // If we're here, something is wrong
return benchBottom; return benchBottom;
} }
//Textures in your inventory // Textures in your inventory
@Override @Override
public IIcon getIcon(int side, int meta) public IIcon getIcon(int side, int meta){
{ if(meta == Info.AE_META){
if (meta == Info.AE_META)
{
return emitter; return emitter;
} }
if (meta == Info.AT_META) if(meta == Info.AT_META){
{
// TODO: Give transformer better textures // TODO: Give transformer better textures
return atInput; return atInput;
} }
switch (side) switch(side){
{
case 0: // bottom case 0: // bottom
return meta == Info.SM_META ? smBottom : benchBottom; return meta == Info.SM_META ? smBottom : benchBottom;
case 1: // top case 1: // top
if (meta < 3) // CB tops if(meta < 3) // CB tops
{ {
return benchTop[meta - Info.CB_META]; return benchTop[meta - Info.CB_META];
} }else if(meta < 11) // Battery Station top
else if (meta < 11) // Battery Station top
{ {
return benchTop[meta - Info.BS_META]; return benchTop[meta - Info.BS_META];
} }else{
else
{
return smTop; return smTop;
} }
default: // side default: // side
if (meta < 3) // Charging Bench if(meta < 3) // Charging Bench
{ {
return cbSides[meta - Info.CB_META][0][0]; 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]; return bsSides[meta - Info.BS_META][0];
} }else{
else
{
return smInvalid; return smInvalid;
} }
} }
} }
@Override @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); 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 @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; return 0;
} }
@Override @Override
public boolean canProvidePower() public boolean canProvidePower(){
{
return false; // Old means of causing visual RedPower wire connections. return false; // Old means of causing visual RedPower wire connections.
} }
@Override @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; return true;
} }
@Override @Override
public boolean isBlockNormalCube() public boolean isBlockNormalCube(){
{
return false; return false;
} }
@Override @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; return true;
} }
@Override @Override
public TileEntity createNewTileEntity(World world, int i) public TileEntity createNewTileEntity(World world, int i){
{
return null; return null;
} }
@Override @Override
public TileEntity createTileEntity(World world, int metadata) public TileEntity createTileEntity(World world, int metadata){
{ // if (ChargingBench.isDebugging)
//if (ChargingBench.isDebugging) System.out.println("BlockAdvPwrMan.createTileEntity"); // System.out.println("BlockAdvPwrMan.createTileEntity");
switch (metadata) switch(metadata){
{
case 0: case 0:
return new TEChargingBench(1); return new TEChargingBench(1);
case 1: case 1:
return new TEChargingBench(2); return new TEChargingBench(2);
case 2: case 2:
return new TEChargingBench(3); return new TEChargingBench(3);
case 3: case 3:
return new TEAdvEmitter(1); // Update old emitter tier 1 return new TEAdvEmitter(1); // Update old emitter tier 1
case 4: case 4:
return new TEAdvEmitter(2); // Update old emitter tier 2 return new TEAdvEmitter(2); // Update old emitter tier 2
case 5: case 5:
return new TEAdvEmitter(3); // Update old emitter tier 3 return new TEAdvEmitter(3); // Update old emitter tier 3
case 6: case 6:
return new TEAdjustableTransformer(); return new TEAdjustableTransformer();
case 7: case 7:
return new TEAdvEmitter(); return new TEAdvEmitter();
case 8: case 8:
return new TEBatteryStation(1); return new TEBatteryStation(1);
case 9: case 9:
return new TEBatteryStation(2); return new TEBatteryStation(2);
case 10: case 10:
return new TEBatteryStation(3); return new TEBatteryStation(3);
case 11: case 11:
return new TEStorageMonitor(); return new TEStorageMonitor();
default: default:
return null; return null;
} }
} }
@Override @Override
public boolean hasTileEntity(int metadata) public boolean hasTileEntity(int metadata){
{
return metadata >= 0 && metadata <= Info.LAST_META_VALUE; 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 @Override
public Item getItemDropped(int var1, Random var2, int var3) public int damageDropped(int meta){
{ // if (ChargingBench.isDebugging)
//if (ChargingBench.isDebugging) System.out.println("BlockAdvPwrMan.idDropped"); // System.out.println("BlockAdvPwrMan.damageDropped");
return blockID;
}
*/
@Override
public int damageDropped(int meta)
{
//if (ChargingBench.isDebugging) System.out.println("BlockAdvPwrMan.damageDropped");
return meta; return meta;
} }
@Override @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); preDestroyBlock(world, x, y, z);
} }
public static void preDestroyBlock(World world, int i, int j, int k) public static void preDestroyBlock(World world, int i, int j, int k){
{ if(!AdvancedPowerManagement.proxy.isClient()){
if (!AdvancedPowerManagement.proxy.isClient())
{
TileEntity tile = world.getTileEntity(i, j, k); TileEntity tile = world.getTileEntity(i, j, k);
if (tile == null) return; if(tile == null)
try return;
{ try{
((TECommon)tile).dropContents(); ((TECommon) tile).dropContents();
} }catch(ClassCastException e){
catch (ClassCastException e) FMLLog.warning("[AdvancedPowerManagement] " + "Attempted to destroy APM block with non-APM tile entity at: " + i + ", " + j + ", "
{ + k);
FMLLog.warning("[AdvancedPowerManagement] " + "Attempted to destroy APM block with non-APM tile entity at: " + i + ", " + j + ", " + k);
} }
tile.invalidate(); tile.invalidate();
} }

View file

@ -12,153 +12,141 @@ import net.minecraft.inventory.ICrafting;
import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly; import cpw.mods.fml.relauncher.SideOnly;
public class ContainerAdjustableTransformer extends Container public class ContainerAdjustableTransformer extends Container{
{
private final int playerInventoryStartSlot = 1; private final int playerInventoryStartSlot = 1;
public TEAdjustableTransformer tile; public TEAdjustableTransformer tile;
public int outputRate; public int outputRate;
public int packetSize; 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 outputAvg;
public int inputAvg; public int inputAvg;
public int energyBuffer; public int energyBuffer;
public ContainerAdjustableTransformer(TEAdjustableTransformer tileentity) public ContainerAdjustableTransformer(TEAdjustableTransformer tileentity) {
{ // if (Info.isDebugging)
//if (Info.isDebugging) System.out.println("ContainerAdjustableTransformer"); // System.out.println("ContainerAdjustableTransformer");
tile = tileentity; tile = tileentity;
outputRate = -1; outputRate = -1;
packetSize = -1; packetSize = -1;
for (int i : sideSettings) for(int i : sideSettings)
i = (byte)255; i = (byte) 255;
outputAvg = -1; outputAvg = -1;
inputAvg = -1; inputAvg = -1;
energyBuffer = -1; energyBuffer = -1;
} }
@Override @Override
public void detectAndSendChanges() public void detectAndSendChanges(){
{ final int syncOutAvg = (int) (tile.outputTracker.getAverage() * 100);
final int syncOutAvg = (int)(tile.outputTracker.getAverage() * 100); final int syncInAvg = (int) (tile.inputTracker.getAverage() * 100);
final int syncInAvg = (int)(tile.inputTracker.getAverage() * 100);
for(int crafterIndex = 0; crafterIndex < crafters.size(); ++crafterIndex){
for (int crafterIndex = 0; crafterIndex < crafters.size(); ++crafterIndex) ICrafting crafter = (ICrafting) crafters.get(crafterIndex);
{
ICrafting crafter = (ICrafting)crafters.get(crafterIndex); if(this.outputRate != tile.outputRate){
if (this.outputRate != tile.outputRate)
{
crafter.sendProgressBarUpdate(this, 0, tile.outputRate & 65535); crafter.sendProgressBarUpdate(this, 0, tile.outputRate & 65535);
crafter.sendProgressBarUpdate(this, 1, tile.outputRate >>> 16); 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, 2, tile.packetSize & 65535);
crafter.sendProgressBarUpdate(this, 3, tile.packetSize >>> 16); crafter.sendProgressBarUpdate(this, 3, tile.packetSize >>> 16);
} }
for (int i = 0; i < 6; i++) for(int i = 0; i < 6; i++)
if (this.sideSettings[i] != tile.sideSettings[i]) if(this.sideSettings[i] != tile.sideSettings[i]){
{ crafter.sendProgressBarUpdate(this, 4 + i, tile.sideSettings[i]);
crafter.sendProgressBarUpdate(this, 4 + i, tile.sideSettings[i]); }
}
if(outputAvg != syncOutAvg){
if (outputAvg != syncOutAvg)
{
crafter.sendProgressBarUpdate(this, 10, syncOutAvg & 65535); crafter.sendProgressBarUpdate(this, 10, syncOutAvg & 65535);
crafter.sendProgressBarUpdate(this, 11, syncOutAvg >>> 16); crafter.sendProgressBarUpdate(this, 11, syncOutAvg >>> 16);
} }
if (inputAvg != syncInAvg) if(inputAvg != syncInAvg){
{
crafter.sendProgressBarUpdate(this, 12, syncInAvg & 65535); crafter.sendProgressBarUpdate(this, 12, syncInAvg & 65535);
crafter.sendProgressBarUpdate(this, 13, syncInAvg >>> 16); 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, 14, tile.energyBuffer & 65535);
crafter.sendProgressBarUpdate(this, 15, tile.energyBuffer >>> 16); crafter.sendProgressBarUpdate(this, 15, tile.energyBuffer >>> 16);
} }
} }
// Done sending updates, record the new current values // Done sending updates, record the new current values
this.outputRate = tile.outputRate; this.outputRate = tile.outputRate;
this.packetSize = tile.packetSize; this.packetSize = tile.packetSize;
for (int i = 0; i < 6; i++) for(int i = 0; i < 6; i++){
{
this.sideSettings[i] = tile.sideSettings[i]; this.sideSettings[i] = tile.sideSettings[i];
} }
outputAvg = syncOutAvg; outputAvg = syncOutAvg;
inputAvg = syncInAvg; inputAvg = syncInAvg;
this.energyBuffer = tile.energyBuffer; this.energyBuffer = tile.energyBuffer;
} }
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
@Override @Override
public void updateProgressBar(int param, int value) public void updateProgressBar(int param, int value){
{ switch(param){
switch (param)
{
case 0: case 0:
tile.outputRate = tile.outputRate & -65536 | value; tile.outputRate = tile.outputRate & -65536 | value;
break; break;
case 1: case 1:
tile.outputRate = tile.outputRate & 65535 | (value << 16); tile.outputRate = tile.outputRate & 65535 | (value << 16);
break; break;
case 2: case 2:
tile.packetSize = tile.packetSize & -65536 | value; tile.packetSize = tile.packetSize & -65536 | value;
break; break;
case 3: case 3:
tile.packetSize = tile.packetSize & 65535 | (value << 16); tile.packetSize = tile.packetSize & 65535 | (value << 16);
break; break;
case 4: case 4:
case 5: case 5:
case 6: case 6:
case 7: case 7:
case 8: case 8:
case 9: case 9:
tile.sideSettings[param - 4] = (byte)value; tile.sideSettings[param - 4] = (byte) value;
break; break;
case 10: case 10:
outputAvg = outputAvg & -65536 | value; outputAvg = outputAvg & -65536 | value;
break; break;
case 11: case 11:
outputAvg = outputAvg & 65535 | (value << 16); outputAvg = outputAvg & 65535 | (value << 16);
break; break;
case 12: case 12:
inputAvg = inputAvg & -65536 | value; inputAvg = inputAvg & -65536 | value;
break; break;
case 13: case 13:
inputAvg = inputAvg & 65535 | (value << 16); inputAvg = inputAvg & 65535 | (value << 16);
break; break;
case 14: case 14:
tile.energyBuffer = tile.energyBuffer & -65536 | value; tile.energyBuffer = tile.energyBuffer & -65536 | value;
break; break;
case 15: case 15:
tile.energyBuffer = tile.energyBuffer & 65535 | (value << 16); tile.energyBuffer = tile.energyBuffer & 65535 | (value << 16);
break; break;
default: default:
System.out.println("ContainerAdvEmitter.updateProgressBar - Warning: default case!"); System.out.println("ContainerAdvEmitter.updateProgressBar - Warning: default case!");
} }
} }
@Override @Override
public boolean canInteractWith(EntityPlayer var1) public boolean canInteractWith(EntityPlayer var1){
{
return tile.isUseableByPlayer(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.Side;
import cpw.mods.fml.relauncher.SideOnly; import cpw.mods.fml.relauncher.SideOnly;
public class ContainerAdvEmitter extends Container public class ContainerAdvEmitter extends Container{
{
private final int playerInventoryStartSlot = 1; private final int playerInventoryStartSlot = 1;
public TEAdvEmitter te; public TEAdvEmitter te;
public int outputRate; public int outputRate;
public int packetSize; public int packetSize;
public ContainerAdvEmitter(TEAdvEmitter tile) public ContainerAdvEmitter(TEAdvEmitter tile) {
{ // if (Info.isDebugging) System.out.println("ContainerAdvEmitter");
//if (Info.isDebugging) System.out.println("ContainerAdvEmitter");
te = tile; te = tile;
outputRate = -1; outputRate = -1;
packetSize = -1; packetSize = -1;
} }
@Override @Override
public void detectAndSendChanges() public void detectAndSendChanges(){
{ // if (ChargingBench.isDebugging)
// if (ChargingBench.isDebugging) System.out.println("ContainerChargingBench.updateCraftingResults"); // System.out.println("ContainerChargingBench.updateCraftingResults");
for (int crafterIndex = 0; crafterIndex < crafters.size(); ++crafterIndex) for(int crafterIndex = 0; crafterIndex < crafters.size(); ++crafterIndex){
{ ICrafting crafter = (ICrafting) crafters.get(crafterIndex);
ICrafting crafter = (ICrafting)crafters.get(crafterIndex);
if(this.outputRate != te.outputRate){
if (this.outputRate != te.outputRate)
{
crafter.sendProgressBarUpdate(this, 0, te.outputRate & 65535); crafter.sendProgressBarUpdate(this, 0, te.outputRate & 65535);
crafter.sendProgressBarUpdate(this, 1, te.outputRate >>> 16); 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, 2, te.packetSize & 65535);
crafter.sendProgressBarUpdate(this, 3, te.packetSize >>> 16); crafter.sendProgressBarUpdate(this, 3, te.packetSize >>> 16);
} }
@ -56,38 +51,45 @@ public class ContainerAdvEmitter extends Container
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
@Override @Override
public void updateProgressBar(int param, int value) public void updateProgressBar(int param, int value){
{ switch(param){
switch (param)
{
case 0: 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; te.outputRate = te.outputRate & -65536 | value;
break; break;
case 1: 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); te.outputRate = te.outputRate & 65535 | (value << 16);
break; break;
case 2: 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; te.packetSize = te.packetSize & -65536 | value;
break; break;
case 3: 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); te.packetSize = te.packetSize & 65535 | (value << 16);
break; break;
default: default:
System.out.println("ContainerAdvEmitter.updateProgressBar - Warning: default case!"); System.out.println("ContainerAdvEmitter.updateProgressBar - Warning: default case!");
} }
} }
@Override @Override
public boolean canInteractWith(EntityPlayer var1) public boolean canInteractWith(EntityPlayer var1){
{
return te.isUseableByPlayer(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.Side;
import cpw.mods.fml.relauncher.SideOnly; 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 shiftClickRange = 13;
private static final int playerInventoryStartSlot = 14; private static final int playerInventoryStartSlot = 14;
public TEBatteryStation tileentity; public TEBatteryStation tileentity;
public int opMode; public int opMode;
public int average; public int average;
public int itemsEnergyTotal; public int itemsEnergyTotal;
public ContainerBatteryStation(InventoryPlayer player, TEBatteryStation tile) public ContainerBatteryStation(InventoryPlayer player, TEBatteryStation tile) {
{
tileentity = tile; tileentity = tile;
opMode = -1; opMode = -1;
average = -1; average = -1;
itemsEnergyTotal = -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 xCol;
int yRow; int yRow;
// Discharging slots, in reverse order // 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 // Input Slot
this.addSlotToContainer(new SlotPowerSource(tile, 0, 17, topOffset, tile.powerTier)); this.addSlotToContainer(new SlotPowerSource(tile, 0, 17, topOffset, tile.powerTier));
// Output slot // Output slot
this.addSlotToContainer(new SlotOutput(tile, 1, 143, topOffset + 54)); this.addSlotToContainer(new SlotOutput(tile, 1, 143, topOffset + 54));
// Player inventory // Player inventory
for (yRow = 0; yRow < 3; ++yRow) for(yRow = 0; yRow < 3; ++yRow){
{ for(xCol = 0; xCol < 9; ++xCol){
for (xCol = 0; xCol < 9; ++xCol)
{
this.addSlotToContainer(new Slot(player, xCol + yRow * 9 + 9, 8 + xCol * 18, topOffset + 76 + yRow * 18)); this.addSlotToContainer(new Slot(player, xCol + yRow * 9 + 9, 8 + xCol * 18, topOffset + 76 + yRow * 18));
} }
} }
// Player hot bar // 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)); this.addSlotToContainer(new Slot(player, yRow, 8 + yRow * 18, topOffset + 134));
} }
} }
@Override @Override
public void detectAndSendChanges() public void detectAndSendChanges(){
{ // if (ChargingBench.isDebugging)
// if (ChargingBench.isDebugging) System.out.println("ContainerChargingBench.updateCraftingResults"); // System.out.println("ContainerChargingBench.updateCraftingResults");
super.detectAndSendChanges(); super.detectAndSendChanges();
final int syncAvg = (int)(tileentity.outputTracker.getAverage() * 100); final int syncAvg = (int) (tileentity.outputTracker.getAverage() * 100);
final int energy = tileentity.getTotalEnergy(); final int energy = tileentity.getTotalEnergy();
for (int crafterIndex = 0; crafterIndex < crafters.size(); ++crafterIndex) for(int crafterIndex = 0; crafterIndex < crafters.size(); ++crafterIndex){
{ ICrafting crafter = (ICrafting) this.crafters.get(crafterIndex);
ICrafting crafter = (ICrafting)this.crafters.get(crafterIndex);
if(average != syncAvg){
if (average != syncAvg)
{
crafter.sendProgressBarUpdate(this, 0, syncAvg & 65535); crafter.sendProgressBarUpdate(this, 0, syncAvg & 65535);
crafter.sendProgressBarUpdate(this, 1, syncAvg >>> 16); crafter.sendProgressBarUpdate(this, 1, syncAvg >>> 16);
} }
if (itemsEnergyTotal != energy) if(itemsEnergyTotal != energy){
{
crafter.sendProgressBarUpdate(this, 2, energy & 65535); crafter.sendProgressBarUpdate(this, 2, energy & 65535);
crafter.sendProgressBarUpdate(this, 3, energy >>> 16); crafter.sendProgressBarUpdate(this, 3, energy >>> 16);
} }
if (opMode != tileentity.opMode) if(opMode != tileentity.opMode){
{
crafter.sendProgressBarUpdate(this, 4, tileentity.opMode); crafter.sendProgressBarUpdate(this, 4, tileentity.opMode);
} }
} }
@ -105,80 +104,70 @@ public class ContainerBatteryStation extends Container
average = syncAvg; average = syncAvg;
itemsEnergyTotal = energy; itemsEnergyTotal = energy;
} }
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
@Override @Override
public void updateProgressBar(int param, int value) public void updateProgressBar(int param, int value){
{
super.updateProgressBar(param, value); super.updateProgressBar(param, value);
switch (param) switch(param){
{
case 0: case 0:
average = average & -65536 | value; average = average & -65536 | value;
break; break;
case 1: case 1:
average = average & 65535 | (value << 16); average = average & 65535 | (value << 16);
break; break;
case 2: case 2:
itemsEnergyTotal = itemsEnergyTotal & -65536 | value; itemsEnergyTotal = itemsEnergyTotal & -65536 | value;
break; break;
case 3: case 3:
itemsEnergyTotal = itemsEnergyTotal & 65535 | (value << 16); itemsEnergyTotal = itemsEnergyTotal & 65535 | (value << 16);
break; break;
case 4: case 4:
this.opMode = value; this.opMode = value;
break; break;
default: default:
System.out.println("ContainerBatteryStation.updateProgressBar - Warning: default case!"); 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 @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; boolean result = false;
int slotID = startSlot; int slotID = startSlot;
if (reverseOrder) if(reverseOrder){
{
slotID = endSlot - 1; slotID = endSlot - 1;
} }
Slot currentSlot; Slot currentSlot;
ItemStack currentStack; ItemStack currentStack;
if (stack.isStackable()) if(stack.isStackable()){
{ while(stack.stackSize > 0 && (!reverseOrder && slotID < endSlot || reverseOrder && slotID >= startSlot)){
while (stack.stackSize > 0 && (!reverseOrder && slotID < endSlot || reverseOrder && slotID >= startSlot)) currentSlot = (Slot) inventorySlots.get(slotID);
{
currentSlot = (Slot)inventorySlots.get(slotID);
currentStack = currentSlot.getStack(); 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()) && (!stack.getHasSubtypes() || stack.getItemDamage() == currentStack.getItemDamage())
&& ItemStack.areItemStackTagsEqual(stack, currentStack) && ItemStack.areItemStackTagsEqual(stack, currentStack) && currentSlot.isItemValid(stack)){
&& currentSlot.isItemValid(stack))
{
int limit = Math.min(stack.getMaxStackSize(), currentSlot.getSlotStackLimit()); int limit = Math.min(stack.getMaxStackSize(), currentSlot.getSlotStackLimit());
int sum = currentStack.stackSize + stack.stackSize; int sum = currentStack.stackSize + stack.stackSize;
if (sum <= limit) if(sum <= limit){
{
stack.stackSize = 0; stack.stackSize = 0;
currentStack.stackSize = sum; currentStack.stackSize = sum;
currentSlot.onSlotChanged(); currentSlot.onSlotChanged();
result = true; result = true;
} }else if(currentStack.stackSize < limit){
else if (currentStack.stackSize < limit)
{
int diff = limit - currentStack.stackSize; int diff = limit - currentStack.stackSize;
stack.stackSize -= diff; stack.stackSize -= diff;
currentStack.stackSize = limit; currentStack.stackSize = limit;
@ -186,279 +175,195 @@ public class ContainerBatteryStation extends Container
result = true; result = true;
} }
} }
if (reverseOrder) if(reverseOrder){
{
--slotID; --slotID;
} }else{
else
{
++slotID; ++slotID;
} }
} }
} }
if (stack.stackSize > 0) if(stack.stackSize > 0){
{ if(reverseOrder){
if (reverseOrder)
{
slotID = endSlot - 1; slotID = endSlot - 1;
} }else{
else
{
slotID = startSlot; slotID = startSlot;
} }
while (!reverseOrder && slotID < endSlot || reverseOrder && slotID >= startSlot) while(!reverseOrder && slotID < endSlot || reverseOrder && slotID >= startSlot){
{ currentSlot = (Slot) inventorySlots.get(slotID);
currentSlot = (Slot)inventorySlots.get(slotID);
currentStack = currentSlot.getStack(); currentStack = currentSlot.getStack();
if (currentStack == null && currentSlot.isItemValid(stack)) if(currentStack == null && currentSlot.isItemValid(stack)){
{
int limit = currentSlot.getSlotStackLimit(); int limit = currentSlot.getSlotStackLimit();
if (stack.stackSize <= limit) if(stack.stackSize <= limit){
{
currentSlot.putStack(stack.copy()); currentSlot.putStack(stack.copy());
currentSlot.onSlotChanged(); currentSlot.onSlotChanged();
stack.stackSize = 0; stack.stackSize = 0;
result = true; result = true;
break; break;
} }else{
else
{
currentSlot.putStack(stack.splitStack(limit)); currentSlot.putStack(stack.splitStack(limit));
currentSlot.onSlotChanged(); currentSlot.onSlotChanged();
result = true; result = true;
} }
} }
if (reverseOrder) if(reverseOrder){
{
--slotID; --slotID;
} }else{
else
{
++slotID; ++slotID;
} }
} }
} }
return result; 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 @Override
public ItemStack transferStackInSlot(EntityPlayer p, int slotID) public ItemStack transferStackInSlot(EntityPlayer p, int slotID){
{
ItemStack original = null; ItemStack original = null;
Slot slotclicked = (Slot)inventorySlots.get(slotID); Slot slotclicked = (Slot) inventorySlots.get(slotID);
if (slotclicked != null && slotclicked.getHasStack()) if(slotclicked != null && slotclicked.getHasStack()){
{
ItemStack sourceStack = slotclicked.getStack(); ItemStack sourceStack = slotclicked.getStack();
original = sourceStack.copy(); original = sourceStack.copy();
if (slotID < playerInventoryStartSlot) if(slotID < playerInventoryStartSlot){
{
// Move stuff to the player's inventory // 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; return null;
} }
} }else{
else
{
// Move stuff to the battery station's inventory // Move stuff to the battery station's inventory
if (!this.mergeItemStack(sourceStack, 0, shiftClickRange, false)) if(!this.mergeItemStack(sourceStack, 0, shiftClickRange, false)){
{
return null; return null;
} }
} }
if (sourceStack.stackSize == 0) if(sourceStack.stackSize == 0){
{ slotclicked.putStack((ItemStack) null);
slotclicked.putStack((ItemStack)null); }else{
}
else
{
slotclicked.onSlotChanged(); slotclicked.onSlotChanged();
} }
} }
return original; return original;
} }
/* @Override /*
public ItemStack slotClick(int slotID, int button, int shiftclick, EntityPlayer par4EntityPlayer) * @Override public ItemStack slotClick(int slotID, int button, int
{ * shiftclick, EntityPlayer par4EntityPlayer) { ItemStack result = null;
ItemStack result = null; *
* //if (ChargingBench.isDebugging && ChargingBench.proxy.isServer())
//if (ChargingBench.isDebugging && ChargingBench.proxy.isServer()) System.out.println("ContainerBatteryStation.slotClick(slotID=" + slotID + ", button=" + button + ", shift=" + shiftclick + ");"); * System.out.println("ContainerBatteryStation.slotClick(slotID=" + slotID +
* ", button=" + button + ", shift=" + shiftclick + ");");
if (button > 1) *
{ * if (button > 1) { return null; } else { if (button == 0 || button == 1) {
return null; * InventoryPlayer invPlayer = par4EntityPlayer.inventory;
} *
else * if (slotID == -999) // Dropping items outside GUI, identical to vanilla
{ * behavior { if (invPlayer.getItemStack() != null && slotID == -999) { if
if (button == 0 || button == 1) * (button == 0) {
{ * par4EntityPlayer.dropPlayerItem(invPlayer.getItemStack());
InventoryPlayer invPlayer = par4EntityPlayer.inventory; * invPlayer.setItemStack((ItemStack)null); }
*
if (slotID == -999) // Dropping items outside GUI, identical to vanilla behavior * if (button == 1) {
{ * par4EntityPlayer.dropPlayerItem(invPlayer.getItemStack().splitStack(1));
if (invPlayer.getItemStack() != null && slotID == -999) *
{ * if (invPlayer.getItemStack().stackSize == 0) {
if (button == 0) * invPlayer.setItemStack((ItemStack)null); } } } } else if (shiftclick ==
{ * 1) { ItemStack original = this.transferStackInSlot(par4EntityPlayer,
par4EntityPlayer.dropPlayerItem(invPlayer.getItemStack()); * slotID);
invPlayer.setItemStack((ItemStack)null); *
} * // 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 !=
if (button == 1) * null) { int originalID = original.itemID; result = original.copy(); Slot
{ * slot = (Slot)inventorySlots.get(slotID);
par4EntityPlayer.dropPlayerItem(invPlayer.getItemStack().splitStack(1)); *
* if (slot != null && slot.getStack() != null && slot.getStack().itemID ==
if (invPlayer.getItemStack().stackSize == 0) * originalID) { this.retrySlotClick(slotID, button, true,
{ * par4EntityPlayer); } } } else { if (slotID < 0) { return null; }
invPlayer.setItemStack((ItemStack)null); *
} * Slot slot = (Slot)inventorySlots.get(slotID);
} *
} * if (slot != null) { ItemStack clickedStack = slot.getStack(); ItemStack
} * mouseStack = invPlayer.getItemStack();
else if (shiftclick == 1) *
{ * if (clickedStack != null) { //if (ChargingBench.isDebugging)
ItemStack original = this.transferStackInSlot(par4EntityPlayer, slotID); * System.out.println("Clicked stack tag: " + clickedStack.stackTagCompound
* + " / Item ID: " + clickedStack.itemID); result = clickedStack.copy(); }
// 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 quantity;
{ *
int originalID = original.itemID; * if (clickedStack == null) { // There's nothing in the slot, place the
result = original.copy(); * held item there if possible if (mouseStack != null &&
Slot slot = (Slot)inventorySlots.get(slotID); * slot.isItemValid(mouseStack)) { quantity = button == 0 ?
* mouseStack.stackSize : 1; if (quantity > slot.getSlotStackLimit())
if (slot != null && slot.getStack() != null && slot.getStack().itemID == originalID) * quantity = slot.getSlotStackLimit();
{ *
this.retrySlotClick(slotID, button, true, par4EntityPlayer); * 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
else * quantity = button == 0 ? clickedStack.stackSize : (clickedStack.stackSize
{ * + 1) / 2; ItemStack remainder = slot.decrStackSize(quantity);
if (slotID < 0) * invPlayer.setItemStack(remainder);
{ *
return null; * if (clickedStack.stackSize == 0) { slot.putStack((ItemStack)null); }
} *
* slot.onPickupFromSlot(par4EntityPlayer, invPlayer.getItemStack()); } else
Slot slot = (Slot)inventorySlots.get(slotID); * if (slot.isItemValid(mouseStack)) { // Both the mouse and the slot
* contain items, run this code if the item can be placed here if
if (slot != null) * (clickedStack.itemID == mouseStack.itemID &&
{ * (!clickedStack.getHasSubtypes() || clickedStack.getItemDamage() ==
ItemStack clickedStack = slot.getStack(); * mouseStack.getItemDamage()) &&
ItemStack mouseStack = invPlayer.getItemStack(); * ItemStack.areItemStackTagsEqual(clickedStack, mouseStack)) { quantity =
* button == 0 ? mouseStack.stackSize : 1;
if (clickedStack != null) *
{ * if (quantity > slot.getSlotStackLimit() - clickedStack.stackSize) {
//if (ChargingBench.isDebugging) System.out.println("Clicked stack tag: " + clickedStack.stackTagCompound + " / Item ID: " + clickedStack.itemID); * quantity = slot.getSlotStackLimit() - clickedStack.stackSize; }
result = clickedStack.copy(); *
} * if (quantity > mouseStack.getMaxStackSize() - clickedStack.stackSize) {
* quantity = mouseStack.getMaxStackSize() - clickedStack.stackSize; }
int quantity; *
* mouseStack.splitStack(quantity);
if (clickedStack == null) *
{ // There's nothing in the slot, place the held item there if possible * if (mouseStack.stackSize == 0) { invPlayer.setItemStack((ItemStack)null);
if (mouseStack != null && slot.isItemValid(mouseStack)) * }
{ *
quantity = button == 0 ? mouseStack.stackSize : 1; * clickedStack.stackSize += quantity; } else if (mouseStack.stackSize <=
if (quantity > slot.getSlotStackLimit()) quantity = slot.getSlotStackLimit(); * slot.getSlotStackLimit()) { // Exchange the items since they don't match
* slot.putStack(mouseStack); invPlayer.setItemStack(clickedStack); } } else
ItemStack temp = mouseStack.splitStack(quantity); * if (clickedStack.itemID == mouseStack.itemID &&
slot.putStack(temp); * mouseStack.getMaxStackSize() > 1 && (!clickedStack.getHasSubtypes() ||
* clickedStack.getItemDamage() == mouseStack.getItemDamage()) &&
if (mouseStack.stackSize == 0) * ItemStack.areItemStackTagsEqual(clickedStack, mouseStack)) { // Both the
{ * mouse and the slot contain items, run this code if they match quantity =
invPlayer.setItemStack((ItemStack)null); * clickedStack.stackSize;
} *
} * if (quantity > 0 && quantity + mouseStack.stackSize <=
} * mouseStack.getMaxStackSize()) { mouseStack.stackSize += quantity;
else if (mouseStack == null) * clickedStack = slot.decrStackSize(quantity);
{ // Pick up what's in the slot *
quantity = button == 0 ? clickedStack.stackSize : (clickedStack.stackSize + 1) / 2; * if (clickedStack.stackSize == 0) { slot.putStack((ItemStack)null); }
ItemStack remainder = slot.decrStackSize(quantity); *
invPlayer.setItemStack(remainder); * slot.onPickupFromSlot(par4EntityPlayer, invPlayer.getItemStack()); } }
*
if (clickedStack.stackSize == 0) * slot.onSlotChanged();
{ *
slot.putStack((ItemStack)null); * } } }
} *
* return result; } }
slot.onPickupFromSlot(par4EntityPlayer, invPlayer.getItemStack()); */
}
else if (slot.isItemValid(mouseStack)) public boolean canInteractWith(EntityPlayer var1){
{ // Both the mouse and the slot contain items, run this code if the item can be placed here // if (ChargingBench.isDebugging)
if (clickedStack.itemID == mouseStack.itemID && (!clickedStack.getHasSubtypes() || clickedStack.getItemDamage() == mouseStack.getItemDamage()) && ItemStack.areItemStackTagsEqual(clickedStack, mouseStack)) // System.out.println("ContainerChargingBench.canInteractWith");
{
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); return tileentity.isUseableByPlayer(var1);
} }
} }

View file

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

View file

@ -17,11 +17,10 @@ import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly; import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
public class CButton extends GuiButton public class CButton extends GuiButton{
{
/** Path to custom texture for button */ /** Path to custom texture for button */
protected String texture; protected String texture;
protected int uLoc; protected int uLoc;
protected int vLoc; protected int vLoc;
protected int uHoverLoc; protected int uHoverLoc;
@ -29,25 +28,42 @@ public class CButton extends GuiButton
protected int color; protected int color;
protected int hoverColor; protected int hoverColor;
protected boolean isHovering; 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 id
* @param xLoc - x location of button on screen * - ID of button
* @param yLoc - y location of button on screen * @param xLoc
* @param width - width of button * - x location of button on screen
* @param height - height of button * @param yLoc
* @param uLoc - x location of start of texture in texture file * - y location of button on screen
* @param vLoc - y location of start of texture in texture file * @param width
* @param uHoverLoc - x location of start of texture for mouse over in texture file * - width of button
* @param vHoverLoc - x location of start of texture for mouse over in texture file * @param height
* @param text - text to display on button * - height of button
* @param color - color for the text * @param uLoc
* @param hoverColor - color for the text while hovering * - x location of start of texture in texture file
* @param texture - path to 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); super(id, xLoc, yLoc, width, height, text);
this.enabled = true; this.enabled = true;
this.visible = true; this.visible = true;
@ -65,48 +81,39 @@ public class CButton extends GuiButton
this.hoverColor = hoverColor; this.hoverColor = hoverColor;
this.texture = texture; this.texture = texture;
} }
/** /**
* Draws this button to the screen. * Draws this button to the screen.
*/ */
@Override @Override
public void drawButton(Minecraft mc, int xLoc, int yLoc) public void drawButton(Minecraft mc, int xLoc, int yLoc){
{ if(visible){
if (visible)
{
FontRenderer fr = mc.fontRenderer; FontRenderer fr = mc.fontRenderer;
if (texture != null) if(texture != null){
{
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
mc.renderEngine.bindTexture(new ResourceLocation(Info.TITLE_PACKED.toLowerCase(), texture)); mc.renderEngine.bindTexture(new ResourceLocation(Info.TITLE_PACKED.toLowerCase(), texture));
} }
isHovering = xLoc >= xPosition && yLoc >= yPosition && xLoc < xPosition + width && yLoc < yPosition + height; isHovering = xLoc >= xPosition && yLoc >= yPosition && xLoc < xPosition + width && yLoc < yPosition + height;
int hoverState = this.getHoverState(isHovering); int hoverState = this.getHoverState(isHovering);
if (hoverState == 2) if(hoverState == 2){
{
this.drawTexturedModalRect(xPosition, yPosition, uHoverLoc, vHoverLoc, width, height); this.drawTexturedModalRect(xPosition, yPosition, uHoverLoc, vHoverLoc, width, height);
} }else{
else
{
this.drawTexturedModalRect(xPosition, yPosition, uLoc, vLoc, width, height); this.drawTexturedModalRect(xPosition, yPosition, uLoc, vLoc, width, height);
} }
int defaultColor = color; int defaultColor = color;
int renderColor = defaultColor; int renderColor = defaultColor;
if (!enabled) if(!enabled){
{ renderColor = -6250336;
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); 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; import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
public class GuiAdjustableTransformer extends GuiContainer public class GuiAdjustableTransformer extends GuiContainer{
{
IInventory playerInventory; IInventory playerInventory;
public TEAdjustableTransformer tile; public TEAdjustableTransformer tile;
private CButton buttons[] = new CButton[16]; private CButton buttons[] = new CButton[16];
private CButton dirButtons[] = new CButton[6]; private CButton dirButtons[] = new CButton[6];
private int xLoc; private int xLoc;
private int yLoc; private int yLoc;
private final int yOff = 30; private final int yOff = 30;
private static final String displayStrings[] = {"+1", "+10", "+64", "x2", "-1", "-10", "-64", "/2"}; private static final String displayStrings[] = {"+1", "+10", "+64", "x2", "-1", "-10", "-64", "/2"};
private static final int GREEN = 0x55FF55; private static final int GREEN = 0x55FF55;
private static final int GREENGLOW = Utils.multiplyColorComponents(GREEN, 0.16F); private static final int GREENGLOW = Utils.multiplyColorComponents(GREEN, 0.16F);
private DecimalFormat fraction = new DecimalFormat("##0.00"); private DecimalFormat fraction = new DecimalFormat("##0.00");
public GuiAdjustableTransformer(TEAdjustableTransformer tileentity) public GuiAdjustableTransformer(TEAdjustableTransformer tileentity) {
{
super(new ContainerAdjustableTransformer(tileentity)); super(new ContainerAdjustableTransformer(tileentity));
tile = tileentity; tile = tileentity;
xSize = 240; // The X size of the GUI window in pixels. xSize = 240; // The X size of the GUI window in pixels.
ySize = 140; // The Y 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 // Button definition - mouse over CButton for details
for (int i = 0; i < buttons.length; i++) for(int i = 0; i < buttons.length; i++){
{ // 16777120 old highlight color code, saved here for reference
//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); 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++) 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,
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); Info.GUI_TEX_ADJ_TRANSFORMER);
} }
} }
@Override @Override
public void initGui() public void initGui(){
{
super.initGui(); // Don't forget this or MC will crash super.initGui(); // Don't forget this or MC will crash
// Upper left corner of GUI panel // Upper left corner of GUI panel
xLoc = (width - xSize) / 2; // Half the difference between screen width and GUI width xLoc = (width - xSize) / 2; // Half the difference between screen width
yLoc = (height - ySize) / 2; // Half the difference between screen height and GUI height // and GUI width
yLoc = (height - ySize) / 2; // Half the difference between screen
for (int i = 0; i < 16; i++) // height and GUI height
{
buttons[i].xPosition = xLoc + 8 + 24 * (i % 4); 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); 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].xPosition = xLoc + 173;
dirButtons[i].yPosition = yLoc + yOff + 24 + 13 * i; dirButtons[i].yPosition = yLoc + yOff + 24 + 13 * i;
} }
} }
@Override @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); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
mc.renderEngine.bindTexture(new ResourceLocation(Info.TITLE_PACKED.toLowerCase(), Info.GUI_TEX_ADJ_TRANSFORMER)); mc.renderEngine.bindTexture(new ResourceLocation(Info.TITLE_PACKED.toLowerCase(), Info.GUI_TEX_ADJ_TRANSFORMER));
// Draw GUI background graphic // Draw GUI background graphic
drawTexturedModalRect(xLoc, yLoc, 0, 0, xSize, ySize); drawTexturedModalRect(xLoc, yLoc, 0, 0, xSize, ySize);
// Draw title text // Draw title text
Utils.drawCenteredText(fontRendererObj, I18n.format(tile.getInvName()), width / 2, yLoc + 6, 4210752); Utils.drawCenteredText(fontRendererObj, I18n.format(tile.getInvName()), width / 2, yLoc + 6, 4210752);
// Draw stats text // 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_EU), xLoc + 180, yLoc + 26, 4210752);
Utils.drawRightAlignedText(fontRendererObj, I18n.format(Info.KEY_STATS_AVERAGE_INPUT), xLoc + 180, yLoc + 36, 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.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); Utils.drawRightAlignedGlowingText(fontRendererObj, Integer.toString(tile.energyBuffer), xLoc + 44, yLoc + 26, GREEN, GREENGLOW);
// Factor of 100 because data is in fixed point (x100) // Factor of 100 because data is in fixed point (x100)
final float outAvg = (float)(((ContainerAdjustableTransformer)inventorySlots).outputAvg) / 100F; final float outAvg = (float) (((ContainerAdjustableTransformer) inventorySlots).outputAvg) / 100F;
final float inAvg = (float)(((ContainerAdjustableTransformer)inventorySlots).inputAvg) / 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(outAvg), xLoc + 230, yLoc + 26, GREEN, GREENGLOW);
Utils.drawRightAlignedGlowingText(fontRendererObj, fraction.format(inAvg), xLoc + 230, yLoc + 36, GREEN, GREENGLOW); Utils.drawRightAlignedGlowingText(fontRendererObj, fraction.format(inAvg), xLoc + 230, yLoc + 36, GREEN, GREENGLOW);
// Packet size section text // Packet size section text
Utils.drawCenteredText(fontRendererObj, I18n.format(Info.KEY_EMITTER_PACKET), xLoc + 88, yLoc + yOff + 21, 0xB00000); 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); 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(Info.AE_PACKET_RANGE, xLoc + 110, yLoc + yOff + 35, 4210752);
fontRendererObj.drawString(I18n.format(Info.KEY_EU), xLoc + 152, yLoc + yOff + 49, 4210752); fontRendererObj.drawString(I18n.format(Info.KEY_EU), xLoc + 152, yLoc + yOff + 49, 4210752);
// Transfer rate section text // Transfer rate section text
Utils.drawCenteredText(fontRendererObj, I18n.format(Info.KEY_TRANSFORMER_OUTPUT), xLoc + 88, yLoc + yOff + 64, 0xB00000); 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); 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(Info.AE_OUTPUT_RANGE, xLoc + 110, yLoc + yOff + 78, 4210752);
fontRendererObj.drawString(I18n.format(Info.KEY_EU), xLoc + 152, yLoc + yOff + 92, 4210752); fontRendererObj.drawString(I18n.format(Info.KEY_EU), xLoc + 152, yLoc + yOff + 92, 4210752);
// Side input/output settings text // Side input/output settings text
for (int i = 0; i < 6; i++) 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
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); + 27 + 13 * i, GREEN, GREENGLOW);
} }
//Buttons MUST be drawn after other texture stuff or it will not draw the battery meter correctly // Buttons MUST be drawn after other texture stuff or it will not draw
for (CButton button : buttons) // the battery meter correctly
{ for(CButton button : buttons){
button.drawButton(mc, mouseX, mouseY); button.drawButton(mc, mouseX, mouseY);
} }
for (CButton button : dirButtons) for(CButton button : dirButtons){
{
button.drawButton(mc, mouseX, mouseY); button.drawButton(mc, mouseX, mouseY);
} }
} }
@Override @Override
protected void mouseClicked(int par1, int par2, int par3) protected void mouseClicked(int par1, int par2, int par3){
{ if(par3 == 0) // On a left click,
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, // mc.sndManager.playSoundFX("random.click", 1.0F, 1.0F); //
tile.sendGuiButton(b.id); // and inform the server of the button click. // provide audio feedback,
tile.sendGuiButton(b.id); // and inform the server of the
// button click.
} }
} }
for (CButton b : dirButtons) for(CButton b : dirButtons){
{ if(b.enabled && b.mousePressed(this.mc, par1, par2)) // if it's
if (b.enabled && b.mousePressed(this.mc, par1, par2)) // if it's enabled and was under the pointer, // enabled
// and
// was
// under
// the
// pointer,
{ {
//mc.sndManager.playSoundFX("random.click", 1.0F, 1.0F); // provide audio feedback, // mc.sndManager.playSoundFX("random.click", 1.0F, 1.0F); //
tile.sendGuiButton(b.id); // and inform the server of the button click. // 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; import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
public class GuiAdvEmitter extends GuiContainer public class GuiAdvEmitter extends GuiContainer{
{
IInventory playerInventory; IInventory playerInventory;
public TEAdvEmitter tile; public TEAdvEmitter tile;
private CButton buttons[] = new CButton[16]; private CButton buttons[] = new CButton[16];
private int xLoc; private int xLoc;
private int yLoc; private int yLoc;
private static final String displayStrings[] = {"+1", "+10", "+64", "x2", "-1", "-10", "-64", "/2"}; private static final String displayStrings[] = {"+1", "+10", "+64", "x2", "-1", "-10", "-64", "/2"};
private static final int GREEN = 0x55FF55; private static final int GREEN = 0x55FF55;
private static final int GREENGLOW = Utils.multiplyColorComponents(GREEN, 0.16F); private static final int GREENGLOW = Utils.multiplyColorComponents(GREEN, 0.16F);
public GuiAdvEmitter(TEAdvEmitter tileentity) public GuiAdvEmitter(TEAdvEmitter tileentity) {
{
super(new ContainerAdvEmitter(tileentity)); super(new ContainerAdvEmitter(tileentity));
tile = tileentity; tile = tileentity;
xSize = 176; // The X size of the GUI window in pixels. xSize = 176; // The X size of the GUI window in pixels.
ySize = 110; // The Y 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 // Button definition - mouse over CButton for details
for (int i = 0; i < buttons.length; i++) for(int i = 0; i < buttons.length; i++){
{ // 16777120 old highlight color code, saved here for reference
//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); buttons[i] = new CButton(i, 0, 0, 24, 13, 1, 192, 1, 207, displayStrings[i % 8], 4210752, 16777120, Info.GUI_TEX_EMITTER);
} }
} }
@Override @Override
public void initGui() public void initGui(){
{
super.initGui(); // Don't forget this or MC will crash super.initGui(); // Don't forget this or MC will crash
// Upper left corner of GUI panel // Upper left corner of GUI panel
xLoc = (width - xSize) / 2; // Half the difference between screen width and GUI width xLoc = (width - xSize) / 2; // Half the difference between screen width
yLoc = (height - ySize) / 2; // Half the difference between screen height and GUI height // and GUI width
yLoc = (height - ySize) / 2; // Half the difference between screen
for (int i = 0; i < 16; i++) // height and GUI height
{
buttons[i].xPosition = xLoc + 8 + 24 * (i % 4); 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); buttons[i].yPosition = yLoc + 33 + 13 * (i / 4) + 17 * (i / 8);
} }
} }
@Override @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); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
mc.renderEngine.bindTexture(new ResourceLocation(Info.TITLE_PACKED.toLowerCase(), Info.GUI_TEX_EMITTER)); mc.renderEngine.bindTexture(new ResourceLocation(Info.TITLE_PACKED.toLowerCase(), Info.GUI_TEX_EMITTER));
// Draw GUI background graphic // Draw GUI background graphic
drawTexturedModalRect(xLoc, yLoc, 0, 0, xSize, ySize); drawTexturedModalRect(xLoc, yLoc, 0, 0, xSize, ySize);
// Draw title text // Draw title text
Utils.drawCenteredText(fontRendererObj, I18n.format(tile.getInvName()), width / 2, yLoc + 7, 4210752); Utils.drawCenteredText(fontRendererObj, I18n.format(tile.getInvName()), width / 2, yLoc + 7, 4210752);
// Packet size section text // Packet size section text
Utils.drawCenteredText(fontRendererObj, I18n.format(Info.KEY_EMITTER_PACKET), width / 2, yLoc + 21, 0xB00000); 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); 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(Info.AE_PACKET_RANGE, xLoc + 110, yLoc + 35, 4210752);
fontRendererObj.drawString(I18n.format(Info.KEY_EU), xLoc + 152, yLoc + 49, 4210752); fontRendererObj.drawString(I18n.format(Info.KEY_EU), xLoc + 152, yLoc + 49, 4210752);
// Output rate section text // Output rate section text
Utils.drawCenteredText(fontRendererObj, I18n.format(Info.KEY_EMITTER_OUTPUT), width / 2, yLoc + 64, 0xB00000); 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); 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(Info.AE_OUTPUT_RANGE, xLoc + 110, yLoc + 78, 4210752);
fontRendererObj.drawString(I18n.format(Info.KEY_EU), xLoc + 152, yLoc + 92, 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 // Buttons MUST be drawn after other texture stuff or it will not draw
for (CButton button : buttons) // the battery meter correctly
{ for(CButton button : buttons){
button.drawButton(mc, mouseX, mouseY); button.drawButton(mc, mouseX, mouseY);
} }
} }
@Override @Override
protected void mouseClicked(int par1, int par2, int par3) protected void mouseClicked(int par1, int par2, int par3){
{ if(par3 == 0) // On a left click,
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, // mc.sndManager.playSoundFX("random.click", 1.0F, 1.0F); //
tile.sendGuiButton(b.id); // and inform the server of the button click. // 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; import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
public class GuiBatteryStation extends GuiContainer public class GuiBatteryStation extends GuiContainer{
{
IInventory playerInventory; IInventory playerInventory;
public TEBatteryStation tile; public TEBatteryStation tile;
private CButton button; private CButton button;
private int mode = -1; private int mode = -1;
private int xLoc; private int xLoc;
private int yLoc; private int yLoc;
private int xCenter; private int xCenter;
private DecimalFormat fraction = new DecimalFormat("##0.00"); private DecimalFormat fraction = new DecimalFormat("##0.00");
private DecimalFormat time = new DecimalFormat("00"); private DecimalFormat time = new DecimalFormat("00");
private DecimalFormat days = new DecimalFormat("#0"); private DecimalFormat days = new DecimalFormat("#0");
private DecimalFormat dayFrac = new DecimalFormat("0.#"); private DecimalFormat dayFrac = new DecimalFormat("0.#");
private static final int GREEN = 0x55FF55; private static final int GREEN = 0x55FF55;
private static final int GREENGLOW = Utils.multiplyColorComponents(GREEN, 0.16F); 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)); super(new ContainerBatteryStation(player, tileentity));
tile = tileentity; tile = tileentity;
xSize = 176; // The X size of the GUI window in pixels. xSize = 176; // The X size of the GUI window in pixels.
ySize = 182; // The Y 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); button = new CButton(0, 0, 0, 18, 12, 30, 200, 30, 200, "", 4210752, 16777120, Info.GUI_TEX_BATTERY_STATION);
} }
@Override @Override
public void initGui() public void initGui(){
{
super.initGui(); // Don't forget this or MC will crash super.initGui(); // Don't forget this or MC will crash
// Upper left corner of GUI panel // Upper left corner of GUI panel
xLoc = (width - xSize) / 2; // Half the difference between screen width and GUI width xLoc = (width - xSize) / 2; // Half the difference between screen width
yLoc = (height - ySize) / 2; // Half the difference between screen height and GUI height // and GUI width
yLoc = (height - ySize) / 2; // Half the difference between screen
// height and GUI height
xCenter = width / 2; xCenter = width / 2;
button.xPosition = xLoc + 16; button.xPosition = xLoc + 16;
button.yPosition = yLoc + 44; button.yPosition = yLoc + 44;
mode = -1; mode = -1;
} }
@Override @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); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
mc.renderEngine.bindTexture(new ResourceLocation(Info.TITLE_PACKED.toLowerCase(), Info.GUI_TEX_BATTERY_STATION)); mc.renderEngine.bindTexture(new ResourceLocation(Info.TITLE_PACKED.toLowerCase(), Info.GUI_TEX_BATTERY_STATION));
this.drawTexturedModalRect(xLoc, yLoc, 0, 0, xSize, ySize); this.drawTexturedModalRect(xLoc, yLoc, 0, 0, xSize, ySize);
// Draw title text // Draw title text
Utils.drawCenteredText(fontRendererObj, I18n.format(tile.getInventoryName()), xCenter, yLoc + 8, 4210752); Utils.drawCenteredText(fontRendererObj, I18n.format(tile.getInventoryName()), xCenter, yLoc + 8, 4210752);
if (mode != ((ContainerBatteryStation)inventorySlots).opMode) if(mode != ((ContainerBatteryStation) inventorySlots).opMode){
{ mode = ((ContainerBatteryStation) inventorySlots).opMode;
mode = ((ContainerBatteryStation)inventorySlots).opMode; if(mode == 0){
if (mode == 0)
{
button.vLoc = 200; button.vLoc = 200;
button.vHoverLoc = 200; button.vHoverLoc = 200;
} }else{
else
{
button.vLoc = 185; button.vLoc = 185;
button.vHoverLoc = 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_LINE1), xLoc + 7, yLoc + 59, 4210752);
Utils.drawLeftAlignedText(fontRendererObj, I18n.format(Info.KEY_DISCHARGER_MODE_LINE2), xLoc + 7, yLoc + 70, 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_AVERAGE_EU), xLoc + 144, yLoc + 27, 4210752);
Utils.drawCenteredText(fontRendererObj, I18n.format(Info.KEY_STATS_TIME_REMAINING), xLoc + 144, yLoc + 65, 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) // 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); Utils.drawRightAlignedGlowingText(fontRendererObj, fraction.format(rate), xLoc + 166, yLoc + 41, GREEN, GREENGLOW);
String clock; String clock;
if (rate > 0) if(rate > 0){
{
// Rate * 20 to convert per tick to per second // Rate * 20 to convert per tick to per second
int timeScratch = (int)((float)(((ContainerBatteryStation)inventorySlots).itemsEnergyTotal) / (rate * 20)); int timeScratch = (int) ((float) (((ContainerBatteryStation) inventorySlots).itemsEnergyTotal) / (rate * 20));
if (timeScratch <= 345600) // 60 * 60 * 96 or 4 days if(timeScratch <= 345600) // 60 * 60 * 96 or 4 days
{ {
final int sec = timeScratch % 60; final int sec = timeScratch % 60;
timeScratch /= 60; timeScratch /= 60;
final int min = timeScratch % 60; final int min = timeScratch % 60;
timeScratch /= 60; timeScratch /= 60;
clock = time.format(timeScratch) + ":" + time.format(min) + ":" + time.format(sec); 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 }else
{ clock = I18n.format(Info.KEY_STATS_DISPLAY_UNKNOWN);
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);
Utils.drawRightAlignedGlowingText(fontRendererObj, clock, xLoc + 166, yLoc + 51, GREEN, GREENGLOW); Utils.drawRightAlignedGlowingText(fontRendererObj, clock, xLoc + 166, yLoc + 51, GREEN, GREENGLOW);
button.drawButton(mc, mouseX, mouseY); button.drawButton(mc, mouseX, mouseY);
} }
@Override @Override
protected void mouseClicked(int par1, int par2, int par3) protected void mouseClicked(int par1, int par2, int par3){
{ if(par3 == 0) // On a left click,
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, // mc.sndManager.playSoundFX("random.click", 1.0F, 1.0F); //
tile.sendGuiButton(button.id); // and inform the server of the button click. // 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; import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
public class GuiChargingBench extends GuiContainer public class GuiChargingBench extends GuiContainer{
{
IInventory playerInventory; IInventory playerInventory;
public TEChargingBench tile; public TEChargingBench tile;
private int xLoc; private int xLoc;
private int yLoc; private int yLoc;
private int xCenter; private int xCenter;
private DecimalFormat fraction = new DecimalFormat("##0.00"); private DecimalFormat fraction = new DecimalFormat("##0.00");
private DecimalFormat time = new DecimalFormat("00"); private DecimalFormat time = new DecimalFormat("00");
private DecimalFormat days = new DecimalFormat("#0"); private DecimalFormat days = new DecimalFormat("#0");
private DecimalFormat dayFrac = new DecimalFormat("0.#"); private DecimalFormat dayFrac = new DecimalFormat("0.#");
private static final int GREEN = 0x55FF55; private static final int GREEN = 0x55FF55;
private static final int GREENGLOW = Utils.multiplyColorComponents(GREEN, 0.16F); 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)); super(new ContainerChargingBench(player, tileentity));
tile = tileentity; tile = tileentity;
xSize = 176; // The X size of the GUI window in pixels. xSize = 176; // The X size of the GUI window in pixels.
ySize = 226; // The Y size of the GUI window in pixels. ySize = 226; // The Y size of the GUI window in pixels.
} }
@Override @Override
public void initGui() public void initGui(){
{
super.initGui(); // Don't forget this or MC will crash super.initGui(); // Don't forget this or MC will crash
// Upper left corner of GUI panel // Upper left corner of GUI panel
xLoc = (width - xSize) / 2; // Half the difference between screen width and GUI width xLoc = (width - xSize) / 2; // Half the difference between screen width
yLoc = (height - ySize) / 2; // Half the difference between screen height and GUI height // and GUI width
yLoc = (height - ySize) / 2; // Half the difference between screen
// height and GUI height
xCenter = width / 2; xCenter = width / 2;
} }
@Override @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); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
mc.renderEngine.bindTexture(new ResourceLocation(Info.TITLE_PACKED.toLowerCase(), Info.GUI_TEX_CHARGING_BENCH)); mc.renderEngine.bindTexture(new ResourceLocation(Info.TITLE_PACKED.toLowerCase(), Info.GUI_TEX_CHARGING_BENCH));
// Draw GUI background // Draw GUI background
drawTexturedModalRect(xLoc, yLoc, 0, 0, xSize, ySize); drawTexturedModalRect(xLoc, yLoc, 0, 0, xSize, ySize);
// Energy bar // Energy bar
if (tile.currentEnergy > 0) if(tile.currentEnergy > 0){
{ // Make each box light up all at once like a LED instead of
// Make each box light up all at once like a LED instead of gradually using barLength = tile.gaugeEnergyScaled(66); // gradually using barLength = tile.gaugeEnergyScaled(66);
int barLength = 5 * tile.gaugeEnergyScaled(13); 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); drawTexturedModalRect(xLoc + 32, yLoc + 136 - barLength, 176, 66 - barLength, 12, barLength);
} }
// Redstone power indicator // Redstone power indicator
drawTexturedModalRect(xLoc + 129, yLoc + 48, tile.receivingRedstoneSignal() ? 188 : 206, 0, 18, 15); drawTexturedModalRect(xLoc + 129, yLoc + 48, tile.receivingRedstoneSignal() ? 188 : 206, 0, 18, 15);
// Draw labels // Draw labels
Utils.drawCenteredText(fontRendererObj, I18n.format(tile.getInventoryName()), xCenter, yLoc + 7, 4210752); 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.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.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.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.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.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); Utils.drawLeftAlignedText(fontRendererObj, I18n.format(Info.KEY_CHARGER_PWR), xLoc + 151, yLoc + 52, 4210752);
// Draw current and max storage // Draw current and max storage
Utils.drawRightAlignedGlowingText(fontRendererObj, Integer.toString(tile.currentEnergy), xCenter - 7, yLoc + 23, GREEN, GREENGLOW); 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); Utils.drawGlowingText(fontRendererObj, " / " + Integer.toString(tile.adjustedStorage), xCenter - 7, yLoc + 23, GREEN, GREENGLOW);
// Factor of 100 because data is in fixed point (x100) // 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); Utils.drawRightAlignedGlowingText(fontRendererObj, fraction.format(rate), xLoc + 122, yLoc + 52, GREEN, GREENGLOW);
// Charging stats (only displayed while charging items) // Charging stats (only displayed while charging items)
if (tile.energyRequired > 0) if(tile.energyRequired > 0){
{
final String clock; final String clock;
if (tile.ticksRequired > 0) if(tile.ticksRequired > 0){
{
int timeScratch = tile.ticksRequired / 20; 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; final int sec = timeScratch % 60;
timeScratch /= 60; timeScratch /= 60;
final int min = timeScratch % 60; final int min = timeScratch % 60;
timeScratch /= 60; timeScratch /= 60;
clock = time.format(timeScratch) + ":" + time.format(min) + ":" + time.format(sec); 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 }else
{ clock = I18n.format(Info.KEY_STATS_DISPLAY_UNKNOWN);
float dayScratch = ((float)timeScratch) / 86400F; // 60 * 60 * 24 or 1 day final String energyReq = tile.energyRequired > 9999999 ? dayFrac.format(((float) tile.energyRequired) / 1000000F) + "M" : Integer
clock = (dayScratch < 10F ? dayFrac.format(dayScratch) : dayScratch < 100 ? days.format((int)dayScratch) : "??") + I18n.format(Info.KEY_STATS_DISPLAY_DAYS); .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, energyReq, xCenter - 7, yLoc + 33, GREEN, GREENGLOW);
Utils.drawRightAlignedGlowingText(fontRendererObj, clock, xLoc + 144, 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; import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
public class GuiStorageMonitor extends GuiContainer public class GuiStorageMonitor extends GuiContainer{
{
IInventory playerInventory; IInventory playerInventory;
public TEStorageMonitor tile; public TEStorageMonitor tile;
private CButton buttons[] = new CButton[8]; private CButton buttons[] = new CButton[8];
private int xLoc; private int xLoc;
private int yLoc; private int yLoc;
private static final String DISPLAYSTRINGS[] = {"-10", "-1", "+1", "+10"}; private static final String DISPLAYSTRINGS[] = {"-10", "-1", "+1", "+10"};
private static final int HORIZONTALOFFSETS[] = {-57, -33, 25, 49}; private static final int HORIZONTALOFFSETS[] = {-57, -33, 25, 49};
private static final int RED = 0xFF5555; private static final int RED = 0xFF5555;
private static final int GREEN = 0x55FF55; private static final int GREEN = 0x55FF55;
private static final int REDGLOW = Utils.multiplyColorComponents(RED, 0.16F); private static final int REDGLOW = Utils.multiplyColorComponents(RED, 0.16F);
private static final int GREENGLOW = Utils.multiplyColorComponents(GREEN, 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)); super(new ContainerStorageMonitor(player, tileentity));
tile = tileentity; tile = tileentity;
xSize = 176; // The X size of the GUI window in pixels. xSize = 176; // The X size of the GUI window in pixels.
ySize = 190; // The Y 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 // Button definition - mouse over CButton for details
for (int i = 0; i < buttons.length; i++) for(int i = 0; i < buttons.length; i++){
{ // 16777120 old highlight color code, saved here for reference
//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); buttons[i] = new CButton(i, 0, 0, 24, 13, 1, 192, 1, 207, DISPLAYSTRINGS[i % 4], 4210752, 0xFFFFAF, Info.GUI_TEX_STORAGE_MONITOR);
} }
} }
@Override @Override
public void initGui() public void initGui(){
{
super.initGui(); // Don't forget this or MC will crash super.initGui(); // Don't forget this or MC will crash
// Upper left corner of GUI panel // Upper left corner of GUI panel
xLoc = (width - xSize) / 2; // Half the difference between screen width and GUI width xLoc = (width - xSize) / 2; // Half the difference between screen width
yLoc = (height - ySize) / 2; // Half the difference between screen height and GUI height // and GUI width
yLoc = (height - ySize) / 2; // Half the difference between screen
// height and GUI height
// Reposition buttons // 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].xPosition = width / 2 + HORIZONTALOFFSETS[i % 4];
buttons[i].yPosition = yLoc + 60 + 29 * (i / 4); buttons[i].yPosition = yLoc + 60 + 29 * (i / 4);
} }
} }
@Override @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); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
mc.renderEngine.bindTexture(new ResourceLocation(Info.TITLE_PACKED.toLowerCase(), Info.GUI_TEX_STORAGE_MONITOR)); mc.renderEngine.bindTexture(new ResourceLocation(Info.TITLE_PACKED.toLowerCase(), Info.GUI_TEX_STORAGE_MONITOR));
// Draw GUI background // Draw GUI background
drawTexturedModalRect(xLoc, yLoc, 0, 0, xSize, ySize); drawTexturedModalRect(xLoc, yLoc, 0, 0, xSize, ySize);
// Draw energy meter // Draw energy meter
if (tile.energyStored > 0) if(tile.energyStored > 0){
{
// Which color energy meter should be used? // Which color energy meter should be used?
final int offset = tile.isPowering ? 12 : 0; 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); 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); drawTexturedModalRect(xLoc + 10, yLoc + 100 - barLength, 176 + offset, 66 - barLength, 12, barLength);
} }
// Draw title text // Draw title text
Utils.drawCenteredText(fontRendererObj, I18n.format(tile.getInventoryName()), xLoc + 96, yLoc + 12, 4210752); 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 // Error message: No card or storage unit not found
Utils.drawCenteredGlowingText(fontRendererObj, I18n.format(Info.KEY_MONITOR_INVALID), xLoc + 96, yLoc + 35, RED, REDGLOW); Utils.drawCenteredGlowingText(fontRendererObj, I18n.format(Info.KEY_MONITOR_INVALID), xLoc + 96, yLoc + 35, RED, REDGLOW);
} }else{
else
{
// Draw right-aligned current energy number // Draw right-aligned current energy number
Utils.drawRightAlignedGlowingText(fontRendererObj, Integer.toString(tile.energyStored), xLoc + 90, yLoc + 35, GREEN, GREENGLOW); Utils.drawRightAlignedGlowingText(fontRendererObj, Integer.toString(tile.energyStored), xLoc + 90, yLoc + 35, GREEN, GREENGLOW);
// Draw separator and left-aligned max energy number // Draw separator and left-aligned max energy number
Utils.drawGlowingText(fontRendererObj, " / " + Integer.toString(tile.energyCapacity), xLoc + 90, yLoc + 35, GREEN, GREENGLOW); Utils.drawGlowingText(fontRendererObj, " / " + Integer.toString(tile.energyCapacity), xLoc + 90, yLoc + 35, GREEN, GREENGLOW);
// Test strings // Test strings
//Utils.drawCenteredGlowingText(fontRenderer, " / ", xLoc + 96, yLoc + 35, 0x55FF55, glowFactor); // Utils.drawCenteredGlowingText(fontRenderer, " / ", xLoc + 96,
//Utils.drawRightAlignedGlowingText(fontRenderer, "123456789", xLoc + 90, yLoc + 35, 0x55FF55, 0.15F); // yLoc + 35, 0x55FF55, glowFactor);
//Utils.drawGlowingText(fontRenderer, " / 123456789", xLoc + 90, yLoc + 35, 0x55FF55, 0.15F); // 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 // Draw control section labels and readouts
Utils.drawCenteredText(fontRendererObj, I18n.format(Info.KEY_MONITOR_UPPER), xLoc + 96, yLoc + 49, 0xB00000); 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.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.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); 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 // Draw ALL of the things?! :o
button.drawButton(mc, mouseX, mouseY); button.drawButton(mc, mouseX, mouseY);
} }
} }
@Override @Override
protected void mouseClicked(int par1, int par2, int par3) protected void mouseClicked(int par1, int par2, int par3){
{ if(par3 == 0) // On a left click,
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, // mc.sndManager.playSoundFX("random.click", 1.0F, 1.0F); //
tile.sendGuiButton(b.id); // and inform the server of the button click. // 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.Side;
import cpw.mods.fml.relauncher.SideOnly; 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"}; public static final String[] benchToolsNames = new String[] {"toolkit", "LV-kit", "MV-kit", "HV-kit"};
protected IIcon[] itemIcons; protected IIcon[] itemIcons;
public ItemBenchTools(String name) public ItemBenchTools(String name) {
{
super(); super();
this.setHasSubtypes(true); this.setHasSubtypes(true);
this.setMaxDamage(0); this.setMaxDamage(0);
@ -38,27 +36,25 @@ public class ItemBenchTools extends Item
this.setCreativeTab(CreativeTabs.tabMisc); this.setCreativeTab(CreativeTabs.tabMisc);
GameRegistry.registerItem(this, name); GameRegistry.registerItem(this, name);
} }
/** /**
* Gets an icon based on an item's damage value * Gets an icon based on an item's damage value
*/ */
@Override @Override
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
public IIcon getIconFromDamage(int par1) public IIcon getIconFromDamage(int par1){
{
return itemIcons[MathHelper.clamp_int(par1, 0, 3)]; return itemIcons[MathHelper.clamp_int(par1, 0, 3)];
} }
@Override @Override
public void registerIcons(IIconRegister iconRegister) public void registerIcons(IIconRegister iconRegister){
{
itemIcons = new IIcon[benchToolsNames.length]; 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]); 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.iconSlotChargeable = iconRegister.registerIcon(Info.TITLE_PACKED + ":SlotChargeable");
Info.iconSlotDrainable = iconRegister.registerIcon(Info.TITLE_PACKED + ":SlotDrainable"); Info.iconSlotDrainable = iconRegister.registerIcon(Info.TITLE_PACKED + ":SlotDrainable");
Info.iconSlotInput = iconRegister.registerIcon(Info.TITLE_PACKED + ":SlotInput"); 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.iconSlotLinkCard = iconRegister.registerIcon(Info.TITLE_PACKED + ":SlotLinkCard");
Info.iconSlotPowerSource = new IIcon[3]; Info.iconSlotPowerSource = new IIcon[3];
Info.iconSlotPlayerArmor = new IIcon[4]; 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)); 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)); Info.iconSlotPlayerArmor[i] = iconRegister.registerIcon(Info.TITLE_PACKED + ":SlotPlayerArmor" + Integer.toString(i));
} }
@Override @Override
public boolean isRepairable() public boolean isRepairable(){
{
return false; return false;
} }
@Override @Override
public String getUnlocalizedName(ItemStack par1ItemStack) public String getUnlocalizedName(ItemStack par1ItemStack){
{
int meta = MathHelper.clamp_int(par1ItemStack.getItemDamage(), 0, 3); int meta = MathHelper.clamp_int(par1ItemStack.getItemDamage(), 0, 3);
return "item.benchTools." + benchToolsNames[meta]; 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 entityitem = player.dropPlayerItemWithRandomChoice(stack, false);
entityitem.delayBeforeCanPickup = 0; entityitem.delayBeforeCanPickup = 0;
} }
/** /**
* This is called when the item is used, before the block is activated. * 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 stack
* @param world The Current World * The Item Stack
* @param x Target X Position * @param player
* @param y Target Y Position * The Player that used the item
* @param z Target Z Position * @param world
* @param side The side of the target hit * 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. * @return Return true to prevent any further processing.
*/ */
@Override @Override
public boolean onItemUseFirst(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) 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())
if (AdvancedPowerManagement.proxy.isClient()) return false; 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. // Test if the target is a charging bench and the item is a component
if (world.getBlock(x, y, z) != AdvancedPowerManagement.blockAdvPwrMan || stack.getItemDamage() < 1 || stack.getItemDamage() > 3 || player == null) // 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; return false;
} }
TileEntity tile = world.getTileEntity(x, y, z); TileEntity tile = world.getTileEntity(x, y, z);
if (!(tile instanceof TEChargingBench)) if(!(tile instanceof TEChargingBench)){
{
return false; return false;
} }
int recoveredTier = ((TEChargingBench)tile).swapBenchComponents(stack.getItemDamage()); int recoveredTier = ((TEChargingBench) tile).swapBenchComponents(stack.getItemDamage());
generateItemStack(new ItemStack(AdvancedPowerManagement.itemBenchTools, 1, recoveredTier), player); generateItemStack(new ItemStack(AdvancedPowerManagement.itemBenchTools, 1, recoveredTier), player);
stack.stackSize--; stack.stackSize--;
return true; 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 @Override
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player){
{ if(player.isSneaking() && stack.getItemDamage() > 0 && stack.getItemDamage() < 4){
if (player.isSneaking() && stack.getItemDamage() > 0 && stack.getItemDamage() < 4) switch(stack.getItemDamage()){
{
switch (stack.getItemDamage())
{
case 1: case 1:
generateItemStack(Info.componentCopperCable.copy(), player); generateItemStack(Info.componentCopperCable.copy(), player);
generateItemStack(Info.componentBatBox.copy(), player); generateItemStack(Info.componentBatBox.copy(), player);
@ -154,16 +153,15 @@ public class ItemBenchTools extends Item
} }
return stack; 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 @Override
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
public void getSubItems(Item par1, CreativeTabs par2CreativeTabs, List par3List) public void getSubItems(Item par1, CreativeTabs par2CreativeTabs, List par3List){
{ for(int meta = 0; meta < 4; ++meta){
for (int meta = 0; meta < 4; ++meta)
{
par3List.add(new ItemStack(par1, 1, meta)); par3List.add(new ItemStack(par1, 1, meta));
} }
} }

View file

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

View file

@ -11,71 +11,57 @@ import net.minecraft.item.Item;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
public class ItemCardBase extends Item public class ItemCardBase extends Item{
{
protected ItemCardBase(String name) {
protected ItemCardBase(String name)
{
super(); super();
setUnlocalizedName(name); setUnlocalizedName(name);
GameRegistry.registerItem(this, name); GameRegistry.registerItem(this, name);
} }
@Override @Override
public boolean isRepairable() public boolean isRepairable(){
{
return false; return false;
} }
public static int[] getCoordinates(ItemStack itemStack) public static int[] getCoordinates(ItemStack itemStack){
{ if(!(itemStack.getItem() instanceof ItemStorageLinkCard))
if (!(itemStack.getItem() instanceof ItemStorageLinkCard))
return null; return null;
NBTTagCompound nbtTagCompound = itemStack.getTagCompound(); NBTTagCompound nbtTagCompound = itemStack.getTagCompound();
if (nbtTagCompound == null) if(nbtTagCompound == null){
{
return null; return null;
} }
int[] coordinates = new int[]{ int[] coordinates = new int[] {nbtTagCompound.getInteger("x"), nbtTagCompound.getInteger("y"), nbtTagCompound.getInteger("z"),
nbtTagCompound.getInteger("x"), nbtTagCompound.getInteger("dim")};
nbtTagCompound.getInteger("y"),
nbtTagCompound.getInteger("z"),
nbtTagCompound.getInteger("dim")
};
return coordinates; 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"}; final String tags[] = {"x", "y", "z", "dim"};
NBTTagCompound nbtTagCompound = Utils.getOrCreateStackTag(itemStack); 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]); 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 nbtTagCompound = Utils.getOrCreateStackTag(itemStack);
nbtTagCompound.setInteger("x", x); nbtTagCompound.setInteger("x", x);
nbtTagCompound.setInteger("y", y); nbtTagCompound.setInteger("y", y);
nbtTagCompound.setInteger("z", z); nbtTagCompound.setInteger("z", z);
nbtTagCompound.setInteger("dim", dim); nbtTagCompound.setInteger("dim", dim);
} }
public String getTitle(ItemStack stack) public String getTitle(ItemStack stack){
{ if(!(stack.getItem() instanceof ItemStorageLinkCard))
if (!(stack.getItem() instanceof ItemStorageLinkCard))
return ""; return "";
NBTTagCompound nbtTagCompound = stack.getTagCompound(); NBTTagCompound nbtTagCompound = stack.getTagCompound();
if (nbtTagCompound == null) if(nbtTagCompound == null)
return ""; return "";
return nbtTagCompound.getString("title"); return nbtTagCompound.getString("title");
} }
public void setTitle(ItemStack stack, String title) public void setTitle(ItemStack stack, String title){
{
Utils.getOrCreateStackTag(stack).setString("title", 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.Side;
import cpw.mods.fml.relauncher.SideOnly; 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"; private static final String HINT_TEMPLATE = "X: %d, Y: %d, Z: %d, Dim: %d";
public ItemStorageLinkCard(String name) public ItemStorageLinkCard(String name) {
{
super(name); super(name);
setMaxStackSize(1); setMaxStackSize(1);
setTextureName(Info.TITLE_PACKED + ":LinkCard"); setTextureName(Info.TITLE_PACKED + ":LinkCard");
// This shouldn't be easily spawnable, so don't show in creative tabs // This shouldn't be easily spawnable, so don't show in creative tabs
// setTabToDisplayOn(CreativeTabs.tabMisc); // setTabToDisplayOn(CreativeTabs.tabMisc);
} }
@Override @Override
@SideOnly(Side.SERVER) @SideOnly(Side.SERVER)
public boolean getShareTag() public boolean getShareTag(){
{
return true; return true;
} }
@Override @Override
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({"rawtypes", "unchecked"})
public void addInformation(ItemStack itemStack, EntityPlayer player, List info, boolean bool) public void addInformation(ItemStack itemStack, EntityPlayer player, List info, boolean bool){
{
int[] coordinates = getCoordinates(itemStack); int[] coordinates = getCoordinates(itemStack);
if (coordinates != null) if(coordinates != null){
{
NBTTagCompound nbtTagCompound = itemStack.getTagCompound(); NBTTagCompound nbtTagCompound = itemStack.getTagCompound();
String title = nbtTagCompound.getString("title"); String title = nbtTagCompound.getString("title");
if (title != null && !title.isEmpty()) if(title != null && !title.isEmpty()){
{
info.add(title); 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); 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. * @return The ItemStack to replace it with.
*/ */
@Override @Override
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player){
{ if(player.isSneaking()){
if (player.isSneaking())
{
return new ItemStack(AdvancedPowerManagement.itemStorageLinkCardCreator); return new ItemStack(AdvancedPowerManagement.itemStorageLinkCardCreator);
} }else{
else
{
return stack; return stack;
} }
} }

View file

@ -16,24 +16,22 @@ import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World; import net.minecraft.world.World;
public class ItemStorageLinkCardCreator extends ItemCardBase public class ItemStorageLinkCardCreator extends ItemCardBase{
{ public ItemStorageLinkCardCreator(String name) {
public ItemStorageLinkCardCreator(String name)
{
super(name); super(name);
setMaxStackSize(1); setMaxStackSize(1);
setCreativeTab(CreativeTabs.tabMisc); setCreativeTab(CreativeTabs.tabMisc);
setTextureName(Info.TITLE_PACKED + ":LinkCardCreator"); setTextureName(Info.TITLE_PACKED + ":LinkCardCreator");
} }
@Override @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); TileEntity tile = world.getTileEntity(x, y, z);
if (entityplayer instanceof EntityPlayerMP && tile instanceof IEnergyStorage) if(entityplayer instanceof EntityPlayerMP && tile instanceof IEnergyStorage){
{ // if (Info.isDebugging) System.out.println("Clicked on X:" + x +
//if (Info.isDebugging) System.out.println("Clicked on X:" + x + " Y:" + y + " Z:" + z + " Dim:" + world.provider.dimensionId); // " Y:" + y + " Z:" + z + " Dim:" + world.provider.dimensionId);
ItemStack newcard = new ItemStack(AdvancedPowerManagement.itemStorageLinkCard); ItemStack newcard = new ItemStack(AdvancedPowerManagement.itemStorageLinkCard);
setCoordinates(newcard, x, y, z, world.provider.dimensionId); setCoordinates(newcard, x, y, z, world.provider.dimensionId);
entityplayer.inventory.mainInventory[entityplayer.inventory.currentItem] = newcard; 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.item.ItemStack;
import net.minecraft.util.IIcon; import net.minecraft.util.IIcon;
public class SlotChargeable extends SlotCustom public class SlotChargeable extends SlotCustom{
{
public int chargeTier; 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); super(inv, index, xpos, ypos);
chargeTier = tier; chargeTier = tier;
} }
@Override @Override
public boolean isItemValid(ItemStack stack) public boolean isItemValid(ItemStack stack){
{
// Decide if the item is a valid IC2 electrical item // Decide if the item is a valid IC2 electrical item
return Utils.isItemChargeable(stack, chargeTier); return Utils.isItemChargeable(stack, chargeTier);
} }
@Override @Override
public int getSlotStackLimit() public int getSlotStackLimit(){
{
return 1; return 1;
} }
@Override @Override
public IIcon getBackgroundIconIndex() public IIcon getBackgroundIconIndex(){
{
return Info.iconSlotChargeable; 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.IInventory;
import net.minecraft.inventory.Slot; import net.minecraft.inventory.Slot;
public class SlotCustom extends Slot public class SlotCustom extends Slot{
{ public SlotCustom(IInventory inv, int index, int xpos, int ypos) {
public SlotCustom(IInventory inv, int index, int xpos, int ypos)
{
super(inv, index, xpos, ypos); super(inv, index, xpos, ypos);
} }
@Override @Override
public void onSlotChanged() public void onSlotChanged(){
{ if(inventory instanceof TECommon){
if (inventory instanceof TECommon) ((TECommon) inventory).markDirty(this.getSlotIndex());
{ }else{
((TECommon)inventory).markDirty(this.getSlotIndex());
}
else
{
inventory.markDirty(); inventory.markDirty();
} }
} }

View file

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

View file

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

View file

@ -13,49 +13,39 @@ import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon; import net.minecraft.util.IIcon;
public class SlotLinkCard extends Slot public class SlotLinkCard extends Slot{
{ public SlotLinkCard(IInventory inv, int index, int xpos, int ypos) {
public SlotLinkCard(IInventory inv, int index, int xpos, int ypos)
{
super(inv, index, xpos, 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 @Override
public boolean isItemValid(ItemStack stack) public boolean isItemValid(ItemStack stack){
{
// Decide if the item is a link card // 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 true;
} }
return false; return false;
} }
@Override @Override
public int getSlotStackLimit() public int getSlotStackLimit(){
{
return 1; return 1;
} }
@Override @Override
public IIcon getBackgroundIconIndex() public IIcon getBackgroundIconIndex(){
{
return Info.iconSlotLinkCard; return Info.iconSlotLinkCard;
// return 246; // return 246;
} }
@Override @Override
public void onSlotChanged() public void onSlotChanged(){
{ if(this.inventory instanceof TECommon){
if (this.inventory instanceof TECommon) ((TECommon) inventory).markDirty(this.getSlotIndex());
{ }else{
((TECommon)inventory).markDirty(this.getSlotIndex());
}
else
{
inventory.markDirty(); inventory.markDirty();
} }
} }

View file

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

View file

@ -10,26 +10,22 @@ import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon; import net.minecraft.util.IIcon;
public class SlotOutput extends SlotCustom public class SlotOutput extends SlotCustom{
{ public SlotOutput(IInventory inv, int index, int xpos, int ypos) {
public SlotOutput(IInventory inv, int index, int xpos, int ypos)
{
super(inv, index, xpos, 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 @Override
public boolean isItemValid(ItemStack stack) public boolean isItemValid(ItemStack stack){
{ // No items may be placed here, parameter is ignored
// No items may be placed here, parameter is ignored return false;
return false;
} }
@Override @Override
public IIcon getBackgroundIconIndex() public IIcon getBackgroundIconIndex(){
{
return Info.iconSlotOutput; return Info.iconSlotOutput;
// return -1; // 250 // return -1; // 250
} }

View file

@ -14,33 +14,31 @@ import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon; import net.minecraft.util.IIcon;
public class SlotPlayerArmor extends SlotCustom public class SlotPlayerArmor extends SlotCustom{
{ // The armor type that can be placed on that slot, it uses the same values
// The armor type that can be placed on that slot, it uses the same values of armorType field on ItemArmor. // of armorType field on ItemArmor.
final int armorType; 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); super(inv, index, xpos, ypos);
this.armorType = armorType; this.armorType = armorType;
} }
@Override @Override
public int getSlotStackLimit() public int getSlotStackLimit(){
{
return 1; return 1;
} }
@Override @Override
public boolean isItemValid(ItemStack stack) public boolean isItemValid(ItemStack stack){
{ if(stack == null)
if (stack == null) return false; 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); 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 @Override
public IIcon getBackgroundIconIndex() public IIcon getBackgroundIconIndex(){
{
return Info.iconSlotPlayerArmor[armorType]; return Info.iconSlotPlayerArmor[armorType];
// return 240 + armorType; // return 240 + armorType;
} }

View file

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

View file

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

View file

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

View file

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

View file

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