there's all the code?

This commit is contained in:
xbony2 2015-02-11 16:42:18 -05:00
parent 6bd4c5fd86
commit 5e18fc37be
203 changed files with 7955 additions and 0 deletions

View file

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

View file

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

View file

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

View file

@ -0,0 +1,92 @@
/*******************************************************************************
* Copyright (c) 2012-2013 Yancarlo Ramsey and CJ Bowman
* Licensed as open source with restrictions. Please see attached LICENSE.txt.
******************************************************************************/
package com.kaijin.AdvPowerMan;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.io.DataInputStream;
import java.io.IOException;
import com.kaijin.AdvPowerMan.tileentities.TECommon;
import net.minecraft.network.PacketBuffer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.network.FMLNetworkEvent.ClientCustomPacketEvent;
public class ClientPacketHandler
{
/*
* Packet format:
* 0: byte Packet Type
* 1: int x location of TileEntity
* 2: int y location of TileEntity
* 3: int z location of TileEntity
*
* Currently used packet types
*
* Server-to-Client:
* 0 = Universal description packet
* Charging Bench:
* 4: int charge level for texture
* 5: boolean activity state for texture
*
* Battery Station:
* 4: boolean activity state for texture
*
* Storage Monitor:
* 4: int charge level for texture
* 5: boolean power state for texture
* 6: boolean valid state for texture
*/
// @Override
// public void onPacketData(INetworkManager network, Packet250CustomPayload packet, Player player)
@SubscribeEvent
public void onClientPacket(ClientCustomPacketEvent event)
{
ByteBuf stream = event.packet.payload();
//DataInputStream stream = new DataInputStream(new ByteArrayInputStream(packet.data));
// Determine packet type and coordinates of affected tile entity
int packetType = -1;
int x = 0;
int y = 0;
int z = 0;
packetType = stream.readInt();
x = stream.readInt();
y = stream.readInt();
z = stream.readInt();
if (packetType == 0)
{
World world = FMLClientHandler.instance().getClient().theWorld;
TileEntity tile = world.getTileEntity(x, y, z);
Exception e;
try
{
((TECommon)tile).receiveDescriptionData(packetType, stream);
return;
}
catch (ClassCastException ex)
{
e = ex;
}
catch (NullPointerException ex)
{
e = ex;
}
FMLLog.getLogger().info("[AdvancedPowerManagement] " + "Client received description packet for " + x + ", " + y + ", " + z +
" but couldn't deliver to tile entity. (Details: " + e.toString() + ")");
return;
}
}
}

View file

@ -0,0 +1,41 @@
/*******************************************************************************
* Copyright (c) 2012-2013 Yancarlo Ramsey and CJ Bowman
* Licensed as open source with restrictions. Please see attached LICENSE.txt.
******************************************************************************/
package com.kaijin.AdvPowerMan;
import io.netty.buffer.ByteBuf;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Arrays;
import com.kaijin.AdvPowerMan.tileentities.TECommon;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.common.FMLLog;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraftforge.client.MinecraftForgeClient;
public class ClientProxy extends CommonProxy
{
public static EntityPlayer getPlayer()
{
return Minecraft.getMinecraft().thePlayer;
}
/* @Override
public void load()
{
// MinecraftForgeClient.preloadTexture(Info.ITEM_PNG);
// MinecraftForgeClient.preloadTexture(Info.BLOCK_PNG);
// MinecraftForgeClient.preloadTexture(Info.GUI1_PNG);
// MinecraftForgeClient.preloadTexture(Info.GUI2_PNG);
// MinecraftForgeClient.preloadTexture(Info.GUI3_PNG);
// MinecraftForgeClient.preloadTexture(Info.GUI4_PNG);
}*/
}

View file

@ -0,0 +1,176 @@
/*******************************************************************************
* Copyright (c) 2012-2013 Yancarlo Ramsey and CJ Bowman
* Licensed as open source with restrictions. Please see attached LICENSE.txt.
******************************************************************************/
package com.kaijin.AdvPowerMan;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Arrays;
import com.kaijin.AdvPowerMan.containers.ContainerAdjustableTransformer;
import com.kaijin.AdvPowerMan.containers.ContainerAdvEmitter;
import com.kaijin.AdvPowerMan.containers.ContainerBatteryStation;
import com.kaijin.AdvPowerMan.containers.ContainerChargingBench;
import com.kaijin.AdvPowerMan.containers.ContainerStorageMonitor;
import com.kaijin.AdvPowerMan.gui.GuiAdjustableTransformer;
import com.kaijin.AdvPowerMan.gui.GuiAdvEmitter;
import com.kaijin.AdvPowerMan.gui.GuiBatteryStation;
import com.kaijin.AdvPowerMan.gui.GuiChargingBench;
import com.kaijin.AdvPowerMan.gui.GuiStorageMonitor;
import com.kaijin.AdvPowerMan.tileentities.TEAdjustableTransformer;
import com.kaijin.AdvPowerMan.tileentities.TEAdvEmitter;
import com.kaijin.AdvPowerMan.tileentities.TEBatteryStation;
import com.kaijin.AdvPowerMan.tileentities.TEChargingBench;
import com.kaijin.AdvPowerMan.tileentities.TECommon;
import com.kaijin.AdvPowerMan.tileentities.TEStorageMonitor;
import io.netty.buffer.ByteBuf;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
//import net.minecraft.network.packet.Packet250CustomPayload;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.network.IGuiHandler;
//import cpw.mods.fml.common.network.PacketDispatcher;
//import cpw.mods.fml.common.network.Player;
import cpw.mods.fml.relauncher.Side;
public class CommonProxy implements IGuiHandler
{
public void load() {}
public boolean isClient()
{
return FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT;
}
public boolean isServer()
{
return FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER;
}
@Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z)
{
if (!world.blockExists(x, y, z)) return null;
TileEntity tile = world.getTileEntity(x, y, z);
if (ID == 1 && tile instanceof TEChargingBench)
{
return new ContainerChargingBench(player.inventory, (TEChargingBench)tile);
}
else if (ID == 2 && tile instanceof TEBatteryStation)
{
return new ContainerBatteryStation(player.inventory, (TEBatteryStation)tile);
}
else if (ID == 3 && tile instanceof TEStorageMonitor)
{
return new ContainerStorageMonitor(player.inventory, (TEStorageMonitor)tile);
}
else if (ID == 4 && tile instanceof TEAdvEmitter)
{
return new ContainerAdvEmitter((TEAdvEmitter)tile);
}
else if (ID == 5 && tile instanceof TEAdjustableTransformer)
{
return new ContainerAdjustableTransformer((TEAdjustableTransformer)tile);
}
return null;
}
@Override
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z)
{
if (!world.blockExists(x, y, z)) return null;
TileEntity tile = world.getTileEntity(x, y, z);
if (ID == 1 && tile instanceof TEChargingBench)
{
return new GuiChargingBench(player.inventory, (TEChargingBench)tile);
}
else if (ID == 2 && tile instanceof TEBatteryStation)
{
return new GuiBatteryStation(player.inventory, (TEBatteryStation)tile);
}
else if (ID == 3 && tile instanceof TEStorageMonitor)
{
return new GuiStorageMonitor(player.inventory, (TEStorageMonitor)tile);
}
else if (ID == 4 && tile instanceof TEAdvEmitter)
{
return new GuiAdvEmitter((TEAdvEmitter)tile);
}
else if (ID == 5 && tile instanceof TEAdjustableTransformer)
{
return new GuiAdjustableTransformer((TEAdjustableTransformer)tile);
}
return null;
}
/*
* Packet format:
* 0: byte Packet Type
* 1: int x location of TileEntity
* 2: int y location of TileEntity
* 3: int z location of TileEntity
*
* Currently used packet types
*
* Client-to-Server:
* 0 = GUI button command
* 4: int Button ID clicked
*/
public void onPacketDataClient(ByteBuf source, EntityPlayer entityPlayer)
{
DataInputStream stream = new DataInputStream(new ByteArrayInputStream(Arrays.copyOfRange(source.array(), 1, source.array().length)));
// Determine packet type and coordinates of affected tile entity
int packetType = -1;
int x;
int y;
int z;
try
{
packetType = stream.readInt();
x = stream.readInt();
y = stream.readInt();
z = stream.readInt();
}
catch (IOException e)
{
FMLLog.getLogger().info("[AdvancedPowerManagement] " + "Failed to read packet from client. (Details: " + e.toString() + ")");
return;
}
if (packetType == 0)
{
Exception e;
try
{
World world = entityPlayer.worldObj;
TileEntity tile = world.getTileEntity(x, y, z);
int buttonID = stream.readInt();
((TECommon)tile).receiveGuiButton(buttonID);
return;
}
catch (ClassCastException ex) { e = ex; }
catch (NullPointerException ex) { e = ex; }
catch (IOException ex) { e = ex; }
FMLLog.getLogger().info("[AdvancedPowerManagement] " + "Server received GUI button packet for " + x + ", " + y + ", " + z +
" but couldn't deliver to tile entity. (Details: " + e.toString() + ")");
return;
}
}
}

View file

@ -0,0 +1,19 @@
/*******************************************************************************
* Copyright (c) 2012-2013 Yancarlo Ramsey and CJ Bowman
* Licensed as open source with restrictions. Please see attached LICENSE.txt.
******************************************************************************/
package com.kaijin.AdvPowerMan;
public class Coords
{
public int x;
public int y;
public int z;
public Coords(int x, int y, int z)
{
this.x = x;
this.y = y;
this.z = z;
}
}

View file

@ -0,0 +1,144 @@
/*******************************************************************************
* Copyright (c) 2012-2013 Yancarlo Ramsey and CJ Bowman
* Licensed as open source with restrictions. Please see attached LICENSE.txt.
******************************************************************************/
package com.kaijin.AdvPowerMan;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import cpw.mods.fml.common.registry.LanguageRegistry;
public class Info
{
// Mod Info
public static final String TITLE_PACKED = "AdvancedPowerManagement";
public static final String TITLE = "Advanced Power Management";
public static final String TITLE_LOG = "[" + TITLE_PACKED + "] ";
// Textures
public static final String TEX_BASE = "textures/";
public static final String GUI_TEX_CHARGING_BENCH = TEX_BASE + "GUIChargingBench.png";
public static final String GUI_TEX_BATTERY_STATION = TEX_BASE + "GUIBatteryStation.png";
public static final String GUI_TEX_STORAGE_MONITOR = TEX_BASE + "GUIStorageMonitor.png";
public static final String GUI_TEX_EMITTER = TEX_BASE + "GUIAdvEmitter.png";
public static final String GUI_TEX_ADJ_TRANSFORMER = TEX_BASE + "GUIAdjustableTransformer.png";
public static final String[] KEY_BLOCK_NAMES = new String[] {"blockChargingBench1", "blockChargingBench2", "blockChargingBench3",
"blockEmitterBlock1", "blockEmitterBlock2", "blockEmitterBlock3", "blockAdjustableTransformer", "blockEmitterAdjustable",
"blockBatteryStation1", "blockBatteryStation2", "blockBatteryStation3", "blockStorageMonitor"};
public static final String KEY_NAME_SUFFIX = ".name";
// Blocks
public static final String CHARGER_NAME = "Charging Bench";
public static final String DISCHARGER_NAME = "Battery Station";
public static final String MONITOR_NAME = "Storage Monitor";
public static final String EMITTER_NAME = "Emitter";
public static final String ADV_EMITTER_NAME = "Adjustable Emitter";
public static final String ADJ_TRANSFORMER_NAME = "Adjustable Transformer";
// Items
public static final String TOOLKIT_NAME = CHARGER_NAME + " Toolkit";
public static final String COMPONENTS_NAME = CHARGER_NAME + " Components";
public static final String LINK_CARD_NAME = "Energy Link Card";
public static final String LINK_CREATOR_NAME = "Energy Link Card (Blank)";
// GUI IDs
public static final int GUI_ID_CHARGING_BENCH = 1;
public static final int GUI_ID_BATTERY_STATION = 2;
public static final int GUI_ID_STORAGE_MONITOR = 3;
public static final int GUI_ID_ADJUSTABLE_EMITTER = 4;
public static final int GUI_ID_ADJUSTABLE_TRANSFORMER = 5;
// Other constants for use in multiple classes
public static final int LAST_META_VALUE = 11;
public static final int CB_META = 0; // through 2
// 3-5 are unused
public static final int AT_META = 6;
public static final int AE_META = 7;
public static final int BS_META = 8; // through 10
public static final int SM_META = 11;
public static final int CB_SLOT_INPUT = 0;
public static final int CB_SLOT_OUTPUT = 1;
public static final int CB_SLOT_POWER_SOURCE = 2;
public static final int CB_SLOT_CHARGING = 3;
public static final int CB_SLOT_UPGRADE = 15;
public static final int BS_SLOT_INPUT = 0;
public static final int BS_SLOT_OUTPUT = 1;
public static final int BS_SLOT_POWER_START = 2;
public static final int SM_SLOT_UNIVERSAL = 0;
public static final int CB_INVENTORY_SIZE = 19;
public static final int BS_INVENTORY_SIZE = 14;
public static final int SM_INVENTORY_SIZE = 1;
public static final int AE_MIN_PACKET = 4;
public static final int AE_MAX_PACKET = 8192;
public static final int AE_MIN_OUTPUT = 1;
public static final int AE_MAX_OUTPUT = 32768;
public static final int AE_PACKETS_TICK = 64;
// GUI strings
public static final String KEY_TITLE = "AdvPwrMan.title";
public static final String KEY_EU = "AdvPwrMan.misc.EU";
public static final String KEY_IN = "AdvPwrMan.misc.in";
public static final String KEY_OUT = "AdvPwrMan.misc.out";
public static final String KEY_CHARGER_MAX = "AdvPwrMan.charger.maxEU";
public static final String KEY_CHARGER_REQ = "AdvPwrMan.charger.requiredEU";
public static final String KEY_CHARGER_PWR = "AdvPwrMan.charger.redstonePower";
public static final String KEY_CHARGER_ETC = "AdvPwrMan.charger.estimatedTime";
public static final String KEY_CHARGER_AVG = "AdvPwrMan.charger.averageInput";
public static final String KEY_EMITTER_PACKET = "AdvPwrMan.emitter.packet";
public static final String KEY_EMITTER_OUTPUT = "AdvPwrMan.emitter.output";
public static final String KEY_TRANSFORMER_OUTPUT = "AdvPwrMan.transformer.limit";
public static final String KEY_MONITOR_INVALID = "AdvPwrMan.monitor.invalid";
public static final String KEY_MONITOR_UPPER = "AdvPwrMan.monitor.upper";
public static final String KEY_MONITOR_LOWER = "AdvPwrMan.monitor.lower";
public static final String KEY_DISCHARGER_MODE_LINE1 = "AdvPwrMan.station.modeline1";
public static final String KEY_DISCHARGER_MODE_LINE2 = "AdvPwrMan.station.modeline2";
public static final String KEY_STATS_AVERAGE_EU = "AdvPwrMan.station.average";
public static final String KEY_STATS_TIME_REMAINING = "AdvPwrMan.station.remaining";
public static final String KEY_STATS_DISPLAY_DAYS = "AdvPwrMan.station.led.days";
public static final String KEY_STATS_DISPLAY_UNKNOWN = "AdvPwrMan.station.led.unknown";
public static final String KEY_STATS_AVERAGE_INPUT = "AdvPwrMan.station.packetIn";
public static final String KEY_EU_BUFFERED = "AdvPwrMan.station.EUbuffered";
public static final String AE_PACKET_RANGE = "[" + AE_MIN_PACKET + " - " + AE_MAX_PACKET + "]";
public static final String AE_OUTPUT_RANGE = "[" + AE_MIN_OUTPUT + " - " + AE_MAX_OUTPUT + "]";
public static final String[] KEY_DIRECTION_NAMES = {"AdvPwrMan.dir.down", "AdvPwrMan.dir.up", "AdvPwrMan.dir.north", "AdvPwrMan.dir.south", "AdvPwrMan.dir.west", "AdvPwrMan.dir.east"};
// Some global variables
public static boolean isDebugging;
public static int ic2WrenchID;
public static int ic2ElectricWrenchID;
// For returning charging benches and deconstructing them
public static ItemStack componentCopperCable;
public static ItemStack componentGoldCable;
public static ItemStack componentIronCable;
public static ItemStack componentBatBox;
public static ItemStack componentMFE;
public static ItemStack componentMFSU;
public static ItemStack componentCircuit;
// For internal reference to verify items can be placed in inventory.
public static ItemStack ic2overclockerUpg;
public static ItemStack ic2transformerUpg;
public static ItemStack ic2storageUpg;
// Icons for GUI slots
public static IIcon iconSlotChargeable;
public static IIcon iconSlotDrainable;
public static IIcon iconSlotInput;
public static IIcon iconSlotOutput;
public static IIcon iconSlotMachineUpgrade;
public static IIcon iconSlotLinkCard;
public static IIcon[] iconSlotPowerSource;
public static IIcon[] iconSlotPlayerArmor;
}

View file

@ -0,0 +1,95 @@
/*******************************************************************************
* Copyright (c) 2012-2013 Yancarlo Ramsey and CJ Bowman
* Licensed as open source with restrictions. Please see attached LICENSE.txt.
******************************************************************************/
package com.kaijin.AdvPowerMan;
public class MovingAverage
{
protected int packets[] = null;
protected int delays[] = null;
protected int position;
//protected int packetTotal;
//protected int delayTotal;
protected int delay;
protected int window;
protected float average;
protected float delta;
public MovingAverage(int size)
{
packets = new int[size];
delays = new int[size];
position = 0;
//packetTotal = 0;
//delayTotal = size;
delay = 1;
window = size;
average = 0F;
delta = 0F;
for (int i = 0; i < size; i++)
{
packets[i] = 0;
delays[i] = 600;
}
}
public void tick(int value)
{
if (value > 0 || delay >= 600) // 600 ticks (30 sec) is long enough for 1 EU/t to have triggered a 512 EU packet by now
{
position++;
if (position >= packets.length) position = 0;
//packetTotal -= packet[position];
packets[position] = value;
//packetTotal += value;
//delayTotal -= time[position];
delays[position] = delay;
//delayTotal += delay;
delay = 1;
window = sumDelays();
final float newAvg = ((float)sumPackets()) / ((float)window);
delta = newAvg - average;
average = newAvg;
}
else
{
delay++;
// Estimate decline of average based on increased average delay
if (delays.length * delay > window)
{
window++;
average = ((float)sumPackets()) / ((float)window);
}
}
}
protected int sumDelays()
{
if (delays == null) return 1;
int delayTotal = 0;
for (int d : delays) delayTotal += d;
return delayTotal;
}
protected int sumPackets()
{
if (packets == null) return 0;
int packetTotal = 0;
for (int p : packets) packetTotal += p;
return packetTotal;
}
public float getAverage()
{
return average;
}
public int getWindow()
{
return window;
}
}

View file

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

View file

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

View file

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

View file

@ -0,0 +1,93 @@
/*******************************************************************************
* Copyright (c) 2012-2013 Yancarlo Ramsey and CJ Bowman
* Licensed as open source with restrictions. Please see attached LICENSE.txt.
******************************************************************************/
package com.kaijin.AdvPowerMan.containers;
import com.kaijin.AdvPowerMan.tileentities.TEAdvEmitter;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.ICrafting;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ContainerAdvEmitter extends Container
{
private final int playerInventoryStartSlot = 1;
public TEAdvEmitter te;
public int outputRate;
public int packetSize;
public ContainerAdvEmitter(TEAdvEmitter tile)
{
//if (Info.isDebugging) System.out.println("ContainerAdvEmitter");
te = tile;
outputRate = -1;
packetSize = -1;
}
@Override
public void detectAndSendChanges()
{
// if (ChargingBench.isDebugging) System.out.println("ContainerChargingBench.updateCraftingResults");
for (int crafterIndex = 0; crafterIndex < crafters.size(); ++crafterIndex)
{
ICrafting crafter = (ICrafting)crafters.get(crafterIndex);
if (this.outputRate != te.outputRate)
{
crafter.sendProgressBarUpdate(this, 0, te.outputRate & 65535);
crafter.sendProgressBarUpdate(this, 1, te.outputRate >>> 16);
}
if (this.packetSize != te.packetSize)
{
crafter.sendProgressBarUpdate(this, 2, te.packetSize & 65535);
crafter.sendProgressBarUpdate(this, 3, te.packetSize >>> 16);
}
}
// Done sending updates, record the new current values
this.outputRate = te.outputRate;
this.packetSize = te.packetSize;
}
@SideOnly(Side.CLIENT)
@Override
public void updateProgressBar(int param, int value)
{
switch (param)
{
case 0:
//if (ChargingBench.isDebugging) System.out.println("ContainerChargingBench.updateProgressBar case 0 tileentity.currentEnergy = " + (this.tileentity.currentEnergy & -65536) + " | " + value);
te.outputRate = te.outputRate & -65536 | value;
break;
case 1:
//if (ChargingBench.isDebugging) System.out.println("ContainerChargingBench.updateProgressBar case 1 tileentity.currentEnergy = " + (this.tileentity.currentEnergy & 65535) + " | " + (value << 16));
te.outputRate = te.outputRate & 65535 | (value << 16);
break;
case 2:
//if (ChargingBench.isDebugging) System.out.println("ContainerChargingBench.updateProgressBar case 3 tileentity.adjustedStorage = " + (this.tileentity.adjustedStorage & -65536) + " | " + value);
te.packetSize = te.packetSize & -65536 | value;
break;
case 3:
//if (ChargingBench.isDebugging) System.out.println("ContainerChargingBench.updateProgressBar case 4 tileentity.adjustedStorage = " + (this.tileentity.adjustedStorage & 65535) + " | " + (value << 16));
te.packetSize = te.packetSize & 65535 | (value << 16);
break;
default:
System.out.println("ContainerAdvEmitter.updateProgressBar - Warning: default case!");
}
}
@Override
public boolean canInteractWith(EntityPlayer var1)
{
return te.isUseableByPlayer(var1);
}
}

View file

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

View file

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

View file

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

View file

@ -0,0 +1,112 @@
/*******************************************************************************
* Copyright (c) 2012-2013 Yancarlo Ramsey and CJ Bowman
* Licensed as open source with restrictions. Please see attached LICENSE.txt.
******************************************************************************/
package com.kaijin.AdvPowerMan.gui;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import com.kaijin.AdvPowerMan.Info;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class CButton extends GuiButton
{
/** Path to custom texture for button */
protected String texture;
protected int uLoc;
protected int vLoc;
protected int uHoverLoc;
protected int vHoverLoc;
protected int color;
protected int hoverColor;
protected boolean isHovering;
/** CButton will assume the texture size is equal to the width and height of the button
*
* @param id - ID of button
* @param xLoc - x location of button on screen
* @param yLoc - y location of button on screen
* @param width - width of button
* @param height - height of button
* @param uLoc - x location of start of texture in texture file
* @param vLoc - y location of start of texture in texture file
* @param uHoverLoc - x location of start of texture for mouse over in texture file
* @param vHoverLoc - x location of start of texture for mouse over in texture file
* @param text - text to display on button
* @param color - color for the text
* @param hoverColor - color for the text while hovering
* @param texture - path to texture file
*/
public CButton(int id, int xLoc, int yLoc, int width, int height, int uLoc, int vLoc, int uHoverLoc, int vHoverLoc, String text, int color, int hoverColor, String texture)
{
super(id, xLoc, yLoc, width, height, text);
this.enabled = true;
this.visible = true;
this.id = id;
this.xPosition = xLoc;
this.yPosition = yLoc;
this.width = width;
this.height = height;
this.uLoc = uLoc;
this.vLoc = vLoc;
this.uHoverLoc = uHoverLoc;
this.vHoverLoc = vHoverLoc;
this.displayString = text;
this.color = color;
this.hoverColor = hoverColor;
this.texture = texture;
}
/**
* Draws this button to the screen.
*/
@Override
public void drawButton(Minecraft mc, int xLoc, int yLoc)
{
if (visible)
{
FontRenderer fr = mc.fontRenderer;
if (texture != null)
{
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
mc.renderEngine.bindTexture(new ResourceLocation(Info.TITLE_PACKED.toLowerCase(), texture));
}
isHovering = xLoc >= xPosition && yLoc >= yPosition && xLoc < xPosition + width && yLoc < yPosition + height;
int hoverState = this.getHoverState(isHovering);
if (hoverState == 2)
{
this.drawTexturedModalRect(xPosition, yPosition, uHoverLoc, vHoverLoc, width, height);
}
else
{
this.drawTexturedModalRect(xPosition, yPosition, uLoc, vLoc, width, height);
}
int defaultColor = color;
int renderColor = defaultColor;
if (!enabled)
{
renderColor = -6250336;
}
else if (isHovering)
{
renderColor = hoverColor;
}
fr.drawString(displayString, xPosition + (width - fr.getStringWidth(displayString)) / 2, yPosition + (height - 7) / 2, renderColor);
}
}
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -0,0 +1,170 @@
/*******************************************************************************
* Copyright (c) 2012-2013 Yancarlo Ramsey and CJ Bowman
* Licensed as open source with restrictions. Please see attached LICENSE.txt.
******************************************************************************/
package com.kaijin.AdvPowerMan.items;
import java.util.List;
import com.kaijin.AdvPowerMan.AdvancedPowerManagement;
import com.kaijin.AdvPowerMan.Info;
import com.kaijin.AdvPowerMan.tileentities.TEChargingBench;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.IIcon;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ItemBenchTools extends Item
{
public static final String[] benchToolsNames = new String[] {"toolkit", "LV-kit", "MV-kit", "HV-kit"};
protected IIcon[] itemIcons;
public ItemBenchTools(String name)
{
super();
this.setHasSubtypes(true);
this.setMaxDamage(0);
this.setMaxStackSize(1);
this.setCreativeTab(CreativeTabs.tabMisc);
GameRegistry.registerItem(this, name);
}
/**
* Gets an icon based on an item's damage value
*/
@Override
@SideOnly(Side.CLIENT)
public IIcon getIconFromDamage(int par1)
{
return itemIcons[MathHelper.clamp_int(par1, 0, 3)];
}
@Override
public void registerIcons(IIconRegister iconRegister)
{
itemIcons = new IIcon[benchToolsNames.length];
for (int i = 0; i < itemIcons.length; i++)
{
itemIcons[i] = iconRegister.registerIcon(Info.TITLE_PACKED + ":" + benchToolsNames[i]);
}
// Until/unless a better way is found, register GUI slot backgrounds here.
Info.iconSlotChargeable = iconRegister.registerIcon(Info.TITLE_PACKED + ":SlotChargeable");
Info.iconSlotDrainable = iconRegister.registerIcon(Info.TITLE_PACKED + ":SlotDrainable");
Info.iconSlotInput = iconRegister.registerIcon(Info.TITLE_PACKED + ":SlotInput");
Info.iconSlotOutput = iconRegister.registerIcon(Info.TITLE_PACKED + ":SlotOutput");
Info.iconSlotMachineUpgrade = iconRegister.registerIcon(Info.TITLE_PACKED + ":SlotMachineUpgrade");
Info.iconSlotLinkCard = iconRegister.registerIcon(Info.TITLE_PACKED + ":SlotLinkCard");
Info.iconSlotPowerSource = new IIcon[3];
Info.iconSlotPlayerArmor = new IIcon[4];
for (int i = 0; i < 3; i++)
Info.iconSlotPowerSource[i] = iconRegister.registerIcon(Info.TITLE_PACKED + ":SlotPowerSource" + Integer.toString(i));
for (int i = 0; i < 4; i++)
Info.iconSlotPlayerArmor[i] = iconRegister.registerIcon(Info.TITLE_PACKED + ":SlotPlayerArmor" + Integer.toString(i));
}
@Override
public boolean isRepairable()
{
return false;
}
@Override
public String getUnlocalizedName(ItemStack par1ItemStack)
{
int meta = MathHelper.clamp_int(par1ItemStack.getItemDamage(), 0, 3);
return "item.benchTools." + benchToolsNames[meta];
}
protected void generateItemStack(ItemStack stack, EntityPlayer player)
{
EntityItem entityitem = player.dropPlayerItemWithRandomChoice(stack, false);
entityitem.delayBeforeCanPickup = 0;
}
/**
* This is called when the item is used, before the block is activated.
* @param stack The Item Stack
* @param player The Player that used the item
* @param world The Current World
* @param x Target X Position
* @param y Target Y Position
* @param z Target Z Position
* @param side The side of the target hit
* @return Return true to prevent any further processing.
*/
@Override
public boolean onItemUseFirst(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ)
{
if (AdvancedPowerManagement.proxy.isClient()) return false;
// Test if the target is a charging bench and the item is a component kit. If so, do the upgrade and return true.
if (world.getBlock(x, y, z) != AdvancedPowerManagement.blockAdvPwrMan || stack.getItemDamage() < 1 || stack.getItemDamage() > 3 || player == null)
{
return false;
}
TileEntity tile = world.getTileEntity(x, y, z);
if (!(tile instanceof TEChargingBench))
{
return false;
}
int recoveredTier = ((TEChargingBench)tile).swapBenchComponents(stack.getItemDamage());
generateItemStack(new ItemStack(AdvancedPowerManagement.itemBenchTools, 1, recoveredTier), player);
stack.stackSize--;
return true;
}
/**
* Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer
*/
@Override
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player)
{
if (player.isSneaking() && stack.getItemDamage() > 0 && stack.getItemDamage() < 4)
{
switch (stack.getItemDamage())
{
case 1:
generateItemStack(Info.componentCopperCable.copy(), player);
generateItemStack(Info.componentBatBox.copy(), player);
break;
case 2:
generateItemStack(Info.componentGoldCable.copy(), player);
generateItemStack(Info.componentMFE.copy(), player);
break;
case 3:
generateItemStack(Info.componentIronCable.copy(), player);
generateItemStack(Info.componentMFSU.copy(), player);
break;
}
generateItemStack(Info.componentCircuit.copy(), player);
stack.stackSize--;
}
return stack;
}
/**
* returns a list of items with the same ID, but different meta (eg: dye returns 16 items)
*/
@Override
@SideOnly(Side.CLIENT)
public void getSubItems(Item par1, CreativeTabs par2CreativeTabs, List par3List)
{
for (int meta = 0; meta < 4; ++meta)
{
par3List.add(new ItemStack(par1, 1, meta));
}
}
}

View file

@ -0,0 +1,38 @@
/*******************************************************************************
* Copyright (c) 2012-2013 Yancarlo Ramsey and CJ Bowman
* Licensed as open source with restrictions. Please see attached LICENSE.txt.
******************************************************************************/
package com.kaijin.AdvPowerMan.items;
import com.kaijin.AdvPowerMan.Info;
import net.minecraft.block.Block;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
public class ItemBlockAdvPwrMan extends ItemBlock
{
public ItemBlockAdvPwrMan(Block block)
{
super(block);
this.setMaxDamage(0);
this.setHasSubtypes(true);
}
public int getMetadata(int meta)
{
//if (meta >= 3 && meta <= 6) return 7;
return meta;
}
@Override
public String getUnlocalizedName(ItemStack var1)
{
int var2 = var1.getItemDamage();
if (var2 >= 0 && var2 <= Info.LAST_META_VALUE) return Info.KEY_BLOCK_NAMES[var2];
return null;
}
}

View file

@ -0,0 +1,81 @@
/*******************************************************************************
* Copyright (c) 2012-2013 Yancarlo Ramsey and CJ Bowman
* Licensed as open source with restrictions. Please see attached LICENSE.txt.
******************************************************************************/
package com.kaijin.AdvPowerMan.items;
import com.kaijin.AdvPowerMan.Utils;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
public class ItemCardBase extends Item
{
protected ItemCardBase(String name)
{
super();
setUnlocalizedName(name);
GameRegistry.registerItem(this, name);
}
@Override
public boolean isRepairable()
{
return false;
}
public static int[] getCoordinates(ItemStack itemStack)
{
if (!(itemStack.getItem() instanceof ItemStorageLinkCard))
return null;
NBTTagCompound nbtTagCompound = itemStack.getTagCompound();
if (nbtTagCompound == null)
{
return null;
}
int[] coordinates = new int[]{
nbtTagCompound.getInteger("x"),
nbtTagCompound.getInteger("y"),
nbtTagCompound.getInteger("z"),
nbtTagCompound.getInteger("dim")
};
return coordinates;
}
public static void setCoordinates(ItemStack itemStack, int[] coords)
{
final String tags[] = {"x", "y", "z", "dim"};
NBTTagCompound nbtTagCompound = Utils.getOrCreateStackTag(itemStack);
for (int i = 0; i < coords.length && i < 4; i++)
{
nbtTagCompound.setInteger(tags[i], coords[i]);
}
}
public static void setCoordinates(ItemStack itemStack, int x, int y, int z, int dim)
{
NBTTagCompound nbtTagCompound = Utils.getOrCreateStackTag(itemStack);
nbtTagCompound.setInteger("x", x);
nbtTagCompound.setInteger("y", y);
nbtTagCompound.setInteger("z", z);
nbtTagCompound.setInteger("dim", dim);
}
public String getTitle(ItemStack stack)
{
if (!(stack.getItem() instanceof ItemStorageLinkCard))
return "";
NBTTagCompound nbtTagCompound = stack.getTagCompound();
if (nbtTagCompound == null)
return "";
return nbtTagCompound.getString("title");
}
public void setTitle(ItemStack stack, String title)
{
Utils.getOrCreateStackTag(stack).setString("title", title);
}
}

View file

@ -0,0 +1,75 @@
/*******************************************************************************
* Copyright (c) 2012-2013 Yancarlo Ramsey and CJ Bowman
* Licensed as open source with restrictions. Please see attached LICENSE.txt.
******************************************************************************/
package com.kaijin.AdvPowerMan.items;
import java.util.List;
import com.kaijin.AdvPowerMan.AdvancedPowerManagement;
import com.kaijin.AdvPowerMan.Info;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ItemStorageLinkCard extends ItemCardBase
{
private static final String HINT_TEMPLATE = "X: %d, Y: %d, Z: %d, Dim: %d";
public ItemStorageLinkCard(String name)
{
super(name);
setMaxStackSize(1);
setTextureName(Info.TITLE_PACKED + ":LinkCard");
// This shouldn't be easily spawnable, so don't show in creative tabs
// setTabToDisplayOn(CreativeTabs.tabMisc);
}
@Override
@SideOnly(Side.SERVER)
public boolean getShareTag()
{
return true;
}
@Override
@SideOnly(Side.CLIENT)
@SuppressWarnings({ "rawtypes", "unchecked" })
public void addInformation(ItemStack itemStack, EntityPlayer player, List info, boolean bool)
{
int[] coordinates = getCoordinates(itemStack);
if (coordinates != null)
{
NBTTagCompound nbtTagCompound = itemStack.getTagCompound();
String title = nbtTagCompound.getString("title");
if (title != null && !title.isEmpty())
{
info.add(title);
}
String hint = String.format(HINT_TEMPLATE, coordinates[0], coordinates[1], coordinates[2], coordinates [3]);
info.add(hint);
}
}
/**
* Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer
* @return The ItemStack to replace it with.
*/
@Override
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player)
{
if (player.isSneaking())
{
return new ItemStack(AdvancedPowerManagement.itemStorageLinkCardCreator);
}
else
{
return stack;
}
}
}

View file

@ -0,0 +1,44 @@
/*******************************************************************************
* Copyright (c) 2012-2013 Yancarlo Ramsey and CJ Bowman
* Licensed as open source with restrictions. Please see attached LICENSE.txt.
******************************************************************************/
package com.kaijin.AdvPowerMan.items;
import com.kaijin.AdvPowerMan.AdvancedPowerManagement;
import com.kaijin.AdvPowerMan.Info;
import ic2.api.tile.IEnergyStorage;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
public class ItemStorageLinkCardCreator extends ItemCardBase
{
public ItemStorageLinkCardCreator(String name)
{
super(name);
setMaxStackSize(1);
setCreativeTab(CreativeTabs.tabMisc);
setTextureName(Info.TITLE_PACKED + ":LinkCardCreator");
}
@Override
public boolean onItemUseFirst(ItemStack itemstack, EntityPlayer entityplayer, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ)
{
TileEntity tile = world.getTileEntity(x, y, z);
if (entityplayer instanceof EntityPlayerMP && tile instanceof IEnergyStorage)
{
//if (Info.isDebugging) System.out.println("Clicked on X:" + x + " Y:" + y + " Z:" + z + " Dim:" + world.provider.dimensionId);
ItemStack newcard = new ItemStack(AdvancedPowerManagement.itemStorageLinkCard);
setCoordinates(newcard, x, y, z, world.provider.dimensionId);
entityplayer.inventory.mainInventory[entityplayer.inventory.currentItem] = newcard;
return true;
}
return false;
}
}

View file

@ -0,0 +1,44 @@
/*******************************************************************************
* Copyright (c) 2012-2013 Yancarlo Ramsey and CJ Bowman
* Licensed as open source with restrictions. Please see attached LICENSE.txt.
******************************************************************************/
package com.kaijin.AdvPowerMan.slots;
import com.kaijin.AdvPowerMan.Info;
import com.kaijin.AdvPowerMan.Utils;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
public class SlotChargeable extends SlotCustom
{
public int chargeTier;
public SlotChargeable(IInventory inv, int index, int xpos, int ypos, int tier)
{
super(inv, index, xpos, ypos);
chargeTier = tier;
}
@Override
public boolean isItemValid(ItemStack stack)
{
// Decide if the item is a valid IC2 electrical item
return Utils.isItemChargeable(stack, chargeTier);
}
@Override
public int getSlotStackLimit()
{
return 1;
}
@Override
public IIcon getBackgroundIconIndex()
{
return Info.iconSlotChargeable;
//return 247;
}
}

View file

@ -0,0 +1,31 @@
/*******************************************************************************
* Copyright (c) 2012-2013 Yancarlo Ramsey and CJ Bowman
* Licensed as open source with restrictions. Please see attached LICENSE.txt.
******************************************************************************/
package com.kaijin.AdvPowerMan.slots;
import com.kaijin.AdvPowerMan.tileentities.TECommon;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
public class SlotCustom extends Slot
{
public SlotCustom(IInventory inv, int index, int xpos, int ypos)
{
super(inv, index, xpos, ypos);
}
@Override
public void onSlotChanged()
{
if (inventory instanceof TECommon)
{
((TECommon)inventory).markDirty(this.getSlotIndex());
}
else
{
inventory.markDirty();
}
}
}

View file

@ -0,0 +1,46 @@
/*******************************************************************************
* Copyright (c) 2012-2013 Yancarlo Ramsey and CJ Bowman
* Licensed as open source with restrictions. Please see attached LICENSE.txt.
******************************************************************************/
package com.kaijin.AdvPowerMan.slots;
import com.kaijin.AdvPowerMan.Info;
import com.kaijin.AdvPowerMan.Utils;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
public class SlotDrainable extends SlotCustom
{
protected int powerTier;
public SlotDrainable(IInventory inv, int index, int xpos, int ypos, int tier)
{
super(inv, index, xpos, ypos);
powerTier = tier;
}
/**
* Check if the stack is a valid item for this slot.
*/
@Override
public boolean isItemValid(ItemStack stack)
{
// Decide if the item is a valid IC2 power source
return Utils.isItemDrainable(stack, powerTier);
}
@Override
public int getSlotStackLimit()
{
return 1;
}
@Override
public IIcon getBackgroundIconIndex()
{
return Info.iconSlotDrainable;
// return -1; // 232;
}
}

View file

@ -0,0 +1,37 @@
/*******************************************************************************
* Copyright (c) 2012-2013 Yancarlo Ramsey and CJ Bowman
* Licensed as open source with restrictions. Please see attached LICENSE.txt.
******************************************************************************/
package com.kaijin.AdvPowerMan.slots;
import com.kaijin.AdvPowerMan.Info;
import com.kaijin.AdvPowerMan.Utils;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
public class SlotInput extends SlotCustom
{
public int chargeTier;
public SlotInput(IInventory inv, int index, int xpos, int ypos, int tier)
{
super(inv, index, xpos, ypos);
chargeTier = tier;
}
@Override
public boolean isItemValid(ItemStack stack)
{
// Decide if the item is a valid IC2 electrical item
return Utils.isItemChargeable(stack, chargeTier);
}
@Override
public IIcon getBackgroundIconIndex()
{
return Info.iconSlotInput;
// return 249;
}
}

View file

@ -0,0 +1,62 @@
/*******************************************************************************
* Copyright (c) 2012-2013 Yancarlo Ramsey and CJ Bowman
* Licensed as open source with restrictions. Please see attached LICENSE.txt.
******************************************************************************/
package com.kaijin.AdvPowerMan.slots;
import com.kaijin.AdvPowerMan.Info;
import com.kaijin.AdvPowerMan.items.ItemStorageLinkCard;
import com.kaijin.AdvPowerMan.tileentities.TECommon;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
public class SlotLinkCard extends Slot
{
public SlotLinkCard(IInventory inv, int index, int xpos, int ypos)
{
super(inv, index, xpos, ypos);
}
/**
* Check if the stack is a valid item for this slot.
*/
@Override
public boolean isItemValid(ItemStack stack)
{
// Decide if the item is a link card
if (stack != null && stack.getItem() instanceof ItemStorageLinkCard)
{
return true;
}
return false;
}
@Override
public int getSlotStackLimit()
{
return 1;
}
@Override
public IIcon getBackgroundIconIndex()
{
return Info.iconSlotLinkCard;
// return 246;
}
@Override
public void onSlotChanged()
{
if (this.inventory instanceof TECommon)
{
((TECommon)inventory).markDirty(this.getSlotIndex());
}
else
{
inventory.markDirty();
}
}
}

View file

@ -0,0 +1,41 @@
/*******************************************************************************
* Copyright (c) 2012-2013 Yancarlo Ramsey and CJ Bowman
* Licensed as open source with restrictions. Please see attached LICENSE.txt.
******************************************************************************/
package com.kaijin.AdvPowerMan.slots;
import com.kaijin.AdvPowerMan.Info;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
public class SlotMachineUpgrade extends SlotCustom
{
public SlotMachineUpgrade(IInventory inv, int index, int xpos, int ypos)
{
super(inv, index, xpos, ypos);
}
/**
* Check if the stack is a valid item for this slot.
*/
@Override
public boolean isItemValid(ItemStack stack)
{
// Decide if the item is a valid IC2 machine upgrade
if (stack == null) return false;
if (stack.isItemEqual(Info.ic2overclockerUpg) || stack.isItemEqual(Info.ic2transformerUpg) || stack.isItemEqual(Info.ic2storageUpg))
{
return true;
}
return false;
}
@Override
public IIcon getBackgroundIconIndex()
{
return Info.iconSlotMachineUpgrade;
// return 245;
}
}

View file

@ -0,0 +1,36 @@
/*******************************************************************************
* Copyright (c) 2012-2013 Yancarlo Ramsey and CJ Bowman
* Licensed as open source with restrictions. Please see attached LICENSE.txt.
******************************************************************************/
package com.kaijin.AdvPowerMan.slots;
import com.kaijin.AdvPowerMan.Info;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
public class SlotOutput extends SlotCustom
{
public SlotOutput(IInventory inv, int index, int xpos, int ypos)
{
super(inv, index, xpos, ypos);
}
/**
* Check if the stack is a valid item for this slot.
*/
@Override
public boolean isItemValid(ItemStack stack)
{
// No items may be placed here, parameter is ignored
return false;
}
@Override
public IIcon getBackgroundIconIndex()
{
return Info.iconSlotOutput;
// return -1; // 250
}
}

View file

@ -0,0 +1,47 @@
/*******************************************************************************
* Copyright (c) 2012-2013 Yancarlo Ramsey and CJ Bowman
* Licensed as open source with restrictions. Please see attached LICENSE.txt.
******************************************************************************/
package com.kaijin.AdvPowerMan.slots;
import com.kaijin.AdvPowerMan.Info;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
public class SlotPlayerArmor extends SlotCustom
{
// The armor type that can be placed on that slot, it uses the same values of armorType field on ItemArmor.
final int armorType;
public SlotPlayerArmor(IInventory inv, int index, int xpos, int ypos, int armorType)
{
super(inv, index, xpos, ypos);
this.armorType = armorType;
}
@Override
public int getSlotStackLimit()
{
return 1;
}
@Override
public boolean isItemValid(ItemStack stack)
{
if (stack == null) return false;
return stack.getItem() instanceof ItemArmor ? ((ItemArmor)stack.getItem()).armorType == this.armorType : (Item.getIdFromItem(stack.getItem()) == Item.getIdFromItem(Item.getItemFromBlock(Blocks.pumpkin)) ? this.armorType == 0 : false);
}
@Override
public IIcon getBackgroundIconIndex()
{
return Info.iconSlotPlayerArmor[armorType];
// return 240 + armorType;
}
}

View file

@ -0,0 +1,55 @@
/*******************************************************************************
* Copyright (c) 2012-2013 Yancarlo Ramsey and CJ Bowman
* Licensed as open source with restrictions. Please see attached LICENSE.txt.
******************************************************************************/
package com.kaijin.AdvPowerMan.slots;
import com.kaijin.AdvPowerMan.Info;
import com.kaijin.AdvPowerMan.Utils;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
public class SlotPowerSource extends SlotCustom
{
private int powerTier;
//private int iconIndex;
public SlotPowerSource(IInventory inv, int index, int xpos, int ypos, int tier)
{
super(inv, index, xpos, ypos);
setTier(tier);
}
public void setTier(int tier)
{
if (tier < 1) tier = 1;
if (tier > 3) tier = 3;
powerTier = tier;
//iconIndex = 223 + tier;
}
/**
* Check if the stack is a valid item for this slot.
*/
@Override
public boolean isItemValid(ItemStack stack)
{
// Decide if the item is a valid IC2 power source
return Utils.isItemDrainable(stack, powerTier);
}
@Override
public int getSlotStackLimit()
{
return 1;
}
@Override
public IIcon getBackgroundIconIndex()
{
return Info.iconSlotPowerSource[powerTier - 1];
// return iconIndex;
}
}

View file

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

View file

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

View file

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

View file

@ -0,0 +1,838 @@
/*******************************************************************************
* Copyright (c) 2012-2013 Yancarlo Ramsey and CJ Bowman
* Licensed as open source with restrictions. Please see attached LICENSE.txt.
******************************************************************************/
package com.kaijin.AdvPowerMan.tileentities;
import ic2.api.Direction;
import ic2.api.item.ElectricItem;
import ic2.api.item.IElectricItem;
import ic2.api.tile.IEnergyStorage;
import ic2.api.energy.event.EnergyTileLoadEvent;
import ic2.api.energy.tile.IEnergySink;
import ic2.core.IC2;
import ic2.core.network.NetworkManager;
import io.netty.buffer.ByteBuf;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import com.kaijin.AdvPowerMan.AdvancedPowerManagement;
import com.kaijin.AdvPowerMan.Info;
import com.kaijin.AdvPowerMan.MovingAverage;
import com.kaijin.AdvPowerMan.Utils;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.Packet;
import net.minecraft.network.PacketBuffer;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.common.MinecraftForge;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class TEChargingBench extends TECommonBench implements IEnergySink, IEnergyStorage, IInventory, ISidedInventory
{
// Base values
public int baseMaxInput;
public int baseStorage;
// Adjustable values that need communicating via container
public int adjustedMaxInput;
public int adjustedStorage;
public int currentEnergy;
//For outside texture display
public int chargeLevel;
public float drainFactor;
public float chargeFactor;
protected int energyReceived = 0;
public MovingAverage inputTracker = new MovingAverage(12);
public int ticksRequired = 0;
public int energyRequired = 0;
private static final int[] ChargingBenchSideInput = {Info.CB_SLOT_INPUT};
private static final int[] ChargingBenchSideOutput = {Info.CB_SLOT_OUTPUT};
private static final int[] ChargingBenchSideInOut = {Info.CB_SLOT_INPUT, Info.CB_SLOT_OUTPUT};
private static final int[] ChargingBenchSidePower = {Info.CB_SLOT_POWER_SOURCE};
public TEChargingBench() // Default constructor used only when loading tile entity from world save
{
super();
// Do nothing else; Creating the inventory array and loading previous values will be handled in NBT read method momentarily.
}
public TEChargingBench(int i) // Constructor used when placing a new tile entity, to set up correct parameters
{
super();
contents = new ItemStack[19];
//base tier = what we're passed, so 1, 2 or 3
baseTier = i;
initializeBaseValues();
//setup Adjusted variables to = defaults, we'll be adjusting them in entityUpdate
adjustedMaxInput = baseMaxInput;
adjustedStorage = baseStorage;
powerTier = baseTier;
drainFactor = 1.0F;
chargeFactor = 1.0F;
}
protected void initializeBaseValues()
{
//if (ChargingBench.isDebugging) System.out.println("Initializing - BaseTier: " + baseTier);
//Max Input math = 32 for tier 1, 128 for tier 2, 512 for tier 3
baseMaxInput = (int)Math.pow(2.0D, (double)(2 * baseTier + 3));
//if (ChargingBench.isDebugging) System.out.println("BaseMaxInput: " + baseMaxInput);
switch(baseTier)
{
case 1:
baseStorage = 40000;
break;
case 2:
baseStorage = 600000;
break;
case 3:
baseStorage = 10000000;
break;
default:
baseStorage = 0;
}
//if (ChargingBench.isDebugging) System.out.println("BaseStorage: " + baseStorage);
}
/**
* Called to upgrade (or downgrade) a charging bench to a certain tier.
* @param newTier The tier to replace the charging bench with, based on the component item used
* @return the original tier of the charging bench, for creating the correct component item
*/
public int swapBenchComponents(int newTier)
{
int oldTier = baseTier;
baseTier = newTier;
worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, Info.CB_META + newTier - 1, 3);
initializeBaseValues();
doUpgradeEffects();
chargeLevel = gaugeEnergyScaled(12);
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
return oldTier;
}
// IC2 API stuff
// IEnergySink
@Override
public void setStored(int energy)
{
// What uses this?
}
@Override
public int addEnergy(int amount)
{
// Returning our current energy value always, we do not implement this function
return currentEnergy;
}
@Override
public int getMaxSafeInput()
{
return adjustedMaxInput;
}
// IEnergyStorage
/**
* Get the amount of energy currently stored in the block.
*
* @return Energy stored in the block
*/
@Override
public int getStored()
{
return currentEnergy;
}
/**
* Get the maximum amount of energy the block can store.
*
* @return Maximum energy stored
*/
@Override
public int getCapacity()
{
return adjustedStorage;
}
/**
* Get the block's energy output.
*
* @return Energy output in EU/t
*/
@Override
public int getOutput()
{
return 0;
}
// End IC2 API
@Override
public int getGuiID()
{
return Info.GUI_ID_CHARGING_BENCH;
}
/**
* This will cause the block to drop anything inside it, create a new item in the
* world of its type, invalidate the tile entity, remove itself from the IC2
* EnergyNet and clear the block space (set it to air)
*/
@Override
protected void selfDestroy()
{
dropContents();
ItemStack stack = new ItemStack(AdvancedPowerManagement.blockAdvPwrMan, 1, Info.CB_META + baseTier - 1);
dropItem(stack);
worldObj.setBlockToAir(xCoord, yCoord, zCoord);
this.invalidate();
}
public void doUpgradeEffects()
{
// Count our upgrades
ItemStack stack;
int ocCount = 0;
int tfCount = 0;
int esCount = 0;
for (int i = Info.CB_SLOT_UPGRADE; i < Info.CB_SLOT_UPGRADE + 4; ++i)
{
stack = contents[i];
if (stack != null)
{
if (stack.isItemEqual(Info.ic2overclockerUpg))
{
ocCount += stack.stackSize;
}
else if (stack.isItemEqual(Info.ic2storageUpg))
{
esCount += stack.stackSize;
}
else if (stack.isItemEqual(Info.ic2transformerUpg))
{
tfCount += stack.stackSize;
}
}
}
// Cap upgrades at sane quantities that won't result in negative energy storage from integer overflows and such.
if (ocCount > 20) ocCount = 20;
if (esCount > 64) esCount = 64;
if (tfCount > 3) tfCount = 3;
// Overclockers:
chargeFactor = (float)Math.pow(1.3F, ocCount); // 30% more power transferred to an item per overclocker, exponential.
drainFactor = (float)Math.pow(1.5F, ocCount); // 50% more power drained per overclocker, exponential. Yes, you waste power, that's how OCs work.
// Transformers:
powerTier = baseTier + tfCount; // Allows better energy storage items to be plugged into the battery slot of lower tier benches.
if (powerTier > 3) powerTier = 3;
adjustedMaxInput = (int)Math.pow(2.0D, (double)(2 * (baseTier + tfCount) + 3));
if (adjustedMaxInput > 2048) adjustedMaxInput = 2048; // You can feed EV in with 1-4 TF upgrades, if you so desire.
// Energy Storage:
switch (baseTier)
{
case 1:
adjustedStorage = baseStorage + esCount * 10000; // LV: 25% additional storage per upgrade (10,000).
break;
case 2:
adjustedStorage = baseStorage + esCount * 60000; // MV: 10% additional storage per upgrade (60,000).
break;
case 3:
adjustedStorage = baseStorage + esCount * 500000; // HV: 5% additional storage per upgrade (500,000).
break;
default:
adjustedStorage = baseStorage; // This shouldn't ever happen, but just in case, it shouldn't crash it - storage upgrades just won't work.
}
if (currentEnergy > adjustedStorage) currentEnergy = adjustedStorage; // If storage has decreased, lose any excess energy.
}
public boolean isItemValid(int slot, ItemStack stack)
{
// Decide if the item is a valid IC2 electrical item
if (stack != null && stack.getItem() instanceof IElectricItem)
{
IElectricItem item = (IElectricItem)(stack.getItem());
// Is the item appropriate for this slot?
if (slot == Info.CB_SLOT_POWER_SOURCE && item.canProvideEnergy(stack) && item.getTier(stack) <= powerTier) return true;
if (slot >= Info.CB_SLOT_CHARGING && slot < Info.CB_SLOT_CHARGING + 12 && item.getTier(stack) <= baseTier) return true;
if (slot >= Info.CB_SLOT_UPGRADE && slot < Info.CB_SLOT_UPGRADE + 4 && (stack.isItemEqual(Info.ic2overclockerUpg) || stack.isItemEqual(Info.ic2transformerUpg) || stack.isItemEqual(Info.ic2storageUpg))) return true;
if (slot == Info.CB_SLOT_INPUT && item.getTier(stack) <= baseTier) return true;
if (slot == Info.CB_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.
}
return false;
}
/**
* Reads a tile entity from NBT.
*/
@Override
public void readFromNBT(NBTTagCompound nbttagcompound)
{
super.readFromNBT(nbttagcompound);
if (Info.isDebugging) System.out.println("CB ID: " + nbttagcompound.getString("id"));
baseTier = nbttagcompound.getInteger("baseTier");
currentEnergy = nbttagcompound.getInteger("currentEnergy");
//if (ChargingBench.isDebugging) System.out.println("ReadNBT.CurrentEergy: " + currentEnergy);
// Our inventory
contents = new ItemStack[Info.CB_INVENTORY_SIZE];
NBTTagList nbttaglist = nbttagcompound.getTagList("Items", Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < nbttaglist.tagCount(); ++i)
{
NBTTagCompound nbttagcompound1 = (NBTTagCompound)nbttaglist.getCompoundTagAt(i);
int j = nbttagcompound1.getByte("Slot") & 255;
if (j >= 0 && j < contents.length)
{
contents[j] = ItemStack.loadItemStackFromNBT(nbttagcompound1);
}
}
// We can calculate these, no need to save/load them.
initializeBaseValues();
doUpgradeEffects();
}
/**
* Writes a tile entity to NBT.
*/
@Override
public void writeToNBT(NBTTagCompound nbttagcompound)
{
super.writeToNBT(nbttagcompound);
nbttagcompound.setInteger("baseTier", baseTier);
nbttagcompound.setInteger("currentEnergy", currentEnergy);
//if (ChargingBench.isDebugging) System.out.println("WriteNBT.CurrentEergy: " + currentEnergy);
// Our inventory
NBTTagList nbttaglist = new NBTTagList();
for (int i = 0; i < contents.length; ++i)
{
if (contents[i] != null)
{
//if (ChargingBench.isDebugging) System.out.println("WriteNBT contents[" + i + "] stack tag: " + contents[i].stackTagCompound);
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
nbttagcompound1.setByte("Slot", (byte)i);
contents[i].writeToNBT(nbttagcompound1);
nbttaglist.appendTag(nbttagcompound1);
}
}
nbttagcompound.setTag("Items", nbttaglist);
}
@Override
public void updateEntity() //TODO Marked for easy access
{
if (AdvancedPowerManagement.proxy.isClient())
{
return;
}
if (!initialized && worldObj != null)
{
EnergyTileLoadEvent loadEvent = new EnergyTileLoadEvent(this);
MinecraftForge.EVENT_BUS.post(loadEvent);
// EnergyNet.getForWorld(worldObj).addTileEntity(this);
initialized = true;
}
inputTracker.tick(energyReceived);
energyReceived = 0;
ticksRequired = 0;
energyRequired = 0;
boolean lastWorkState = doingWork;
doingWork = false;
// Work done every tick
drainPowerSource();
chargeItems();
moveOutputItems();
acceptInputItems();
// Determine if and how completion time will be affected by lack of energy and input rate
if (energyRequired > currentEnergy)
{
final int deficit = energyRequired - currentEnergy;
final float avg = inputTracker.getAverage();
if (avg >= 1.0F)
{
final int time = (int)Math.ceil(((float)deficit) / avg);
if (time > ticksRequired) ticksRequired = time;
}
else ticksRequired = -1;
}
// Trigger this only when charge level passes where it would need to update the client texture
int oldChargeLevel = chargeLevel;
chargeLevel = gaugeEnergyScaled(12);
if (oldChargeLevel != chargeLevel || lastWorkState != doingWork)
{
//if (ChargingBench.isDebugging) System.out.println("TE oldChargeLevel: " + oldChargeLevel + " chargeLevel: " + chargeLevel);
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
}
/**
* Looks in the power item slot to see if it can pull in EU from a valid item in that slot.
* If so, pull in as much EU as the item allows to be transferred per tick up to the maximum
* energy transfer rate based on our tier, limited also by the maximum energy storage capacity.
* ie. do not pull in more than we have room for
* @return
*/
private void drainPowerSource()
{
int chargeReturned = 0;
ItemStack stack = getStackInSlot(Info.CB_SLOT_POWER_SOURCE);
if (stack != null && stack.getItem() instanceof IElectricItem && currentEnergy < adjustedStorage)
{
IElectricItem powerSource = (IElectricItem)(stack.getItem());
Item emptyItem = powerSource.getEmptyItem(stack);
int chargedItemID = Item.getIdFromItem(powerSource.getChargedItem(stack));
if (Item.getIdFromItem(stack.getItem()) == chargedItemID)
{
if (powerSource.getTier(stack) <= powerTier && powerSource.canProvideEnergy(stack))
{
int itemTransferLimit = powerSource.getTransferLimit(stack);
int energyNeeded = adjustedStorage - currentEnergy;
// Test if the amount of energy we have room for is greater than what the item can transfer per tick.
if (energyNeeded > itemTransferLimit)
{
// If so, request the max it can transfer per tick.
energyNeeded = itemTransferLimit;
// If we need less than it can transfer per tick, request only what we have room for so we don't waste power.
}
if (energyNeeded > 0)
{
chargeReturned = ElectricItem.manager.discharge(stack, energyNeeded, powerTier, false, false);
// Add the energy we received to our current energy level,
currentEnergy += chargeReturned;
if (chargeReturned > 0) doingWork = true;
// and make sure that we didn't go over. If we somehow did, drop the excess.
if (currentEnergy > adjustedStorage) currentEnergy = adjustedStorage;
}
}
// Workaround for buggy IC2 API .discharge that automatically switches stack to emptyItemID but leaves a stackTagCompound on it, so it can't be stacked with never-used empties
if (chargedItemID != Item.getIdFromItem(emptyItem) && ElectricItem.manager.discharge(stack, 1, powerTier, false, true) == 0)
{
//if (ChargingBench.isDebugging) System.out.println("Switching to emptyItemID: " + emptyItemID + " from stack.itemID: " + stack.itemID + " - chargedItemID: " + chargedItemID);
setInventorySlotContents(Info.CB_SLOT_POWER_SOURCE, new ItemStack(emptyItem, 1, 0));
//ItemStack newStack = new ItemStack(emptyItemID, 1, 0);
//contents[ChargingBench.slotPowerSource] = newStack;
}
}
}
}
/**
* Look through all of the items in our main inventory and determine the current charge level,
* maximum charge level and maximum base charge rate for each item. Increase maximum charge
* rate for each item based on overclockers as appropriate, then, starting with the first slot
* in the main inventory, transfer one tick worth of energy from our internal storage to the
* item. Continue doing this for all items in the inventory until we reach the end of the main
* inventory or run out of internal EU storage.
*/
private void chargeItems()
{
for (int i = Info.CB_SLOT_CHARGING; i < Info.CB_SLOT_CHARGING + 12; i++)
{
ItemStack stack = contents[i];
if (stack != null && stack.getItem() instanceof IElectricItem && stack.stackSize == 1)
{
IElectricItem item = (IElectricItem)(stack.getItem());
if (item.getTier(stack) <= baseTier)
{
int itemTransferLimit = item.getTransferLimit(stack);
if (itemTransferLimit == 0) itemTransferLimit = baseMaxInput;
int adjustedTransferLimit = (int)Math.ceil(chargeFactor * itemTransferLimit);
int amountNeeded;
int missing;
int consumption;
if (Item.getIdFromItem(item.getChargedItem(stack)) != Item.getIdFromItem(item.getEmptyItem(stack)) || stack.isStackable())
{
// Running stack.copy() on every item every tick would be a horrible thing for performance, but the workaround is needed
// for ElectricItem.charge adding stackTagCompounds for charge level to EmptyItemID batteries even when run in simulate mode.
// Limiting its use by what is hopefully a broad enough test to catch all cases where it's necessary in order to avoid problems.
// Using it for any item types listed as stackable and for any items where the charged and empty item IDs differ.
final ItemStack stackCopy = stack.copy();
amountNeeded = ElectricItem.manager.charge(stackCopy, adjustedTransferLimit, baseTier, true, true);
if (amountNeeded == adjustedTransferLimit)
{
missing = ElectricItem.manager.charge(stackCopy, item.getMaxCharge(stackCopy), baseTier, true, true);
}
else missing = amountNeeded;
}
else
{
amountNeeded = ElectricItem.manager.charge(stack, adjustedTransferLimit, baseTier, true, true);
if (amountNeeded == adjustedTransferLimit)
{
missing = ElectricItem.manager.charge(stack, item.getMaxCharge(stack), baseTier, true, true);
}
else missing = amountNeeded;
}
// How long will this item take and how much will it drain?
final int eta = (int)Math.ceil(((float)missing) / ((float)adjustedTransferLimit));
if (ticksRequired < eta) ticksRequired = eta;
energyRequired += (int)Math.ceil((drainFactor / chargeFactor) * missing);
int adjustedEnergyUse = (int)Math.ceil((drainFactor / chargeFactor) * amountNeeded);
if (adjustedEnergyUse > 0 && currentEnergy > 0)
{
if (adjustedEnergyUse > currentEnergy)
{
// Allow that last trickle of energy to be transferred out of the bench
adjustedTransferLimit = (adjustedTransferLimit * currentEnergy) / adjustedEnergyUse;
adjustedEnergyUse = currentEnergy;
}
// We don't need to do this with the current API, it's switching the ItemID for us. Just make sure we don't try to charge stacked batteries, as mentioned above!
//int chargedItemID = item.getChargedItemId();
//if (stack.itemID != chargedItemID)
//{
// setInventorySlotContents(i, new ItemStack(chargedItemID, 1, 0));
//}
ElectricItem.manager.charge(contents[i], adjustedTransferLimit, baseTier, true, false);
currentEnergy -= adjustedEnergyUse;
if (currentEnergy < 0) currentEnergy = 0;
doingWork = true;
}
}
}
}
}
/**
* First, check the output slot to see if it's empty. If so, look to see if there are any fully
* charged items in the main inventory. Move the first fully charged item to the output slot.
*/
private void moveOutputItems()
{
ItemStack stack = contents[Info.CB_SLOT_OUTPUT];
if (stack == null)
{
// Output slot is empty. Try to find a fully charged item to move there.
for (int slot = Info.CB_SLOT_CHARGING; slot < Info.CB_SLOT_CHARGING + 12; ++slot)
{
ItemStack currentStack = contents[slot];
if (currentStack != null && currentStack.getItem() instanceof IElectricItem)
{
// Test if the item is fully charged (cannot accept any more power).
if (ElectricItem.manager.charge(currentStack.copy(), 1, baseTier, false, true) == 0)
{
contents[Info.CB_SLOT_OUTPUT] = currentStack;
contents[slot] = null;
this.markDirty();
break;
}
}
}
}
}
/**
* Check to see if there are any items in the input slot. If so, check to see if there are any
* free charging slots. If so, move one from the input slot to a free charging slot. Do not
* move more than one, if the stack contains more.
*/
private void acceptInputItems()
{
ItemStack stack = contents[Info.CB_SLOT_INPUT];
if (stack != null && stack.getItem() instanceof IElectricItem)
{
// Input slot contains something electrical. If possible, move one of it into the charging area.
IElectricItem item = (IElectricItem)(stack.getItem());
for (int slot = Info.CB_SLOT_CHARGING; slot < Info.CB_SLOT_CHARGING + 12; ++slot)
{
if (contents[slot] == null)
{
// Grab one unit from input and move it to the selected slot.
contents[slot] = decrStackSize(Info.CB_SLOT_INPUT, 1);
break;
}
}
}
}
public int gaugeEnergyScaled(int gaugeSize)
{
if (currentEnergy <= 0)
{
return 0;
}
int result = currentEnergy * gaugeSize / adjustedStorage;
if (result > gaugeSize) result = gaugeSize;
return result;
}
//Networking stuff
@SideOnly(Side.CLIENT)
@Override
public void receiveDescriptionData(int packetID, ByteBuf stream)
{
final int a;
final boolean b;
//try
//{
a = stream.readInt();
b = stream.readBoolean();
/*}
catch (IOException e)
{
logDescPacketError(e);
return;
}*/
chargeLevel = a;
doingWork = b;
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
@Override
public Packet getDescriptionPacket()
{
return createDescPacket();
}
@Override
protected void addUniqueDescriptionData(ByteBuf data) throws IOException
{
data.writeInt(chargeLevel);
data.writeBoolean(doingWork);
}
// ISidedInventory
/*
@Override
public int getStartInventorySide(ForgeDirection side)
{
switch (side)
{
case UP:
return Info.CB_SLOT_INPUT;
case DOWN:
return Info.CB_SLOT_OUTPUT;
default:
return Info.CB_SLOT_POWER_SOURCE;
}
}
@Override
public int getSizeInventorySide(ForgeDirection side)
{
// Each side accesses a single slot
return 1;
} */
@Override
public int[] getAccessibleSlotsFromSide(int side)
{
switch (side)
{
//Correct values for top and bottom sides: 0 = bottom, 1 = top
case 0:
// return ChargingBenchSideOutput;
case 1:
// return ChargingBenchSideInput;
return ChargingBenchSideInOut;
default:
return ChargingBenchSidePower;
}
}
@Override
public boolean isItemValidForSlot(int i, ItemStack stack)
{
// Decide if the item is a valid IC2 electrical item
if (i == Info.CB_SLOT_POWER_SOURCE) return Utils.isItemDrainable(stack, powerTier);
if (i == Info.CB_SLOT_INPUT) return Utils.isItemChargeable(stack, powerTier);
// Info.CB_SLOT_OUTPUT ?
return false;
}
// Returns true if automation can insert the given item in the given slot from the given side. Args: Slot, item, side
@Override
public boolean canInsertItem(int i, ItemStack itemstack, int j) // canInsertItem
{
if (i == Info.CB_SLOT_INPUT || i == Info.CB_SLOT_POWER_SOURCE) return true;
return false;
}
// Returns true if automation can extract the given item in the given slot from the given side. Args: Slot, item, side
@Override
public boolean canExtractItem(int i, ItemStack itemstack, int j) // canExtractItem
{
if (i == Info.CB_SLOT_OUTPUT || i == Info.CB_SLOT_POWER_SOURCE) return true;
return false;
}
// IInventory
@Override
public int getSizeInventory()
{
// Only input/output slots are accessible to machines
return 3;
}
@Override
public String getInventoryName()
{
switch (baseTier)
{
case 1:
return Info.KEY_BLOCK_NAMES[0] + Info.KEY_NAME_SUFFIX;
case 2:
return Info.KEY_BLOCK_NAMES[1] + Info.KEY_NAME_SUFFIX;
case 3:
return Info.KEY_BLOCK_NAMES[2] + Info.KEY_NAME_SUFFIX;
}
return "";
}
@Override
public void markDirty(int slot)
{
if (slot == Info.CB_SLOT_INPUT || slot == Info.CB_SLOT_OUTPUT)
{
// Move item from input to output if not valid. (Wrong tier or not electric item.)
if (contents[Info.CB_SLOT_INPUT] != null && contents[Info.CB_SLOT_OUTPUT] == null)
{
if (!isItemValid(Info.CB_SLOT_INPUT, contents[Info.CB_SLOT_INPUT]))
{
contents[Info.CB_SLOT_OUTPUT] = contents[Info.CB_SLOT_INPUT];
contents[Info.CB_SLOT_INPUT] = null;
}
}
}
else if (slot >= Info.CB_SLOT_UPGRADE && slot < Info.CB_SLOT_UPGRADE + 4)
{
// One of the upgrade slots was touched, so we need to recalculate.
doUpgradeEffects();
}
else if (slot >= Info.CB_SLOT_CHARGING && slot < Info.CB_SLOT_CHARGING + 12)
{
// Make sure it's not fully charged already? Not sure, full items will be output in updateEntity
}
else if (slot == Info.CB_SLOT_POWER_SOURCE)
{
// Perhaps eject the item if it's not valid? No, just leave it alone.
// If machinery added it the player can figure out the problem by trying to remove and replace it and realizing it won't fit.
}
super.markDirty();
}
@Override
public void markDirty()
{
// We're not sure what called this or what slot was altered, so make sure the upgrade effects are correct just in case and then pass the call on.
doUpgradeEffects();
super.markDirty();
}
@Override
public boolean acceptsEnergyFrom(TileEntity emitter, ForgeDirection direction) {
return true;
}
@Override
public double getOutputEnergyUnitsPerTick() {
return 0;
}
@Override
public boolean isTeleporterCompatible(ForgeDirection side) {
return false;
}
@Override
public double demandedEnergyUnits() {
// return (currentEnergy < adjustedStorage && !receivingRedstoneSignal());
if(!receivingRedstoneSignal())
{
return adjustedStorage - currentEnergy;
}
return 0;
}
@Override
public double injectEnergyUnits(ForgeDirection directionFrom, double amount) {
int surplus = 0;
if (AdvancedPowerManagement.proxy.isServer())
{
// if supply is greater than the max we can take per tick
if (amount > adjustedMaxInput)
{
//If the supplied EU is over the baseMaxInput, we're getting
//supplied higher than acceptable current. Pop ourselves off
//into the world and return all but 1 EU, or if the supply
//somehow was 1EU, return zero to keep IC2 from spitting out
//massive errors in the log
selfDestroy();
if (amount <= 1)
return 0;
else
return amount - 1;
}
else
{
if (currentEnergy > adjustedStorage) currentEnergy = adjustedStorage;
currentEnergy += amount;
energyReceived += amount;
// check if our current energy level is now over the max energy level
if (currentEnergy > adjustedStorage)
{
//if so, our surplus to return is equal to that amount over
surplus = currentEnergy - adjustedStorage;
//and set our current energy level TO our max energy level
currentEnergy = adjustedStorage;
energyReceived -= surplus;
}
//surplus may be zero or greater here
}
}
return surplus;
}
}

View file

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

View file

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

View file

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

View file

@ -0,0 +1,51 @@
blockChargingBench1.name=LV Charging Bench
blockChargingBench2.name=MV Charging Bench
blockChargingBench3.name=HV Charging Bench
blockEmitterBlock1.name=LV Emitter
blockEmitterBlock2.name=MV Emitter
blockEmitterBlock3.name=HV Emitter
blockAdjustableTransformer.name=Adjustable Transformer
blockEmitterAdjustable.name=Adjustable Emitter
blockBatteryStation1.name=LV Battery Station
blockBatteryStation2.name=MV Battery Station
blockBatteryStation3.name=HV Battery Station
blockStorageMonitor.name=Storage Monitor
AdvPwrMan.dir.down=Down
AdvPwrMan.dir.up=Up
AdvPwrMan.dir.north=North
AdvPwrMan.dir.south=South
AdvPwrMan.dir.west=West
AdvPwrMan.dir.east=East
item.benchTools.toolkit.name=Charging Bench Toolkit
item.benchTools.LV-kit.name=LV Charging Bench Components
item.benchTools.MV-kit.name=MV Charging Bench Components
item.benchTools.HV-kit.name=HV Charging Bench Components
item.itemStorageLinkCard.name=Energy Link Card
item.itemStorageLinkCardCreator.name=Energy Link Card (Blank)
AdvPwrMan.title=Advanced Power Management
AdvPwrMan.misc.EU=EU
AdvPwrMan.misc.in=In
AdvPwrMan.misc.out=Out
AdvPwrMan.charger.maxEU=Max
AdvPwrMan.charger.requiredEU=Req
AdvPwrMan.charger.redstonePower=Pwr
AdvPwrMan.charger.estimatedTime=ETC
AdvPwrMan.charger.averageInput=Avg. EU/t In
AdvPwrMan.emitter.packet=Packet size (Voltage)
AdvPwrMan.emitter.output=Output / Tick (Max 64 Packets)
AdvPwrMan.transformer.limit=Transfer Rate (Max 64 Packets)
AdvPwrMan.monitor.invalid=No Valid Link
AdvPwrMan.monitor.upper=Upper Threshold (Off)
AdvPwrMan.monitor.lower=Lower Threshold (On)
AdvPwrMan.station.modeline1=Only when
AdvPwrMan.station.modeline2=required
AdvPwrMan.station.average=Avg. EU/t
AdvPwrMan.station.remaining=Remaining
AdvPwrMan.station.led.days= DAYS
AdvPwrMan.station.led.unknown=UNKNOWN
AdvPwrMan.station.packetIn=Avg. Pkt In
AdvPwrMan.station.EUbuffered=EU Buffered

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 485 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 262 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 274 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 616 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 253 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 254 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 594 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 342 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 347 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 343 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 345 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 337 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 349 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 349 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 351 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 350 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 350 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 349 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 349 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 346 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 342 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 346 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 344 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 345 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 337 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 349 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 349 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 348 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 350 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 349 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 349 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 347 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 346 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 231 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 253 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 254 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 568 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 346 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 347 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 344 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 345 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 338 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 349 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 350 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 351 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 351 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 350 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 350 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 349 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 348 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 343 B

Some files were not shown because too many files have changed in this diff Show more