Revert "Dammit i already deleted those"

This reverts commit 554878ce18.
This commit is contained in:
Francesco Macagno 2015-07-22 17:20:30 -07:00
parent 3eaea54c72
commit b64a600a6a
27 changed files with 9796 additions and 0 deletions

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,818 @@
package cr0s.WarpDrive;
import cpw.mods.fml.common.FMLCommonHandler;
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.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.NetworkMod;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import cr0s.WarpDrive.block.*;
import cr0s.WarpDrive.command.*;
import cr0s.WarpDrive.data.*;
import cr0s.WarpDrive.item.*;
import cr0s.WarpDrive.machines.*;
import cr0s.WarpDrive.render.*;
import cr0s.WarpDrive.world.*;
import dan200.computercraft.api.ComputerCraftAPI;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.Minecraft;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.EnumArmorMaterial;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.packet.Packet250CustomPayload;
import net.minecraft.server.MinecraftServer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraftforge.common.Configuration;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.common.EnumHelper;
import net.minecraftforge.common.ForgeChunkManager;
import net.minecraftforge.common.ForgeChunkManager.LoadingCallback;
import net.minecraftforge.common.ForgeChunkManager.Ticket;
import net.minecraftforge.common.ForgeChunkManager.Type;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.minecraftforge.oredict.ShapelessOreRecipe;
@Mod(modid = "WarpDrive", name = "WarpDrive", version = "1.2.7.0",
dependencies = "required-after:IC2;"
+ " required-after:CoFHCore;"
+ " after:ComputerCraft;"
+ " after:OpenComputer;"
+ " after:CCTurtle;"
+ " after:gregtech_addon;"
+ " required-after:AppliedEnergistics;"
+ " after:AdvancedSolarPanel;"
+ " after:AtomicScience;"
+ " after:ICBM|Explosion;"
+ " after:MFFS;"
+ " after:GraviSuite;"
+ " after:UndergroundBiomes;"
+ " after:NetherOres")
@NetworkMod(clientSideRequired = true, serverSideRequired = true, channels = {
"WarpDriveBeam",
"WarpDriveFreq",
"WarpDriveLaserT",
"WarpDriveCloaks" }, packetHandler = PacketHandler.class)
/**
* @author Cr0s
*/
public class WarpDrive implements LoadingCallback {
public static Block warpCore;
public static Block protocolBlock;
public static Block radarBlock;
public static Block isolationBlock;
public static Block airgenBlock;
public static Block laserBlock;
public static Block laserCamBlock;
public static Block cameraBlock;
public static Block monitorBlock;
public static Block boosterBlock;
public static Block miningLaserBlock;
public static Block laserTreeFarmBlock;
public static Block liftBlock;
public static Block scannerBlock;
public static Block cloakBlock;
public static Block cloakCoilBlock;
public static Block transporterBlock;
public static Block reactorMonitorBlock;
public static Block powerReactorBlock;
public static Block powerLaserBlock;
public static Block powerStoreBlock;
public static Block airBlock;
public static Block gasBlock;
public static Block iridiumBlock;
public static Block transportBeaconBlock;
public static Block chunkLoaderBlock;
public static BlockDecorative decorativeBlock;
public static Item reactorLaserFocusItem;
public static ItemWarpComponent componentItem;
public static ItemWarpUpgrade upgradeItem;
public static EnumArmorMaterial armorMaterial = EnumHelper.addArmorMaterial("WARP", 5, new int[]{1, 3, 2, 1}, 15);
public static ItemWarpArmor helmetItem;
public static ItemWarpAirCanister airCanisterItem;
public static BiomeGenBase spaceBiome;
public World space;
public SpaceWorldGenerator spaceWorldGenerator;
public HyperSpaceWorldGenerator hyperSpaceWorldGenerator;
public World hyperSpace;
// Client settings
public static float normalFOV = 70.0F;
public static float normalSensitivity = 1.0F;
public static CreativeTabs warpdriveTab = new WarpDriveCreativeTab("Warpdrive", "Warpdrive").setBackgroundImageName("warpdrive:creativeTab");
@Instance("WarpDrive")
public static WarpDrive instance;
@SidedProxy(clientSide = "cr0s.WarpDrive.client.ClientProxy", serverSide = "cr0s.WarpDrive.CommonProxy")
public static CommonProxy proxy;
public static WarpCoresRegistry warpCores;
public static JumpgatesRegistry jumpgates;
public static CloakManager cloaks;
public static CamRegistry cams;
public boolean isOverlayEnabled = false;
public int overlayType = 0;
public String debugMessage = "";
public static WarpDrivePeripheralHandler peripheralHandler = null;
public static String defHelpStr = "help(\"functionName\"): returns help for the function specified";
public static String defEnergyStr = "getEnergyLevel(): returns currently contained energy, max contained energy";
public static String defUpgradeStr = "upgrades(): returns a list of currently installed upgrades";
@EventHandler
public void preInit(FMLPreInitializationEvent event) {
WarpDriveConfig.preInit(new Configuration(event.getSuggestedConfigurationFile()));
if (FMLCommonHandler.instance().getSide().isClient()) {
Minecraft mc = Minecraft.getMinecraft();
// System.out.println("[WarpDrive] Registering sounds event handler...");
MinecraftForge.EVENT_BUS.register(new SoundHandler());
normalFOV = mc.gameSettings.fovSetting;
normalSensitivity = mc.gameSettings.mouseSensitivity;
WarpDrive.print("[WarpDrive] FOV is " + normalFOV + " Sensitivity is " + normalSensitivity);
}
}
@SideOnly(Side.CLIENT)
@EventHandler
public void init(FMLInitializationEvent event) {
// FIXME FMLInterModComms.sendMessage("Waila", "register", "cr0s.WarpDrive.client.WailaHandler.callbackRegister");
}
public static void print(String out) {
System.out.println((FMLCommonHandler.instance().getEffectiveSide().isClient() ? "Client ":"Server ") + out);
}
public static void debugPrint(String out) {
if (WarpDriveConfig.G_DEBUGMODE) {
print(out);
}
}
@EventHandler
public void load(FMLInitializationEvent event) {
WarpDriveConfig.load();
// CORE CONTROLLER
protocolBlock = new BlockProtocol(WarpDriveConfig.controllerID,0, Material.rock);
GameRegistry.registerBlock(protocolBlock, "protocolBlock");
GameRegistry.registerTileEntity(TileEntityProtocol.class, "protocolBlock");
// WARP CORE
warpCore = new BlockReactor(WarpDriveConfig.coreID, 0, Material.rock);
GameRegistry.registerBlock(warpCore, "warpCore");
GameRegistry.registerTileEntity(TileEntityReactor.class, "warpCore");
// WARP RADAR
radarBlock = new BlockRadar(WarpDriveConfig.radarID, 0, Material.rock);
GameRegistry.registerBlock(radarBlock, "radarBlock");
GameRegistry.registerTileEntity(TileEntityRadar.class, "radarBlock");
// WARP ISOLATION
isolationBlock = new BlockWarpIsolation( WarpDriveConfig.isolationID, 0, Material.rock);
GameRegistry.registerBlock(isolationBlock, "isolationBlock");
// AIR GENERATOR
airgenBlock = new BlockAirGenerator(WarpDriveConfig.airgenID, 0,Material.rock);
GameRegistry.registerBlock(airgenBlock, "airgenBlock");
GameRegistry.registerTileEntity(TileEntityAirGenerator.class, "airgenBlock");
// AIR BLOCK
airBlock = (new BlockAir(WarpDriveConfig.airID));
GameRegistry.registerBlock(airBlock, "airBlock");
// GAS BLOCK
gasBlock = (new BlockGas(WarpDriveConfig.gasID));
GameRegistry.registerBlock(gasBlock, "gasBlock");
// LASER EMITTER
laserBlock = new BlockLaser(WarpDriveConfig.laserID, 0,Material.rock);
GameRegistry.registerBlock(laserBlock, "laserBlock");
GameRegistry.registerTileEntity(TileEntityLaser.class, "laserBlock");
// LASER EMITTER WITH CAMERA
laserCamBlock = new BlockLaserCam(WarpDriveConfig.laserCamID, 0, Material.rock);
GameRegistry.registerBlock(laserCamBlock, "laserCamBlock");
// CAMERA
cameraBlock = new BlockCamera(WarpDriveConfig.camID, 0,Material.rock);
GameRegistry.registerBlock(cameraBlock, "cameraBlock");
GameRegistry.registerTileEntity(TileEntityCamera.class, "cameraBlock");
// MONITOR
monitorBlock = new BlockMonitor(WarpDriveConfig.monitorID);
GameRegistry.registerBlock(monitorBlock, "monitorBlock");
GameRegistry.registerTileEntity(TileEntityMonitor.class, "monitorBlock");
// MINING LASER
miningLaserBlock = new BlockMiningLaser(WarpDriveConfig.miningLaserID, 0, Material.rock);
GameRegistry.registerBlock(miningLaserBlock, "miningLaserBlock");
GameRegistry.registerTileEntity(TileEntityMiningLaser.class, "miningLaserBlock");
// LASER TREE FARM
laserTreeFarmBlock = new BlockLaserTreeFarm(WarpDriveConfig.laserTreeFarmID, 0, Material.rock);
GameRegistry.registerBlock(laserTreeFarmBlock, "laserTreeFarmBlock");
GameRegistry.registerTileEntity(TileEntityLaserTreeFarm.class,"laserTreeFarmBlock");
// PARTICLE BOOSTER
boosterBlock = new BlockParticleBooster(WarpDriveConfig.particleBoosterID, 0, Material.rock);
GameRegistry.registerBlock(boosterBlock, "boosterBlock");
GameRegistry.registerTileEntity(TileEntityParticleBooster.class, "boosterBlock");
// LASER LIFT
liftBlock = new BlockLift(WarpDriveConfig.liftID, 0, Material.rock);
GameRegistry.registerBlock(liftBlock, "liftBlock");
GameRegistry.registerTileEntity(TileEntityLift.class, "liftBlock");
// IRIDIUM BLOCK
iridiumBlock = new BlockIridium(WarpDriveConfig.iridiumBlockID);
GameRegistry.registerBlock(iridiumBlock, "iridiumBlock");
// SHIP SCANNER
scannerBlock = new BlockShipScanner(WarpDriveConfig.shipScannerID, 0, Material.rock);
GameRegistry.registerBlock(scannerBlock, "scannerBlock");
GameRegistry.registerTileEntity(TileEntityShipScanner.class, "scannerBlock");
// CLOAKING DEVICE CORE
cloakBlock = new BlockCloakingDeviceCore(WarpDriveConfig.cloakCoreID, 0, Material.rock);
GameRegistry.registerBlock(cloakBlock, "cloakBlock");
GameRegistry.registerTileEntity(TileEntityCloakingDeviceCore.class, "cloakBlock");
// CLOAKING DEVICE COIL
cloakCoilBlock = new BlockCloakingCoil(WarpDriveConfig.cloakCoilID, 0, Material.rock);
GameRegistry.registerBlock(cloakCoilBlock, "cloakCoilBlock");
// TRANSPORTER
transporterBlock = new BlockTransporter(WarpDriveConfig.transporterID,Material.rock);
GameRegistry.registerBlock(transporterBlock, "transporter");
GameRegistry.registerTileEntity(TileEntityTransporter.class,"transporter");
// REACTOR MONITOR
reactorMonitorBlock = new BlockLaserReactorMonitor(WarpDriveConfig.reactorMonitorID, Material.rock);
GameRegistry.registerBlock(reactorMonitorBlock, "reactorMonitor");
GameRegistry.registerTileEntity(TileEntityLaserReactorMonitor.class,"reactorMonitor");
// TRANSPORT BEACON
transportBeaconBlock = new BlockTransportBeacon(WarpDriveConfig.transportBeaconID);
GameRegistry.registerBlock(transportBeaconBlock, "transportBeacon");
// POWER REACTOR, LASER, STORE
powerReactorBlock = new BlockPowerReactor(WarpDriveConfig.powerReactorID);
GameRegistry.registerBlock(powerReactorBlock,"powerReactor");
GameRegistry.registerTileEntity(TileEntityPowerReactor.class, "powerReactor");
powerLaserBlock = new BlockPowerLaser(WarpDriveConfig.powerLaserID);
GameRegistry.registerBlock(powerLaserBlock, "powerLaser");
GameRegistry.registerTileEntity(TileEntityPowerLaser.class, "powerLaser");
powerStoreBlock = new BlockPowerStore(WarpDriveConfig.powerStoreID);
GameRegistry.registerBlock(powerStoreBlock,"powerStore");
GameRegistry.registerTileEntity(TileEntityPowerStore.class, "powerStore");
// CHUNK LOADER
chunkLoaderBlock = new BlockChunkLoader(WarpDriveConfig.chunkLoaderID);
GameRegistry.registerBlock(chunkLoaderBlock, "chunkLoader");
GameRegistry.registerTileEntity(TileEntityChunkLoader.class, "chunkLoader");
// DECORATIVE
decorativeBlock = new BlockDecorative(WarpDriveConfig.decorativeID);
GameRegistry.registerBlock(decorativeBlock, ItemBlockDecorative.class, "decorative");
// REACTOR LASER FOCUS
reactorLaserFocusItem = new ItemReactorLaserFocus(WarpDriveConfig.reactorLaserFocusID);
GameRegistry.registerItem(reactorLaserFocusItem, "reactorLaserFocus");
// COMPONENT ITEMS
componentItem = new ItemWarpComponent(WarpDriveConfig.componentID);
GameRegistry.registerItem(componentItem, "component");
helmetItem = new ItemWarpArmor(WarpDriveConfig.helmetID, 0);
GameRegistry.registerItem(helmetItem, "helmet");
airCanisterItem = new ItemWarpAirCanister(WarpDriveConfig.airCanisterID);
GameRegistry.registerItem(airCanisterItem, "airCanisterFull");
upgradeItem = new ItemWarpUpgrade(WarpDriveConfig.upgradeID);
GameRegistry.registerItem(upgradeItem, "upgrade");
proxy.registerEntities();
ForgeChunkManager.setForcedChunkLoadingCallback(instance, instance);
spaceWorldGenerator = new SpaceWorldGenerator();
GameRegistry.registerWorldGenerator(spaceWorldGenerator);
hyperSpaceWorldGenerator = new HyperSpaceWorldGenerator();
GameRegistry.registerWorldGenerator(hyperSpaceWorldGenerator);
registerSpaceDimension();
registerHyperSpaceDimension();
MinecraftForge.EVENT_BUS.register(new SpaceEventHandler());
if (FMLCommonHandler.instance().getEffectiveSide().isClient()) {
warpdriveTab.setBackgroundImageName("items.png");
MinecraftForge.EVENT_BUS.register(new CameraOverlay(Minecraft.getMinecraft()));
}
if (WarpDriveConfig.isCCLoaded) {
peripheralHandler = new WarpDrivePeripheralHandler();
ComputerCraftAPI.registerPeripheralProvider(peripheralHandler);
}
}
@EventHandler
public void postInit(FMLPostInitializationEvent event) {
space = DimensionManager.getWorld(WarpDriveConfig.G_SPACE_DIMENSION_ID);
hyperSpace = DimensionManager.getWorld(WarpDriveConfig.G_HYPERSPACE_DIMENSION_ID);
WarpDriveConfig.postInit();
if (WarpDriveConfig.isICLoaded && WarpDriveConfig.G_ENABLE_IC2_RECIPES) {
initIC2Recipes();
}
if (WarpDriveConfig.isAppliedEnergisticsLoaded && WarpDriveConfig.isThermalExpansionLoaded && WarpDriveConfig.isAtomicScienceLoaded && WarpDriveConfig.G_ENABLE_TDK_RECIPES) {
initAETERecipes();
}
if (WarpDriveConfig.G_ENABLE_VANILLA_RECIPES) {
initVanillaRecipes();
}
warpCores = new WarpCoresRegistry();
jumpgates = new JumpgatesRegistry();
cams = new CamRegistry();
}
private static void initVanillaRecipes() {
componentItem.registerRecipes();
decorativeBlock.initRecipes();
upgradeItem.initRecipes();
//WarpCore
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(warpCore), false, "ipi", "ici", "idi",
'i', Item.ingotIron,
'p', componentItem.getIS(6),
'c', componentItem.getIS(2),
'd', Item.diamond));
//Controller
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(protocolBlock), false, "ici", "idi", "iii",
'i', Item.ingotIron,
'c', componentItem.getIS(5),
'd', Item.diamond));
//Radar
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(radarBlock), false, "ggg", "pdc", "iii",
'i', Item.ingotIron,
'c', componentItem.getIS(5),
'p', componentItem.getIS(6),
'g', Block.glass,
'd', Item.diamond));
//Isolation Block
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(isolationBlock), false, "igi", "geg", "igi",
'i', Item.ingotIron,
'g', Block.glass,
'e', Item.enderPearl));
//Air generator
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(airgenBlock), false, "ibi", "i i", "ipi",
'i', Item.ingotIron,
'b', Block.fenceIron,
'p', componentItem.getIS(6)));
//Laser
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(laserBlock), false, "ili", "iri", "ici",
'i', Item.ingotIron,
'r', Item.redstone,
'c', componentItem.getIS(5),
'l', componentItem.getIS(3),
'p', componentItem.getIS(6)));
//Mining laser
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(miningLaserBlock), false, "ici", "iti", "ili",
'i', Item.ingotIron,
'r', Item.redstone,
't', componentItem.getIS(1),
'c', componentItem.getIS(5),
'l', componentItem.getIS(3)));
//Tree farm laser
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(laserTreeFarmBlock), false, "ili", "sts", "ici",
'i', Item.ingotIron,
's', "treeSapling",
't', componentItem.getIS(1),
'c', componentItem.getIS(5),
'l', componentItem.getIS(3)));
//Laser Lift
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(liftBlock), false, "ipi", "rtr", "ili",
'i', Item.ingotIron,
'r', Item.redstone,
't', componentItem.getIS(1),
'l', componentItem.getIS(3),
'p', componentItem.getIS(6)));
//Transporter
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(transporterBlock), false, "iii", "ptc", "iii",
'i', Item.ingotIron,
't', componentItem.getIS(1),
'c', componentItem.getIS(5),
'p', componentItem.getIS(6)));
//Particle Booster
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(boosterBlock), false, "ipi", "rgr", "iii",
'i', Item.ingotIron,
'r', Item.redstone,
'g', Block.glass,
'p', componentItem.getIS(6)));
//Camera
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(cameraBlock), false, "ngn", "i i", "ici",
'i', Item.ingotIron,
'n', Item.goldNugget,
'g', Block.glass,
'c', componentItem.getIS(5)));
//LaserCamera
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(laserCamBlock), cameraBlock, laserBlock));
//Monitor
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(monitorBlock), false, "ggg", "iti", "ici",
'i', Item.ingotIron,
't', Block.torchWood,
'g', Block.glass,
'c', componentItem.getIS(5)));
//Cloaking device
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(cloakBlock), false, "ipi", "lrl", "ici",
'i', Item.ingotIron,
'r', Item.redstone,
'l', componentItem.getIS(3),
'c', componentItem.getIS(5),
'p', componentItem.getIS(6)));
//Cloaking coil
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(cloakCoilBlock), false, "ini", "rdr", "ini",
'i', Item.ingotIron,
'd', Item.diamond,
'r', Item.redstone,
'n', Item.goldNugget));
//Power Laser
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(powerLaserBlock), false, "iii", "ilg", "ici",
'i', Item.ingotIron,
'g', Block.glass,
'c', componentItem.getIS(5),
'l', componentItem.getIS(3)));
//Power Reactor
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(powerReactorBlock), false, "ipi", "gog", "ici",
'i', Item.ingotIron,
'g', Block.glass,
'o', componentItem.getIS(4),
'c', componentItem.getIS(5),
'p', componentItem.getIS(6)));
//Power Store
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(powerStoreBlock), false, "ipi", "isi", "ici",
'i', Item.ingotIron,
's', componentItem.getIS(7),
'c', componentItem.getIS(5),
'p', componentItem.getIS(6)));
//Transport Beacon
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(transportBeaconBlock), false, " e ", "ldl", " s ",
'e', Item.enderPearl,
'l', "dyeBlue",
'd', Item.diamond,
's', Item.stick));
//Chunk Loader
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(chunkLoaderBlock), false, "ipi", "ici", "ifi",
'i', Item.ingotIron,
'p', componentItem.getIS(6),
'c', componentItem.getIS(0),
'f', componentItem.getIS(5)));
//Helmet
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(helmetItem), false, "iii", "iwi", "gcg",
'i', Item.ingotIron,
'w', Block.cloth,
'g', Block.glass,
'c', componentItem.getIS(8)));
}
private static void initAETERecipes() {
ItemStack redstoneEnergycell = GameRegistry.findItemStack("ThermalExpansion", "cellReinforced", 1);
ItemStack resonantEnergycell = GameRegistry.findItemStack("ThermalExpansion", "cellResonant", 1);
ItemStack bucketEnder = GameRegistry.findItemStack("ThermalExpansion", "bucketEnder", 1);
ItemStack fluixCrystal = WarpDriveConfig.getAEMaterial("matFluxCrystal");
ItemStack quantumEntangledSingularity = WarpDriveConfig.getAEMaterial("matQuantumEntangledSingularity");
ItemStack vibrantQuartzGlass = WarpDriveConfig.getAEBlock("blkQuartzLamp");
vibrantQuartzGlass.setItemDamage(4);
ItemStack antimatter = GameRegistry.findItemStack("ResonantInduction|Atomic", "antimatter", 1);
antimatter.setItemDamage(0);
ItemStack floppy = GameRegistry.findItemStack("ComputerCraft", "disk", 1);
ItemStack ultimateLappack = new ItemStack(WarpDriveConfig.GS_ultimateLappack, 1, 1);
// top = advancedCircuit, redstoneEnergycell, advancedCircuit
// middle = fluix crystal, advancedMachine, fluix crystal
// bottom = advancedCircuit, bucket Resonant ender, advancedCircuit
GameRegistry.addRecipe(new ItemStack(warpCore), "crc", "fmf", "cec",
'm', WarpDriveConfig.getIC2Item("advancedMachine"),
'c', WarpDriveConfig.getIC2Item("advancedCircuit"),
'r', redstoneEnergycell,
'e', bucketEnder,
'f', fluixCrystal);
// top = advancedCircuit, floppy, advancedCircuit
// middle = advancedCircuit, advancedMachine, advancedCircuit
// bottom = advancedCircuit, fluix crystal, advancedCircuit
GameRegistry.addRecipe(new ItemStack(protocolBlock), "coc", "cmc", "cfc",
'm', WarpDriveConfig.getIC2Item("advancedMachine"),
'c', WarpDriveConfig.getIC2Item("advancedCircuit"),
'o', floppy,
'f', fluixCrystal);
// top = Iridium plate, Resonant Energycell, Iridium plate
// middle = Singularity, 125 milligram antimatter, Singularity
// bottom = Iridium plate, Ultimate lappack, Iridium plate
GameRegistry.addRecipe(new ItemStack(powerReactorBlock), "iri", "sas", "ili",
'i', WarpDriveConfig.getIC2Item("iridiumPlate"),
's', quantumEntangledSingularity,
'a', antimatter,
'l', ultimateLappack,
'r', resonantEnergycell);
// top = Advanced circuit, Advanced alloy, Advanced alloy
// middle = Advanced circuit, Warp drive laser, Vibrant quartz glass
// bottom = Advanced circuit, Certus quartz tank, Advanced alloy
ItemStack isMiningLaserBlock = new ItemStack(miningLaserBlock.blockID, 1, 0);
ItemStack isCertusQuartzTank = new ItemStack(WarpDriveConfig.AEExtra_certusQuartzTank.blockID, 1, 0);
GameRegistry.addRecipe(new ItemStack(powerLaserBlock), "caa", "czg", "cta",
'c', WarpDriveConfig.getIC2Item("advancedCircuit"),
'a', WarpDriveConfig.getIC2Item("advancedAlloy"),
'z', isMiningLaserBlock,
't', isCertusQuartzTank,
'g', vibrantQuartzGlass);
}
private static void initIC2Recipes() {
GameRegistry.addRecipe(new ItemStack(warpCore), "ici", "cmc", "ici",
'i', WarpDriveConfig.getIC2Item("iridiumPlate"),
'm', WarpDriveConfig.getIC2Item("advancedMachine"),
'c', WarpDriveConfig.getIC2Item("advancedCircuit"));
GameRegistry.addRecipe(new ItemStack(protocolBlock), "iic", "imi", "cii",
'i', WarpDriveConfig.getIC2Item("iridiumPlate"),
'm', WarpDriveConfig.getIC2Item("advancedMachine"),
'c', WarpDriveConfig.getIC2Item("advancedCircuit"));
GameRegistry.addRecipe(new ItemStack(radarBlock), "ifi", "imi", "imi",
'i', WarpDriveConfig.getIC2Item("iridiumPlate"),
'm', WarpDriveConfig.getIC2Item("advancedMachine"),
'f', WarpDriveConfig.getIC2Item("frequencyTransmitter"));
GameRegistry.addRecipe(new ItemStack(isolationBlock), "iii", "idi", "iii",
'i', WarpDriveConfig.getIC2Item("iridiumPlate"),
'm', WarpDriveConfig.getIC2Item("advancedMachine"),
'd', Block.blockDiamond);
GameRegistry.addRecipe(new ItemStack(airgenBlock), "lcl", "lml", "lll",
'l', Block.leaves,
'm', WarpDriveConfig.getIC2Item("advancedMachine"),
'c', WarpDriveConfig.getIC2Item("advancedCircuit"));
GameRegistry.addRecipe(new ItemStack(laserBlock), "sss", "ama", "aaa",
'm', WarpDriveConfig.getIC2Item("advancedMachine"),
'a', WarpDriveConfig.getIC2Item("advancedAlloy"),
's', WarpDriveConfig.getIC2Item("advancedCircuit"));
GameRegistry.addRecipe(new ItemStack(miningLaserBlock), "aaa", "ama", "ccc",
'c', WarpDriveConfig.getIC2Item("advancedCircuit"),
'a', WarpDriveConfig.getIC2Item("advancedAlloy"),
'm', WarpDriveConfig.getIC2Item("miner"));
GameRegistry.addRecipe(new ItemStack(boosterBlock), "afc", "ama", "cfa",
'c', WarpDriveConfig.getIC2Item("advancedCircuit"),
'a', WarpDriveConfig.getIC2Item("advancedAlloy"),
'f', WarpDriveConfig.getIC2Item("glassFiberCableItem"),
'm', WarpDriveConfig.getIC2Item("mfeUnit"));
GameRegistry.addRecipe(new ItemStack(liftBlock), "aca", "ama", "a#a",
'c', WarpDriveConfig.getIC2Item("advancedCircuit"),
'a', WarpDriveConfig.getIC2Item("advancedAlloy"),
'm', WarpDriveConfig.getIC2Item("magnetizer"));
GameRegistry.addRecipe(new ItemStack(iridiumBlock), "iii", "iii", "iii",
'i', WarpDriveConfig.getIC2Item("iridiumPlate"));
GameRegistry.addShapelessRecipe(
new ItemStack(WarpDriveConfig.getIC2Item("iridiumPlate").getItem(), 9),
new ItemStack(iridiumBlock));
GameRegistry.addRecipe(new ItemStack(laserCamBlock), "imi", "cec", "#k#",
'i', WarpDriveConfig.getIC2Item("iridiumPlate"),
'm', WarpDriveConfig.getIC2Item("advancedMachine"),
'c', WarpDriveConfig.getIC2Item("advancedCircuit"),
'e', laserBlock,
'k', cameraBlock);
GameRegistry.addRecipe(new ItemStack(cameraBlock), "cgc", "gmg", "cgc",
'm', WarpDriveConfig.getIC2Item("advancedMachine"),
'c', WarpDriveConfig.getIC2Item("advancedCircuit"),
'g', Block.glass);
GameRegistry.addRecipe(new ItemStack(monitorBlock), "gcg", "gmg", "ggg",
'm', WarpDriveConfig.getIC2Item("advancedMachine"),
'c', WarpDriveConfig.getIC2Item("advancedCircuit"),
'g', Block.glass);
GameRegistry.addRecipe(new ItemStack(scannerBlock), "sgs", "mma", "amm",
'm', WarpDriveConfig.getIC2Item("advancedMachine"),
'a', WarpDriveConfig.getIC2Item("advancedAlloy"),
's', WarpDriveConfig.getIC2Item("advancedCircuit"),
'g', Block.glass);
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(laserTreeFarmBlock),false,new Object[] {
"cwc", "wmw", "cwc",
'c', WarpDriveConfig.getIC2Item("electronicCircuit"),
'w', "logWood",
'm', miningLaserBlock }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(transporterBlock), false, new Object[] {
"ece", "imi", "iei",
'e', Item.enderPearl,
'c', WarpDriveConfig.getIC2Item("electronicCircuit"),
'i', WarpDriveConfig.getIC2Item("plateiron"),
'm', WarpDriveConfig.getIC2Item("machine") }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(reactorLaserFocusItem),false,new Object[] {
" p ", "pdp", " p ",
'p', WarpDriveConfig.getIC2Item("plateiron"),
'd', "gemDiamond"}));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(reactorMonitorBlock), false, new Object[] {
"pdp", "dmd", "pdp",
'p', WarpDriveConfig.getIC2Item("plateiron"),
'd', "gemDiamond",
'm', WarpDriveConfig.getIC2Item("mfeUnit")}));
GameRegistry.addRecipe(new ItemStack(cloakBlock), "imi", "mcm", "imi",
'i', iridiumBlock,
'c', cloakCoilBlock,
'm', WarpDriveConfig.getIC2Item("advancedMachine"));
GameRegistry.addRecipe(new ItemStack(cloakCoilBlock), "iai", "aca", "iai",
'i', WarpDriveConfig.getIC2Item("iridiumPlate"),
'c', WarpDriveConfig.getIC2Item("advancedCircuit"),
'a', WarpDriveConfig.getIC2Item("advancedAlloy"));
}
private static void registerSpaceDimension() {
spaceBiome = (new BiomeSpace(24))
.setColor(0)
.setDisableRain()
.setBiomeName("Space");
DimensionManager.registerProviderType(WarpDriveConfig.G_SPACE_PROVIDER_ID, SpaceProvider.class, true);
DimensionManager.registerDimension(WarpDriveConfig.G_SPACE_DIMENSION_ID, WarpDriveConfig.G_SPACE_PROVIDER_ID);
}
private static void registerHyperSpaceDimension() {
DimensionManager.registerProviderType(WarpDriveConfig.G_HYPERSPACE_PROVIDER_ID, HyperSpaceProvider.class, true);
DimensionManager.registerDimension(WarpDriveConfig.G_HYPERSPACE_DIMENSION_ID, WarpDriveConfig.G_HYPERSPACE_PROVIDER_ID);
}
@EventHandler
public void serverLoad(FMLServerStartingEvent event) {
cloaks = new CloakManager();
MinecraftForge.EVENT_BUS.register(new CloakChunkWatcher());
event.registerServerCommand(new GenerateCommand());
event.registerServerCommand(new SpaceTpCommand());
event.registerServerCommand(new InvisibleCommand());
event.registerServerCommand(new JumpgateCommand());
event.registerServerCommand(new DebugCommand());
}
public Ticket registerChunkLoadTE(WarpChunkTE te, boolean refreshLoading) {
World worldObj = te.worldObj;
if (ForgeChunkManager.ticketCountAvailableFor(this, worldObj) > 0)
{
Ticket t = ForgeChunkManager.requestTicket(this, worldObj, Type.NORMAL);
if (t != null) {
te.giveTicket(t); // FIXME calling the caller is a bad idea
if(refreshLoading)
te.refreshLoading();
return t;
}
else
{
WarpDrive.debugPrint("Ticket not granted");
}
}
else
{
WarpDrive.debugPrint("No tickets left!");
}
return null;
}
public Ticket registerChunkLoadTE(WarpChunkTE te)
{
return registerChunkLoadTE(te, true);
}
public Ticket getTicket(WarpChunkTE te)
{
return registerChunkLoadTE(te, false);
}
@Override
public void ticketsLoaded(List<Ticket> tickets, World world)
{
for (Ticket ticket : tickets)
{
NBTTagCompound data = ticket.getModData();
if(data != null)
{
int w = data.getInteger("ticketWorldObj");
int x = data.getInteger("ticketX");
int y = data.getInteger("ticketY");
int z = data.getInteger("ticketZ");
if(w != 0 || x != 0 || y != 0 || z != 0)
{
WorldServer ws = DimensionManager.getWorld(w);
if(ws != null)
{
TileEntity te = ws.getBlockTileEntity(x, y, z);
if(te != null && te instanceof WarpChunkTE)
{
if(((WarpChunkTE)te).shouldChunkLoad())
{
WarpDrive.debugPrint("[TicketCallback] Regiving Ticket!");
((WarpChunkTE)te).giveTicket(ticket);
((WarpChunkTE)te).refreshLoading(true);
return;
}
}
}
}
}
ForgeChunkManager.releaseTicket(ticket);
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,98 @@
package cr0s.WarpDrive.block;
import java.util.List;
import cpw.mods.fml.common.registry.GameRegistry;
import cr0s.WarpDrive.WarpDrive;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.ItemStack;
import net.minecraft.util.Icon;
import net.minecraftforge.oredict.ShapedOreRecipe;
public class BlockDecorative extends Block
{
public static enum decorativeTypes { Plain , Energized , Network };
private ItemStack[] isCache = new ItemStack[decorativeTypes.values().length];
private Icon[] iconBuffer = new Icon[decorativeTypes.values().length];
public BlockDecorative(int par1)
{
super(par1, Material.iron);
setHardness(0.5f);
setStepSound(Block.soundMetalFootstep);
setCreativeTab(WarpDrive.warpdriveTab);
}
public boolean isValidDamage(int damage)
{
return damage >= 0 && damage < decorativeTypes.values().length;
}
@Override
public void getSubBlocks(int par1, CreativeTabs par2CreativeTabs, List par3List)
{
for(decorativeTypes val: decorativeTypes.values())
par3List.add(new ItemStack(par1, 1, val.ordinal()));
}
@Override
public void registerIcons(IconRegister ir)
{
for(decorativeTypes val: decorativeTypes.values())
iconBuffer[val.ordinal()] = ir.registerIcon("warpdrive:decorative" + val.toString());
}
@Override
public Icon getIcon(int side, int damage)
{
if(isValidDamage(damage))
return iconBuffer[damage];
return iconBuffer[0];
}
@Override
public int damageDropped(int damage)
{
return damage;
}
public ItemStack getIS(int damage)
{
if(!isValidDamage(damage))
return null;
if(isCache[damage] == null)
isCache[damage] = getISNoCache(damage);
return isCache[damage];
}
public ItemStack getISNoCache(int damage, int amount)
{
if(!isValidDamage(damage))
return null;
return new ItemStack(WarpDrive.decorativeBlock,amount,damage);
}
public ItemStack getISNoCache(int damage)
{
return getISNoCache(damage,1);
}
public void initRecipes()
{
GameRegistry.addRecipe(new ShapedOreRecipe(getISNoCache(0,8),false, "sss","scs","sss",
's', Block.stone,
'c', WarpDrive.componentItem.getIS(0)));
GameRegistry.addRecipe(new ShapedOreRecipe(getISNoCache(2,8),false, "sss","scs","sss",
's', getIS(0),
'c', WarpDrive.componentItem.getIS(5)));
}
}

View file

@ -0,0 +1,57 @@
package cr0s.WarpDrive.block;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import cr0s.WarpDrive.WarpDrive;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
public class BlockTransportBeacon extends Block {
public BlockTransportBeacon(int par1) {
super(par1, Material.iron);
setHardness(0.5F);
setStepSound(Block.soundMetalFootstep);
setCreativeTab(WarpDrive.warpdriveTab);
setUnlocalizedName("warpdrive.blocks.transportBeacon");
}
@Override
public AxisAlignedBB getCollisionBoundingBoxFromPool(World par1World, int par2, int par3, int par4) {
return null;
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IconRegister par1IconRegister) {
this.blockIcon = par1IconRegister.registerIcon("warpdrive:transportBeacon");
}
@Override
public boolean isOpaqueCube() {
return false;
}
@Override
public boolean renderAsNormalBlock() {
return false;
}
@Override
public int getRenderType() {
return 2;
}
@Override
public MovingObjectPosition collisionRayTrace(World par1World, int par2, int par3, int par4, Vec3 par5Vec3, Vec3 par6Vec3) {
float f = 0.065F;
this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 0.6F, 0.5F + f);
return super.collisionRayTrace(par1World, par2, par3, par4, par5Vec3, par6Vec3);
}
}

View file

@ -0,0 +1,40 @@
package cr0s.WarpDrive.block;
import java.util.List;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
public class ItemBlockDecorative extends ItemBlock
{
public ItemBlockDecorative(int par1)
{
super(par1);
setHasSubtypes(true);
setUnlocalizedName("warpdrive.block.decorative");
}
@Override
public int getMetadata (int damage)
{
return damage;
}
@Override
public void getSubItems(int par1, CreativeTabs par2CreativeTabs, List par3List)
{
for(int i = 0; i < BlockDecorative.decorativeTypes.values().length;i++)
par3List.add(new ItemStack(par1,1,i));
}
@Override
public String getUnlocalizedName(ItemStack itemstack)
{
if(itemstack == null)
return getUnlocalizedName();
return "tile.warpdrive.decorative." + BlockDecorative.decorativeTypes.values()[itemstack.getItemDamage()].toString();
}
}

View file

@ -0,0 +1,151 @@
package cr0s.WarpDrive.command;
import cpw.mods.fml.common.FMLCommonHandler;
import cr0s.WarpDrive.WarpDriveConfig;
import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraftforge.common.DimensionManager;
/*
* /wdebug <dimension> <coordinates> <blockId> <Metadata> <actions>
*/
public class DebugCommand extends CommandBase
{
@Override
public String getCommandName()
{
return "wdebug";
}
@Override
public int getRequiredPermissionLevel()
{
return 2;
}
@Override
public String getCommandUsage(ICommandSender par1ICommandSender)
{
return "/" + getCommandName() + " <dimension> <x> <y> <z> <blockId> <Metadata> <action><action>...\n"
+ "dimension: 0/world, 2/space, 3/hyperspace\n"
+ "coordinates: x,y,z\n"
+ "action: I(nvalidate), V(alidate), A(set air), R(emoveEntity), P(setBlock), S(etEntity)";
}
@Override
public void processCommand(ICommandSender icommandsender, String[] params)
{
EntityPlayerMP player = (EntityPlayerMP)icommandsender;
if(params.length > 6 )
{
int dim, x, y, z, blockId, metadata;
String actions;
try
{
String par = params[0].toLowerCase();
if (par.equals("world") || par.equals("overworld") || par.equals("0"))
{
dim = 0;
}
else if (par.equals("nether") || par.equals("thenether") || par.equals("-1"))
{
dim = -1;
}
else if (par.equals("s") || par.equals("space"))
{
dim = WarpDriveConfig.G_SPACE_DIMENSION_ID;
}
else if (par.equals("h") || par.equals("hyper") || par.equals("hyperspace"))
{
dim = WarpDriveConfig.G_HYPERSPACE_DIMENSION_ID;
}
else
{
dim = Integer.parseInt(par);
}
x = Integer.parseInt(params[1]);
y = Integer.parseInt(params[2]);
z = Integer.parseInt(params[3]);
blockId = Integer.parseInt(params[4]);
metadata = Integer.parseInt(params[5]);
actions = params[6];
}
catch (Exception e)
{
e.printStackTrace();
player.addChatMessage(getCommandUsage(icommandsender));
return;
}
notifyAdmins(icommandsender, "/" + getCommandName() + " " + dim + " " + x + "," + y + "," + z + " " + blockId + ":" + metadata + " " + actions);
World worldObj = DimensionManager.getWorld(dim);
TileEntity te = worldObj.getBlockTileEntity(x, y, z);
notifyAdmins(icommandsender, "[" + getCommandName() + "] In dimension " + worldObj.getProviderName() + " - " + worldObj.getWorldInfo().getWorldName() + ", Current block is " + worldObj.getBlockId(x, y, z) + ":" + worldObj.getBlockMetadata(x, y, z) + ", tile entity is " + ((te == null) ? "undefined" : "defined"));
String side = FMLCommonHandler.instance().getEffectiveSide().isClient() ? "Client":"Server";
// I(nvalidate), V(alidate), A(set air), R(emoveEntity), P(setBlock), S(etEntity)
boolean bReturn = false;
for (char ch: actions.toUpperCase().toCharArray()) {
switch (ch) {
case 'I':
notifyAdmins(icommandsender, "[" + getCommandName() + "] " + side + ": invalidating");
if (te != null) {
te.invalidate();
}
break;
case 'V':
notifyAdmins(icommandsender, "[" + getCommandName() + "] " + side + ": validating");
if (te != null) {
te.validate();
}
break;
case 'A':
notifyAdmins(icommandsender, "[" + getCommandName() + "] " + side + ": setting to Air");
bReturn = worldObj.setBlockToAir(x, y, z);
notifyAdmins(icommandsender, "[" + getCommandName() + "] " + side + ": returned " + bReturn);
break;
case 'R':
notifyAdmins(icommandsender, "[" + getCommandName() + "] " + side + ": remove entity");
worldObj.removeBlockTileEntity(x, y, z);
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
notifyAdmins(icommandsender, "[" + getCommandName() + "] " + side + ": set block " + x + ", " + y + ", " + z + " to " + blockId + ":" + metadata);
bReturn = worldObj.setBlock(x, y, z, blockId, metadata, ch - '0');
notifyAdmins(icommandsender, "[" + getCommandName() + "] " + side + ": returned " + bReturn);
break;
case 'P':
notifyAdmins(icommandsender, "[" + getCommandName() + "] " + side + ": set block " + x + ", " + y + ", " + z + " to " + blockId + ":" + metadata);
bReturn = worldObj.setBlock(x, y, z, blockId, metadata, 2);
notifyAdmins(icommandsender, "[" + getCommandName() + "] " + side + ": returned " + bReturn);
break;
case 'S':
notifyAdmins(icommandsender, "[" + getCommandName() + "] " + side + ": set entity");
worldObj.setBlockTileEntity(x, y, z, te);
break;
case 'C':
notifyAdmins(icommandsender, "[" + getCommandName() + "] " + side + ": update containing block info");
if (te != null) {
te.updateContainingBlockInfo();
}
break;
}
}
}
else
{
player.addChatMessage(getCommandUsage(icommandsender));
}
}
}

View file

@ -0,0 +1,137 @@
package cr0s.WarpDrive.item;
import java.util.List;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import cr0s.WarpDrive.WarpDrive;
import cr0s.WarpDrive.data.EnumUpgradeTypes;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.Icon;
import net.minecraftforge.oredict.ShapedOreRecipe;
public class ItemWarpUpgrade extends Item
{
private ItemStack[] isCache = new ItemStack[EnumUpgradeTypes.values().length];
private Icon[] iconBuffer = new Icon[EnumUpgradeTypes.values().length];
public ItemWarpUpgrade(int par1)
{
super(par1);
setHasSubtypes(true);
setUnlocalizedName("warpdrive.upgrade.Malformed");
setCreativeTab(WarpDrive.warpdriveTab);
}
private boolean isValidDamage(int damage)
{
return damage >= 0 && damage < EnumUpgradeTypes.values().length;
}
public ItemStack getIS(int damage)
{
if(!isValidDamage(damage))
return null;
if(isCache[damage] == null)
isCache[damage] = getISNoCache(damage);
return isCache[damage];
}
public ItemStack getISNoCache(int damage)
{
if(!isValidDamage(damage))
return null;
return new ItemStack(WarpDrive.upgradeItem,1,damage);
}
@Override
public String getUnlocalizedName(ItemStack is)
{
if(is == null)
return null;
int damage = is.getItemDamage();
if(isValidDamage(damage))
return "item.warpdrive.upgrade." + EnumUpgradeTypes.values()[damage].toString();
return null;
}
@Override
@SideOnly(Side.CLIENT)
public void getSubItems(int par1, CreativeTabs par2CreativeTabs, List par3List)
{
for(int i=0;i<EnumUpgradeTypes.values().length;i++)
par3List.add(getIS(i));
}
@Override
public void addInformation(ItemStack is, EntityPlayer pl, List list, boolean par4)
{
if(is == null)
return;
int damage = is.getItemDamage();
if(damage == EnumUpgradeTypes.Energy.ordinal())
list.add("Increases the max energy of the machine");
else if(damage == EnumUpgradeTypes.Power.ordinal())
list.add( "Decreases the power usage of the machine");
else if(damage == EnumUpgradeTypes.Speed.ordinal())
list.add( "Increases the speed of the machine");
else if(damage == EnumUpgradeTypes.Range.ordinal())
list.add( "Increases the range of the machine");
}
public void initRecipes()
{
GameRegistry.addRecipe(new ShapedOreRecipe(getIS(EnumUpgradeTypes.Energy.ordinal()),false,"c","e","r",
'c', WarpDrive.componentItem.getIS(0),
'e', WarpDrive.componentItem.getIS(7),
'r', Item.redstone));
GameRegistry.addRecipe(new ShapedOreRecipe(getIS(EnumUpgradeTypes.Power.ordinal()),false,"c","e","r",
'c', WarpDrive.componentItem.getIS(0),
'e', WarpDrive.componentItem.getIS(6),
'r', Item.redstone));
GameRegistry.addRecipe(new ShapedOreRecipe(getIS(EnumUpgradeTypes.Speed.ordinal()),false,"c","e","r",
'c', WarpDrive.componentItem.getIS(0),
'e', Item.sugar,
'r', Item.redstone));
GameRegistry.addRecipe(new ShapedOreRecipe(getIS(EnumUpgradeTypes.Range.ordinal()),false,"c","e","r",
'c', WarpDrive.componentItem.getIS(0),
'e', WarpDrive.transportBeaconBlock,
'r', Item.redstone));
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IconRegister ir)
{
for(EnumUpgradeTypes val : EnumUpgradeTypes.values())
{
iconBuffer[val.ordinal()] = ir.registerIcon("warpdrive:upgrade" + val.toString());
}
}
@Override
@SideOnly(Side.CLIENT)
public Icon getIconFromDamage(int damage)
{
if(damage >= 0 && damage < EnumUpgradeTypes.values().length)
return iconBuffer[damage];
return iconBuffer[0];
}
}

View file

@ -0,0 +1,37 @@
package cr0s.WarpDrive.machines;
import cr0s.WarpDrive.machines.WarpBlockContainer;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Icon;
import net.minecraft.world.World;
public class BlockChunkLoader extends WarpBlockContainer
{
Icon iconBuffer;
public BlockChunkLoader(int par1)
{
super(par1);
setUnlocalizedName("warpdrive.machines.ChunkLoader");
}
@Override
public TileEntity createNewTileEntity(World world)
{
return new TileEntityChunkLoader();
}
@Override
public void registerIcons(IconRegister ir)
{
iconBuffer = ir.registerIcon("warpdrive:chunkLoader");
}
@Override
public Icon getIcon(int side, int damage)
{
return iconBuffer;
}
}

View file

@ -0,0 +1,38 @@
package cr0s.WarpDrive.machines;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import cr0s.WarpDrive.WarpDrive;
public class BlockLaserReactorMonitor extends BlockContainer {
public BlockLaserReactorMonitor(int id, int texture, Material material) {
super(id, material);
setHardness(0.5F);
setStepSound(Block.soundMetalFootstep);
setCreativeTab(WarpDrive.warpdriveTab);
setUnlocalizedName("warpdrive.machines.LaserReactorMonitor");
}
public BlockLaserReactorMonitor(int id, Material material) {
this(id, 0, material);
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IconRegister par1IconRegister) {
// Solid textures
blockIcon = par1IconRegister.registerIcon("warpdrive:reactorMonitor");
}
@Override
public TileEntity createNewTileEntity(World var1) {
return new TileEntityLaserReactorMonitor();
}
}

View file

@ -0,0 +1,66 @@
package cr0s.WarpDrive.machines;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import cr0s.WarpDrive.WarpDrive;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Icon;
import net.minecraft.world.World;
public class BlockLaserTreeFarm extends BlockContainer {
private Icon[] iconBuffer;
public BlockLaserTreeFarm(int id, int texture, Material material) {
super(id, material);
setHardness(0.5F);
setStepSound(Block.soundMetalFootstep);
setCreativeTab(WarpDrive.warpdriveTab);
setUnlocalizedName("warpdrive.machines.LaserTreeFarm");
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IconRegister par1IconRegister) {
iconBuffer = new Icon[2];
// Solid textures
iconBuffer[0] = par1IconRegister.registerIcon("warpdrive:particleBoosterTopBottom");
iconBuffer[1] = par1IconRegister.registerIcon("warpdrive:laserTreeFarmSide0");
}
@Override
public Icon getIcon(int side, int metadata) {
if (side == 0 || side == 1) {
return iconBuffer[0];
}
return iconBuffer[1];
}
@Override
public TileEntity createNewTileEntity(World var1) {
return new TileEntityLaserTreeFarm();
}
/**
* Returns the quantity of items to drop on block destruction.
*/
@Override
public int quantityDropped(Random par1Random) {
return 1;
}
/**
* Returns the ID of the items to drop on destruction.
*/
@Override
public int idDropped(int par1, Random par2Random, int par3) {
return this.blockID;
}
}

View file

@ -0,0 +1,63 @@
package cr0s.WarpDrive.machines;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Icon;
import net.minecraft.world.World;
public class BlockPowerLaser extends WarpBlockContainer {
static Icon[] iconBuffer = new Icon[16];
public BlockPowerLaser(int id) {
super(id);
setUnlocalizedName("warpdrive.power.Laser");
setResistance(100.0F);
}
@Override
public TileEntity createNewTileEntity(World world) {
return new TileEntityPowerLaser();
}
private static boolean isActive(int side, int meta) {
if (side == 3 && meta == 1) {
return true;
}
if (side == 2 && meta == 2) {
return true;
}
if (side == 4 && meta == 4) {
return true;
}
if (side == 5 && meta == 3) {
return true;
}
return false;
}
@Override
@SideOnly(Side.CLIENT)
public Icon getIcon(int side, int meta) {
if (side == 0 || side == 1) {
return iconBuffer[0];
}
if(isActive(side,meta)) {
return iconBuffer[2];
}
return iconBuffer[1];
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IconRegister par1IconRegister) {
iconBuffer[0] = par1IconRegister.registerIcon("warpdrive:powerLaserTopBottom");
iconBuffer[1] = par1IconRegister.registerIcon("warpdrive:powerLaserSides");
iconBuffer[2] = par1IconRegister.registerIcon("warpdrive:powerLaserActive");
}
}

View file

@ -0,0 +1,70 @@
package cr0s.WarpDrive.machines;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Icon;
import net.minecraft.world.World;
public class BlockPowerReactor extends WarpBlockContainer {
Icon[] iconBuffer = new Icon[17];
public BlockPowerReactor(int id) {
super(id);
setUnlocalizedName("warpdrive.power.Reactor");
}
@Override
public TileEntity createNewTileEntity(World world) {
return new TileEntityPowerReactor();
}
@Override
public void breakBlock(World w,int x,int y,int z, int oid,int om) {
super.breakBlock(w, x, y, z, oid, om);
int[] xo = {-2, 2, 0, 0};
int[] zo = { 0, 0,-2, 2};
for(int i = 0; i < 4; i++) {
TileEntity te = w.getBlockTileEntity(x+xo[i], y, z+zo[i]);
if(te instanceof TileEntityPowerLaser) {
((TileEntityPowerLaser)te).unlink();
}
}
}
@Override
@SideOnly(Side.CLIENT)
public Icon getIcon(int side, int meta) {
if (side == 0 || side == 1) {
return iconBuffer[16];
}
if (meta >= 0 && meta < 16) {
return iconBuffer[meta];
}
return iconBuffer[0];
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IconRegister par1IconRegister) {
iconBuffer[16] = par1IconRegister.registerIcon("warpdrive:reactorTB");
iconBuffer[0] = par1IconRegister.registerIcon("warpdrive:reactorSide00");
iconBuffer[1] = par1IconRegister.registerIcon("warpdrive:reactorSide01");
iconBuffer[2] = par1IconRegister.registerIcon("warpdrive:reactorSide02");
iconBuffer[3] = par1IconRegister.registerIcon("warpdrive:reactorSide03");
iconBuffer[4] = par1IconRegister.registerIcon("warpdrive:reactorSide10");
iconBuffer[5] = par1IconRegister.registerIcon("warpdrive:reactorSide11");
iconBuffer[6] = par1IconRegister.registerIcon("warpdrive:reactorSide12");
iconBuffer[7] = par1IconRegister.registerIcon("warpdrive:reactorSide13");
iconBuffer[8] = par1IconRegister.registerIcon("warpdrive:reactorSide20");
iconBuffer[9] = par1IconRegister.registerIcon("warpdrive:reactorSide21");
iconBuffer[10] = par1IconRegister.registerIcon("warpdrive:reactorSide22");
iconBuffer[11] = par1IconRegister.registerIcon("warpdrive:reactorSide23");
iconBuffer[12] = par1IconRegister.registerIcon("warpdrive:reactorSide30");
iconBuffer[13] = par1IconRegister.registerIcon("warpdrive:reactorSide31");
iconBuffer[14] = par1IconRegister.registerIcon("warpdrive:reactorSide32");
iconBuffer[15] = par1IconRegister.registerIcon("warpdrive:reactorSide33");
}
}

View file

@ -0,0 +1,54 @@
package cr0s.WarpDrive.machines;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Icon;
import net.minecraft.world.World;
public class BlockPowerStore extends WarpBlockContainer {
private Icon iconBuffer;
public BlockPowerStore(int par1) {
super(par1);
setUnlocalizedName("warpdrive.power.Store");
}
@Override
public TileEntity createNewTileEntity(World world) {
return new TileEntityPowerStore();
}
@Override
@SideOnly(Side.CLIENT)
public Icon getIcon(int side, int meta) {
return iconBuffer;
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IconRegister par1IconRegister) {
iconBuffer = par1IconRegister.registerIcon("warpdrive:powerStore");
}
/**
* Called upon block activation (right click on the block.)
*/
@Override
public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) {
if (FMLCommonHandler.instance().getEffectiveSide().isClient()) {
return false;
}
WarpEnergyTE te = (WarpEnergyTE)par1World.getBlockTileEntity(par2, par3, par4);
if (te != null && (par5EntityPlayer.getHeldItem() == null)) {
par5EntityPlayer.addChatMessage(te.getStatus());
return true;
}
return false;
}
}

View file

@ -0,0 +1,47 @@
package cr0s.WarpDrive.machines;
import java.util.Random;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import cr0s.WarpDrive.WarpDrive;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Icon;
import net.minecraft.world.World;
public class BlockTransporter extends WarpBlockContainer {
private Icon[] iconBuffer;
public BlockTransporter(int par1, Material par2Material) {
super(par1, par2Material);
setUnlocalizedName("warpdrive.machines.Transporter");
}
@Override
public TileEntity createNewTileEntity(World world) {
return new TileEntityTransporter();
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IconRegister par1IconRegister) {
iconBuffer = new Icon[3];
// Solid textures
iconBuffer[0] = par1IconRegister.registerIcon("warpdrive:transporterBottom");
iconBuffer[1] = par1IconRegister.registerIcon("warpdrive:transporterTop");
iconBuffer[2] = par1IconRegister.registerIcon("warpdrive:transporterSide");
}
@Override
public Icon getIcon(int side, int metadata) {
if (side == 0 || side == 1) {
return iconBuffer[side];
}
return iconBuffer[2];
}
}

View file

@ -0,0 +1,8 @@
package cr0s.WarpDrive.machines;
public abstract class TileEntityAbstractLaser extends WarpChunkTE
{
}

View file

@ -0,0 +1,540 @@
package cr0s.WarpDrive.machines;
import java.util.ArrayList;
import java.util.List;
import appeng.api.IAEItemStack;
import appeng.api.Util;
import appeng.api.WorldCoord;
import appeng.api.events.GridTileLoadEvent;
import appeng.api.events.GridTileUnloadEvent;
import appeng.api.me.tiles.IGridMachine;
import appeng.api.me.tiles.ITileCable;
import appeng.api.me.util.IGridInterface;
import appeng.api.me.util.IMEInventoryHandler;
import net.minecraft.block.Block;
import net.minecraft.block.BlockFluid;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.ChunkCoordIntPair;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import cr0s.WarpDrive.data.Vector3;
import cr0s.WarpDrive.PacketHandler;
import cr0s.WarpDrive.WarpDrive;
import cr0s.WarpDrive.WarpDriveConfig;
public abstract class TileEntityAbstractMiner extends TileEntityAbstractLaser implements IGridMachine, ITileCable
{
//FOR STORAGE
private boolean silkTouch = false;
private int fortuneLevel = 0;
private TileEntityParticleBooster booster = null;
private Vector3 minerVector;
Boolean powerStatus = false;
private IGridInterface grid;
private boolean isMEReady = false;
abstract boolean canSilkTouch();
abstract int minFortune();
abstract int maxFortune();
abstract double laserBelow();
abstract float getColorR();
abstract float getColorG();
abstract float getColorB();
public TileEntityAbstractMiner()
{
super();
fixMinerVector();
}
private void fixMinerVector()
{
if(minerVector == null)
minerVector = new Vector3(xCoord,yCoord-laserBelow(),zCoord);
minerVector.x = xCoord;
minerVector.y = yCoord - (laserBelow());
minerVector.z = zCoord;
minerVector.translate(0.5);
}
private List<ItemStack> getItemStackFromBlock(int i, int j, int k, int blockID, int blockMeta)
{
Block block = Block.blocksList[blockID];
if (block == null)
return null;
if (silkTouch(blockID))
{
if (block.canSilkHarvest(worldObj, null, i, j, k, blockMeta))
{
ArrayList<ItemStack> t = new ArrayList<ItemStack>();
t.add(new ItemStack(blockID, 1, blockMeta));
return t;
}
}
return block.getBlockDropped(worldObj, i, j, k, blockMeta, fortuneLevel);
}
protected boolean isOnEarth()
{
return worldObj.provider.dimensionId == 0;
}
private IInventory findChest() {
TileEntity result = null;
for(int i = 0; i < 6; i++) {
Vector3 sideOffset = adjacentSideOffsets[i];
result = worldObj.getBlockTileEntity(xCoord + sideOffset.intX(), yCoord + sideOffset.intY(), zCoord + sideOffset.intZ());
if (result != null && !(result instanceof TileEntityAbstractMiner) && (result instanceof IInventory)) {
return (IInventory) result;
}
}
return null;
}
//GETTERSETTERS
protected int fortune()
{
return fortuneLevel;
}
protected boolean silkTouch()
{
return silkTouch;
}
protected boolean silkTouch(int blockID)
{
return silkTouch();
}
protected boolean silkTouch(boolean b)
{
silkTouch = canSilkTouch() && b;
return silkTouch();
}
protected boolean silkTouch(Object o)
{
return silkTouch(toBool(o));
}
protected int fortune(int f)
{
try
{
fortuneLevel = clamp(f,minFortune(),maxFortune());
}
catch(NumberFormatException e)
{
fortuneLevel = minFortune();
}
return fortune();
}
protected TileEntityParticleBooster booster()
{
if(booster == null)
findFirstBooster();
return booster;
}
protected int energy() {
TileEntityParticleBooster te = booster();
if (te != null) {
return te.getEnergyStored();
}
return 0;
}
//DATA RET
protected int calculateLayerCost()
{
return isOnEarth() ? WarpDriveConfig.ML_EU_PER_LAYER_EARTH : WarpDriveConfig.ML_EU_PER_LAYER_SPACE;
}
protected int calculateBlockCost()
{
return calculateBlockCost(0);
}
protected int calculateBlockCost(int blockID)
{
int enPerBlock = isOnEarth() ? WarpDriveConfig.ML_EU_PER_BLOCK_EARTH : WarpDriveConfig.ML_EU_PER_BLOCK_SPACE;
if(silkTouch(blockID))
return (int) Math.round(enPerBlock * WarpDriveConfig.ML_EU_MUL_SILKTOUCH);
return (int) Math.round(enPerBlock * (Math.pow(WarpDriveConfig.ML_EU_MUL_FORTUNE, fortune())));
}
protected boolean isRoomForHarvest()
{
if(isMEReady && grid != null)
return true;
IInventory inv = findChest();
if(inv != null)
{
int size = inv.getSizeInventory();
for(int i=0;i<size;i++)
if(inv.getStackInSlot(i) == null)
return true;
}
return false;
}
private boolean canDig(int blockID, int x, int y, int z) {// not used
// ignore air & fluids
if (!WarpDriveConfig.isAirBlock(worldObj, blockID, x, y, z) && Block.blocksList[blockID] != null && !(Block.blocksList[blockID] instanceof BlockFluid)) {
return false;
}
// check blacklist
if (blockID == Block.bedrock.blockID) {
return false;
}
if (WarpDriveConfig.forceFieldBlocks.contains(blockID)) {
// isMining = false;
return false;
}
// check whitelist
// WarpDriveConfig.MinerOres.contains(blockID) then true ?
else if (blockID == WarpDriveConfig.GT_Granite || blockID == WarpDriveConfig.GT_Ores || blockID == WarpDriveConfig.iridiumBlockID) {
return true;
}
// check default
else if ( (Block.blocksList[blockID] != null) && (Block.blocksList[blockID].blockResistance <= Block.obsidian.blockResistance) ) {
return true;
}
return false;
}
//MINING FUNCTIONS
protected void laserBlock(Vector3 valuable)
{
fixMinerVector();
float r = getColorR();
float g = getColorG();
float b = getColorB();
PacketHandler.sendBeamPacket(worldObj, minerVector, valuable.clone().translate(0.5D), r, g, b, 2 * WarpDriveConfig.ML_MINE_DELAY_TICKS, 0, 50);
//worldObj.playSoundEffect(xCoord + 0.5f, yCoord, zCoord + 0.5f, "warpdrive:lowlaser", 4F, 1F);
}
private void mineBlock(Vector3 valuable,int blockID, int blockMeta)
{
laserBlock(valuable);
worldObj.playAuxSFXAtEntity(null, 2001, valuable.intX(), valuable.intY(), valuable.intZ(), blockID + (blockMeta << 12));
worldObj.setBlockToAir(valuable.intX(), valuable.intY(), valuable.intZ());
}
protected boolean harvestBlock(Vector3 valuable)
{
int blockID = worldObj.getBlockId(valuable.intX(), valuable.intY(), valuable.intZ());
int blockMeta = worldObj.getBlockMetadata(valuable.intX(), valuable.intY(), valuable.intZ());
if (blockID != Block.waterMoving.blockID && blockID != Block.waterStill.blockID && blockID != Block.lavaMoving.blockID && blockID != Block.lavaStill.blockID)
{
boolean didPlace = true;
List<ItemStack> stacks = getItemStackFromBlock(valuable.intX(), valuable.intY(), valuable.intZ(), blockID, blockMeta);
if (stacks != null)
{
for (ItemStack stack : stacks)
{
didPlace = didPlace && dumpToInv(stack) == stack.stackSize;
}
}
mineBlock(valuable,blockID,blockMeta);
return didPlace;
}
else if (blockID == Block.waterMoving.blockID || blockID == Block.waterStill.blockID)
// Evaporate water
worldObj.playSoundEffect(valuable.intX() + 0.5D, valuable.intY() + 0.5D, valuable.intZ() + 0.5D, "random.fizz", 0.5F, 2.6F + (worldObj.rand.nextFloat() - worldObj.rand.nextFloat()) * 0.8F);
worldObj.setBlockToAir(valuable.intX(), valuable.intY(), valuable.intZ());
return true;
}
protected int dumpToInv(ItemStack item)
{
if (grid != null)
return putInGrid(item);
else
return putInChest(findChest(), item);
}
private int putInGrid(ItemStack itemStackSource)
{
int transferred = 0;
if(isMEReady && grid != null)
{
IMEInventoryHandler cellArray = grid.getCellArray();
if (cellArray != null)
{
IAEItemStack ret = cellArray.addItems(Util.createItemStack(itemStackSource));
if (ret != null)
transferred = (int) ret.getStackSize();
}
}
return transferred;
}
private static int putInChest(IInventory inventory, ItemStack itemStackSource)
{
if (inventory == null || itemStackSource == null)
{
return 0;
}
int transferred = 0;
for (int i = 0; i < inventory.getSizeInventory(); i++)
{
if (!inventory.isItemValidForSlot(i, itemStackSource))
{
continue;
}
ItemStack itemStack = inventory.getStackInSlot(i);
if (itemStack == null || !itemStack.isItemEqual(itemStackSource))
{
continue;
}
int transfer = Math.min(itemStackSource.stackSize - transferred, itemStack.getMaxStackSize() - itemStack.stackSize);
itemStack.stackSize += transfer;
transferred += transfer;
if (transferred == itemStackSource.stackSize)
{
return transferred;
}
}
for (int i = 0; i < inventory.getSizeInventory(); i++)
{
if (!inventory.isItemValidForSlot(i, itemStackSource))
{
continue;
}
ItemStack itemStack = inventory.getStackInSlot(i);
if (itemStack != null)
{
continue;
}
int transfer = Math.min(itemStackSource.stackSize - transferred, itemStackSource.getMaxStackSize());
ItemStack dest = copyWithSize(itemStackSource, transfer);
inventory.setInventorySlotContents(i, dest);
transferred += transfer;
if (transferred == itemStackSource.stackSize)
{
return transferred;
}
}
return transferred;
}
protected boolean consumeEnergyFromBooster(int requiredEnergy, boolean simulate)
{
TileEntityParticleBooster te = booster();
if (te != null) {
return te.consumeEnergy(requiredEnergy, simulate);
}
return false;
}
private TileEntityParticleBooster findFirstBooster()
{
TileEntity result;
int[] xPos = {1,-1,0,0,0,0};
int[] yPos = {0,0,-1,1,0,0};
int[] zPos = {0,0,0,0,-1,1};
for(int i=0;i<6;i++)
{
result = worldObj.getBlockTileEntity(xCoord + xPos[i], yCoord + yPos[i], zCoord + zPos[i]);
if (result != null && result instanceof TileEntityParticleBooster)
{
booster = (TileEntityParticleBooster) result;
return (TileEntityParticleBooster) result;
}
}
booster = null;
return null;
}
protected void defineMiningArea(int xSize,int zSize)
{
int xmax, zmax, x1, x2, z1, z2;
int xmin, zmin;
x1 = xCoord + xSize / 2;
x2 = xCoord - xSize / 2;
if (x1 < x2)
{
xmin = x1;
xmax = x2;
}
else
{
xmin = x2;
xmax = x1;
}
z1 = zCoord + zSize / 2;
z2 = zCoord - zSize / 2;
if (z1 < z2)
{
zmin = z1;
zmax = z2;
}
else
{
zmin = z2;
zmax = z1;
}
defineMiningArea(xmin,zmin,xmax,zmax);
}
protected void defineMiningArea(int minX, int minZ, int maxX, int maxZ)
{
if(worldObj == null)
return;
ChunkCoordIntPair a = worldObj.getChunkFromBlockCoords(minX, minZ).getChunkCoordIntPair();
ChunkCoordIntPair b = worldObj.getChunkFromBlockCoords(maxX, maxZ).getChunkCoordIntPair();
if(minChunk != null && a.equals(minChunk))
if(maxChunk != null && b.equals(maxChunk))
return;
if(minChunk != null && b.equals(minChunk))
if(maxChunk != null && a.equals(maxChunk))
return;
minChunk = a;
maxChunk = b;
refreshLoading(true);
}
private static ItemStack copyWithSize(ItemStack itemStack, int newSize)
{
ItemStack ret = itemStack.copy();
ret.stackSize = newSize;
return ret;
}
//NBT DATA
@Override
public void readFromNBT(NBTTagCompound tag)
{
super.readFromNBT(tag);
silkTouch = tag.getBoolean("silkTouch");
fortuneLevel = tag.getInteger("fortuneLevel");
minerVector.x = xCoord;
minerVector.y = yCoord - (laserBelow());
minerVector.z = zCoord;
minerVector = minerVector.translate(0.5);
}
@Override
public void writeToNBT(NBTTagCompound tag)
{
super.writeToNBT(tag);
tag.setBoolean("silkTouch", silkTouch);
tag.setInteger("fortuneLevel", fortuneLevel);
}
//AE INTERFACE
@Override
public void setNetworkReady( boolean isReady )
{
isMEReady = isReady;
}
@Override
public boolean isMachineActive()
{
return isMEReady;
}
@Override
public float getPowerDrainPerTick()
{
return 1;
}
@Override
public void validate()
{
super.validate();
MinecraftForge.EVENT_BUS.post(new GridTileLoadEvent(this, worldObj, getLocation()));
}
@Override
public void invalidate()
{
super.invalidate();
MinecraftForge.EVENT_BUS.post(new GridTileUnloadEvent(this, worldObj, getLocation()));
}
@Override
public WorldCoord getLocation()
{
return new WorldCoord(xCoord, yCoord, zCoord);
}
@Override
public boolean isValid()
{
return true;
}
@Override
public void setPowerStatus(boolean hasPower)
{
powerStatus = hasPower;
}
@Override
public boolean isPowered()
{
return powerStatus;
}
@Override
public IGridInterface getGrid()
{
return grid;
}
@Override
public void setGrid(IGridInterface gi)
{
grid = gi;
}
@Override
public boolean coveredConnections()
{
return true;
}
@Override
public World getWorld()
{
return worldObj;
}
}

View file

@ -0,0 +1,231 @@
package cr0s.WarpDrive.machines;
import java.util.Map;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.ChunkCoordIntPair;
import net.minecraft.world.chunk.Chunk;
import cr0s.WarpDrive.data.EnumUpgradeTypes;
import cr0s.WarpDrive.WarpDrive;
import cr0s.WarpDrive.WarpDriveConfig;
import cr0s.WarpDrive.api.IUpgradable;
import dan200.computercraft.api.lua.ILuaContext;
import dan200.computercraft.api.peripheral.IComputerAccess;
public class TileEntityChunkLoader extends WarpChunkTE implements IUpgradable
{
private boolean canLoad = false;
private boolean shouldLoad = false;
private boolean inited = false;
private ChunkCoordIntPair myChunk;
int negDX, posDX, negDZ, posDZ;
int area = 1;
public TileEntityChunkLoader() {
super();
negDX = 0;
negDZ = 0;
posDX = 0;
posDZ = 0;
peripheralName = "warpdriveChunkloader";
methodsArray = new String[] {
"getEnergyLevel",
"radius",
"bounds",
"active",
"upgrades",
"help"
};
}
@Override
public int getMaxEnergyStored() {
return WarpDriveConfig.CL_MAX_ENERGY;
}
@Override
public boolean shouldChunkLoad()
{
return shouldLoad && canLoad;
}
@Override
public void updateEntity()
{
super.updateEntity();
if(!inited)
{
inited = true;
myChunk = worldObj.getChunkFromBlockCoords(xCoord, zCoord).getChunkCoordIntPair();
changedDistance();
}
if(shouldLoad)
{
canLoad = consumeEnergy(area * WarpDriveConfig.CL_RF_PER_CHUNKTICK, false);
}
else
{
canLoad = consumeEnergy(area * WarpDriveConfig.CL_RF_PER_CHUNKTICK, true);
}
}
private int clampDistance(int dis)
{
return clamp(dis,0,WarpDriveConfig.CL_MAX_DISTANCE);
}
private void changedDistance()
{
if(worldObj == null) {
return;
}
if (myChunk == null) {
Chunk aChunk = worldObj.getChunkFromBlockCoords(xCoord, zCoord);
if (aChunk != null) {
myChunk = aChunk.getChunkCoordIntPair();
} else {
return;
}
}
negDX = -clampDistance(negDX);
posDX = clampDistance(posDX);
negDZ = -clampDistance(negDZ);
posDZ = clampDistance(posDZ);
minChunk = new ChunkCoordIntPair(myChunk.chunkXPos+negDX,myChunk.chunkZPos+negDZ);
maxChunk = new ChunkCoordIntPair(myChunk.chunkXPos+posDX,myChunk.chunkZPos+posDZ);
area = (posDX - negDX + 1) * (posDZ - negDZ + 1);
refreshLoading(true);
}
@Override
public void readFromNBT(NBTTagCompound nbt)
{
super.readFromNBT(nbt);
negDX = nbt.getInteger("negDX");
negDZ = nbt.getInteger("negDZ");
posDX = nbt.getInteger("posDX");
posDZ = nbt.getInteger("posDZ");
changedDistance();
}
@Override
public void writeToNBT(NBTTagCompound nbt)
{
super.writeToNBT(nbt);
nbt.setInteger("negDX", negDX);
nbt.setInteger("negDZ", negDZ);
nbt.setInteger("posDX", posDX);
nbt.setInteger("posDZ", posDZ);
}
// OpenComputer callback methods
// FIXME: implement OpenComputers...
// ComputerCraft IPeripheral methods implementation
private String helpStr(Object[] args)
{
if(args.length == 1)
{
String m = args[0].toString().toLowerCase();
if(m.equals("energy"))
return WarpDrive.defEnergyStr;
else if(m.equals("radius"))
return "radius(int): sets the radius in chunks";
else if(m.equals("bounds"))
return "bounds(int,int,int,int): sets the bounds of chunks to load\nbounds(): returns the 4 bounds\nFormat is -X, +X, -Z, +Z";
else if(m.equals("active"))
return "active(): returns whether active or not\nactive(boolean): sets whether it should be active or not";
else if(m.equals("upgrades"))
return WarpDrive.defUpgradeStr;
}
return WarpDrive.defHelpStr;
}
@Override
public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws Exception {
String meth = methodsArray[method];
if(meth.equals("getEnergyLevel")) {
return getEnergyLevel();
} else if(meth.equals("radius"))
{
if(arguments.length == 1)
{
int dist = toInt(arguments[0]);
negDX = dist;
negDZ = dist;
posDX = dist;
posDZ = dist;
changedDistance();
return new Object[] { true };
}
return new Object[] { false };
}
else if(meth.equals("bounds"))
{
if(arguments.length == 4)
{
negDX = toInt(arguments[0]);
posDX = toInt(arguments[1]);
negDZ = toInt(arguments[2]);
posDZ = toInt(arguments[3]);
changedDistance();
}
return new Object[] { negDX, posDX, negDZ, posDZ };
}
else if(meth.equals("active"))
{
if(arguments.length == 1)
shouldLoad = toBool(arguments[0]);
return new Object[] { shouldChunkLoad() };
}
else if(meth.equals("upgrades"))
{
return getUpgrades();
}
else if(meth.equals("help"))
{
return new Object[] {helpStr(arguments) };
}
return null;
}
@Override
public boolean takeUpgrade(EnumUpgradeTypes upgradeType, boolean simulate)
{
int max = 0;
if(upgradeType == EnumUpgradeTypes.Energy)
max = 2;
else if(upgradeType == EnumUpgradeTypes.Power)
max = 2;
if(max == 0)
return false;
if(upgrades.containsKey(upgradeType))
if(upgrades.get(upgradeType) >= max)
return false;
if(!simulate)
{
int c = 0;
if(upgrades.containsKey(upgradeType))
c = upgrades.get(upgradeType);
upgrades.put(upgradeType, c+1);
}
return true;
}
@Override
public Map<EnumUpgradeTypes, Integer> getInstalledUpgrades()
{
return upgrades;
}
}

View file

@ -0,0 +1,147 @@
package cr0s.WarpDrive.machines;
import ic2.api.reactor.IReactor;
import ic2.api.reactor.IReactorChamber;
import java.util.HashSet;
import java.util.Set;
import cpw.mods.fml.common.FMLCommonHandler;
import cr0s.WarpDrive.data.Vector3;
import cr0s.WarpDrive.PacketHandler;
import cr0s.WarpDrive.WarpDrive;
import cr0s.WarpDrive.WarpDriveConfig;
import cr0s.WarpDrive.item.ItemReactorLaserFocus;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ChunkCoordinates;
import net.minecraftforge.common.ForgeDirection;
public class TileEntityLaserReactorMonitor extends TileEntityAbstractLaser {
private final int workRate = 10;
private int ticks = 0;
private Set<Object> findReactors() {//returns either IReactor or IReactorChamber tile entity
int[] xD = {-2, 2, 0, 0, 0, 0};
int[] yD = { 0, 0,-2, 2, 0, 0};
int[] zD = { 0, 0, 0, 0,-2, 2};
Set<Object> output = new HashSet<Object>();
for(int i = 0; i < xD.length; i++) {
int xO = xCoord + xD[i];
int yO = yCoord + yD[i];
int zO = zCoord + zD[i];
TileEntity te = worldObj.getBlockTileEntity(xO, yO, zO);
if(te == null)
continue;
if (te instanceof IReactor) {
output.add(te);
} else if(te instanceof IReactorChamber) {
IReactor reactor = ((IReactorChamber)te).getReactor();
if(reactor == null)
continue;
ChunkCoordinates coords = reactor.getPosition();
if(Math.abs(coords.posX - xCoord) == 1)
continue;
if(Math.abs(coords.posY - yCoord) == 1)
continue;
if(Math.abs(coords.posZ - zCoord) == 1)
continue;
output.add(te);
}
}
return output;
}
private boolean coolReactor(IReactor react) {
boolean didCoolReactor = false;
for(int x = 0; x < 9; x++) {
for(int y = 0; y < 6; y++) {
ItemStack item = react.getItemAt(x, y);
if (item != null) {
if(item.getItem() instanceof ItemReactorLaserFocus) {
int heat = item.getItemDamage();
int heatRemoval = (int) Math.floor(Math.min(getEnergyStored() / WarpDriveConfig.RM_EU_PER_HEAT, heat));
if (heatRemoval > 0) {
didCoolReactor = true;
consumeEnergy((int) Math.ceil(heatRemoval * WarpDriveConfig.RM_EU_PER_HEAT), false);
item.setItemDamage(heat - heatRemoval);
}
}
}
}
}
return didCoolReactor;
}
@Override
public void updateEntity() {
if (FMLCommonHandler.instance().getEffectiveSide().isClient()) {
return;
}
super.updateEntity();
ticks++;
if (ticks > workRate) {
ticks = 0;
Vector3 myPos = new Vector3(this).translate(0.5);
Set<Object> reactors = findReactors();
if(reactors.size() == 0)
return;
for(Object o : reactors)
{
IReactor react = null;
if(o instanceof TileEntity)
{
if(o instanceof IReactor)
react = (IReactor)o;
else if(o instanceof IReactorChamber)
react = ((IReactorChamber)o).getReactor();
if(react != null)
{
if(coolReactor(react))
{
TileEntity te = (TileEntity)o;
PacketHandler.sendBeamPacket(worldObj, myPos, new Vector3(te.xCoord,te.yCoord,te.zCoord).translate(0.5D), 0f, 0.8f, 1f, 20, 0, 20);
}
}
}
}
}
}
@Override
public void writeToNBT(NBTTagCompound tag) {
super.writeToNBT(tag);
}
@Override
public void readFromNBT(NBTTagCompound tag) {
super.readFromNBT(tag);
}
@Override
public boolean shouldChunkLoad() {
return false;
}
@Override
public int getMaxEnergyStored() {
return WarpDriveConfig.RM_MAX_ENERGY;
}
@Override
public int getMaxSafeInput() {
return Integer.MAX_VALUE;
}
@Override
public boolean canInputEnergy(ForgeDirection from) {
return true;
}
}

View file

@ -0,0 +1,350 @@
package cr0s.WarpDrive.machines;
import java.util.LinkedList;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import cr0s.WarpDrive.data.Vector3;
import cr0s.WarpDrive.WarpDrive;
import cr0s.WarpDrive.WarpDriveConfig;
import dan200.computercraft.api.peripheral.IComputerAccess;
import dan200.computercraft.api.lua.ILuaContext;
public class TileEntityLaserTreeFarm extends TileEntityAbstractMiner {
Boolean active = false;
private int mode = 0;
private boolean doLeaves = false;
private boolean silkTouchLeaves = false;
private boolean treeTap = false;
private final int defSize = 8;
private final int scanWait = 40;
private final int mineWait = 4;
private int delayMul = 4;
private int totalHarvested=0;
private int scan = 0;
private int xSize = defSize;
private int zSize = defSize;
LinkedList<Vector3> logs;
private int logIndex = 0;
public TileEntityLaserTreeFarm() {
super();
peripheralName = "treefarmLaser";
methodsArray = new String[] {
"start",
"stop",
"area",
"leaves",
"silkTouch",
"silkTouchLeaves",
"treetap",
"state"
};
}
@Override
public void updateEntity() {
super.updateEntity();
if (active) {
scan++;
if (mode == 0) {
if (scan >= scanWait) {
scan = 0;
logs = scanTrees();
if(logs.size() > 0)
mode = treeTap ? 2 : 1;
logIndex = 0;
}
} else {
if (scan >= mineWait * delayMul) {
scan = 0;
if (logIndex >= logs.size()) {
mode = 0;
return;
}
Vector3 pos = logs.get(logIndex);
int blockID = worldObj.getBlockId(pos.intX(), pos.intY(), pos.intZ());
if (mode == 1) {
int cost = calculateBlockCost(blockID);
if (consumeEnergyFromBooster(cost, true)) {
if (isLog(blockID) || (doLeaves && isLeaf(blockID))) {
delayMul = 1;
if (isRoomForHarvest()) {
if (consumeEnergyFromBooster(cost, false)) {
if (isLog(blockID)) {
delayMul = 4;
totalHarvested++;
}
harvestBlock(pos);
} else {
return;
}
} else {
return;
}
}
logIndex++;
}
} else if(mode == 2) {
int cost = calculateBlockCost(blockID);
if (consumeEnergyFromBooster(cost, true)) {
if (isRoomForHarvest()) {
if (blockID == WarpDriveConfig.IC2_RubberWood) {
int metadata = worldObj.getBlockMetadata(pos.intX(), pos.intY(), pos.intZ());
if (metadata >= 2 && metadata <= 5) {
WarpDrive.debugPrint("wetspot found");
if (consumeEnergyFromBooster(cost, false)) {
ItemStack resin = WarpDriveConfig.IC2_Resin.copy();
resin.stackSize = (int) Math.round(Math.random() * 4);
dumpToInv(resin);
worldObj.setBlockMetadataWithNotify(pos.intX(), pos.intY(), pos.intZ(), metadata+6, 3);
laserBlock(pos);
totalHarvested++;
delayMul = 4;
} else {
return;
}
} else {
delayMul = 1;
}
} else if(isLog(blockID)) {
if (consumeEnergyFromBooster(cost, false)) {
delayMul = 4;
totalHarvested++;
harvestBlock(pos);
} else {
return;
}
} else if(isLeaf(blockID)) {
if (consumeEnergyFromBooster(cost, true)) {
delayMul = 1;
harvestBlock(pos);
} else {
return;
}
}
} else {
return;
}
logIndex++;
}
}
}
}
}
}
private static boolean isLog(int blockID) {
return WarpDriveConfig.MinerLogs.contains(blockID);
}
private static boolean isLeaf(int blockID) {
return WarpDriveConfig.MinerLeaves.contains(blockID);
}
private static void addTree(LinkedList<Vector3> list, Vector3 newTree) {
WarpDrive.debugPrint("Adding tree position:" + newTree.x + "," + newTree.y + "," + newTree.z);
list.add(newTree);
}
private LinkedList<Vector3> scanTrees() {
int xmax, zmax, x1, x2, z1, z2;
int xmin, zmin;
x1 = xCoord + xSize / 2;
x2 = xCoord - xSize / 2;
xmin = Math.min(x1, x2);
xmax = Math.max(x1, x2);
z1 = zCoord + zSize / 2;
z2 = zCoord - zSize / 2;
zmin = Math.min(z1, z2);
zmax = Math.max(z1, z2);
LinkedList<Vector3> logPositions = new LinkedList<Vector3>();
for(int x = xmin; x <= xmax; x++) {
for(int z = zmin; z <= zmax; z++) {
int blockID = worldObj.getBlockId(x, yCoord, z);
if (isLog(blockID)) {
Vector3 pos = new Vector3(x, yCoord, z);
logPositions.add(pos);
scanNearby(logPositions, x, yCoord, z, 0);
}
}
}
return logPositions;
}
private void scanNearby(LinkedList<Vector3> current, int x, int y, int z, int d) {
int[] deltas = {0, -1, 1};
for(int dx : deltas) {
for(int dy = 1; dy >= 0; dy--) {
for(int dz : deltas) {
int blockID = worldObj.getBlockId(x+dx, y+dy, z+dz);
if (isLog(blockID) || (doLeaves && isLeaf(blockID))) {
Vector3 pos = new Vector3(x + dx, y + dy, z + dz);
if (!current.contains(pos)) {
addTree(current, pos);
if (d < 35) {
scanNearby(current,x+dx,y+dy,z+dz,d+1);
}
}
}
}
}
}
}
@Override
public void writeToNBT(NBTTagCompound tag) {
super.writeToNBT(tag);
tag.setInteger("xSize", xSize);
tag.setInteger("zSize", zSize);
tag.setBoolean("doLeaves", doLeaves);
tag.setBoolean("active", active);
tag.setBoolean("treetap", treeTap);
tag.setBoolean("silkTouchLeaves", silkTouchLeaves);
}
@Override
public void readFromNBT(NBTTagCompound tag) {
super.readFromNBT(tag);
xSize = tag.getInteger("xSize");
zSize = tag.getInteger("zSize");
defineMiningArea(xSize,zSize);
doLeaves = tag.getBoolean("doLeaves");
active = tag.getBoolean("active");
treeTap = tag.getBoolean("treetap");
silkTouchLeaves = tag.getBoolean("silkTouchLeaves");
}
@Override
public boolean shouldChunkLoad() {
return active;
}
// OpenComputer callback methods
// FIXME: implement OpenComputers...
// ComputerCraft IPeripheral methods implementation
@Override
public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws Exception {
String methodName = methodsArray[method];
if (methodName.equals("start")) {
if (!active) {
mode = 0;
totalHarvested = 0;
active = true;
}
return new Boolean[] { true };
} else if (methodName.equals("stop")) {
active = false;
} else if (methodName.equals("area")) {
try {
if (arguments.length == 1) {
xSize = clamp(toInt(arguments[0]),3,WarpDriveConfig.TF_MAX_SIZE);
zSize = xSize;
} else if (arguments.length == 2) {
xSize = clamp(toInt(arguments[0]),3,WarpDriveConfig.TF_MAX_SIZE);
zSize = clamp(toInt(arguments[1]),3,WarpDriveConfig.TF_MAX_SIZE);
}
} catch(NumberFormatException e) {
xSize = defSize;
zSize = defSize;
}
defineMiningArea(xSize,zSize);
return new Integer[] { xSize , zSize };
} else if (methodName.equals("leaves")) {
try {
if (arguments.length > 0) {
doLeaves = toBool(arguments[0]);
}
} catch(Exception e) {
}
return new Boolean[] { doLeaves };
} else if (methodName.equals("silkTouch")) {
try {
silkTouch(arguments[0]);
} catch(Exception e) {
silkTouch(false);
}
return new Object[] { silkTouch() };
} else if (methodName.equals("silkTouchLeaves")) {
try {
if (arguments.length >= 1) {
silkTouchLeaves = toBool(arguments[0]);
}
} catch(Exception e) {
silkTouchLeaves = false;
}
return new Object[] { silkTouchLeaves };
} else if (methodName.equals("treetap")) {
try {
if (arguments.length >= 1) {
treeTap = toBool(arguments[0]);
}
} catch(Exception e) {
treeTap = false;
}
return new Object[] { treeTap };
} else if (methodName.equals("state")) {
String state = active ? (mode==0?"scanning" : (mode == 1 ? "harvesting" : "tapping")) : "inactive";
return new Object[] { state, xSize, zSize, energy(), totalHarvested };
}
return null;
}
//ABSTRACT LASER IMPLEMENTATION
@Override
protected boolean silkTouch(int blockID) {
if (isLeaf(blockID)) {
return silkTouchLeaves;
}
return silkTouch();
}
@Override
protected boolean canSilkTouch() {
return true;
}
@Override
protected int minFortune() {
return 0;
}
@Override
protected int maxFortune() {
return 0;
}
@Override
protected double laserBelow() {
return -0.5;
}
@Override
protected float getColorR() {
return 0.2f;
}
@Override
protected float getColorG() {
return 0.7f;
}
@Override
protected float getColorB() {
return 0.4f;
}
}

View file

@ -0,0 +1,219 @@
package cr0s.WarpDrive.machines;
import cr0s.WarpDrive.api.IBlockUpdateDetector;
import cr0s.WarpDrive.data.Vector3;
import cr0s.WarpDrive.PacketHandler;
import cr0s.WarpDrive.WarpDrive;
import dan200.computercraft.api.lua.ILuaContext;
import dan200.computercraft.api.peripheral.IComputerAccess;
import dan200.computercraft.api.peripheral.IPeripheral;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.ForgeDirection;
public class TileEntityPowerLaser extends TileEntityAbstractLaser implements IPeripheral, IBlockUpdateDetector {
Vector3 myVec;
Vector3 reactorVec;
ForgeDirection side = ForgeDirection.UNKNOWN;
TileEntityParticleBooster booster;
TileEntityPowerReactor reactor;
boolean useLaser = false;
boolean doOnce = false;
String[] methodArray = {
"energy",
"hasReactor",
"side",
"sendLaser",
"help"
};
@Override
public boolean shouldChunkLoad() {
return false;
}
public TileEntityPowerReactor scanForReactor() {
reactor = null;
TileEntity te;
//I AM ON THE NORTH SIDE
side = ForgeDirection.UNKNOWN;
te = worldObj.getBlockTileEntity(xCoord, yCoord, zCoord + 2);
if (te instanceof TileEntityPowerReactor && worldObj.isAirBlock(xCoord, yCoord, zCoord + 1)) {
side = ForgeDirection.NORTH;
reactor = (TileEntityPowerReactor) te;
}
//I AM ON THE SOUTH SIDE
te = worldObj.getBlockTileEntity(xCoord, yCoord, zCoord - 2);
if (te instanceof TileEntityPowerReactor && worldObj.isAirBlock(xCoord, yCoord, zCoord - 1)) {
side = ForgeDirection.SOUTH;
reactor = (TileEntityPowerReactor) te;
}
//I AM ON THE WEST SIDE
te = worldObj.getBlockTileEntity(xCoord + 2, yCoord, zCoord);
if (te instanceof TileEntityPowerReactor && worldObj.isAirBlock(xCoord + 1, yCoord, zCoord)) {
side = ForgeDirection.WEST;
reactor = (TileEntityPowerReactor) te;
}
//I AM ON THE EAST SIDE
te = worldObj.getBlockTileEntity(xCoord - 2, yCoord, zCoord);
if (te instanceof TileEntityPowerReactor && worldObj.isAirBlock(xCoord - 1, yCoord, zCoord)) {
side = ForgeDirection.EAST;
reactor = (TileEntityPowerReactor) te;
}
setMetadata();
if (reactor != null) {
reactorVec = new Vector3(reactor).translate(0.5);
}
return reactor;
}
private void setMetadata() {
int metadata = 0;
if (side != ForgeDirection.UNKNOWN) {
metadata = side.ordinal() - 1;
}
if (getBlockMetadata() != metadata) {
worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, metadata, 3);
}
}
public TileEntityParticleBooster scanForBooster() {
booster = null;
TileEntity te;
te = worldObj.getBlockTileEntity(xCoord, yCoord + 1, zCoord);
if (te != null && te instanceof TileEntityParticleBooster) {
booster = (TileEntityParticleBooster)te;
}
te = worldObj.getBlockTileEntity(xCoord, yCoord - 1, zCoord);
if (te != null && te instanceof TileEntityParticleBooster) {
booster = (TileEntityParticleBooster)te;
}
return booster;
}
@Override
public void updateEntity() {
if (doOnce == false) {
scanForReactor();
scanForBooster();
myVec = new Vector3(this).translate(0.5);
doOnce = true;
}
if (useLaser == true) {
PacketHandler.sendBeamPacket(worldObj, myVec, reactorVec, 0.1F, 0.2F, 1.0F, 25, 50, 100);
useLaser = false;
}
}
public void unlink() {
side = ForgeDirection.UNKNOWN;
setMetadata();
}
@Override
public void updatedNeighbours() {
scanForBooster();
scanForReactor();
}
private void laserReactor(int energy) {
if (energy <= 0) {
return;
}
scanForBooster();
scanForReactor();
if(booster == null)
return;
if(reactor == null)
return;
if (booster.consumeEnergy(energy, false)) {
// WarpDrive.debugPrint("ReactorLaser on " + side.toString() +" side sending " + amount);
useLaser = true;
reactor.decreaseInstability(side, energy);
}
}
@Override
public void writeToNBT(NBTTagCompound nbt) {
super.writeToNBT(nbt);
}
@Override
public void readFromNBT(NBTTagCompound nbt) {
super.readFromNBT(nbt);
}
@Override
public String getType() {
return "warpdriveReactorLaser";
}
@Override
public String[] getMethodNames() {
return methodArray;
}
private static String helpStr(Object[] args) {
if (args.length > 0) {
String arg = args[0].toString().toLowerCase();
if (arg.equals("energy")) {
return WarpDrive.defEnergyStr;
} else if(arg.equals("hasReactor")) {
return "hasReactor(): returns true if the laser can see a reactor and false otherwise";
} else if(arg.equals("sendlaser")) {
return "sendLaser(int): sends a laser of energy int to the reactor";
} else if(arg.equals("side")) {
return "side(): returns 0-3 depending on which side of the reactor its on";
}
}
return WarpDrive.defHelpStr;
}
@Override
public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws Exception {
String methodName = methodArray[method];
if (methodName.equals("energy")) {
scanForBooster();
if (booster == null) {
return new Object[] { 0,0 };
} else {
return new Object[] { booster.getEnergyStored(), booster.getMaxEnergyStored() };
}
} else if (methodName.equals("hasReactor")) {
return new Object[] { scanForReactor() != null };
} else if (methodName.equals("sendLaser")) {
if (arguments.length >= 1) {
laserReactor(toInt(arguments[0]));
}
} else if (methodName.equals("help")) {
return new Object[] {helpStr(arguments)};
} else if (methodName.equals("side")) {
return new Object[] { side.ordinal() - 2 };
}
return null;
}
@Override
public void attach(IComputerAccess computer) {
}
@Override
public void detach(IComputerAccess computer) {
}
@Override
public boolean equals(IPeripheral other) {
return other == this;
}
}

View file

@ -0,0 +1,523 @@
package cr0s.WarpDrive.machines;
import java.util.HashMap;
import java.util.Random;
import java.util.Set;
import cpw.mods.fml.common.FMLCommonHandler;
import cr0s.WarpDrive.WarpDrive;
import cr0s.WarpDrive.WarpDriveConfig;
import cr0s.WarpDrive.api.IBlockUpdateDetector;
import dan200.computercraft.api.ComputerCraftAPI;
import dan200.computercraft.api.lua.ILuaContext;
import dan200.computercraft.api.peripheral.IComputerAccess;
import net.minecraft.entity.Entity;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.ForgeDirection;
public class TileEntityPowerReactor extends WarpEnergyTE implements IBlockUpdateDetector {
private int containedEnergy = 0;
// generation & instability is 'per tick'
private static final int PR_MIN_GENERATION = 4;
private static final int PR_MAX_GENERATION = 64000;
private static final double PR_MIN_INSTABILITY = 0.004D;
private static final double PR_MAX_INSTABILITY = 0.060D;
// explosion parameters
private static final int PR_MAX_EXPLOSION_RADIUS = 6;
private static final double PR_MAX_EXPLOSION_REMOVAL_CHANCE = 0.1D;
// laser stabilization is per shot
// target is to consume 10% max output power every second, hence 2.5% per side
// laser efficiency is 33% at 16% power (target spot), 50% at 24% power, 84% at 50% power, etc.
// 10% * 20 * PR_MAX_GENERATION / (4 * 0.16) => ~200kRF => ~ max laser energy
private static final double PR_MAX_LASER_ENERGY = 200000.0D;
private static final double PR_MAX_LASER_EFFECT = PR_MAX_INSTABILITY * 20 / 0.33D;
private int tickCount = 0;
private double[] instabilityValues = { 0.0D, 0.0D, 0.0D, 0.0D }; // no instability = 0, explosion = 100
private float lasersReceived = 0;
private int lastGenerationRate = 0;
private int releasedThisTick = 0; // amount of energy released during current tick update
private int releasedThisCycle = 0; // amount of energy released during current cycle
private int releasedLastCycle = 0;
private boolean hold = true; // hold updates and power output until reactor is controlled (i.e. don't explode on chunk-loading while computer is booting)
private boolean active = false;
private static final int MODE_DONT_RELEASE = 0;
private static final int MODE_MANUAL_RELEASE = 1;
private static final int MODE_RELEASE_ABOVE = 2;
private static final int MODE_RELEASE_AT_RATE = 3;
private static final String[] MODE_STRING = {"OFF", "MANUAL", "ABOVE", "RATE"};
private int releaseMode = 0;
private int releaseRate = 0;
private int releaseAbove = 0;
private boolean init = false;
public TileEntityPowerReactor() {
super();
peripheralName = "warpdriveReactor";
methodsArray = new String[] {
"active",
"energy", // returns energy, max energy, energy rate
"instability", // returns ins0,1,2,3
"release", // releases all energy
"releaseRate", // releases energy when more than arg0 is produced
"releaseAbove", // releases any energy above arg0 amount
"help" // returns help on arg0 function
};
}
private void increaseInstability(ForgeDirection from, boolean isNatural) {
if (canOutputEnergy(from) || hold) {
return;
}
int side = from.ordinal() - 2;
if (containedEnergy > WarpDriveConfig.PR_TICK_TIME * PR_MIN_GENERATION * 100) {
double amountToIncrease = WarpDriveConfig.PR_TICK_TIME * Math.max(PR_MIN_INSTABILITY, PR_MAX_INSTABILITY * Math.pow((worldObj.rand.nextDouble() * containedEnergy) / WarpDriveConfig.PR_MAX_ENERGY, 0.1));
// WarpDrive.debugPrint("InsInc" + amountToIncrease);
instabilityValues[side] += amountToIncrease * (isNatural ? 1.0D : 0.25D);
} else {
double amountToDecrease = WarpDriveConfig.PR_TICK_TIME * Math.max(PR_MIN_INSTABILITY, instabilityValues[side] * 0.02D);
instabilityValues[side] = Math.max(0.0D, instabilityValues[side] - amountToDecrease);
}
}
private void increaseInstability(boolean isNatural) {
increaseInstability(ForgeDirection.NORTH, isNatural);
increaseInstability(ForgeDirection.SOUTH, isNatural);
increaseInstability(ForgeDirection.EAST, isNatural);
increaseInstability(ForgeDirection.WEST, isNatural);
}
public void decreaseInstability(ForgeDirection from, int energy) {
if (canOutputEnergy(from)) {
return;
}
// laser is active => start updating reactor
hold = false;
int amount = convertInternalToRF(energy);
if (amount <= 1) {
return;
}
lasersReceived = Math.min(10.0F, lasersReceived + 1F / WarpDriveConfig.PR_MAX_LASERS);
double nospamFactor = 1.0;
if (lasersReceived > 1.0F) {
nospamFactor = 0.5;
worldObj.newExplosion((Entity) null, xCoord + from.offsetX, yCoord + from.offsetY, zCoord + from.offsetZ, 1, false, false);
// increaseInstability(from, false);
// increaseInstability(false);
}
double normalisedAmount = Math.min(1.0D, Math.max(0.0D, amount / PR_MAX_LASER_ENERGY)); // 0.0 to 1.0
double baseLaserEffect = 0.5D + 0.5D * Math.cos(Math.PI - (1.0D + Math.log10(0.1D + 0.9D * normalisedAmount)) * Math.PI); // 0.0 to 1.0
double randomVariation = 0.8D + 0.4D * worldObj.rand.nextDouble(); // ~1.0
double amountToRemove = PR_MAX_LASER_EFFECT * baseLaserEffect * randomVariation * nospamFactor;
int side = from.ordinal() - 2;
/*
if (side == 3) WarpDrive.debugPrint("Instability on " + from.toString() + " decreased by " + String.format("%.1f", amountToRemove) + "/" + String.format("%.1f", PR_MAX_LASER_EFFECT)
+ " after consuming " + amount + "/" + PR_MAX_LASER_ENERGY + " lasersReceived is " + String.format("%.1f", lasersReceived) + " hence nospamFactor is " + nospamFactor);
/**/
instabilityValues[side] = Math.max(0, instabilityValues[side] - amountToRemove);
updateSideTextures();
}
private void generateEnergy() {
double stabilityOffset = 0.5;
for(int i = 0; i < 4; i++) {
stabilityOffset *= Math.max(0.01D, instabilityValues[i] / 100.0D);
}
if (active) {// producing, instability increase output, you want to take the risk
int amountToGenerate = (int)Math.ceil( WarpDriveConfig.PR_TICK_TIME * (0.5D + stabilityOffset) * (PR_MIN_GENERATION + PR_MAX_GENERATION * Math.pow(containedEnergy / (double) WarpDriveConfig.PR_MAX_ENERGY, 0.6D)));
containedEnergy = Math.min(containedEnergy + amountToGenerate, WarpDriveConfig.PR_MAX_ENERGY);
lastGenerationRate = amountToGenerate / WarpDriveConfig.PR_TICK_TIME;
// WarpDrive.debugPrint("Generated " + amountToGenerate);
} else {// decaying over 20s without producing power, you better have power for those lasers
int amountToDecay = (int)( WarpDriveConfig.PR_TICK_TIME * (1.0D - stabilityOffset) * (PR_MIN_GENERATION + containedEnergy * 0.01D) );
containedEnergy = Math.max(0, containedEnergy - amountToDecay);
lastGenerationRate = 0;
// WarpDrive.debugPrint("Decayed " + amountToDecay);
}
}
@Override
public void updateEntity() {
if (FMLCommonHandler.instance().getEffectiveSide().isClient()) {
return;
}
super.updateEntity();
// WarpDrive.debugPrint("tickCount " + tickCount + " releasedThisTick " + releasedThisTick + " lasersReceived " + lasersReceived + " releasedThisCycle " + releasedThisCycle + " containedEnergy " + containedEnergy);
releasedThisTick = 0;
lasersReceived = Math.max(0.0F, lasersReceived - 0.05F);
tickCount++;
if (tickCount < WarpDriveConfig.PR_TICK_TIME) {
return;
}
tickCount = 0;
releasedLastCycle = releasedThisCycle;
releasedThisCycle = 0;
if (!init) {
init = true;
updatedNeighbours();
}
updateSideTextures();
// unstable at all time
if (shouldExplode()) {
explode();
}
increaseInstability(true);
generateEnergy();
sendEvent("reactorPulse", new Object[] { lastGenerationRate });
}
private void explode() {
// remove blocks randomly up to x blocks around (breaking whatever protection is there)
double normalizedEnergy = containedEnergy / (double)WarpDriveConfig.PR_MAX_ENERGY;
int radius = (int) Math.round(PR_MAX_EXPLOSION_RADIUS * Math.pow(normalizedEnergy, 0.125));
double c = PR_MAX_EXPLOSION_REMOVAL_CHANCE * Math.pow(normalizedEnergy, 0.125);
WarpDrive.debugPrint(this + " Explosion radius is " + radius + ", Chance of removal is " + c);
if (radius > 1) {
for(int x = xCoord - radius; x <= xCoord + radius; x++) {
for(int y = yCoord - radius; y <= yCoord + radius; y++) {
for(int z = zCoord - radius; z <= zCoord + radius; z++) {
if (z != zCoord || y != yCoord || x != xCoord) {
if (worldObj.rand.nextDouble() < c) {
worldObj.setBlockToAir(x, y, z);
}
}
}
}
}
}
// remove reactor
worldObj.setBlockToAir(xCoord, yCoord, zCoord);
// set a few TnT augmented around reactor
for (int i = 0; i < 3; i++) {
worldObj.newExplosion((Entity) null,
xCoord + worldObj.rand.nextInt(3) - 0.5D,
yCoord + worldObj.rand.nextInt(3) - 0.5D,
zCoord + worldObj.rand.nextInt(3) - 0.5D,
4.0F + worldObj.rand.nextInt(3),
true, true);
}
}
private void updateSideTextures() {
double maxInstability = 0.0D;
for (Double ins:instabilityValues) {
if (ins > maxInstability) {
maxInstability = ins;
}
}
int instabilityNibble = (int) Math.max(0, Math.min(3, Math.round( maxInstability / 25.0D)));
int energyNibble = (int) Math.max(0, Math.min(3, Math.round(4.0D * containedEnergy / WarpDriveConfig.PR_MAX_ENERGY)));
int metadata = 4 * instabilityNibble + energyNibble;
if (getBlockMetadata() != metadata) {
worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, metadata, 3);
}
}
private boolean shouldExplode() {
boolean exploding = false;
for(int i = 0; i < 4; i++) {
exploding = exploding || (instabilityValues[i] >= 100);
}
exploding &= (worldObj.rand.nextInt(4) == 2);
if (exploding) {
WarpDrive.print(this + String.format(" Explosion trigerred, Instability is [%.2f, %.2f, %.2f, %.2f], Energy stored is %d, Laser received is %.2f, %s", new Object[] {
instabilityValues[0], instabilityValues[1], instabilityValues[2], instabilityValues[3],
this.containedEnergy,
this.lasersReceived,
this.active ? "ACTIVE" : "INACTIVE" }));
active = false;
}
return exploding;
}
//Takes the arguments passed by function call and returns an appropriate string
private static String helpStr(Object[] args) {
if (args.length > 0) {
String arg = args[0].toString().toLowerCase();
if (arg.equals("getactive")) {
return "getActive(): returns true if the reactor is active and false otherwise";
} else if (arg.equals("setactive")) {
return "setActive(bool): activates the reactor if passed true and deactivates if passed false";
} else if (arg.equals("energy")) {
return WarpDrive.defEnergyStr;
} else if (arg.equals("instability")) {
return "instability(): returns the 4 instability values (100 is the point when the reactor explodes)";
} else if (arg.equals("release")) {
return "release(bool): sets the reactor to output all energy or disables outputting of energy";
} else if (arg.equals("releaserate")) {
return "releaseRate(int): sets the reactor to try to release exactly int/tick";
} else if (arg.equals("releaseabove")) {
return "releaseAbove(int): releases all energy above stored int";
}
}
return WarpDrive.defHelpStr;
}
@Override
public void updatedNeighbours() {
TileEntity te;
super.updatedNeighbours();
int[] xo = { 0, 0,-2, 2};
int[] zo = { 2,-2, 0, 0};
for(int i = 0; i < 4; i++) {
te = worldObj.getBlockTileEntity(xCoord + xo[i], yCoord, zCoord + zo[i]);
if (te instanceof TileEntityPowerLaser) {
((TileEntityPowerLaser)te).scanForReactor();
}
}
}
// OpenComputer callback methods
// FIXME: implement OpenComputers...
public Object[] active(Object[] arguments) throws Exception {
if (arguments.length == 1) {
boolean activate = false;
try {
activate = toBool(arguments[0]);
} catch(Exception e) {
throw new Exception("Function expects an boolean value");
}
if (active && !activate) {
sendEvent("reactorDeactivation", null);
} else if(!active && activate) {
sendEvent("reactorActivation", null);
}
active = activate;
}
if (releaseMode == MODE_DONT_RELEASE || releaseMode == MODE_MANUAL_RELEASE) {
return new Object[] { active, MODE_STRING[releaseMode], 0 };
} else if (releaseMode == MODE_RELEASE_ABOVE) {
return new Object[] { active, MODE_STRING[releaseMode], releaseAbove };
} else {
return new Object[] { active, MODE_STRING[releaseMode], releaseRate };
}
}
private Object[] release(Object[] arguments) throws Exception {
boolean doRelease = false;
if (arguments.length > 0) {
try {
doRelease = toBool(arguments[0]);
} catch(Exception e) {
throw new Exception("Function expects an boolean value");
}
releaseMode = doRelease ? MODE_MANUAL_RELEASE : MODE_DONT_RELEASE;
releaseAbove = 0;
releaseRate = 0;
}
return new Object[] { releaseMode != MODE_DONT_RELEASE };
}
private Object[] releaseRate(Object[] arguments) throws Exception {
int rate = -1;
try {
rate = toInt(arguments[0]);
} catch(Exception e) {
throw new Exception("Function expects an integer value");
}
if (rate <= 0) {
releaseMode = MODE_DONT_RELEASE;
releaseRate = 0;
} else {
/* releaseAbove = (int)Math.ceil(Math.pow(rate, 1.0 / 0.6));
WarpDrive.debugPrint("releaseAbove " + releaseAbove);
releaseMode = MODE_RELEASE_ABOVE;/**/
// player has to adjust it
releaseRate = rate;
releaseMode = MODE_RELEASE_AT_RATE;
}
return new Object[] { MODE_STRING[releaseMode], releaseRate };
}
private Object[] releaseAbove(Object[] arguments) throws Exception {
int above = -1;
try {
above = toInt(arguments[0]);
} catch(Exception e) {
throw new Exception("Function expects an integer value");
}
if (above <= 0) {
releaseMode = 0;
releaseAbove = MODE_DONT_RELEASE;
} else {
releaseMode = MODE_RELEASE_ABOVE;
releaseAbove = above;
}
return new Object[] { MODE_STRING[releaseMode], releaseAbove };
}
// ComputerCraft IPeripheral methods implementation
@Override
public void attach(IComputerAccess computer) {
super.attach(computer);
int id = computer.getID();
connectedComputers.put(id, computer);
if (WarpDriveConfig.G_LUA_SCRIPTS != WarpDriveConfig.LUA_SCRIPTS_NONE) {
computer.mount("/power", ComputerCraftAPI.createResourceMount(WarpDrive.class, "warpdrive", "lua/power"));
computer.mount("/warpupdater", ComputerCraftAPI.createResourceMount(WarpDrive.class, "warpdrive", "lua/common/updater"));
if (WarpDriveConfig.G_LUA_SCRIPTS == WarpDriveConfig.LUA_SCRIPTS_ALL) {
computer.mount("/startup", ComputerCraftAPI.createResourceMount(WarpDrive.class, "warpdrive", "lua/power/startup"));
}
}
}
@Override
public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws Exception {
// computer is alive => start updating reactor
hold = false;
String methodName = methodsArray[method];
if (methodName.equals("active")) {
return active(arguments);
} else if (methodName.equals("energy")) {
return new Object[] { containedEnergy, WarpDriveConfig.PR_MAX_ENERGY, releasedLastCycle / WarpDriveConfig.PR_TICK_TIME };
} else if (methodName.equals("instability")) {
Object[] retVal = new Object[4];
for(int i = 0; i < 4; i++) {
retVal[i] = instabilityValues[i];
}
return retVal;
} else if (methodName.equals("release")) {
return release(arguments);
} else if (methodName.equals("releaseRate")) {
return releaseRate(arguments);
} else if (methodName.equals("releaseAbove")) {
return releaseAbove(arguments);
} else if (methodName.equals("help")) {
return new Object[] { helpStr(arguments) };
}
return null;
}
// POWER INTERFACES
@Override
public int getPotentialEnergyOutput() {
if (hold) {// still loading/booting => hold output
return 0;
}
int result = 0;
int capacity = Math.max(0, 2 * lastGenerationRate - releasedThisTick);
if (releaseMode == MODE_MANUAL_RELEASE) {
result = Math.min(Math.max(0, containedEnergy ), capacity);
// WarpDrive.debugPrint("PotentialOutput Manual " + result + " RF (" + convertRFtoInternal(result) + " internal) capacity " + capacity);
} else if (releaseMode == MODE_RELEASE_ABOVE) {
result = Math.min(Math.max(0, containedEnergy - releaseAbove), capacity);
// WarpDrive.debugPrint("PotentialOutput Above " + result + " RF (" + convertRFtoInternal(result) + " internal) capacity " + capacity);
} else if (releaseMode == MODE_RELEASE_AT_RATE) {
int remainingRate = Math.max(0, releaseRate - releasedThisTick);
result = Math.min(Math.max(0, containedEnergy ), Math.min(remainingRate, capacity));
// WarpDrive.debugPrint("PotentialOutput Rated " + result + " RF (" + convertRFtoInternal(result) + " internal) remainingRate " + remainingRate + " RF/t capacity " + capacity);
}
return convertRFtoInternal(result);
}
@Override
public boolean canOutputEnergy(ForgeDirection from) {
if (from.equals(ForgeDirection.UP) || from.equals(ForgeDirection.DOWN)) {
return true;
}
return false;
}
@Override
protected void energyOutputDone(int energyOutput_internal) {
int energyOutput_RF = convertInternalToRF(energyOutput_internal);
containedEnergy -= energyOutput_RF;
if (containedEnergy < 0) {
containedEnergy = 0;
}
releasedThisTick += energyOutput_RF;
releasedThisCycle += energyOutput_RF;
// WarpDrive.debugPrint("OutputDone " + energyOutput_internal + " (" + energyOutput_RF + " RF)");
}
@Override
public int getEnergyStored() {
return convertRFtoInternal(containedEnergy);
}
@Override
public int getMaxEnergyStored() {
return convertRFtoInternal(WarpDriveConfig.PR_MAX_ENERGY);
}
// Forge overrides
@Override
public void writeToNBT(NBTTagCompound nbt) {
super.writeToNBT(nbt);
nbt.setInteger("energy", containedEnergy);
nbt.setInteger("releaseMode", releaseMode);
nbt.setInteger("releaseRate", releaseRate);
nbt.setInteger("releaseAbove", releaseAbove);
nbt.setDouble("i0", instabilityValues[0]);
nbt.setDouble("i1", instabilityValues[1]);
nbt.setDouble("i2", instabilityValues[2]);
nbt.setDouble("i3", instabilityValues[3]);
nbt.setBoolean("active", active);
}
@Override
public void readFromNBT(NBTTagCompound nbt) {
super.readFromNBT(nbt);
containedEnergy = nbt.getInteger("energy");
releaseMode = nbt.getInteger("releaseMode");
releaseRate = nbt.getInteger("releaseRate");
releaseAbove = nbt.getInteger("releaseAbove");
instabilityValues[0] = nbt.getDouble("i0");
instabilityValues[1] = nbt.getDouble("i1");
instabilityValues[2] = nbt.getDouble("i2");
instabilityValues[3] = nbt.getDouble("i3");
active = nbt.getBoolean("active");
}
@Override
public String toString() {
return String.format("%s \'%s\' @ \'%s\' %.2f, %.2f, %.2f", new Object[] {
getClass().getSimpleName(),
this.connectedComputers == null ? "~NULL~" : this.connectedComputers,
worldObj == null ? "~NULL~" : worldObj.getWorldInfo().getWorldName(),
Double.valueOf(xCoord), Double.valueOf(yCoord), Double.valueOf(zCoord)});
}
}

View file

@ -0,0 +1,63 @@
package cr0s.WarpDrive.machines;
import cpw.mods.fml.common.Optional;
import cr0s.WarpDrive.WarpDriveConfig;
import dan200.computercraft.api.lua.ILuaContext;
import dan200.computercraft.api.peripheral.IComputerAccess;
import net.minecraftforge.common.ForgeDirection;
public class TileEntityPowerStore extends WarpEnergyTE {
public TileEntityPowerStore() {
super();
peripheralName = "warpdrivePowerStore";
methodsArray = new String[] {
"getEnergyLevel"
};
}
@Override
public int getPotentialEnergyOutput() {
return getEnergyStored();
}
@Override
protected void energyOutputDone(int energyOutput) {
consumeEnergy(energyOutput, false);
}
@Override
public int getMaxEnergyStored() {
return WarpDriveConfig.PS_MAX_ENERGY;
}
@Override
public boolean canInputEnergy(ForgeDirection from) {
return true;
}
@Override
public boolean canOutputEnergy(ForgeDirection to) {
return true;
}
// ComputerCraft IPeripheral methods implementation
@Override
public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws Exception {
String methodName = methodsArray[method];
if (methodName == "getEnergyLevel") {
return getEnergyLevel();
}
return null;
}
@Override
public void attach(IComputerAccess computer) {
// nothing to see here
}
@Override
public void detach(IComputerAccess computer) {
// nothing to see here
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,482 @@
package cr0s.WarpDrive.machines;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import cr0s.WarpDrive.api.IUpgradable;
import cr0s.WarpDrive.data.EnumUpgradeTypes;
import cr0s.WarpDrive.data.Vector3;
import cr0s.WarpDrive.WarpDrive;
import cr0s.WarpDrive.WarpDriveConfig;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.ChatMessageComponent;
import net.minecraft.util.DamageSource;
import net.minecraftforge.common.ForgeDirection;
import dan200.computercraft.api.peripheral.IComputerAccess;
import dan200.computercraft.api.lua.ILuaContext;
public class TileEntityTransporter extends WarpEnergyTE implements IUpgradable
{
private double scanRange=2;
private int scanDist = 4;
private double beaconEffect = 0;
private double powerBoost = 1;
private double baseLockStrength=-1;
private double lockStrengthMul = 1;
private boolean isLocked=false;
private final static Vector3 centreOnMe = new Vector3(0.5D, 1.0D, 0.5D);
private Vector3 sourceVec = new Vector3();
private Vector3 destVec = new Vector3();
private TeleporterDamage teleDam = new TeleporterDamage("teleporter");
public TileEntityTransporter() {
super();
peripheralName = "transporter";
methodsArray = new String[] {
"source",
"dest",
"lock",
"release",
"lockStrength",
"energize",
"getEnergyLevel",
"powerBoost",
"energyCost",
"upgrades",
"help" };
}
@Override
public void updateEntity() {
super.updateEntity();
if(isLocked) {
if(lockStrengthMul > 0.8) {
lockStrengthMul *= 0.995;
} else {
lockStrengthMul*= 0.98;
}
}
}
// OpenComputer callback methods
// FIXME: implement OpenComputers...
// ComputerCraft IPeripheral methods implementation
private static String helpStr(Object[] function) {
if (function != null && function.length > 0) {
String fun = function[0].toString().toLowerCase();
if(fun.equals("source")) {
if(WarpDriveConfig.TR_RELATIVE_COORDS) {
return "source(x,y,z): sets the coordinates (relative to the transporter) to teleport from\ndest(): returns the relative x,y,z coordinates of the source";
} else {
return "source(x,y,z): sets the absolute coordinates to teleport from\ndest(): returns the x,y,z coordinates of the source";
}
} else if(fun.equals("dest")) {
if(WarpDriveConfig.TR_RELATIVE_COORDS) {
return "dest(x,y,z): sets the coordinates (relative to the transporter) to teleport to\ndest(): returns the relative x,y,z coordinates of the destination";
} else {
return "dest(x,y,z): sets the absolute coordinates to teleport to\ndest(): returns the x,y,z coordinates of the destination";
}
} else if(fun.equals("lock")) {
return "lock(): locks the source and dest coordinates in and returns the lock strength (float)";
} else if(fun.equals("release")) {
return "release(): releases the current lock";
} else if(fun.equals("lockstrength")) {
return "lockStrength(): returns the current lock strength (float)";
} else if(fun.equals("energize")) {
return "energize(): attempts to teleport all entities at source to dest. Returns the number of entities transported (-1 indicates a problem).";
} else if(fun.equals("powerboost")) {
return "powerBoost(boostAmount): sets the level of power to use (1 being default), returns the level of power\npowerBoost(): returns the level of power";
} else if(fun.equals("energycost")) {
return "energyCost(): returns the amount of energy it will take for a single entity to transport with the current settings";
} else if(fun.equals("upgrades")) {
return WarpDrive.defUpgradeStr;
} else if(fun.equals("getEnergyLevel")) {
return WarpDrive.defEnergyStr;
}
}
return WarpDrive.defHelpStr;
}
private Object[] setVec3(boolean src,Object... arguments) {
Vector3 vec = src ? sourceVec : destVec;
if (vec == null) {
Vector3 sV = WarpDriveConfig.TR_RELATIVE_COORDS ? new Vector3(this) : new Vector3(0,0,0);
if(src)
sourceVec = sV;
else
destVec = sV;
vec = src ? sourceVec : destVec;
}
try {
if (arguments.length >= 3) {
unlock();
vec.x = toDouble(arguments[0]);
vec.y = toDouble(arguments[1]);
vec.z = toDouble(arguments[2]);
} else if(arguments.length == 1) {
unlock();
if(WarpDriveConfig.TR_RELATIVE_COORDS) {
vec.x = centreOnMe.x;
vec.y = centreOnMe.y;
vec.z = centreOnMe.z;
} else {
vec.x = xCoord + centreOnMe.x;
vec.y = yCoord + centreOnMe.y;
vec.z = zCoord + centreOnMe.z;
}
}
} catch(NumberFormatException e) {
return setVec3(src,"this");
}
return new Object[] { vec.x, vec.y, vec.z };
}
@Override
public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws Exception {
String methodName = methodsArray[method];
if (methodName.equals("getEnergyLevel")) {
return new Object[] { getEnergyStored(), getMaxEnergyStored() };
} else if (methodName.equals("source")) {
return setVec3(true,arguments);
} else if (methodName.equals("dest")) {
return setVec3(false,arguments);
} else if (methodName.equals("lock")) {
return new Object[] { lock(sourceVec, destVec) };
} else if (methodName.equals("release")) {
unlock();
return null;
} else if (methodName.equals("lockStrength")) {
return new Object[] { getLockStrength() };
} else if (methodName.equals("energize")) {
return new Object[] { energize () };
} else if (methodName.equals("powerBoost")) {
try {
if (arguments.length >= 1) {
powerBoost = clamp(toDouble(arguments[0]),1,WarpDriveConfig.TR_MAX_BOOST_MUL);
}
} catch(NumberFormatException e) {
powerBoost = 1;
}
return new Object[] { powerBoost };
} else if (methodName.equals("energyCost")) {
return new Object[] { energyCost() };
} else if (methodName.equals("help")) {
return new Object[] { helpStr(arguments) };
}
return null;
}
private Integer energyCost() {
if (sourceVec != null && destVec != null) {
return (int) Math.ceil(Math.pow(3, powerBoost - 1) * WarpDriveConfig.TR_EU_PER_METRE * sourceVec.distanceTo(destVec));
}
return null;
}
private int energize() {
if (isLocked) {
int count = 0;
double ls = getLockStrength();
WarpDrive.debugPrint("LS:" + getLockStrength());
ArrayList<Entity> entitiesToTransport = findEntities(sourceVec, ls);
Integer energyReq = energyCost();
if (energyReq == null) {
return -1;
}
Vector3 modDest = destVec.clone().translate(centreOnMe);
for(Entity ent : entitiesToTransport) {
WarpDrive.debugPrint("" + this + " Handling entity " + ent.getEntityName());
if (consumeEnergy(energyReq, false)) {
WarpDrive.debugPrint("" + this + " Energy taken");
inflictNegativeEffect(ent, ls);
transportEnt(ent, modDest);
count++;
} else {
break;
}
}
return count;
}
return -1;
}
private void transportEnt(Entity ent, Vector3 dest) {
if (ent instanceof EntityLivingBase) {
EntityLivingBase livingEnt = (EntityLivingBase) ent;
if (WarpDriveConfig.TR_RELATIVE_COORDS) {
livingEnt.setPositionAndUpdate(xCoord+dest.x, yCoord+dest.y, zCoord+dest.z);
} else {
livingEnt.setPositionAndUpdate(dest.x, dest.y, dest.z);
}
} else {
if (WarpDriveConfig.TR_RELATIVE_COORDS) {
ent.setPosition(xCoord+dest.x, yCoord+dest.y, zCoord+dest.z);
} else {
ent.setPosition(dest.x, dest.y, dest.z);
}
}
}
private void inflictNegativeEffect(Entity ent, double lockStrength) {
double value = Math.random() + lockStrength;
WarpDrive.debugPrint("TRANSPORTER INFLICTION: " + value);
if (value < 0.1) {
ent.attackEntityFrom(teleDam, 1000);
}
if (value < 0.2) {
ent.attackEntityFrom(teleDam, 10);
}
if (value < 0.5) {
ent.attackEntityFrom(teleDam, 1);
}
}
private double beaconScan(int xV, int yV, int zV)
{
WarpDrive.debugPrint("BeaconScan:" + xV + ","+yV + "," + zV);
double beacon = 0;
int beaconCount = 0;
int xL = xV - scanDist;
int xU = xV + scanDist;
int yL = yV - scanDist;
int yU = yV + scanDist;
int zL = zV - scanDist;
int zU = zV + scanDist;
for(int x=xL;x<=xU;x++)
{
for(int y=yL;y<=yU;y++)
{
if(y < 0 || y > 254) {
continue;
}
for(int z=zL;z<=zU;z++)
{
if(worldObj.getBlockId(x, y, z) != WarpDriveConfig.transportBeaconID) {
continue;
}
double dist = 1 + Math.abs(x - xV) + Math.abs(y - yV) + Math.abs(z - zV);
beaconCount++;
if (worldObj.getBlockMetadata(x, y, z) == 0) {
beacon += 1/dist;
} else {
beacon -= 1/dist;
}
}
}
}
if (beaconCount > 0) {
beacon /= Math.sqrt(beaconCount);
}
return beacon;
}
private double beaconScan(Vector3 s, Vector3 d)
{
s = absoluteVector(s);
d = absoluteVector(d);
return beaconScan(toInt(s.x), toInt(s.y), toInt(s.z)) + beaconScan(toInt(d.x), toInt(d.y), toInt(d.z));
}
private Vector3 absoluteVector(Vector3 a)
{
if(WarpDriveConfig.TR_RELATIVE_COORDS)
return a.clone().translate(new Vector3(this));
else
return a;
}
private double calculatePower(Vector3 d)
{
Vector3 myCoords;
if(WarpDriveConfig.TR_RELATIVE_COORDS)
myCoords = centreOnMe;
else
myCoords = new Vector3(this).translate(centreOnMe);
return calculatePower(myCoords,d);
}
private static double calculatePower(Vector3 s, Vector3 d)
{
double dist = s.distanceTo(d);
return clamp(Math.pow(Math.E, -dist / 300), 0, 1);
}
private static double min(double... ds)
{
double curMin = Double.MAX_VALUE;
for(double d: ds)
curMin = Math.min(curMin, d);
return curMin;
}
private double getLockStrength() {
if (isLocked) {
double upgradeBoost = 1;
if (upgrades.containsKey(EnumUpgradeTypes.Range))
upgradeBoost = Math.pow(1.2, upgrades.get(EnumUpgradeTypes.Range));
return clamp(baseLockStrength * lockStrengthMul * Math.pow(2, powerBoost-1) * upgradeBoost * (1 + beaconEffect), 0, 1);
}
return -1;
}
private void unlock() {
isLocked = false;
baseLockStrength = 0;
}
private double lock(Vector3 source,Vector3 dest) {
if (source != null && dest != null) {
double basePower = min(calculatePower(source), calculatePower(dest), calculatePower(source,dest));
beaconEffect = beaconScan(source, dest);
WarpDrive.debugPrint("BEACON:" + beaconEffect);
baseLockStrength = basePower;
lockStrengthMul = 1;
isLocked = true;
WarpDrive.debugPrint(baseLockStrength + "," + getLockStrength());
return getLockStrength();
} else {
unlock();
return 0;
}
}
private AxisAlignedBB getAABB() {
Vector3 tS = new Vector3(this);
Vector3 bS = new Vector3(this);
Vector3 scanPos = new Vector3( scanRange/2, 2, scanRange/2);
Vector3 scanNeg = new Vector3(-scanRange/2,-1,-scanRange/2);
if(WarpDriveConfig.TR_RELATIVE_COORDS) {
tS.translate(sourceVec).translate(scanPos);
bS.translate(sourceVec).translate(scanNeg);
} else {
tS = sourceVec.clone().translate(scanPos);
bS = sourceVec.clone().translate(scanNeg);
}
return AxisAlignedBB.getBoundingBox(bS.x,bS.y,bS.z,tS.x,tS.y,tS.z);
}
private ArrayList<Entity> findEntities(Vector3 source, double lockStrength) {
AxisAlignedBB bb = getAABB();
WarpDrive.debugPrint("Transporter:" +bb.toString());
List data = worldObj.getEntitiesWithinAABBExcludingEntity(null, bb);
ArrayList<Entity> output = new ArrayList<Entity>(data.size());
for(Object ent : data) {
if (lockStrength >= 1 || worldObj.rand.nextDouble() < lockStrength) {// If weak lock, don't transport
WarpDrive.debugPrint("" + this + " Entity '" + ent.toString() + "' found and added");
if (ent instanceof Entity) {
output.add((Entity) ent);
}
} else {
WarpDrive.debugPrint("" + this + " Entity '" + ent.toString() + "' discarded");
}
}
return output;
}
@Override
public int getMaxEnergyStored() {
int max = WarpDriveConfig.TR_MAX_ENERGY;
if (upgrades.containsKey(EnumUpgradeTypes.Energy)) {
max = (int) Math.floor(max * Math.pow(1.2, upgrades.get(EnumUpgradeTypes.Energy)));
}
return max;
}
@Override
public boolean canInputEnergy(ForgeDirection from) {
if (from == ForgeDirection.UP) {
return false;
}
return true;
}
@Override
public int getMaxSafeInput() {
return Integer.MAX_VALUE;
}
@Override
public void writeToNBT(NBTTagCompound tag) {
super.writeToNBT(tag);
tag.setDouble("powerBoost", powerBoost);
}
@Override
public void readFromNBT(NBTTagCompound tag) {
super.readFromNBT(tag);
powerBoost = tag.getDouble("powerBoost");
}
class TeleporterDamage extends DamageSource {
protected TeleporterDamage(String par1Str) {
super(par1Str);
}
@Override
public ChatMessageComponent getDeathMessage(EntityLivingBase e) {
String mess = "";
if(e instanceof EntityPlayer || e instanceof EntityPlayerMP) {
mess = ((EntityPlayer) e).username + " was killed by a teleporter malfunction";
} else {
mess = e.getEntityName() + " was killed by a teleporter malfunction";
}
WarpDrive.debugPrint(mess);
return ChatMessageComponent.createFromText(mess);
}
}
@Override
public boolean takeUpgrade(EnumUpgradeTypes upgradeType, boolean simulate)
{
int max = 0;
if(upgradeType == EnumUpgradeTypes.Energy)
max = 2;
else if(upgradeType == EnumUpgradeTypes.Power)
max = 4;
else if(upgradeType == EnumUpgradeTypes.Range)
max = 4;
if(max == 0)
return false;
if(upgrades.containsKey(upgradeType))
if(upgrades.get(upgradeType) >= max)
return false;
if(!simulate)
{
int c = 0;
if(upgrades.containsKey(upgradeType))
c = upgrades.get(upgradeType);
upgrades.put(upgradeType, c+1);
}
return true;
}
@Override
public Map<EnumUpgradeTypes,Integer> getInstalledUpgrades()
{
return upgrades;
}
}

View file

@ -0,0 +1,85 @@
package cr0s.WarpDrive.machines;
import cpw.mods.fml.common.FMLCommonHandler;
import cr0s.WarpDrive.WarpDrive;
import cr0s.WarpDrive.api.IBlockUpdateDetector;
import cr0s.WarpDrive.api.IUpgradable;
import cr0s.WarpDrive.data.EnumUpgradeTypes;
import cr0s.WarpDrive.item.ItemWarpUpgrade;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
public abstract class WarpBlockContainer extends BlockContainer {
protected WarpBlockContainer(int par1) {
super(par1, Material.iron);
}
protected WarpBlockContainer(int par1, Material m) {
super(par1, m);
setHardness(0.5F);
setStepSound(Block.soundMetalFootstep);
setCreativeTab(WarpDrive.warpdriveTab);
}
@Override
public void onBlockAdded(World w, int x, int y, int z) {
super.onBlockAdded(w, x, y, z);
TileEntity te = w.getBlockTileEntity(x, y, z);
if (te instanceof IBlockUpdateDetector) {
((IBlockUpdateDetector)te).updatedNeighbours();
}
}
/* FIXME untested
@Override
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int par6, float par7, float par8, float par9)
{
if (FMLCommonHandler.instance().getEffectiveSide().isClient()) {
return false;
}
boolean hasResponse = false;
TileEntity te = world.getBlockTileEntity(x, y, z);
if(te != null && te instanceof IUpgradable)
{
IUpgradable upgradable = (IUpgradable)te;
ItemStack is = player.inventory.getCurrentItem();
if(is != null)
{
Item i = is.getItem();
if(i instanceof ItemWarpUpgrade)
{
if(upgradable.takeUpgrade(EnumUpgradeTypes.values()[is.getItemDamage()],false))
{
if(!player.capabilities.isCreativeMode)
player.inventory.decrStackSize(player.inventory.currentItem, 1);
player.addChatMessage("Upgrade accepted");
}
else
{
player.addChatMessage("Upgrade declined");
}
hasResponse = true;
}
}
}
return hasResponse;
}
/**/
@Override
public void onNeighborBlockChange(World w, int x, int y, int z, int b) {
super.onNeighborBlockChange(w, x, y, z, b);
TileEntity te = w.getBlockTileEntity(x, y, z);
if (te instanceof IBlockUpdateDetector) {
((IBlockUpdateDetector)te).updatedNeighbours();
}
}
}