Update BuildCraft API to 218FB4A

This commit is contained in:
Tom Elfring committed 2017-07-10 18:19:00 +02:00
1 parent 5e17742c45
commit e860089535
127 files changed
+2015 -2634

No files matched your search

+122
View File
@@ -0,0 +1,122 @@
package buildcraft.api;
import java.util.HashSet;
import java.util.Set;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.LoaderState;
import buildcraft.api.core.BCDebugging;
import buildcraft.api.core.BCLog;
/** Stores all of BuildCraft's blocks, from all of its modules. If any of them have been disabled by the user (or it the
* module is not installed) then they will be null. This is the equivalent of {@link Blocks} */
public class BCBlocks {
private static final boolean DEBUG = BCDebugging.shouldDebugLog("api.blocks");
// BC Core
public static final Block CORE_DECORATED;
public static final Block CORE_ENGINE;
public static final Block CORE_MARKER_VOLUME;
public static final Block CORE_MARKER_PATH;
// BC Builders
// BC Energy
// BC Factory
public static final Block FACTORY_TANK;
public static final Block FACTORY_PUMP;
public static final Block FACTORY_CHUTE;
public static final Block FACTORY_FLOOD_GATE;
public static final Block FACTORY_MINING_WELL;
public static final Block FACTORY_AUTOWORKBENCH_ITEM;
public static final Block FACTORY_DISTILLER;
public static final Block FACTORY_HEAT_EXCHANGE_START;
public static final Block FACTORY_HEAT_EXCHANGE_MIDDLE;
public static final Block FACTORY_HEAT_EXCHANGE_END;
// BC Robotics
// BC Silicon
public static final Block SILICON_LASER;
public static final Block SILICON_TABLE_ASSEMBLY;
public static final Block SILICON_TABLE_INTEGRATION;
public static final Block SILICON_TABLE_ADV_CRAFT;
public static final Block SILICON_TABLE_CHARGING;
public static final Block SILICON_TABLE_PROGRAMMING;
// BC Transport
// Set of items scanned
private static final Set<String> SCANNED = DEBUG ? new HashSet<>() : null;
static {
if (!Loader.instance().hasReachedState(LoaderState.INITIALIZATION)) {
throw new RuntimeException("Accessed BC blocks too early! You can only use them from init onwards!");
}
String core = "core";
CORE_DECORATED = getRegisteredBlock(core, "decorated");
CORE_ENGINE = getRegisteredBlock(core, "engine");
CORE_MARKER_VOLUME = getRegisteredBlock(core, "marker_volume");
CORE_MARKER_PATH = getRegisteredBlock(core, "marker_path");
String energy = "energy";
String factory = "factory";
FACTORY_TANK = getRegisteredBlock(factory, "tank");
FACTORY_PUMP = getRegisteredBlock(factory, "pump");
FACTORY_CHUTE = getRegisteredBlock(factory, "chute");
FACTORY_FLOOD_GATE = getRegisteredBlock(factory, "flood_gate");
FACTORY_MINING_WELL = getRegisteredBlock(factory, "mining_well");
FACTORY_AUTOWORKBENCH_ITEM = getRegisteredBlock(factory, "autoworkbench_item");
FACTORY_DISTILLER = getRegisteredBlock(factory, "distiller");
FACTORY_HEAT_EXCHANGE_START = getRegisteredBlock(factory, "heat_exchange_start");
FACTORY_HEAT_EXCHANGE_MIDDLE = getRegisteredBlock(factory, "heat_exchange_middle");
FACTORY_HEAT_EXCHANGE_END = getRegisteredBlock(factory, "heat_exchange_end");
String silicon = "silicon";
SILICON_LASER = getRegisteredBlock(silicon, "laser");
SILICON_TABLE_ASSEMBLY = getRegisteredBlock(silicon, "assembly_table");
SILICON_TABLE_INTEGRATION = getRegisteredBlock(silicon, "integration_table");
SILICON_TABLE_ADV_CRAFT = getRegisteredBlock(silicon, "advanced_crafting_table");
SILICON_TABLE_CHARGING = getRegisteredBlock(silicon, "charging_table");
SILICON_TABLE_PROGRAMMING = getRegisteredBlock(silicon, "programming_table");
if (DEBUG) {
for (Block block : Block.REGISTRY) {
ResourceLocation id = block.getRegistryName();
if (id.getResourceDomain().startsWith("buildcraft")) {
if (!SCANNED.contains(id.toString())) {
BCLog.logger.warn("[api.blocks] Found a block " + id.toString() + " that was not registered with the API! Is this a bug?");
}
}
}
}
}
private static Block getRegisteredBlock(String module, String regName) {
String modid = "buildcraft" + module;
Block block = Block.REGISTRY.getObject(new ResourceLocation(modid, regName));
if (block != Blocks.AIR) {
if (DEBUG) {
BCLog.logger.info("[api.blocks] Found the block " + regName + " from the module " + module);
SCANNED.add(modid + ":" + regName);
}
return block;
}
if (DEBUG) {
if (Loader.isModLoaded(modid)) {
BCLog.logger.info("[api.blocks] Did not find the block " + regName + " despite the appropriate mod being loaded (" + modid + ")");
} else {
BCLog.logger.info("[api.blocks] Did not find the block " + regName + " probably because the mod is not loaded (" + modid + ")");
}
}
return null;
}
}
+167
View File
@@ -0,0 +1,167 @@
package buildcraft.api;
import java.util.HashSet;
import java.util.Set;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.LoaderState;
import buildcraft.api.core.BCDebugging;
import buildcraft.api.core.BCLog;
/** Stores all of BuildCraft's items, from all of its modules. If any of them have been disabled by the user (or it the
* module is not installed) then they will be null. This is the equivalent of {@link Items} */
public class BCItems {
private static final boolean DEBUG = BCDebugging.shouldDebugLog("api.items");
// The (optional) items in BC LIB, and has other rules for when they are enabled.
public static final Item LIB_GUIDE;
public static final Item LIB_DEBUGGER;
// BC Core
public static final Item CORE_WRENCH;
public static final Item CORE_DIAMOND_SHARD;
public static final Item CORE_LIST;
public static final Item CORE_MAP_LOCATION;
public static final Item CORE_PAINTBRUSH;
public static final Item CORE_GEAR_WOOD;
public static final Item CORE_GEAR_STONE;
public static final Item CORE_GEAR_IRON;
public static final Item CORE_GEAR_GOLD;
public static final Item CORE_GEAR_DIAMOND;
public static final Item CORE_MARKER_CONNECTOR;
public static final Item CORE_GOGGLES;
// BC Builders
public static final Item BUILDERS_SINGLE_SCHEMATIC;
public static final Item BUILDERS_SNAPSHOT;
// BC Energy
public static final Item ENERGY_GLOB_OF_OIL;
// BC Factory
public static final Item FACTORY_PLASTIC_SHEET;
// BC Robotics
public static final Item ROBOTICS_REDSTONE_BOARD;
public static final Item ROBOTICS_ROBOT;
public static final Item ROBOTICS_ROBOT_GOGGLES;
public static final Item ROBOTICS_PLUGGABLE_ROBOT_STATION;
// BC Silicon
public static final Item SILICON_REDSTONE_CHIPSET;
// BC Transport
public static final Item TRANSPORT_WATERPROOF;
public static final Item TRANSPORT_GATE_COPIER;
public static final Item TRANSPORT_PLUGGABLE_GATE;
public static final Item TRANSPORT_PLUGGABLE_WIRE;
public static final Item TRANSPORT_PLUGGABLE_BLOCKER;
public static final Item TRANSPORT_PLUGGABLE_LENS;
public static final Item TRANSPORT_PLUGGABLE_POWER_ADAPTOR;
public static final Item TRANSPORT_PLUGGABLE_FACADE;
public static final Item TRANSPORT_PIPE_WOOD_ITEM;
public static final Item TRANSPORT_PIPE_WOOD_FLUID;
public static final Item TRANSPORT_PIPE_WOOD_POWER;
// ... a few more needed...
public static final Item TRANSPORT_PIPE_DIAMOND_ITEM;
// Set of items scanned
private static final Set<String> SCANNED = DEBUG ? new HashSet<>() : null;
static {
if (!Loader.instance().hasReachedState(LoaderState.INITIALIZATION)) {
throw new RuntimeException("Accessed BC items too early! You can only use them from init onwards!");
}
final String lib = "lib";
LIB_GUIDE = getRegisteredItem(lib, "guide");
LIB_DEBUGGER = getRegisteredItem(lib, "debugger");
final String core = "core";
CORE_WRENCH = getRegisteredItem(core, "wrench");
CORE_DIAMOND_SHARD = getRegisteredItem(core, "diamond_shard");
CORE_LIST = getRegisteredItem(core, "list");
CORE_MAP_LOCATION = getRegisteredItem(core, "map_location");
CORE_PAINTBRUSH = getRegisteredItem(core, "paintbrush");
CORE_GEAR_WOOD = getRegisteredItem(core, "gear_wood");
CORE_GEAR_STONE = getRegisteredItem(core, "gear_stone");
CORE_GEAR_IRON = getRegisteredItem(core, "gear_iron");
CORE_GEAR_GOLD = getRegisteredItem(core, "gear_gold");
CORE_GEAR_DIAMOND = getRegisteredItem(core, "gear_diamond");
CORE_MARKER_CONNECTOR = getRegisteredItem(core, "marker_connector");
CORE_GOGGLES = getRegisteredItem(core, "goggles");
final String builders = "builders";
BUILDERS_SINGLE_SCHEMATIC = getRegisteredItem(builders, "single_schematic");
BUILDERS_SNAPSHOT = getRegisteredItem(builders, "snapshot");
final String energy = "energy";
ENERGY_GLOB_OF_OIL = getRegisteredItem(energy, "glob_oil");
final String factory = "factory";
FACTORY_PLASTIC_SHEET = getRegisteredItem(factory, "plastic_sheet");
final String robotics = "robotics";
ROBOTICS_REDSTONE_BOARD = getRegisteredItem(robotics, "redstone_board");
ROBOTICS_ROBOT = getRegisteredItem(robotics, "robot");
ROBOTICS_PLUGGABLE_ROBOT_STATION = getRegisteredItem(robotics, "robot_station");
ROBOTICS_ROBOT_GOGGLES = getRegisteredItem(robotics, "robot_goggles");
final String silicon = "silicon";
SILICON_REDSTONE_CHIPSET = getRegisteredItem(silicon, "redstone_chipset");
final String transport = "transport";
TRANSPORT_WATERPROOF = getRegisteredItem(transport, "waterproof");
TRANSPORT_GATE_COPIER = getRegisteredItem(transport, "gate_copier");
TRANSPORT_PLUGGABLE_GATE = getRegisteredItem(transport, "plug_gate");
TRANSPORT_PLUGGABLE_WIRE = getRegisteredItem(transport, "plug_wire");
TRANSPORT_PLUGGABLE_BLOCKER = getRegisteredItem(transport, "plug_blocker");
TRANSPORT_PLUGGABLE_LENS = getRegisteredItem(transport, "plug_lens");
TRANSPORT_PLUGGABLE_FACADE = getRegisteredItem(transport, "plug_facade");
TRANSPORT_PLUGGABLE_POWER_ADAPTOR = getRegisteredItem(transport, "plug_power_adapter");
TRANSPORT_PIPE_WOOD_ITEM = getRegisteredItem(transport, "pipe_wood_item");
TRANSPORT_PIPE_WOOD_FLUID = getRegisteredItem(transport, "pipe_wood_fluid");
TRANSPORT_PIPE_WOOD_POWER = getRegisteredItem(transport, "pipe_wood_power");
TRANSPORT_PIPE_DIAMOND_ITEM = getRegisteredItem(transport, "pipe_diamond_item");
if (DEBUG) {
for (Item item : Item.REGISTRY) {
ResourceLocation id = item.getRegistryName();
if (id.getResourceDomain().startsWith("buildcraft")) {
if (!SCANNED.contains(id.toString())) {
BCLog.logger.warn("[api.items] Found an item " + id.toString() + " that was not registered with the API! Is this a bug?");
}
}
}
}
}
private static Item getRegisteredItem(String module, String regName) {
String modid = "buildcraft" + module;
Item item = Item.REGISTRY.getObject(new ResourceLocation(modid, regName));
if (item != null) {
if (DEBUG) {
BCLog.logger.info("[api.items] Found the item " + regName + " from the module " + module);
SCANNED.add(modid + ":" + regName);
}
return item;
}
if (DEBUG) {
if (Loader.isModLoaded(modid)) {
BCLog.logger.info("[api.items] Did not find the item " + regName + " despite the appropriate mod being loaded (" + modid + ")");
} else {
BCLog.logger.info("[api.items] Did not find the item " + regName + " probably because the mod is not loaded (" + modid + ")");
}
}
return null;
}
}
@@ -0,0 +1,67 @@
package buildcraft.api;
import java.util.Locale;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.LoaderState;
import buildcraft.api.core.BCLog;
public enum BCModules {
LIB,
// Base module for all BC.
CORE,
// Potentially optional modules for adding more BC functionality
BUILDERS,
ENERGY,
FACTORY,
ROBOTICS,
SILICON,
TRANSPORT,
// Optional module for compatibility with other mods
COMPAT;
public static final BCModules[] VALUES = values();
private static final String MODID_START = "buildcraft";
private final String modid, part;
BCModules() {
part = name().toLowerCase(Locale.ROOT);
this.modid = MODID_START + part;
}
public static void fmlPreInit() {}
public static boolean isBcMod(String modid) {
if (!modid.startsWith(MODID_START)) return false;
String post = modid.substring(MODID_START.length());
for (BCModules module : VALUES) {
if (post.equals(module.part)) {
return true;
}
}
return false;
}
public boolean isLoaded() {
return Loader.isModLoaded(modid);
}
public String getModId() {
return modid;
}
static {
if (!Loader.instance().hasReachedState(LoaderState.CONSTRUCTING)) {
throw new RuntimeException("Accessed BC modules too early! You can only use them from construction onwards!");
}
for (BCModules module : values()) {
if (module.isLoaded()) {
BCLog.logger.info("[api.modules] Module " + module.name().toLowerCase(Locale.ROOT) + " is loaded!");
} else {
BCLog.logger.warn("[api.modules] Module " + module.name().toLowerCase(Locale.ROOT) + " is NOT loaded!");
}
}
}
}
@@ -1,30 +0,0 @@
/** Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com
*
* The BuildCraft API is distributed under the terms of the MIT License. Please check the contents of the license, which
* should be located as "LICENSE.API" in the BuildCraft source code distribution. */
package buildcraft.api.blueprints;
import java.io.File;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
/** This class is provided as a utility class for third-party mods that would like to easily deploy structures that are
* written in blueprints. It does not offer control on material that needs to get in, or how the structure is deployed,
* but allows to create contents of a blueprint in one cycle. Note that these functionalities will only work if
* BuildCraft is installed. */
public abstract class BlueprintDeployer {
/** The deployed instantiated by BuildCraft. This is set by the BuildCraft builder mod. Mods that want to work with
* BuildCraft not installed should check for this value to be not null. */
public static BlueprintDeployer instance;
/** Deploy the contents of the blueprints as if the builder was located at {pos} facing the direction dir. */
public abstract void deployBlueprint(World world, BlockPos pos, EnumFacing facing, File file);
/** Deploy the contents of the byte array as if the builder was located at {pos} facing the direction dir. */
public abstract void deployBlueprintFromFileStream(World world, BlockPos pos, EnumFacing dir, byte[] data);
}
@@ -1,16 +0,0 @@
/** Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com
*
* The BuildCraft API is distributed under the terms of the MIT License. Please check the contents of the license, which
* should be located as "LICENSE.API" in the BuildCraft source code distribution. */
package buildcraft.api.blueprints;
public final class BuilderAPI {
public static ISchematicRegistry schematicRegistry;
public static ISchematicHelper schematicHelper;
private static final long MJ = 1000 * 1000;
public static final long BREAK_POWER = 16 * MJ;// micro Mj
public static final long BUILD_POWER = 24 * MJ;// micro Mj
private BuilderAPI() {}
}
@@ -1,21 +0,0 @@
/** Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com
*
* The BuildCraft API is distributed under the terms of the MIT License. Please check the contents of the license, which
* should be located as "LICENSE.API" in the BuildCraft source code distribution. */
package buildcraft.api.blueprints;
/** Schematics recorded in the blueprints can restrict situations where a blueprint can be used. A same schematic class
* can have different permissions depending on its contents. It's particularly useful when fixing a schematic, if
* blueprints that saved the previous version should not be built because of a bug (such as dupe bug on inventories). */
public enum BuildingPermission {
/** No restrictions, blueprints using this schematic are good in all contexts. */
ALL,
/** This blueprints containing this schematic can only be used in creative. Maybe the block can't be crafted in
* survival in the first place, or the content of the schematic is known to have dupe bugs. */
CREATIVE_ONLY,
/** Blueprints containing this schematic should not be built. This is typically used when a critical problems have
* been fixed, but older versions of the schematic are too badly broken to be retreived. */
NONE,
}
@@ -1,22 +0,0 @@
/** Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com
*
* The BuildCraft API is distributed under the terms of the MIT License. Please check the contents of the license, which
* should be located as "LICENSE.API" in the BuildCraft source code distribution. */
package buildcraft.api.blueprints;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import buildcraft.api.core.IBox;
/** This interface provide contextual information when building or initializing blueprint slots. */
public interface IBuilderContext {
Vec3d rotatePositionLeft(Vec3d pos);
IBox surroundingBox();
World world();
MappingRegistry getMappingRegistry();
}
@@ -1,7 +0,0 @@
package buildcraft.api.blueprints;
import net.minecraft.item.ItemStack;
public interface ISchematicHelper {
boolean isEqualItem(ItemStack a, ItemStack b);
}
@@ -1,19 +0,0 @@
/** Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com
*
* The BuildCraft API is distributed under the terms of the MIT License. Please check the contents of the license, which
* should be located as "LICENSE.API" in the BuildCraft source code distribution. */
package buildcraft.api.blueprints;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
public interface ISchematicRegistry {
void registerSchematicBlock(Block block, Class<? extends Schematic> clazz, Object... params);
void registerSchematicBlock(IBlockState state, Class<? extends Schematic> clazz, Object... params);
void registerSchematicEntity(Class<? extends Entity> entityClass, Class<? extends SchematicEntity> schematicClass, Object... params);
boolean isSupported(IBlockState state);
}
@@ -1,13 +0,0 @@
/** Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com
*
* The BuildCraft API is distributed under the terms of the MIT License. Please check the contents of the license, which
* should be located as "LICENSE.API" in the BuildCraft source code distribution. */
package buildcraft.api.blueprints;
import net.minecraft.inventory.IInventory;
public interface ITileBuilder extends IInventory {
boolean isBuildingMaterialSlot(int i);
}
@@ -1,13 +0,0 @@
/** Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com
*
* The BuildCraft API is distributed under the terms of the MIT License. Please check the contents of the license, which
* should be located as "LICENSE.API" in the BuildCraft source code distribution. */
package buildcraft.api.blueprints;
public class MappingNotFoundException extends Exception {
private static final long serialVersionUID = 1L;
public MappingNotFoundException(String msg) {
super(msg);
}
}
@@ -1,422 +0,0 @@
/** Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com
*
* The BuildCraft API is distributed under the terms of the MIT License. Please check the contents of the license, which
* should be located as "LICENSE.API" in the BuildCraft source code distribution. */
package buildcraft.api.blueprints;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map.Entry;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import org.apache.logging.log4j.Level;
import net.minecraft.block.Block;
import net.minecraft.crash.CrashReportCategory;
import net.minecraft.entity.Entity;
import net.minecraft.item.Item;
import net.minecraft.nbt.NBTTagByte;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTTagShort;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.fml.common.FMLModContainer;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.event.FMLMissingMappingsEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;
import buildcraft.api.core.BCLog;
public class MappingRegistry {
public HashMap<Block, Integer> blockToId = new HashMap<Block, Integer>();
public ArrayList<Block> idToBlock = new ArrayList<Block>();
public HashMap<Item, Integer> itemToId = new HashMap<Item, Integer>();
public ArrayList<Item> idToItem = new ArrayList<Item>();
public HashMap<Class<? extends Entity>, Integer> entityToId = new HashMap<Class<? extends Entity>, Integer>();
public ArrayList<Class<? extends Entity>> idToEntity = new ArrayList<Class<? extends Entity>>();
private void registerItem(Item item) {
if (item == null) throw new IllegalArgumentException("Cannot register a null item!");
if (!itemToId.containsKey(item)) {
idToItem.add(item);
itemToId.put(item, idToItem.size() - 1);
}
}
private void registerBlock(Block block) {
if (block == null) throw new IllegalArgumentException("Cannot register a null block!");
if (!blockToId.containsKey(block)) {
idToBlock.add(block);
blockToId.put(block, idToBlock.size() - 1);
}
}
private void registerEntity(Class<? extends Entity> entityClass) {
if (entityClass == null) throw new IllegalArgumentException("Cannot register a null entityClass!");
if (!entityToId.containsKey(entityClass)) {
idToEntity.add(entityClass);
entityToId.put(entityClass, idToEntity.size() - 1);
}
}
public Item getItemForId(int id) throws MappingNotFoundException {
if (id >= idToItem.size()) {
throw new MappingNotFoundException("no item mapping at position " + id);
}
Item result = idToItem.get(id);
if (result == null) {
throw new MappingNotFoundException("no item mapping at position " + id);
} else {
return result;
}
}
public int getIdForItem(Item item) {
if (item == null) throw new NullPointerException("item");
if (!itemToId.containsKey(item)) {
registerItem(item);
}
return itemToId.get(item);
}
public int itemIdToRegistry(int id) {
Item item = Item.getItemById(id);
return getIdForItem(item);
}
public ResourceLocation itemIdToWorld(int id) throws MappingNotFoundException {
Item item = getItemForId(id);
return Item.REGISTRY.getNameForObject(item);
}
public Block getBlockForId(int id) throws MappingNotFoundException {
if (id >= idToBlock.size()) {
throw new MappingNotFoundException("no block mapping at position " + id);
}
Block result = idToBlock.get(id);
if (result == null) {
throw new MappingNotFoundException("no block mapping at position " + id);
} else {
return result;
}
}
public int getIdForBlock(Block block) {
if (!blockToId.containsKey(block)) {
registerBlock(block);
}
return blockToId.get(block);
}
public int blockIdToRegistry(int id) {
Block block = Block.getBlockById(id);
return getIdForBlock(block);
}
public ResourceLocation blockIdToWorld(int id) throws MappingNotFoundException {
Block block = getBlockForId(id);
return Block.REGISTRY.getNameForObject(block);
}
public Class<? extends Entity> getEntityForId(int id) throws MappingNotFoundException {
if (id >= idToEntity.size()) {
throw new MappingNotFoundException("no entity mapping at position " + id);
}
Class<? extends Entity> result = idToEntity.get(id);
if (result == null) {
throw new MappingNotFoundException("no entity mapping at position " + id);
} else {
return result;
}
}
public int getIdForEntity(Class<? extends Entity> entity) {
if (!entityToId.containsKey(entity)) {
registerEntity(entity);
}
return entityToId.get(entity);
}
/** Relocates a stack nbt from the registry referential to the world referential. */
public void stackToWorld(NBTTagCompound nbt) throws MappingNotFoundException {
if (nbt.hasKey("id", Constants.NBT.TAG_SHORT)) {
Item item = getItemForId(nbt.getShort("id"));
nbt.setString("id", (item.getRegistryName().toString()));
}
}
// versions before 1.8 saved stacks with an Item ID as a short
private boolean isOldStackLayout(NBTTagCompound nbt) {
return nbt.hasKey("id") && nbt.hasKey("Count") && nbt.hasKey("Damage") && nbt.getTag("id") instanceof NBTTagShort && nbt.getTag(
"Count") instanceof NBTTagByte && nbt.getTag("Damage") instanceof NBTTagShort;
}
public void scanAndTranslateStacksToWorld(NBTTagCompound nbt) throws MappingNotFoundException {
// First, check if this nbt is itself a stack
if (isOldStackLayout(nbt)) {
stackToWorld(nbt);
}
// Then, look at the nbt compound contained in this nbt (even if it's a
// stack) and checks for stacks in it.
for (String key : (Collection<String>) nbt.getKeySet()) {
if (nbt.getTag(key) instanceof NBTTagCompound) {
try {
scanAndTranslateStacksToWorld(nbt.getCompoundTag(key));
} catch (MappingNotFoundException e) {
nbt.removeTag(key);
}
}
if (nbt.getTag(key) instanceof NBTTagList) {
NBTTagList list = (NBTTagList) nbt.getTag(key);
if (list.getTagType() == Constants.NBT.TAG_COMPOUND) {
for (int i = list.tagCount() - 1; i >= 0; --i) {
try {
scanAndTranslateStacksToWorld(list.getCompoundTagAt(i));
} catch (MappingNotFoundException e) {
list.removeTag(i);
}
}
}
}
}
}
public void write(NBTTagCompound nbt) {
NBTTagList blocksMapping = new NBTTagList();
for (Block b : idToBlock) {
NBTTagCompound sub = new NBTTagCompound();
if (b != null) {
Object obj = Block.REGISTRY.getNameForObject(b);
if (obj == null) {
BCLog.logger.error("Block " + b.getUnlocalizedName() + " (" + b.getClass().getName()
+ ") does not have a registry name! This is a bug!");
} else {
String name = obj.toString();
if (name == null || name.length() == 0) {
BCLog.logger.error("Block " + b.getUnlocalizedName() + " (" + b.getClass().getName()
+ ") has an empty registry name! This is a bug!");
} else {
sub.setString("name", name);
}
}
} else {
throw new IllegalArgumentException("Found a null block!");
}
blocksMapping.appendTag(sub);
}
nbt.setTag("blocksMapping", blocksMapping);
NBTTagList itemsMapping = new NBTTagList();
for (Item i : idToItem) {
NBTTagCompound sub = new NBTTagCompound();
if (i != null) {
ResourceLocation obj = Item.REGISTRY.getNameForObject(i);
if (obj == null) {
BCLog.logger.error("Item " + i.getUnlocalizedName() + " (" + i.getClass().getName()
+ ") does not have a registry name! This is a bug!");
} else {
String name = obj.toString();
if (name == null || name.length() == 0) {
BCLog.logger.error("Item " + i.getUnlocalizedName() + " (" + i.getClass().getName()
+ ") has an empty registry name! This is a bug!");
} else {
sub.setString("name", name);
}
}
} else {
throw new IllegalArgumentException("Found a null item!");
}
itemsMapping.appendTag(sub);
}
nbt.setTag("itemsMapping", itemsMapping);
NBTTagList entitiesMapping = new NBTTagList();
for (Class<? extends Entity> e : idToEntity) {
NBTTagCompound sub = new NBTTagCompound();
sub.setString("name", e.getCanonicalName());
entitiesMapping.appendTag(sub);
}
nbt.setTag("entitiesMapping", entitiesMapping);
// System.out.println("[W] idToItem size : " + idToItem.size());
// for (Item i : idToItem) {
// System.out.println("- " + (i != null ? i.toString() : "null"));
// }
}
private Object getMissingMappingFromFML(boolean isBlock, String name, int i) {
ResourceLocation location = new ResourceLocation(name);
String modName = name.split(":")[0];
if (Loader.isModLoaded(modName)) {
try {
FMLMissingMappingsEvent.MissingMapping mapping = new FMLMissingMappingsEvent.MissingMapping(isBlock ? GameRegistry.Type.BLOCK
: GameRegistry.Type.ITEM, location, i);
ListMultimap<String, FMLMissingMappingsEvent.MissingMapping> missingMapping = ArrayListMultimap.create();
missingMapping.put(modName, mapping);
FMLMissingMappingsEvent event = new FMLMissingMappingsEvent(missingMapping);
for (ModContainer container : Loader.instance().getModList()) {
if (container instanceof FMLModContainer) {
event.applyModContainer(container);
((FMLModContainer) container).handleModStateEvent(event);
if (mapping.getAction() != FMLMissingMappingsEvent.Action.DEFAULT) {
break;
}
}
}
if (mapping.getAction() == FMLMissingMappingsEvent.Action.REMAP) {
return mapping.getTarget();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
public void read(NBTTagCompound nbt) {
NBTTagList blocksMapping = nbt.getTagList("blocksMapping", Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < blocksMapping.tagCount(); ++i) {
NBTTagCompound sub = blocksMapping.getCompoundTagAt(i);
if (!sub.hasKey("name")) {
// Keeping the order correct
idToBlock.add(null);
BCLog.logger.log(Level.WARN, "Can't load a block - corrupt blueprint!");
continue;
}
String name = sub.getString("name");
ResourceLocation location = new ResourceLocation(name);
Block b = null;
if (!Block.REGISTRY.containsKey(location) && name.contains(":")) {
b = (Block) getMissingMappingFromFML(true, name, i);
if (b != null) {
BCLog.logger.info("Remapped " + name + " to " + Block.REGISTRY.getNameForObject(b));
}
}
if (b == null && Block.REGISTRY.containsKey(location)) {
b = (Block) Block.REGISTRY.getObject(location);
}
if (b != null) {
registerBlock(b);
} else {
// Keeping the order correct
idToBlock.add(null);
BCLog.logger.log(Level.WARN, "Can't load block " + name);
}
}
NBTTagList itemsMapping = nbt.getTagList("itemsMapping", Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < itemsMapping.tagCount(); ++i) {
NBTTagCompound sub = itemsMapping.getCompoundTagAt(i);
if (!sub.hasKey("name")) {
// Keeping the order correct
idToItem.add(null);
BCLog.logger.log(Level.WARN, "Can't load an item - corrupt blueprint!");
continue;
}
String name = sub.getString("name");
ResourceLocation location = new ResourceLocation(name);
Item item = null;
if (!Item.REGISTRY.containsKey(location) && name.contains(":")) {
item = (Item) getMissingMappingFromFML(false, name, i);
if (item != null) {
BCLog.logger.info("Remapped " + name + " to " + Item.REGISTRY.getNameForObject(item));
}
}
if (item == null && Item.REGISTRY.containsKey(location)) {
item = (Item) Item.REGISTRY.getObject(location);
}
if (item != null) {
registerItem(item);
} else {
// Keeping the order correct
idToItem.add(null);
BCLog.logger.log(Level.WARN, "Can't load item " + name);
}
}
NBTTagList entitiesMapping = nbt.getTagList("entitiesMapping", Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < entitiesMapping.tagCount(); ++i) {
NBTTagCompound sub = entitiesMapping.getCompoundTagAt(i);
String name = sub.getString("name");
Class<? extends Entity> e = null;
try {
e = (Class<? extends Entity>) Class.forName(name);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
if (e != null) {
registerEntity(e);
} else {
// Keeping the order correct
idToEntity.add(null);
BCLog.logger.log(Level.WARN, "Can't load entity " + name);
}
}
// System.out.println("[R] idToItem size : " + idToItem.size());
// for (Item i : idToItem) {
// System.out.println("- " + (i != null ? i.toString() : "null"));
// }
}
public void addToCrashReport(CrashReportCategory cat) {
cat.addCrashSection("Item Map Count", itemToId.size());
for (Entry<Item, Integer> e : itemToId.entrySet()) {
cat.addCrashSection(" - ID " + e.getValue(), Item.REGISTRY.getNameForObject(e.getKey()));
}
cat.addCrashSection("Block Map Count", blockToId.size());
for (Entry<Block, Integer> e : blockToId.entrySet()) {
cat.addCrashSection(" - ID " + e.getValue(), Block.REGISTRY.getNameForObject(e.getKey()));
}
cat.addCrashSection("Entity Map Count", entityToId.size());
for (Entry<Class<? extends Entity>, Integer> e : entityToId.entrySet()) {
cat.addCrashSection(" - ID " + e.getValue(), e.getKey());
}
}
}
@@ -1,196 +0,0 @@
/** Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com
*
* The BuildCraft API is distributed under the terms of the MIT License. Please check the contents of the license, which
* should be located as "LICENSE.API" in the BuildCraft source code distribution. */
package buildcraft.api.blueprints;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import buildcraft.api.core.IInvSlot;
/** A schematic is a piece of a blueprint. It allows to stock blocks or entities to blueprints, and can have a state
* that moves from a blueprint referential to a world referential. Although default schematic behavior will be OK for a
* lot of objects, specific blocks and entities may be associated with a dedicated schematic class, which will be
* instantiated automatically.
*
* Schematic perform "id translation" in case the block ids between a blueprint and the world installation are
* different. Mapping is done through the builder context.
*
* Detailed documentation on the schematic behavior can be found on
* http://www.mod-buildcraft.com/wiki/doku.php?id=builder_support
*
* Example of schematics for minecraft blocks are available in the package buildcraft.core.schematics. */
// is being replaced by a different schematic implementation
// a simalir styled one to this might be made ontop of the other one though
public abstract class Schematic {
/** Blocks are build in various stages, in order to make sure that a block can indeed be placed, and that it's
* unlikely to disturb other blocks. */
public enum BuildingStage {
/** Standalone blocks do not change once placed. */
STANDALONE,
/** Expanding blocks will grow and may disturb other block locations, like liquids. */
EXPANDING
}
/** This is called to verify whether the required item is equal to the supplied item.
*
* Primarily rely on this for checking metadata/NBT - the item ID itself might have been filtered out by previously
* running code. */
public boolean isItemMatchingRequirement(ItemStack suppliedStack, ItemStack requiredStack) {
return BuilderAPI.schematicHelper.isEqualItem(suppliedStack, requiredStack);
}
/** This is called each time an item matches a requirement. By default, it will increase damage of items that can be
* damaged by the amount of the requirement, and remove the intended amount of items that can't be damaged.
*
* Client may override this behavior. Note that this subprogram may be called twice with the same parameters, once
* with a copy of requirements and stack to check if the entire requirements can be fulfilled, and once with the
* real inventory. Implementer is responsible for updating req (with the remaining requirements if any) and slot
* (after usage).
*
* returns what was used (similar to req, but created from slot, so that any NBT based differences are drawn from
* the correct source) */
public ItemStack useItem(IBuilderContext context, ItemStack req, IInvSlot slot) {
ItemStack stack = slot.getStackInSlot();
ItemStack result = stack.copy();
if (stack.isItemStackDamageable()) {
if (req.getItemDamage() + stack.getItemDamage() <= stack.getMaxDamage()) {
stack.setItemDamage(req.getItemDamage() + stack.getItemDamage());
result.setItemDamage(req.getItemDamage());
req.setCount(0);
}
if (stack.getItemDamage() >= stack.getMaxDamage()) {
slot.decreaseStackInSlot(1);
}
} else {
if (stack.getCount() >= req.getCount()) {
result.setCount(req.getCount());
stack.setCount(stack.getCount() - req.getCount());
req.setCount(0);
} else {
req.setCount(req.getCount() - stack.getCount());
stack.setCount(0);
}
}
if (stack.getCount() == 0) {
stack.setCount(1);
if (stack.getItem().hasContainerItem(stack)) {
ItemStack newStack = stack.getItem().getContainerItem(stack);
slot.setStackInSlot(newStack);
} else {
slot.setStackInSlot(null);
}
}
return result;
}
/** Perform a 90 degree rotation to the slot. */
public void rotateLeft(IBuilderContext context) {
}
/** Applies translations to all positions in the schematic to center in the blueprint referential */
public void translateToBlueprint(Vec3d transform) {
}
/** Apply translations to all positions in the schematic to center in the builder referential */
public void translateToWorld(Vec3d transform) {}
/** Translates blocks and item ids to the blueprint referential */
public void idsToBlueprint(MappingRegistry registry) {}
/** Translates blocks and item ids to the world referential */
public void idsToWorld(MappingRegistry registry) {}
/** Initializes a schematic for blueprint according to an objet placed on {x, y, z} on the world. For blocks, block
* and meta fields will be initialized automatically. */
public void initializeFromObjectAt(IBuilderContext context, BlockPos pos) {}
/** Places the block in the world, at the location specified in the slot, using the stack in parameters */
public void placeInWorld(IBuilderContext context, BlockPos pos, NonNullList<ItemStack> stacks) {}
/** Write specific requirements coming from the world to the blueprint. */
public void storeRequirements(IBuilderContext context, BlockPos pos) {}
/** Returns the requirements needed to build this block. When the requirements are met, they will be removed all at
* once from the builder, before calling writeToWorld. */
public void getRequirementsForPlacement(IBuilderContext context, NonNullList<ItemStack> requirements) {}
/** Returns the amount of energy required to build this slot, depends on the stacks selected for the build. */
public int getEnergyRequirement(NonNullList<ItemStack> stacksUsed) {
int result = 0;
if (stacksUsed != null) {
for (ItemStack s : stacksUsed) {
result += s.getCount() ;//* BuilderAPI.BUILD_ENERGY;
}
}
return result;
}
/** Returns the flying stacks to display in the builder animation. */
public NonNullList<ItemStack> getStacksToDisplay(NonNullList<ItemStack> stackConsumed) {
return stackConsumed;
}
/** Return the stage where this schematic has to be built. */
public BuildingStage getBuildStage() {
return BuildingStage.STANDALONE;
}
/** Return true if the block on the world correspond to the block stored in the blueprint at the location given by
* the slot. By default, this subprogram is permissive and doesn't take into account metadata.
*
* Post processing will be called on these blocks. */
public boolean isAlreadyBuilt(IBuilderContext context, BlockPos pos) {
return true;
}
/** Return true if the block should not be placed to the world. Requirements will not be asked on such a block, and
* building will not be called.
*
* Post processing will be called on these blocks. */
public boolean doNotBuild() {
return false;
}
/** Return true if the schematic should not be used at all. This is computed straight after readFromNBT can be used
* to deactivate schematics in which an inconsistency is detected. It will be considered as a block of air instead.
*
* Post processing will *not* be called on these blocks. */
public boolean doNotUse() {
return false;
}
/** Return the maximium building permission for blueprint containing this schematic. */
public BuildingPermission getBuildingPermission() {
return BuildingPermission.ALL;
}
/** Called on a block when the blueprint has finished to place all the blocks. This may be useful to adjust variable
* depending on surrounding blocks that may not be there already at initial building. */
public void postProcessing(IBuilderContext context, BlockPos pos) {}
/** Saves this schematic to the blueprint NBT. */
public void writeSchematicToNBT(NBTTagCompound nbt, MappingRegistry registry) {}
/** Loads this schematic from the blueprint NBT. */
public void readSchematicFromNBT(NBTTagCompound nbt, MappingRegistry registry) {}
/** Returns the number of cycles to wait after building this schematic. Tiles and entities typically require more
* wait, around 5 cycles. */
public int buildTime() {
return 1;
}
}
@@ -1,193 +0,0 @@
/** Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com
*
* The BuildCraft API is distributed under the terms of the MIT License. Please check the contents of the license, which
* should be located as "LICENSE.API" in the BuildCraft source code distribution. */
package buildcraft.api.blueprints;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import net.minecraft.block.Block;
import net.minecraft.block.BlockFalling;
import net.minecraft.block.BlockLiquid;
import net.minecraft.block.state.IBlockState;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.NonNullList;
import net.minecraft.util.Rotation;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.fluids.BlockFluidBase;
import buildcraft.api.core.BCLog;
public class SchematicBlock extends SchematicBlockBase {
public IBlockState state = null;
public BuildingPermission defaultPermission = BuildingPermission.ALL;
/** This field contains requirements for a given block when stored in the blueprint. Modders can either rely on this
* list or compute their own int Schematic. */
public NonNullList<ItemStack> storedRequirements = NonNullList.create();
private boolean doNotUse = false;
@Override
public void getRequirementsForPlacement(IBuilderContext context, NonNullList<ItemStack> requirements) {
if (state != null) {
if (storedRequirements.size() != 0) {
requirements.addAll(storedRequirements);
} else {
requirements.add(getItemStack(state));
}
}
}
@Override
public boolean isAlreadyBuilt(IBuilderContext context, BlockPos pos) {
IBlockState placed = context.world().getBlockState(pos);
if (state == placed) return true;
if (state.getBlock() != placed.getBlock()) return false;
// This fixes bugs with blocks like stairs that return extra properties that were not visible from the meta.
if (state.getBlock().getMetaFromState(state) == placed.getBlock().getMetaFromState(placed)) return true;
return false;
}
@Override
public void placeInWorld(IBuilderContext context, BlockPos pos, NonNullList<ItemStack> stacks) {
super.placeInWorld(context, pos, stacks);
this.setBlockInWorld(context, pos);
}
@Override
public void storeRequirements(IBuilderContext context, BlockPos pos) {
super.storeRequirements(context, pos);
if (state != null) {
storedRequirements = NonNullList.create();
List<ItemStack> drops = state.getBlock().getDrops(context.world(), pos, state, 0);
if (drops != null) {
storedRequirements.addAll(drops);
}
}
}
@Override
public void writeSchematicToNBT(NBTTagCompound nbt, MappingRegistry registry) {
super.writeSchematicToNBT(nbt, registry);
writeBlockToNBT(nbt, registry);
writeRequirementsToNBT(nbt, registry);
}
@Override
public void readSchematicFromNBT(NBTTagCompound nbt, MappingRegistry registry) {
super.readSchematicFromNBT(nbt, registry);
readBlockFromNBT(nbt, registry);
if (!doNotUse()) {
readRequirementsFromNBT(nbt, registry);
}
}
/** Get a list of relative block coordinates which have to be built before this block can be placed. */
public Set<BlockPos> getPrerequisiteBlocks(IBuilderContext context) {
Set<BlockPos> indexes = new HashSet<BlockPos>();
if (state.getBlock() instanceof BlockFalling) {
indexes.add(new BlockPos(0, -1, 0));
}
return indexes;
}
@Override
public BuildingStage getBuildStage() {
if (state.getBlock() instanceof BlockFluidBase || state.getBlock() instanceof BlockLiquid) {
return BuildingStage.EXPANDING;
} else {
return BuildingStage.STANDALONE;
}
}
@Override
public BuildingPermission getBuildingPermission() {
return defaultPermission;
}
// Utility functions
protected void setBlockInWorld(IBuilderContext context, BlockPos pos) {
context.world().setBlockState(pos, state, 3);
}
@Override
public boolean doNotUse() {
return doNotUse;
}
protected void readBlockFromNBT(NBTTagCompound nbt, MappingRegistry registry) {
try {
Block block = registry.getBlockForId(nbt.getInteger("blockId"));
state = block.getStateFromMeta(nbt.getInteger("blockMeta"));
} catch (MappingNotFoundException e) {
BCLog.logger.info(e);
doNotUse = true;
}
}
protected void readRequirementsFromNBT(NBTTagCompound nbt, MappingRegistry registry) {
storedRequirements = NonNullList.create();
if (nbt.hasKey("rq")) {
NBTTagList rq = nbt.getTagList("rq", Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < rq.tagCount(); ++i) {
try {
NBTTagCompound sub = rq.getCompoundTagAt(i);
registry.stackToWorld(sub);
storedRequirements.add(new ItemStack(sub));
} catch (MappingNotFoundException e) {
defaultPermission = BuildingPermission.CREATIVE_ONLY;
} catch (Throwable t) {
t.printStackTrace();
defaultPermission = BuildingPermission.CREATIVE_ONLY;
}
}
}
}
protected void writeBlockToNBT(NBTTagCompound nbt, MappingRegistry registry) {
nbt.setInteger("blockId", registry.getIdForBlock(state.getBlock()));
nbt.setInteger("blockMeta", state.getBlock().getMetaFromState(state));
}
protected void writeRequirementsToNBT(NBTTagCompound nbt, MappingRegistry registry) {
if (storedRequirements.size() > 0) {
NBTTagList rq = new NBTTagList();
for (ItemStack stack : storedRequirements) {
if (stack.isEmpty() || stack.getItem() == null) throw new IllegalStateException("Found a null requirement! " + getClass());
NBTTagCompound sub = new NBTTagCompound();
stack.writeToNBT(sub);
rq.appendTag(sub);
}
nbt.setTag("rq", rq);
}
}
protected ItemStack getItemStack(IBlockState state, int quantity) {
return new ItemStack(state.getBlock(), quantity, state.getBlock().damageDropped(state));
}
protected ItemStack getItemStack(IBlockState state) {
return getItemStack(state, 1);
}
// Pretty much all blocks (that rotate) rotate this way now
@Override
public void rotateLeft(IBuilderContext context) {
// FIXME: This might be the wrong way
state = state.withRotation(Rotation.CLOCKWISE_90);
}
}
@@ -1,9 +0,0 @@
/** Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com
*
* The BuildCraft API is distributed under the terms of the MIT License. Please check the contents of the license, which
* should be located as "LICENSE.API" in the BuildCraft source code distribution. */
package buildcraft.api.blueprints;
public abstract class SchematicBlockBase extends Schematic {
}
@@ -1,193 +0,0 @@
/** Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com
*
* The BuildCraft API is distributed under the terms of the MIT License. Please check the contents of the license, which
* should be located as "LICENSE.API" in the BuildCraft source code distribution. */
package buildcraft.api.blueprints;
import java.util.Collections;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagDouble;
import net.minecraft.nbt.NBTTagFloat;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.Vec3d;
import net.minecraftforge.common.util.Constants;
public class SchematicEntity extends Schematic {
public Class<? extends Entity> entity;
/** This tree contains additional data to be stored in the blueprint. By default, it will be initialized from
* Schematic.readFromWord with the standard readNBT function of the corresponding tile (if any) and will be loaded
* from BptBlock.writeToWorld using the standard writeNBT function. */
public NBTTagCompound entityNBT = new NBTTagCompound();
/** This field contains requirements for a given block when stored in the blueprint. Modders can either rely on this
* list or compute their own int Schematic. */
public NonNullList<ItemStack> storedRequirements = NonNullList.withSize(0, null);
public BuildingPermission defaultPermission = BuildingPermission.ALL;
@Override
public void getRequirementsForPlacement(IBuilderContext context, NonNullList<ItemStack> requirements) {
requirements.addAll(storedRequirements);
}
public void writeToWorld(IBuilderContext context) {
Entity e = EntityList.createEntityFromNBT(entityNBT, context.world());
context.world().spawnEntity(e);
}
public void readFromWorld(IBuilderContext context, Entity entity) {
entity.writeToNBTOptional(entityNBT);
}
@Override
public void translateToBlueprint(Vec3d transform) {
NBTTagList nbttaglist = entityNBT.getTagList("Pos", 6);
Vec3d pos = new Vec3d(nbttaglist.getDoubleAt(0), nbttaglist.getDoubleAt(1), nbttaglist.getDoubleAt(2));
pos = pos.add(transform);
entityNBT.setTag("Pos", this.newDoubleNBTList(pos.xCoord, pos.yCoord, pos.zCoord));
}
@Override
public void translateToWorld(Vec3d transform) {
NBTTagList nbttaglist = entityNBT.getTagList("Pos", 6);
Vec3d pos = new Vec3d(nbttaglist.getDoubleAt(0), nbttaglist.getDoubleAt(1), nbttaglist.getDoubleAt(2));
pos = pos.add(transform);
entityNBT.setTag("Pos", this.newDoubleNBTList(pos.xCoord, pos.yCoord, pos.zCoord));
}
@Override
public void idsToBlueprint(MappingRegistry registry) {}
@Override
public void idsToWorld(MappingRegistry registry) {
try {
registry.scanAndTranslateStacksToWorld(entityNBT);
} catch (MappingNotFoundException e) {
entityNBT = new NBTTagCompound();
}
}
@Override
public void rotateLeft(IBuilderContext context) {
NBTTagList nbttaglist = entityNBT.getTagList("Pos", 6);
Vec3d pos = new Vec3d(nbttaglist.getDoubleAt(0), nbttaglist.getDoubleAt(1), nbttaglist.getDoubleAt(2));
pos = context.rotatePositionLeft(pos);
entityNBT.setTag("Pos", this.newDoubleNBTList(pos.xCoord, pos.yCoord, pos.zCoord));
nbttaglist = entityNBT.getTagList("Rotation", 5);
float yaw = nbttaglist.getFloatAt(0);
yaw += 90;
entityNBT.setTag("Rotation", this.newFloatNBTList(yaw, nbttaglist.getFloatAt(1)));
}
@Override
public void writeSchematicToNBT(NBTTagCompound nbt, MappingRegistry registry) {
super.writeSchematicToNBT(nbt, registry);
nbt.setInteger("entityId", registry.getIdForEntity(entity));
nbt.setTag("entity", entityNBT);
NBTTagList rq = new NBTTagList();
for (ItemStack stack : storedRequirements) {
NBTTagCompound sub = new NBTTagCompound();
stack.writeToNBT(stack.writeToNBT(sub));
sub.setInteger("id", registry.getIdForItem(stack.getItem()));
rq.appendTag(sub);
}
nbt.setTag("rq", rq);
}
@Override
public void readSchematicFromNBT(NBTTagCompound nbt, MappingRegistry registry) {
super.readSchematicFromNBT(nbt, registry);
entityNBT = nbt.getCompoundTag("entity");
NBTTagList rq = nbt.getTagList("rq", Constants.NBT.TAG_COMPOUND);
NonNullList<ItemStack> rqs = NonNullList.create();
for (int i = 0; i < rq.tagCount(); ++i) {
try {
NBTTagCompound sub = rq.getCompoundTagAt(i);
if (sub.getInteger("id") >= 0) {
// Maps the id in the blueprint to the id in the world
sub.setInteger("id", Item.REGISTRY.getIDForObject(registry.getItemForId(sub.getInteger("id"))));
rqs.add(new ItemStack(sub));
} else {
defaultPermission = BuildingPermission.CREATIVE_ONLY;
}
} catch (Throwable t) {
t.printStackTrace();
defaultPermission = BuildingPermission.CREATIVE_ONLY;
}
}
storedRequirements = rqs;
}
protected NBTTagList newDoubleNBTList(double... par1ArrayOfDouble) {
NBTTagList nbttaglist = new NBTTagList();
double[] adouble = par1ArrayOfDouble;
int i = par1ArrayOfDouble.length;
for (int j = 0; j < i; ++j) {
double d1 = adouble[j];
nbttaglist.appendTag(new NBTTagDouble(d1));
}
return nbttaglist;
}
protected NBTTagList newFloatNBTList(float... par1ArrayOfFloat) {
NBTTagList nbttaglist = new NBTTagList();
float[] afloat = par1ArrayOfFloat;
int i = par1ArrayOfFloat.length;
for (int j = 0; j < i; ++j) {
float f1 = afloat[j];
nbttaglist.appendTag(new NBTTagFloat(f1));
}
return nbttaglist;
}
public boolean isAlreadyBuilt(IBuilderContext context) {
NBTTagList nbttaglist = entityNBT.getTagList("Pos", 6);
Vec3d newPosition = new Vec3d(nbttaglist.getDoubleAt(0), nbttaglist.getDoubleAt(1), nbttaglist.getDoubleAt(2));
for (Object o : context.world().loadedEntityList) {
Entity e = (Entity) o;
Vec3d existingPositon = new Vec3d(e.posX, e.posY, e.posZ);
if (existingPositon.distanceTo(newPosition) <= 0.1) {
return true;
}
}
return false;
}
@Override
public int buildTime() {
return 5;
}
@Override
public BuildingPermission getBuildingPermission() {
return defaultPermission;
}
}
@@ -1,51 +0,0 @@
/** Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com
*
* The BuildCraft API is distributed under the terms of the MIT License. Please check the contents of the license, which
* should be located as "LICENSE.API" in the BuildCraft source code distribution. */
package buildcraft.api.blueprints;
import java.util.HashMap;
import net.minecraft.nbt.NBTTagCompound;
public abstract class SchematicFactory<S extends Schematic> {
private static final HashMap<String, SchematicFactory<?>> factories = new HashMap<String, SchematicFactory<?>>();
private static final HashMap<Class<? extends Schematic>, SchematicFactory<?>> schematicToFactory =
new HashMap<Class<? extends Schematic>, SchematicFactory<?>>();
protected abstract S loadSchematicFromWorldNBT(NBTTagCompound nbt, MappingRegistry registry) throws MappingNotFoundException;
public void saveSchematicToWorldNBT(NBTTagCompound nbt, S object, MappingRegistry registry) {
nbt.setString("factoryID", getClass().getCanonicalName());
}
public static Schematic createSchematicFromWorldNBT(NBTTagCompound nbt, MappingRegistry registry) throws MappingNotFoundException {
String factoryName = nbt.getString("factoryID");
if (factories.containsKey(factoryName)) {
return factories.get(factoryName).loadSchematicFromWorldNBT(nbt, registry);
} else {
return null;
}
}
public static void registerSchematicFactory(Class<? extends Schematic> clas, SchematicFactory<?> factory) {
schematicToFactory.put(clas, factory);
factories.put(factory.getClass().getCanonicalName(), factory);
}
public static SchematicFactory getFactory(Class<? extends Schematic> clas) {
Class superClass = clas.getSuperclass();
if (schematicToFactory.containsKey(clas)) {
return schematicToFactory.get(clas);
} else if (superClass != null) {
return getFactory(superClass);
} else {
return null;
}
}
}
@@ -1,83 +0,0 @@
/** Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com
*
* The BuildCraft API is distributed under the terms of the MIT License. Please check the contents of the license, which
* should be located as "LICENSE.API" in the BuildCraft source code distribution. */
package buildcraft.api.blueprints;
import net.minecraft.block.BlockLiquid;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.fluids.FluidStack;
@Deprecated
public class SchematicFluid extends SchematicBlock {
private final ItemStack fluidItem;
public SchematicFluid(FluidStack fluidStack) {
this.fluidItem = new ItemStack(fluidStack.getFluid().getBlock(), 1);
}
@Override
public void getRequirementsForPlacement(IBuilderContext context, NonNullList<ItemStack> requirements) {
if (getLevel() == 0) {
requirements.add(fluidItem);
}
}
@Override
public void storeRequirements(IBuilderContext context, BlockPos pos) {
// cancel requirements reading
}
@Override
public boolean isAlreadyBuilt(IBuilderContext context, BlockPos pos) {
if (getLevel() == 0) {
return state == context.world().getBlockState(pos) && (context.world().getBlockState(pos).getValue(BlockLiquid.LEVEL)) == 0;
} else {
return state == context.world().getBlockState(pos);
}
}
@Override
public void rotateLeft(IBuilderContext context) {
}
@Override
public boolean doNotBuild() {
return getLevel() != 0;
}
@Override
public void placeInWorld(IBuilderContext context, BlockPos pos, NonNullList<ItemStack> stacks) {
if (getLevel() == 0) {
context.world().setBlockState(pos, state, 3);
}
}
@Override
public void postProcessing(IBuilderContext context, BlockPos pos) {
if (getLevel() != 0) {
context.world().setBlockState(pos, state, 3);
}
}
@Override
public NonNullList<ItemStack> getStacksToDisplay(NonNullList<ItemStack> stackConsumed) {
NonNullList<ItemStack> result = NonNullList.create();
result.add(fluidItem);
return result;
}
@Override
public int getEnergyRequirement(NonNullList<ItemStack> stacksUsed) {
return 1;// * BuilderAPI.BUILD_ENERGY;
}
public int getLevel() {
return state.getValue(BlockLiquid.LEVEL);
}
}
@@ -1,83 +0,0 @@
/** Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com
*
* The BuildCraft API is distributed under the terms of the MIT License. Please check the contents of the license, which
* should be located as "LICENSE.API" in the BuildCraft source code distribution. */
package buildcraft.api.blueprints;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.WorldServer;
import buildcraft.api.core.BuildCraftAPI;
public class SchematicMask extends SchematicBlockBase {
/** True of the block should be a solid block (stone, grass or a furnace) and false if it shouldn't (flowers, air or
* vines) */
public boolean isConcrete = true;
public SchematicMask() {
}
public SchematicMask(boolean isConcrete) {
this.isConcrete = isConcrete;
}
@Override
public void placeInWorld(IBuilderContext context, BlockPos pos, NonNullList<ItemStack> stacks) {
if (isConcrete) {
if (stacks.size() == 0 || !BuildCraftAPI.isSoftBlock(context.world(), pos)) {
return;
} else {
ItemStack stack = stacks.get(0);
EntityPlayer player = BuildCraftAPI.fakePlayerProvider.getBuildCraftPlayer((WorldServer) context.world());
// force the block to be air block, in case it's just a soft
// block which replacement is not straightforward
context.world().setBlockToAir(pos);
// Find nearest solid surface to place on
EnumFacing solidFace = null;
for (EnumFacing face : EnumFacing.values()) {
BlockPos offset = pos.offset(face);
if (!BuildCraftAPI.isSoftBlock(context.world(), offset)) {
solidFace = face;
break;
}
}
ItemBlock itemBlock = (ItemBlock) stack.getItem();
IBlockState state = itemBlock.block.getStateForPlacement(context.world(), pos, solidFace, 0, 0, 0, stack.getMetadata(), player, EnumHand.MAIN_HAND);
itemBlock.placeBlockAt(stack, player, context.world(), pos, solidFace, 0, 0, 0, state);
}
} else {
context.world().setBlockToAir(pos);
}
}
@Override
public boolean isAlreadyBuilt(IBuilderContext context, BlockPos pos) {
if (isConcrete) {
return !BuildCraftAPI.getWorldProperty("replaceable").get(context.world(), pos);
} else {
return BuildCraftAPI.getWorldProperty("replaceable").get(context.world(), pos);
}
}
@Override
public void writeSchematicToNBT(NBTTagCompound nbt, MappingRegistry registry) {
nbt.setBoolean("isConcrete", isConcrete);
}
@Override
public void readSchematicFromNBT(NBTTagCompound nbt, MappingRegistry registry) {
isConcrete = nbt.getBoolean("isConcrete");
}
}
@@ -1,109 +0,0 @@
/** Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com
*
* The BuildCraft API is distributed under the terms of the MIT License. Please check the contents of the license, which
* should be located as "LICENSE.API" in the BuildCraft source code distribution. */
package buildcraft.api.blueprints;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
public class SchematicTile extends SchematicBlock {
/** This tree contains additional data to be stored in the blueprint. By default, it will be initialized from
* Schematic.readFromWord with the standard readNBT function of the corresponding tile (if any) and will be loaded
* from BptBlock.writeToWorld using the standard writeNBT function. */
public NBTTagCompound tileNBT = new NBTTagCompound();
@Override
public void idsToBlueprint(MappingRegistry registry) {}
@Override
public void idsToWorld(MappingRegistry registry) {
try {
registry.scanAndTranslateStacksToWorld(tileNBT);
} catch (MappingNotFoundException e) {
tileNBT = new NBTTagCompound();
}
}
public void onNBTLoaded() {
}
/** Places the block in the world, at the location specified in the slot. */
@Override
public void placeInWorld(IBuilderContext context, BlockPos pos, NonNullList<ItemStack> stacks) {
super.placeInWorld(context, pos, stacks);
if (state.getBlock().hasTileEntity(state)) {
tileNBT.setInteger("x", pos.getX());
tileNBT.setInteger("y", pos.getY());
tileNBT.setInteger("z", pos.getZ());
TileEntity tile = TileEntity.create(context.world(), tileNBT);
if (tile != null) {
tile.setWorld(context.world());
context.world().setTileEntity(pos, tile);
}
}
}
@Override
public void initializeFromObjectAt(IBuilderContext context, BlockPos pos) {
super.initializeFromObjectAt(context, pos);
if (state.getBlock().hasTileEntity(state)) {
TileEntity tile = context.world().getTileEntity(pos);
if (tile != null) {
tile.writeToNBT(tileNBT);
}
tileNBT = tileNBT.copy();
onNBTLoaded();
}
}
@Override
public void storeRequirements(IBuilderContext context, BlockPos pos) {
super.storeRequirements(context, pos);
if (state.getBlock().hasTileEntity(state)) {
TileEntity tile = context.world().getTileEntity(pos);
if (tile instanceof IInventory) {
IInventory inv = (IInventory) tile;
for (int i = 0; i < inv.getSizeInventory(); ++i) {
ItemStack stack = inv.getStackInSlot(i);
if (!stack.isEmpty()) {
storedRequirements.add(stack);
}
}
}
}
}
@Override
public void writeSchematicToNBT(NBTTagCompound nbt, MappingRegistry registry) {
super.writeSchematicToNBT(nbt, registry);
nbt.setTag("blockCpt", tileNBT);
}
@Override
public void readSchematicFromNBT(NBTTagCompound nbt, MappingRegistry registry) {
super.readSchematicFromNBT(nbt, registry);
tileNBT = nbt.getCompoundTag("blockCpt");
onNBTLoaded();
}
@Override
public int buildTime() {
return 5;
}
}
@@ -1,8 +0,0 @@
/** Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com
*
* The BuildCraft API is distributed under the terms of the MIT License. Please check the contents of the license, which
* should be located as "LICENSE.API" in the BuildCraft source code distribution. */
@API(apiVersion = "1.5", owner = "BuildCraftAPI|core", provides = "BuildCraftAPI|blueprints")
package buildcraft.api.blueprints;
import net.minecraftforge.fml.common.API;
@@ -1,81 +0,0 @@
/** Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com
*
* The BuildCraft API is distributed under the terms of the MIT License. Please check the contents of the license, which
* should be located as "LICENSE.API" in the BuildCraft source code distribution. */
package buildcraft.api.core;
import java.util.Arrays;
import org.apache.commons.lang3.StringUtils;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.LoaderState;
public class APIHelper {
public static <T> T getInstance(String clsName, Class<T> baseVersion) {
return getNamedInstance(clsName, "INSTANCE", baseVersion);
}
public static <T> T getInstance(String clsName, Class<T> baseVersion, T nullVersion) {
return getNamedInstance(clsName, "INSTANCE", baseVersion, nullVersion);
}
@SuppressWarnings("unchecked")
public static <T> T getNamedInstance(String clsName, String enumName, Class<T> baseVersion) {
T instance = getNamedInstance(clsName, enumName, baseVersion, null);
if (instance != null) return instance;
Class<?>[] types = baseVersion.getClasses();
Class<?> voidType = null;
for (Class<?> class1 : types) {
if (baseVersion.isAssignableFrom(class1)) voidType = class1;
}
if (voidType != null) {
Object[] arr = voidType.getEnumConstants();
if (arr == null) return null;
Enum<?>[] eArr = ((Class<Enum<?>>) voidType).getEnumConstants();
for (Enum<?> e : eArr) {
if (e.name().equals(enumName) && baseVersion.isInstance(e)) return (T) e;
}
}
return null;
}
@SuppressWarnings("unchecked")
public static <T> T getNamedInstance(String clsName, String enumName, Class<T> baseVersion, T nullVersion) {
if (!Loader.instance().hasReachedState(LoaderState.PREINITIALIZATION)) throw new IllegalStateException(
"Called this API too early, you are not allowed to use BC api before pre init!");
try {
Class<?> cls = Class.forName(clsName);
Object[] arr = cls.getEnumConstants();
if (arr == null) {
return fail(clsName, nullVersion);
}
Enum<?>[] enumArr = ((Class<Enum<?>>) cls).getEnumConstants();
for (Enum<?> e : enumArr) {
if (e.name().equals(enumName) && baseVersion.isInstance(e)) return (T) e;
}
return fail(clsName, nullVersion);
} catch (ClassNotFoundException e) {
return fail(clsName, nullVersion);
}
}
private static <M> M fail(String clsName, M failure) {
String[] split = clsName.split("\\.");
String module;
if (split.length < 2) {
BCLog.logger.warn("Tried and failed to get the module name from " + Arrays.toString(split) + " (" + clsName + ")!");
module = "invalid";
} else {
module = split[1];
}
module = StringUtils.capitalize(module);
String bcMod = "BuildCraft|" + module;
if (Loader.isModLoaded(bcMod)) {
BCLog.logger.warn("Failed to load the " + clsName + " dispite the appropriate buildcraft module being installed (" + module + ")");
}
return failure;
}
}
@@ -15,7 +15,7 @@ public class BCDebugging {
NONE,
ENABLE,
LOGGING_ONLY,
ALL;
ALL
}
enum DebugLevel {
@@ -100,7 +100,7 @@ public class BCDebugging {
log.append(option);
log.append(" add the option \"-D");
log.append(prop);
log.append("=true\" to your launch config as a VM argument (" + type + ").");
log.append("=true\" to your launch config as a VM argument (").append(type).append(").");
BCLog.logger.info(log);
}
return false;
@@ -4,7 +4,6 @@
* should be located as "LICENSE.API" in the BuildCraft source code distribution. */
package buildcraft.api.core;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Set;
@@ -12,12 +11,15 @@ import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import net.minecraft.block.Block;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public final class BuildCraftAPI {
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.ModContainer;
public static IBCFakePlayer fakePlayerProvider;
public final class BuildCraftAPI {
public static IFakePlayerProvider fakePlayerProvider;
public static final Set<Block> softBlocks = Sets.newHashSet();
public static final HashMap<String, IWorldProperty> worldProperties = Maps.newHashMap();
@@ -26,13 +28,11 @@ public final class BuildCraftAPI {
private BuildCraftAPI() {}
public static String getVersion() {
try {
Class<?> clazz = Class.forName("buildcraft.core.Version");
Method method = clazz.getDeclaredMethod("getVersion");
return String.valueOf(method.invoke(null));
} catch (Exception e) {
return "UNKNOWN VERSION";
ModContainer container = Loader.instance().getIndexedModList().get("buildcraftlib");
if (container != null) {
return container.getDisplayVersion();
}
return "UNKNOWN VERSION";
}
public static IWorldProperty getWorldProperty(String name) {
@@ -41,7 +41,7 @@ public final class BuildCraftAPI {
public static void registerWorldProperty(String name, IWorldProperty property) {
if (worldProperties.containsKey(name)) {
BCLog.logger.warn("The WorldProperty key '" + name + "' is being overidden with " + property.getClass().getSimpleName() + "!");
BCLog.logger.warn("The WorldProperty key '" + name + "' is being overridden with " + property.getClass().getSimpleName() + "!");
}
worldProperties.put(name, property);
}
@@ -49,4 +49,13 @@ public final class BuildCraftAPI {
public static boolean isSoftBlock(World world, BlockPos pos) {
return worldProperties.get("soft").get(world, pos);
}
public static ResourceLocation nameToResourceLocation(String name) {
if (name.indexOf(':') > 0) return new ResourceLocation(name);
ModContainer modContainer = Loader.instance().activeModContainer();
if (modContainer == null) {
throw new IllegalStateException("Illegal recipe name " + name + ". Provide domain id to register it correctly.");
}
return new ResourceLocation(modContainer.getModId(), name);
}
}
@@ -0,0 +1,37 @@
package buildcraft.api.core;
import javax.annotation.Nonnull;
import net.minecraft.nbt.NBTBase;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityManager;
public class CapabilitiesHelper {
public static <T> void registerCapability(Class<T> clazz) {
CapabilityManager.INSTANCE.register(clazz, new VoidStorage<>(), () -> {
throw new IllegalStateException("You must create your own instances!");
});
}
@Nonnull
public static <T> Capability<T> ensureRegistration(Capability<T> cap, Class<T> clazz) {
if (cap == null) {
throw new Error("Capability registration failed for " + clazz);
}
return cap;
}
public static class VoidStorage<T> implements Capability.IStorage<T> {
@Override
public NBTBase writeNBT(Capability<T> capability, T instance, EnumFacing side) {
throw new IllegalStateException("You must create your own instances!");
}
@Override
public void readNBT(Capability<T> capability, T instance, EnumFacing side, NBTBase nbt) {
throw new IllegalStateException("You must create your own instances!");
}
}
}
@@ -1,48 +0,0 @@
package buildcraft.api.core;
import java.util.Map;
import com.google.common.collect.Maps;
import net.minecraftforge.common.config.Property;
/** Use this to access the various config options. It is recommended that you use this as opposed to the variables in
* the mod, as users may only install the modules that they want, and not the one you may have refereed to. */
@Deprecated
public final class ConfigAccessor {
public enum EMod {
CORE,
BUILDERS,
ENERGY,
FACTORY,
ROBITICS,
SILICON,
TRANSPORT
}
private static Map<EMod, IBuildCraftMod> mods = Maps.newHashMap();
private ConfigAccessor() {}
public static Property getOption(EMod mod, String name) {
if (mods.containsKey(mod)) {
return mods.get(mod).getOption(name);
} else {
return null;
}
}
public static boolean getBoolean(EMod mod, String name, boolean defaultBoolean) {
Property prop = getOption(mod, name);
if (prop == null) {
return defaultBoolean;
} else {
return prop.getBoolean(defaultBoolean);
}
}
/** WARNING: INTERNAL USE ONLY! */
public static void addMod(EMod mod, IBuildCraftMod actual) {
mods.put(mod, actual);
}
}
@@ -0,0 +1,17 @@
/*
* Copyright (c) 2017 SpaceToad and the BuildCraft team
* The BuildCraft API is distributed under the terms of the MIT License. Please check the contents of the license, which
* should be located as "LICENSE.API" in the BuildCraft source code distribution.
*/
package buildcraft.api.core;
public enum EnumHandlerPriority implements Comparable<EnumHandlerPriority> {
HIGHEST,
HIGH,
NORMAL,
LOW,
LOWEST;
public static final EnumHandlerPriority[] VALUES = values();
}
@@ -11,9 +11,7 @@ import net.minecraft.nbt.NBTTagString;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.IStringSerializable;
import io.netty.buffer.ByteBuf;
public enum EnumPipePart implements IStringSerializable, INetworkLoadable_BC8<EnumPipePart> {
public enum EnumPipePart implements IStringSerializable {
DOWN(EnumFacing.DOWN),
UP(EnumFacing.UP),
NORTH(EnumFacing.NORTH),
@@ -24,7 +22,9 @@ public enum EnumPipePart implements IStringSerializable, INetworkLoadable_BC8<En
CENTER(null);
public static final EnumPipePart[] VALUES = values();
public static final EnumPipePart[] FACES = { DOWN, UP, NORTH, SOUTH, WEST, EAST };
public static final EnumPipePart[] FACES;
public static final EnumPipePart[] HORIZONTALS;
private static final Map<EnumFacing, EnumPipePart> facingMap = Maps.newEnumMap(EnumFacing.class);
private static final Map<String, EnumPipePart> nameMap = Maps.newHashMap();
private static final int MAX_VALUES = values().length;
@@ -36,6 +36,16 @@ public enum EnumPipePart implements IStringSerializable, INetworkLoadable_BC8<En
nameMap.put(part.name(), part);
if (part.face != null) facingMap.put(part.face, part);
}
FACES = fromFacingArray(EnumFacing.VALUES);
HORIZONTALS = fromFacingArray(EnumFacing.HORIZONTALS);
}
private static EnumPipePart[] fromFacingArray(EnumFacing... faces) {
EnumPipePart[] arr = new EnumPipePart[faces.length];
for (int i = 0; i < faces.length; i++) {
arr[i] = fromFacing(faces[i]);
}
return arr;
}
public static int ordinal(EnumFacing face) {
@@ -43,7 +53,9 @@ public enum EnumPipePart implements IStringSerializable, INetworkLoadable_BC8<En
}
public static EnumPipePart fromFacing(EnumFacing face) {
if (face == null) return EnumPipePart.CENTER;
if (face == null) {
return EnumPipePart.CENTER;
}
return facingMap.get(face);
}
@@ -52,11 +64,13 @@ public enum EnumPipePart implements IStringSerializable, INetworkLoadable_BC8<En
}
public static EnumPipePart fromMeta(int meta) {
if (meta < 0 || meta >= MAX_VALUES) return EnumPipePart.CENTER;
if (meta < 0 || meta >= MAX_VALUES) {
return EnumPipePart.CENTER;
}
return VALUES[meta];
}
private EnumPipePart(EnumFacing face) {
EnumPipePart(EnumFacing face) {
this.face = face;
}
@@ -90,19 +104,25 @@ public enum EnumPipePart implements IStringSerializable, INetworkLoadable_BC8<En
}
public EnumPipePart opposite() {
if (this == CENTER) return CENTER;
if (this == CENTER) {
return CENTER;
}
return fromFacing(face.getOpposite());
}
public static EnumPipePart readFromNBT(NBTBase base) {
if (base == null) return CENTER;
if (base == null) {
return CENTER;
}
if (base instanceof NBTTagString) {
NBTTagString nbtString = (NBTTagString) base;
String string = nbtString.getString();
return nameMap.containsKey(string) ? nameMap.get(string) : CENTER;
return nameMap.getOrDefault(string, CENTER);
} else {
byte ord = ((NBTPrimitive) base).getByte();
if (ord < 0 || ord > 6) return CENTER;
if (ord < 0 || ord > 6) {
return CENTER;
}
return values()[ord];
}
}
@@ -110,15 +130,4 @@ public enum EnumPipePart implements IStringSerializable, INetworkLoadable_BC8<En
public NBTBase writeToNBT() {
return new NBTTagString(name());
}
@Override
public EnumPipePart readFromByteBuf(ByteBuf buf) {
byte ord = buf.readByte();
return fromMeta(ord);
}
@Override
public void writeToByteBuf(ByteBuf buf) {
buf.writeByte(ordinal());
}
}
@@ -1,25 +0,0 @@
/** Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com
*
* The BuildCraft API is distributed under the terms of the MIT License. Please check the contents of the license, which
* should be located as "LICENSE.API" in the BuildCraft source code distribution. */
package buildcraft.api.core;
import com.mojang.authlib.GameProfile;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.util.FakePlayer;
public interface IBCFakePlayer {
/** Returns the generic buildcraft fake player. Note that you shouldn't use this anymore, as you should store the
* UUID of the real player who created the block or entity that calls this. */
@Deprecated
FakePlayer getBuildCraftPlayer(WorldServer world);
/** @param world
* @param profile The owner's profile.
* @return A fake player that can be used IN THE CURRENT METHOD CONTEXT ONLY! This will cause problems if this
* player is left around as it holds a reference to the world object. */
FakePlayer getFakePlayer(WorldServer world, GameProfile profile);
}
@@ -1,8 +0,0 @@
package buildcraft.api.core;
import net.minecraftforge.common.config.Property;
@Deprecated
public interface IBuildCraftMod {
Property getOption(String name);
}
@@ -0,0 +1,5 @@
package buildcraft.api.core;
public interface IEngineType {
String getItemModelLocation();
}
@@ -0,0 +1,40 @@
/**
* Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com
* <p>
* The BuildCraft API is distributed under the terms of the MIT License. Please check the contents of the license, which
* should be located as "LICENSE.API" in the BuildCraft source code distribution.
*/
package buildcraft.api.core;
import com.mojang.authlib.GameProfile;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.util.FakePlayer;
public interface IFakePlayerProvider {
/**
* Returns the generic buildcraft fake player. Note that you shouldn't use this anymore, as you should store the
* UUID of the real player who created the block or entity that calls this.
*/
@Deprecated
FakePlayer getBuildCraftPlayer(WorldServer world);
/**
* @param world
* @param profile The owner's profile.
* @return A fake player that can be used IN THE CURRENT METHOD CONTEXT ONLY! This will cause problems if this
* player is left around as it holds a reference to the world object.
*/
FakePlayer getFakePlayer(WorldServer world, GameProfile profile);
/**
* @param world
* @param profile The owner's profile.
* @param pos
* @return A fake player that can be used IN THE CURRENT METHOD CONTEXT ONLY! This will cause problems if this
* player is left around as it holds a reference to the world object.
*/
FakePlayer getFakePlayer(WorldServer world, GameProfile profile, BlockPos pos);
}
@@ -1,14 +0,0 @@
package buildcraft.api.core;
import net.minecraft.nbt.NBTBase;
/** @param <T> The type that will be loaded from and saved too. This essentially allows Immutable objects to be safely
* loaded without helper methods everywhere. However you are allowed to return this if you are a mutable
* object */
public interface INBTLoadable_BC8<T> {
/** @return An object that has the properties loaded. WARNIG! This might be the same object as the one this method
* was called on! (You should always replace the object you have stored with whatever this returns) */
T readFromNBT(NBTBase nbt);
NBTBase writeToNBT();
}
@@ -1,12 +0,0 @@
package buildcraft.api.core;
import net.minecraft.nbt.NBTTagCompound;
/** Use {@link INBTLoadable_BC8} instead of this, as this gives you more control over what NBT goes where, and what
* objects are allowed to do. */
@Deprecated
public interface INBTStoreable {
void readFromNBT(NBTTagCompound tag);
void writeToNBT(NBTTagCompound tag);
}
@@ -1,10 +0,0 @@
package buildcraft.api.core;
import io.netty.buffer.ByteBuf;
@Deprecated
public interface INetworkLoadable_BC8<T> {
T readFromByteBuf(ByteBuf buf);
void writeToByteBuf(ByteBuf buf);
}
@@ -1,4 +1,4 @@
package buildcraft.api.permission;
package buildcraft.api.core;
import com.mojang.authlib.GameProfile;
@@ -1,21 +0,0 @@
/** Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public License 1.0, or MMPL. Please check the contents
* of the license located in http://www.mod-buildcraft.com/MMPL-1.0.txt */
package buildcraft.api.core;
import io.netty.buffer.ByteBuf;
/** Use {@link INetworkLoadable_BC8} instead, as that gives you more control over how you use objects */
@Deprecated
public interface ISerializable {
/** Serializes the state to the stream
*
* @param data */
void writeData(ByteBuf data);
/** Deserializes the state from the stream
*
* @param data */
void readData(ByteBuf data);
}
@@ -7,6 +7,7 @@ package buildcraft.api.core;
import javax.annotation.Nonnull;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
/** This interface provides a convenient means of dealing with entire classes of items without having to specify each
* item individually. */
@@ -17,4 +18,11 @@ public interface IStackFilter {
* @param stack The stack to test. stack.isEmpty will always return false.
* @return True if it does match, false otherwise. */
boolean matches(@Nonnull ItemStack stack);
/**
* Returns example stack to match this filter
*/
default NonNullList<ItemStack> getExamples() {
return NonNullList.withSize(0, ItemStack.EMPTY);
}
}
@@ -0,0 +1,29 @@
/*
* Copyright (c) 2017 SpaceToad and the BuildCraft team
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/
*/
package buildcraft.api.core;
import java.io.IOException;
/**
* Indicates that we failed to load from NBT or some other file.
*/
public class InvalidInputDataException extends IOException {
public InvalidInputDataException() {
}
public InvalidInputDataException(String message) {
super(message);
}
public InvalidInputDataException(Throwable cause) {
super(cause);
}
public InvalidInputDataException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -1,27 +0,0 @@
/** Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public License 1.0, or MMPL. Please check the contents
* of the license located in http://www.mod-buildcraft.com/MMPL-1.0.txt */
package buildcraft.api.core.render;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
/* This interface designates a block as a state machine responsible for culling For implementation details look into
* FakeBlock implementation */
public interface ICullable {
// Side Rendering States
// They are used to effectively cull obstructed sides while processing facades.
// Make sure your implementation is correct otherwise expect FPS drop
void setRenderSide(EnumFacing side, boolean render);
void setRenderAllSides();
boolean shouldSideBeRendered(IBlockAccess blockAccess, BlockPos pos, int side);
void setRenderMask(int mask);
}
@@ -1,7 +0,0 @@
package buildcraft.api.core.render;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
public interface ITextureStateManager {
void set(TextureAtlasSprite icon);
}
@@ -1,18 +0,0 @@
/** Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public License 1.0, or MMPL. Please check the contents
* of the license located in http://www.mod-buildcraft.com/MMPL-1.0.txt */
package buildcraft.api.core.render;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
public interface ITextureStates extends ICullable {
ITextureStateManager getTextureState();
TextureAtlasSprite getIcon(int side, int meta);
Block getBlock();
}
@@ -12,7 +12,7 @@ import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
public final class CropManager {
private static List<ICropHandler> handlers = new ArrayList<ICropHandler>();
private static List<ICropHandler> handlers = new ArrayList<>();
private static ICropHandler defaultHandler;
private CropManager() {
@@ -1,7 +1,5 @@
package buildcraft.api.crops;
import com.mojang.authlib.GameProfile;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
@@ -0,0 +1,50 @@
package buildcraft.api.data;
import java.util.zip.GZIPInputStream;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
public class NbtSquishConstants {
/** Default written NBT Tag type- this is provided by
* {@link CompressedStreamTools#write(NBTTagCompound, java.io.DataOutput)} and
* {@link CompressedStreamTools#read(java.io.DataInput, net.minecraft.nbt.NBTSizeTracker)}.
*
* Generally more suited to smaller NBT tags, and it writes fairly quickly. Can quickly use up a lot of space for
* larger/more complex tags so it is recommended that you also pass it through a GZIP compressor to take up a much
* smaller space. */
public static final int VANILLA = 0;
public static final int VANILLA_COMPRESSED = 1;
/** Buildcraft provided NBT compressor - puts every tag type into a dictionary and then refers to the dictionary for
* every tag which is written out. Can get much better space usage than {@link #VANILLA}, but at the cost of
* time. */
public static final int BUILDCRAFT_V1 = 2;
public static final int BUILDCRAFT_V1_COMPRESSED = 3;
public static final int BUILDCRAFT_MAGIC_1 = 0xbc;
public static final int BUILDCRAFT_MAGIC_2 = 0xa1;
/** The magic identifier for this type of file. First byte is BC, second is A1. */
public static final int BUILDCRAFT_MAGIC = (BUILDCRAFT_MAGIC_1 << 8) | BUILDCRAFT_MAGIC_2;
// GZIP uses the opposite byte order to us, so swap it around for us
public static final int GZIP_MAGIC_1 = GZIPInputStream.GZIP_MAGIC & 0xff;
public static final int GZIP_MAGIC_2 = GZIPInputStream.GZIP_MAGIC >> 8;
public static final int GZIP_MAGIC = (GZIP_MAGIC_1 << 8) | GZIP_MAGIC_2;
// The flags used by BUILDCRAFT_V1 to check the existence of each dictionary
public static final int FLAG_HAS_BYTES = 1 << 0;
public static final int FLAG_HAS_SHORTS = 1 << 1;
public static final int FLAG_HAS_INTS = 1 << 2;
public static final int FLAG_HAS_LONGS = 1 << 3;
public static final int FLAG_HAS_FLOATS = 1 << 4;
public static final int FLAG_HAS_DOUBLES = 1 << 5;
public static final int FLAG_HAS_BYTE_ARRAYS = 1 << 6;
public static final int FLAG_HAS_INT_ARRAYS = 1 << 7;
public static final int FLAG_HAS_STRINGS = 1 << 8;
public static final int FLAG_HAS_COMPLEX = 1 << 9;
// Complex types
public static final int COMPLEX_COMPOUND = 0;
public static final int COMPLEX_LIST = 1;
public static final int COMPLEX_LIST_PACKED = 2;
}
@@ -1,29 +0,0 @@
package buildcraft.api.enums;
import net.minecraft.item.ItemStack;
import buildcraft.api.items.IBlueprintItem;
public enum EnumBlueprintType {
NONE,
BLUEPRINT,
TEMPLATE;
public static EnumBlueprintType valueOf(int index) {
if (index <= 0 || index >= values().length) {
return NONE;
} else {
return values()[index];
}
}
public static EnumBlueprintType getType(ItemStack item) {
if (item == null) {
return NONE;
} else if (item.getItem() instanceof IBlueprintItem) {
return ((IBlueprintItem) item.getItem()).getType(item);
} else {
return NONE;
}
}
}
@@ -16,7 +16,7 @@ public enum EnumDecoratedBlock implements IStringSerializable {
public final int lightValue;
private EnumDecoratedBlock(int lightValue) {
EnumDecoratedBlock(int lightValue) {
this.lightValue = lightValue;
}
@@ -2,7 +2,9 @@ package buildcraft.api.enums;
import net.minecraft.util.IStringSerializable;
public enum EnumEngineType implements IStringSerializable {
import buildcraft.api.core.IEngineType;
public enum EnumEngineType implements IStringSerializable, IEngineType {
WOOD("core", "wood"),
STONE("energy", "stone"),
IRON("energy", "iron"),
@@ -15,7 +17,12 @@ public enum EnumEngineType implements IStringSerializable {
EnumEngineType(String mod, String loc) {
unlocalizedTag = loc;
resourceLocation = "buildcraft" + mod + ":blocks/engine/inv/" + loc + "/";
resourceLocation = "buildcraft" + mod + ":blocks/engine/inv/" + loc;
}
@Override
public String getItemModelLocation() {
return resourceLocation;
}
@Override
@@ -11,7 +11,7 @@ public enum EnumMachineState implements IStringSerializable {
DONE;
public static EnumMachineState getType(IBlockState state) {
return (EnumMachineState) state.getValue(BuildCraftProperties.MACHINE_STATE);
return state.getValue(BuildCraftProperties.MACHINE_STATE);
}
@Override
@@ -0,0 +1,36 @@
package buildcraft.api.enums;
import java.util.Locale;
import net.minecraft.util.IStringSerializable;
public enum EnumOptionalSnapshotType implements IStringSerializable {
NONE(null),
TEMPLATE(EnumSnapshotType.TEMPLATE),
BLUEPRINT(EnumSnapshotType.BLUEPRINT);
public final EnumSnapshotType type;
EnumOptionalSnapshotType(EnumSnapshotType type) {
this.type = type;
}
public static EnumOptionalSnapshotType fromNullable(EnumSnapshotType type) {
if (type == null) {
return NONE;
}
switch (type) {
case TEMPLATE:
return TEMPLATE;
case BLUEPRINT:
return BLUEPRINT;
default:
return NONE;
}
}
@Override
public String getName() {
return name().toLowerCase(Locale.ROOT);
}
}
@@ -1,22 +1,26 @@
package buildcraft.api.enums;
import java.util.Locale;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IStringSerializable;
public enum EnumRedstoneChipset {
import buildcraft.api.BCItems;
public enum EnumRedstoneChipset implements IStringSerializable {
RED,
IRON,
GOLD,
DIAMOND,
PULSATING,
QUARTZ,
COMP,
EMERALD;
DIAMOND;
private final String name = name().toLowerCase(Locale.ROOT);
public ItemStack getStack(int stackSize) {
Item chipset = Item.getByNameOrId("buildcraft|silicon:redstoneChipset");
Item chipset = BCItems.SILICON_REDSTONE_CHIPSET;
if (chipset == null) {
return null;
return ItemStack.EMPTY;
}
return new ItemStack(chipset, stackSize, ordinal());
@@ -39,4 +43,9 @@ public enum EnumRedstoneChipset {
}
return values()[ordinal];
}
@Override
public String getName() {
return name;
}
}
@@ -0,0 +1,12 @@
package buildcraft.api.enums;
public enum EnumSnapshotType {
TEMPLATE(9),
BLUEPRINT(3);
public final int maxPerTick;
EnumSnapshotType(int maxPerTick) {
this.maxPerTick = maxPerTick;
}
}
@@ -1,24 +1,29 @@
package buildcraft.api.enums;
import java.util.Locale;
import java.util.function.Supplier;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.IStringSerializable;
import buildcraft.api.properties.BuildCraftProperties;
public enum EnumSpring implements IStringSerializable {
WATER(5, -1, Blocks.WATER.getDefaultState()),
OIL(6000, 8, null); // Set in BuildCraftEnergy
public static final EnumSpring[] VALUES = values();
public final int tickRate, chance;
public IBlockState liquidBlock;
public boolean canGen = true;
public Supplier<TileEntity> tileConstructor;
private final String lowerCaseName = name().toLowerCase(Locale.ROOT);
private EnumSpring(int tickRate, int chance, IBlockState liquidBlock) {
EnumSpring(int tickRate, int chance, IBlockState liquidBlock) {
this.tickRate = tickRate;
this.chance = chance;
this.liquidBlock = liquidBlock;
@@ -1,9 +1,35 @@
package buildcraft.api.facades;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fml.common.event.FMLInterModComms;
public final class FacadeAPI {
public static final String IMC_MOD_TARGET = "buildcrafttransport";
public static final String IMC_FACADE_DISABLE = "facade_disable_block";
public static final String IMC_FACADE_CUSTOM = "facade_custom_map_block_item";
public static final String NBT_CUSTOM_BLOCK_REG_KEY = "block_registry_name";
public static final String NBT_CUSTOM_BLOCK_META = "block_meta";
public static final String NBT_CUSTOM_ITEM_STACK = "item_stack";
public static IFacadeItem facadeItem;
private FacadeAPI() {
}
public static void disableBlock(Block block) {
FMLInterModComms.sendMessage(IMC_MOD_TARGET, IMC_FACADE_DISABLE, block.getRegistryName());
}
public static void mapStateToStack(IBlockState state, ItemStack stack) {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setString(NBT_CUSTOM_BLOCK_REG_KEY, state.getBlock().getRegistryName().toString());
nbt.setInteger(NBT_CUSTOM_BLOCK_META, state.getBlock().getMetaFromState(state));
nbt.setTag(NBT_CUSTOM_ITEM_STACK, stack.serializeNBT());
FMLInterModComms.sendMessage(IMC_MOD_TARGET, IMC_FACADE_CUSTOM, nbt);
}
}
@@ -4,13 +4,16 @@
* should be located as "LICENSE.API" in the BuildCraft source code distribution. */
package buildcraft.api.facades;
import javax.annotation.Nonnull;
import net.minecraft.block.state.IBlockState;
import net.minecraft.item.ItemStack;
public interface IFacadeItem {
FacadeType getFacadeType(ItemStack facade);
FacadeType getFacadeType(@Nonnull ItemStack facade);
@Nonnull
ItemStack getFacadeForBlock(IBlockState state);
IBlockState[] getBlockStatesForFacade(ItemStack facade);
IBlockState[] getBlockStatesForFacade(@Nonnull ItemStack facade);
}
@@ -4,10 +4,13 @@
* should be located as "LICENSE.API" in the BuildCraft source code distribution. */
package buildcraft.api.fuels;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
public interface ICoolant {
Fluid getFluid();
boolean matchesFluid(FluidStack fluid);
float getDegreesCoolingPerMB(float heat);
/** @param fluid
* @param heat
* @return 0 if the input fluid provides no cooling, or a value greater than 0 if it does. */
float getDegreesCoolingPerMB(FluidStack fluid, float heat);
}
@@ -11,12 +11,14 @@ import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import buildcraft.api.core.StackKey;
public interface ICoolantManager {
ICoolant addCoolant(ICoolant coolant);
ICoolant addCoolant(Fluid fluid, float degreesCoolingPerMB);
ICoolant addCoolant(FluidStack fluid, float degreesCoolingPerMb);
default ICoolant addCoolant(Fluid fluid, float degreesCoolingPerMb) {
return addCoolant(new FluidStack(fluid, 1), degreesCoolingPerMb);
}
ISolidCoolant addSolidCoolant(ISolidCoolant solidCoolant);
@@ -26,7 +28,9 @@ public interface ICoolantManager {
Collection<ISolidCoolant> getSolidCoolants();
ICoolant getCoolant(Fluid fluid);
ICoolant getCoolant(FluidStack fluid);
float getDegreesPerMb(FluidStack fluid, float heat);
ISolidCoolant getSolidCoolant(ItemStack solid);
}
+3 -2
View File
@@ -4,10 +4,11 @@
* should be located as "LICENSE.API" in the BuildCraft source code distribution. */
package buildcraft.api.fuels;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
public interface IFuel {
Fluid getFluid();
/** @return The input fluid. The {@link FluidStack#amount} is ignored. */
FluidStack getFluid();
/** @return The number of ticks that a single bucket (1000mb) of this fuel will burn for. */
int getTotalBurningTime();
@@ -10,17 +10,27 @@ import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
public interface IFuelManager {
IFuel addFuel(IFuel fuel);
<F extends IFuel> F addFuel(F fuel);
IFuel addFuel(Fluid fluid, long powerPerCycle, int totalBurningTime);
IFuel addFuel(FluidStack fluid, long powerPerCycle, int totalBurningTime);
IDirtyFuel addDirtyFuel(Fluid fuel, long powerPerCycle, int totalBurningTime, FluidStack residue);
default IFuel addFuel(Fluid fluid, long powerPerCycle, int totalBurningTime) {
return addFuel(new FluidStack(fluid, 1), powerPerCycle, totalBurningTime);
}
/** @param residue The residue fluidstack, per bucket of the original fuel. */
IDirtyFuel addDirtyFuel(FluidStack fuel, long powerPerCycle, int totalBurningTime, FluidStack residue);
/** @param residue The residue fluidstack, per bucket of the original fuel. */
default IDirtyFuel addDirtyFuel(Fluid fuel, long powerPerCycle, int totalBurningTime, FluidStack residue) {
return addDirtyFuel(new FluidStack(fuel, 1), powerPerCycle, totalBurningTime, residue);
}
Collection<IFuel> getFuels();
IFuel getFuel(Fluid fluid);
IFuel getFuel(FluidStack fluid);
public interface IDirtyFuel extends IFuel {
interface IDirtyFuel extends IFuel {
/** @return The residue fluidstack, per bucket of original fuel. */
FluidStack getResidue();
}
@@ -0,0 +1,72 @@
package buildcraft.api.inventory;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import buildcraft.api.core.IStackFilter;
/** A simple way to define something that deals with item insertion and extraction, without caring about slots. */
public interface IItemTransactor {
/** @param stack The stack to insert. Must not be null!
* @param allOrNone If true then either the entire stack will be used or none of it.
* @param simulate If true then the in-world state of this will not be changed.
* @return The overflow stack. Will be {@link ItemStack#EMPTY} if all of it was accepted. */
@Nonnull
ItemStack insert(@Nonnull ItemStack stack, boolean allOrNone, boolean simulate);
/** Similar to {@link #insert(ItemStack, boolean, boolean)} but probably be more efficient at inserting lots of
* items.
*
* @param stacks The stacks to insert. Must not be null!
* @param simulate If true then the in-world state of this will not be changed.
* @return The overflow stacks. Will be an empty list if all of it was accepted. */
default NonNullList<ItemStack> insert(NonNullList<ItemStack> stacks, boolean simulate) {
NonNullList<ItemStack> leftOver = NonNullList.create();
for (ItemStack stack : stacks) {
ItemStack leftOverStack = insert(stack, false, simulate);
if (!leftOverStack.isEmpty()) {
leftOver.add(leftOverStack);
}
}
return leftOver;
}
/** Extracts a number of items that match the given filter
*
* @param filter The filter that MUST be met by the extracted stack. Null means no filter - it can be any item.
* @param min The minimum number of items to extract, or 0 if not enough items can be extracted
* @param max The maximum number of items to extract.
* @param simulate If true then the in-world state of this will not be changed.
* @return The stack that was extracted, or {@link ItemStack#EMPTY} if it could not be. */
@Nonnull
ItemStack extract(@Nullable IStackFilter filter, int min, int max, boolean simulate);
default boolean canFullyAccept(@Nonnull ItemStack stack) {
return insert(stack, true, true).isEmpty();
}
default boolean canPartiallyAccept(@Nonnull ItemStack stack) {
return insert(stack, false, true).getCount() < stack.getCount();
}
@FunctionalInterface
interface IItemInsertable extends IItemTransactor {
@Nonnull
@Override
default ItemStack extract(IStackFilter filter, int min, int max, boolean simulate) {
return ItemStack.EMPTY;
}
}
@FunctionalInterface
interface IItemExtractable extends IItemTransactor {
@Nonnull
@Override
default ItemStack insert(@Nonnull ItemStack stack, boolean allOrNone, boolean simulate) {
return stack;
}
}
}
@@ -1,9 +0,0 @@
package buildcraft.api.items;
import net.minecraft.item.ItemStack;
import buildcraft.api.enums.EnumBlueprintType;
public interface IBlueprintItem extends INamedItem {
EnumBlueprintType getType(ItemStack stack);
}
@@ -13,7 +13,7 @@ import buildcraft.api.core.IZone;
/** Created by asie on 2/28/15. */
public interface IMapLocation extends INamedItem {
public enum MapLocationType {
enum MapLocationType {
CLEAN,
SPOT,
AREA,
@@ -5,7 +5,7 @@ import java.util.Set;
@Deprecated
public final class LibraryAPI {
private static final Set<LibraryTypeHandler> handlers = new HashSet<LibraryTypeHandler>();
private static final Set<LibraryTypeHandler> handlers = new HashSet<>();
private LibraryAPI() {
@@ -7,8 +7,8 @@ import java.util.List;
import net.minecraft.item.Item;
public final class ListRegistry {
public static final List<Class<? extends Item>> itemClassAsType = new ArrayList<Class<? extends Item>>();
private static final List<ListMatchHandler> handlers = new ArrayList<ListMatchHandler>();
public static final List<Class<? extends Item>> itemClassAsType = new ArrayList<>();
private static final List<ListMatchHandler> handlers = new ArrayList<>();
private ListRegistry() {
@@ -9,15 +9,16 @@ package buildcraft.api.mj;
* The respective Block MUST implement ILaserTargetBlock! */
public interface ILaserTarget {
/** Returns true if the target currently needs power. For example, if the Advanced Crafting Table has work to do.
/** Returns The amount of power this target currently needs.
*
* @return true if needs power */
boolean requiresLaserPower();
* @return The amount of power required, or 0 if no power is required. */
long getRequiredLaserPower();
/** Transfers power from the laser to the target.
*
* @param microJoules The number of micro Minecraft Joules to accept */
void receiveLaserPower(long microJoules);
* @param microJoules The number of micro Minecraft Joules to accept
* @return The excess power. If the input is less than or equal to {@link #getRequiredLaserPower()} then this will return 0. */
long receiveLaserPower(long microJoules);
/** Return true if the Tile Entity object is no longer a valid target. For example, if its been invalidated.
*
@@ -12,8 +12,19 @@ public interface IMjReceiver extends IMjConnector {
* <li>Refuse all power (if you have no more work to do or your {@link MjBattery} is full).
* </ul>
*
* Note that callers are NOT expected to call {@link #canReceive()} before calling this - implementors should check
* all of the conditions in {@link #canReceive()} before accepting power.
*
* @param microJoules The number of micro joules to add.
* @param simulate If true then just pretend you received power- don't actually change any of your internal state.
* @return The excess power. */
long receivePower(long microJoules, boolean simulate);
/** Checks to see if {@link #receivePower(long, boolean)} *might* accept any power right now, ignoring the amount of
* power contained right now (if any).
*
* @return True if this {@link IMjReceiver} can receive power right now. */
default boolean canReceive() {
return true;
}
}
+42 -107
View File
@@ -1,20 +1,17 @@
package buildcraft.api.mj;
import java.text.DecimalFormat;
import java.util.concurrent.Callable;
import javax.annotation.Nonnull;
import net.minecraft.nbt.NBTBase;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import net.minecraftforge.common.capabilities.CapabilityManager;
import buildcraft.api.core.APIHelper;
import buildcraft.api.core.CapabilitiesHelper;
public class MjAPI {
@@ -30,9 +27,38 @@ public class MjAPI {
public static final long MJ = ONE_MINECRAFT_JOULE;
/** The decimal format used to display values of MJ to the player. Note that this */
public static final DecimalFormat MJ_DISPLAY_FORMAT = new DecimalFormat("###0.##");
public static final DecimalFormat MJ_DISPLAY_FORMAT = new DecimalFormat("#,##0.##");
public static final IMjEffectManager EFFECT_MANAGER = APIHelper.getInstance("", IMjEffectManager.class, NullaryEffectManager.INSTANCE);
public static IMjEffectManager EFFECT_MANAGER = NullaryEffectManager.INSTANCE;
// ###############
//
// Helpful methods
//
// ###############
/** Formats a given MJ value to a player-oriented string. Note that this does not append "MJ" to the value. */
public static String formatMj(long microMj) {
return formatMjInternal(microMj / (double) MJ);
}
private static String formatMjInternal(double val) {
return MJ_DISPLAY_FORMAT.format(val);
}
// ########################################
//
// Null based classes
//
// ########################################
public enum NullaryEffectManager implements IMjEffectManager {
INSTANCE;
@Override public void createPowerLossEffect(World world, Vec3d center, long microJoulesLost) {}
@Override public void createPowerLossEffect(World world, Vec3d center, EnumFacing direction, long microJoulesLost) {}
@Override public void createPowerLossEffect(World world, Vec3d center, Vec3d direction, long microJoulesLost) {}
}
// @formatter:on
// ###############
//
@@ -55,63 +81,6 @@ public class MjAPI {
@Nonnull
public static final Capability<IMjPassiveProvider> CAP_PASSIVE_PROVIDER;
// ###############
//
// Helpful methods
//
// ###############
/** Formats a given MJ value to a player-oriented string. Note that this does not append "MJ" to the value. */
public static String formatMj(long microMj) {
return formatMjInternal(microMj / (double) MJ);
}
/** Formats a given MJ value to a player-oriented string. Note that this DOES append "*MJ" to the value. This does
* however shorten it down to a small length, and displays "µ", "m", "K" or "M" or "G" before the MJ depending on
* how big or small the value is. */
public static String formatMjShort(long microJoules) {
if (microJoules == 0) {
return "0 Mj";
}
long limit = 1;
final long nextUnitCap = 800;
if (microJoules < nextUnitCap * limit) {// micro MJ
return formatMjInternal(microJoules) + " µMJ";
}
limit *= 1000;
if (microJoules < nextUnitCap * limit) { // milli MJ
return formatMjInternal(microJoules / (double) limit) + " mMJ";
}
limit *= 1000;
if (microJoules < nextUnitCap * limit) { // MJ
return formatMjInternal(microJoules / (double) limit) + " MJ";
}
limit *= 1000;
if (microJoules < nextUnitCap * limit) {// kilo MJ
return formatMjInternal(microJoules / (double) limit) + " KMJ";
}
limit *= 1000;
if (microJoules < nextUnitCap * limit) {// mega MJ
return formatMjInternal(microJoules / (double) limit) + " MMJ";
}
limit *= 1000;
return formatMjInternal(microJoules / (double) limit) + " GMJ";
}
// ########################################
//
// Null based classes
//
// ########################################
public enum NullaryEffectManager implements IMjEffectManager {
INSTANCE;
@Override public void createPowerLossEffect(World world, Vec3d center, long microJoulesLost) {}
@Override public void createPowerLossEffect(World world, Vec3d center, EnumFacing direction, long microJoulesLost) {}
@Override public void createPowerLossEffect(World world, Vec3d center, Vec3d direction, long microJoulesLost) {}
}
// @formatter:on
// ####################
//
// Internal API logic
@@ -135,50 +104,16 @@ public class MjAPI {
private static final Capability<IMjPassiveProvider> CAP_PASSIVE_PROVIDER_FIRST = null;
static {
registerCapability(IMjConnector.class);
registerCapability(IMjReceiver.class);
registerCapability(IMjRedstoneReceiver.class);
registerCapability(IMjReadable.class);
registerCapability(IMjPassiveProvider.class);
CapabilitiesHelper.registerCapability(IMjConnector.class);
CapabilitiesHelper.registerCapability(IMjReceiver.class);
CapabilitiesHelper.registerCapability(IMjRedstoneReceiver.class);
CapabilitiesHelper.registerCapability(IMjReadable.class);
CapabilitiesHelper.registerCapability(IMjPassiveProvider.class);
CAP_CONNECTOR = ensureRegistration(CAP_CONNECTOR_FIRST, IMjConnector.class);
CAP_RECEIVER = ensureRegistration(CAP_RECEIVER_FIRST, IMjReceiver.class);
CAP_REDSTONE_RECEIVER = ensureRegistration(CAP_REDSTONE_RECEIVER_FIRST, IMjRedstoneReceiver.class);
CAP_READABLE = ensureRegistration(CAP_READABLE_FIRST, IMjReadable.class);
CAP_PASSIVE_PROVIDER = ensureRegistration(CAP_PASSIVE_PROVIDER_FIRST, IMjPassiveProvider.class);
}
private static <T> void registerCapability(Class<T> clazz) {
CapabilityManager.INSTANCE.register(clazz, new VoidStorage<T>(), new Callable<T>() {
// No lambda because of java 6... :(
@Override
public T call() throws Exception {
throw new IllegalStateException("You must create your own instances!");
}
});
}
@Nonnull
private static <T> Capability<T> ensureRegistration(Capability<T> cap, Class<T> clazz) {
if (cap == null) {
throw new Error("Capability registration failed for " + clazz);
}
return cap;
}
private static class VoidStorage<T> implements Capability.IStorage<T> {
@Override
public NBTBase writeNBT(Capability<T> capability, T instance, EnumFacing side) {
throw new IllegalStateException("You must create your own instances!");
}
@Override
public void readNBT(Capability<T> capability, T instance, EnumFacing side, NBTBase nbt) {
throw new IllegalStateException("You must create your own instances!");
}
}
private static String formatMjInternal(double val) {
return MJ_DISPLAY_FORMAT.format(val);
CAP_CONNECTOR = CapabilitiesHelper.ensureRegistration(CAP_CONNECTOR_FIRST, IMjConnector.class);
CAP_RECEIVER = CapabilitiesHelper.ensureRegistration(CAP_RECEIVER_FIRST, IMjReceiver.class);
CAP_REDSTONE_RECEIVER = CapabilitiesHelper.ensureRegistration(CAP_REDSTONE_RECEIVER_FIRST, IMjRedstoneReceiver.class);
CAP_READABLE = CapabilitiesHelper.ensureRegistration(CAP_READABLE_FIRST, IMjReadable.class);
CAP_PASSIVE_PROVIDER = CapabilitiesHelper.ensureRegistration(CAP_PASSIVE_PROVIDER_FIRST, IMjPassiveProvider.class);
}
}
@@ -1,5 +1,7 @@
package buildcraft.api.mj;
import io.netty.buffer.ByteBuf;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
@@ -7,8 +9,6 @@ import net.minecraft.world.World;
import net.minecraftforge.common.util.INBTSerializable;
import io.netty.buffer.ByteBuf;
/** Provides a basic implementation of a simple battery. Note that you should call {@link #tick(World, BlockPos)} or
* {@link #tick(World, Vec3d)} every tick to allow for losing excess power. */
public class MjBattery implements INBTSerializable<NBTTagCompound> {
@@ -35,23 +35,27 @@ public class MjCapabilityHelper implements ICapabilityProvider {
}
@Override
public boolean hasCapability(Capability<?> capability, EnumFacing facing) {
if (capability == MjAPI.CAP_CONNECTOR) return true;
if (capability == MjAPI.CAP_RECEIVER) return receiver != null;
if (capability == MjAPI.CAP_REDSTONE_RECEIVER) return rsReceiver != null;
if (capability == MjAPI.CAP_READABLE) return readable != null;
if (capability == MjAPI.CAP_PASSIVE_PROVIDER) return provider != null;
return false;
public boolean hasCapability(@Nonnull Capability<?> capability, EnumFacing facing) {
return getCapability(capability, facing) != null;
}
@Override
public <T> T getCapability(Capability<T> capability, EnumFacing facing) {
if (capability == MjAPI.CAP_CONNECTOR) return (T) connector;
if (capability == MjAPI.CAP_RECEIVER) return (T) receiver;
if (capability == MjAPI.CAP_REDSTONE_RECEIVER) return (T) rsReceiver;
if (capability == MjAPI.CAP_READABLE) return (T) readable;
if (capability == MjAPI.CAP_PASSIVE_PROVIDER) return (T) provider;
public <T> T getCapability(@Nonnull Capability<T> capability, EnumFacing facing) {
if (capability == MjAPI.CAP_CONNECTOR) {
return MjAPI.CAP_CONNECTOR.cast(connector);
}
if (capability == MjAPI.CAP_RECEIVER) {
return MjAPI.CAP_RECEIVER.cast(receiver);
}
if (capability == MjAPI.CAP_REDSTONE_RECEIVER) {
return MjAPI.CAP_REDSTONE_RECEIVER.cast(rsReceiver);
}
if (capability == MjAPI.CAP_READABLE) {
return MjAPI.CAP_READABLE.cast(readable);
}
if (capability == MjAPI.CAP_PASSIVE_PROVIDER) {
return MjAPI.CAP_PASSIVE_PROVIDER.cast(provider);
}
return null;
}
}
@@ -4,8 +4,8 @@
* power should be passed around in code as micro Mj (10 ^ -6 of an Mj), but shown to the player as full MJ - so divided by 1
* million.
* <p>
* A single MJ as a constant is available in {@link buildcraft.api.mj.MjAPI#ONE_MINECRAFT_JOULE}, and two player
* formatter's ( {@link buildcraft.api.mj.MjAPI#formatMj(long)}, and {@link buildcraft.api.mj.MjAPI#formatMjShort(long)}
* A single MJ as a constant is available in {@link buildcraft.api.mj.MjAPI#ONE_MINECRAFT_JOULE}, and a player
* formatter {@link buildcraft.api.mj.MjAPI#formatMj(long)}
* <p>
* <h1>Capability's</h1>
* <p>
@@ -1,24 +0,0 @@
package buildcraft.api.permission;
import java.util.UUID;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.server.MinecraftServer;
/** Defines an owner -- this is an actual player in the world, or an offline player. */
public interface IOwner {
/** Gets the player, if they actually exist on the server */
@Nullable
EntityPlayer getPlayer(MinecraftServer server);
/** Gets the player's UUID */
@Nonnull
UUID getPlayerUUID();
/** Gets the player's name. */
@Nonnull
String getPlayerName();
}
@@ -1,65 +0,0 @@
package buildcraft.api.properties;
import java.util.List;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import net.minecraftforge.common.property.IExtendedBlockState;
import net.minecraftforge.common.property.IUnlistedProperty;
public class BuildCraftExtendedProperty<T extends Comparable<T>> extends BuildCraftProperty<T> implements IUnlistedProperty<T> {
private final Predicate<T> function;
public BuildCraftExtendedProperty(String name, Class<T> clazz, Predicate<T> allowingFunction) {
super(name, clazz);
function = allowingFunction;
}
public BuildCraftExtendedProperty(String name, Class<T> clazz, List<T> allowedValues) {
super(name, clazz, allowedValues);
function = null;
}
public static BuildCraftExtendedProperty<Double> create(String name, final double min, final double max) {
return new BuildCraftExtendedProperty<Double>(name, Double.class, new Predicate<Double>() {
@Override
public boolean apply(Double input) {
return input >= min && input <= max;
}
});
}
/** This is useful if you want to use a particular class for this property, but don't care what the class contains
* (it will never contain an incorrect value) */
public static <T extends Comparable<T>> BuildCraftExtendedProperty<T> createExtended(String name, Class clazz) {
return new BuildCraftExtendedProperty<T>(name, clazz, Predicates.<T> alwaysTrue());
}
@Override
public boolean isValid(T value) {
if (function == null) {
return values.contains(value);
}
return function.apply(value);
}
@Override
public Class<T> getType() {
return getValueClass();
}
@Override
public String valueToString(T value) {
return valueName(value);
}
public T getUnlistedValue(IExtendedBlockState state) {
return state.getValue(asUnlistedProperty());
}
// Helper methods for arguments
public IUnlistedProperty<T> asUnlistedProperty() {
return this;
}
}
@@ -4,50 +4,54 @@ import java.util.Map;
import com.google.common.collect.Maps;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.properties.PropertyInteger;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.util.EnumFacing;
import buildcraft.api.enums.*;
import buildcraft.api.enums.EnumDecoratedBlock;
import buildcraft.api.enums.EnumEngineType;
import buildcraft.api.enums.EnumFillerPattern;
import buildcraft.api.enums.EnumLaserTableType;
import buildcraft.api.enums.EnumMachineState;
import buildcraft.api.enums.EnumOptionalSnapshotType;
import buildcraft.api.enums.EnumPowerStage;
import buildcraft.api.enums.EnumSpring;
public final class BuildCraftProperties {
public static final BuildCraftProperty<EnumFacing> BLOCK_FACING = BuildCraftProperty.create("facing", EnumFacing.Plane.HORIZONTAL.facings());
public static final BuildCraftProperty<EnumFacing> BLOCK_FACING_6 = BuildCraftProperty.create("facing", EnumFacing.class);
public static final IProperty<EnumFacing> BLOCK_FACING = PropertyEnum.create("facing", EnumFacing.class, EnumFacing.Plane.HORIZONTAL.facings());
public static final IProperty<EnumFacing> BLOCK_FACING_6 = PropertyEnum.create("facing", EnumFacing.class);
public static final BuildCraftProperty<EnumDyeColor> BLOCK_COLOR = BuildCraftProperty.create("color", EnumDyeColor.class);
public static final BuildCraftProperty<EnumSpring> SPRING_TYPE = BuildCraftProperty.create("type", EnumSpring.class);
public static final BuildCraftProperty<EnumEngineType> ENGINE_TYPE = BuildCraftProperty.create("type", EnumEngineType.class);
public static final BuildCraftProperty<EnumLaserTableType> LASER_TABLE_TYPE = BuildCraftProperty.create("type", EnumLaserTableType.class);
public static final BuildCraftProperty<EnumMachineState> MACHINE_STATE = BuildCraftProperty.create("state", EnumMachineState.class);
public static final BuildCraftProperty<EnumPowerStage> ENERGY_STAGE = BuildCraftProperty.create("stage", EnumPowerStage.class);
public static final BuildCraftProperty<EnumBlueprintType> BLUEPRINT_TYPE = BuildCraftProperty.create("blueprint_type", EnumBlueprintType.class);
public static final BuildCraftProperty<EnumDecoratedBlock> DECORATED_BLOCK = BuildCraftProperty.create("decoration_type", EnumDecoratedBlock.class);
public static final IProperty<EnumDyeColor> BLOCK_COLOR = PropertyEnum.create("color", EnumDyeColor.class);
public static final IProperty<EnumSpring> SPRING_TYPE = PropertyEnum.create("type", EnumSpring.class);
public static final IProperty<EnumEngineType> ENGINE_TYPE = PropertyEnum.create("type", EnumEngineType.class);
public static final IProperty<EnumLaserTableType> LASER_TABLE_TYPE = PropertyEnum.create("type", EnumLaserTableType.class);
public static final IProperty<EnumMachineState> MACHINE_STATE = PropertyEnum.create("state", EnumMachineState.class);
public static final IProperty<EnumPowerStage> ENERGY_STAGE = PropertyEnum.create("stage", EnumPowerStage.class);
public static final IProperty<EnumOptionalSnapshotType> SNAPSHOT_TYPE = PropertyEnum.create("snapshot_type", EnumOptionalSnapshotType.class);
public static final IProperty<EnumDecoratedBlock> DECORATED_BLOCK = PropertyEnum.create("decoration_type", EnumDecoratedBlock.class);
public static final BuildCraftProperty<Integer> GENERIC_PIPE_DATA = BuildCraftProperty.create("pipe_data", 0, 15);
public static final BuildCraftProperty<Integer> LED_POWER = BuildCraftProperty.create("led_power", 0, 3);
public static final IProperty<Integer> GENERIC_PIPE_DATA = PropertyInteger.create("pipe_data", 0, 15);
public static final IProperty<Integer> LED_POWER = PropertyInteger.create("led_power", 0, 3);
public static final BuildCraftProperty<Boolean> JOINED_BELOW = BuildCraftProperty.create("joined_below", false);
public static final BuildCraftProperty<Boolean> MOVING = BuildCraftProperty.create("moving", false);
public static final BuildCraftProperty<Boolean> LED_DONE = BuildCraftProperty.create("led_done", false);
public static final BuildCraftProperty<Boolean> ACTIVE = BuildCraftProperty.create("active", false);
public static final BuildCraftProperty<Boolean> VALID = BuildCraftProperty.create("valid", false);
public static final IProperty<Boolean> JOINED_BELOW = PropertyBool.create("joined_below");
public static final IProperty<Boolean> MOVING = PropertyBool.create("moving");
public static final IProperty<Boolean> LED_DONE = PropertyBool.create("led_done");
public static final IProperty<Boolean> ACTIVE = PropertyBool.create("active");
public static final IProperty<Boolean> VALID = PropertyBool.create("valid");
public static final BuildCraftProperty<Boolean> CONNECTED_UP = BuildCraftProperty.create("connected_up", false);
public static final BuildCraftProperty<Boolean> CONNECTED_DOWN = BuildCraftProperty.create("connected_down", false);
public static final BuildCraftProperty<Boolean> CONNECTED_EAST = BuildCraftProperty.create("connected_east", false);
public static final BuildCraftProperty<Boolean> CONNECTED_WEST = BuildCraftProperty.create("connected_west", false);
public static final BuildCraftProperty<Boolean> CONNECTED_NORTH = BuildCraftProperty.create("connected_north", false);
public static final BuildCraftProperty<Boolean> CONNECTED_SOUTH = BuildCraftProperty.create("connected_south", false);
public static final IProperty<Boolean> CONNECTED_UP = PropertyBool.create("connected_up");
public static final IProperty<Boolean> CONNECTED_DOWN = PropertyBool.create("connected_down");
public static final IProperty<Boolean> CONNECTED_EAST = PropertyBool.create("connected_east");
public static final IProperty<Boolean> CONNECTED_WEST = PropertyBool.create("connected_west");
public static final IProperty<Boolean> CONNECTED_NORTH = PropertyBool.create("connected_north");
public static final IProperty<Boolean> CONNECTED_SOUTH = PropertyBool.create("connected_south");
public static final Map<EnumFacing, BuildCraftProperty<Boolean>> CONNECTED_MAP;
public static final Map<EnumFacing, IProperty<Boolean>> CONNECTED_MAP;
// Unlisted properties
// public static final PropertyDouble FLUID_HEIGHT_NE = new PropertyDouble("height_ne", 0, 1);
// public static final PropertyDouble FLUID_HEIGHT_NW = new PropertyDouble("height_nw", 0, 1);
// public static final PropertyDouble FLUID_HEIGHT_SE = new PropertyDouble("height_se", 0, 1);
// public static final PropertyDouble FLUID_HEIGHT_SW = new PropertyDouble("height_sw", 0, 1);
// public static final PropertyDouble FLUID_FLOW_DIRECTION = new PropertyDouble("direction",
// Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
public static final BuildCraftProperty<EnumFillerPattern> FILLER_PATTERN = BuildCraftProperty.create("pattern", EnumFillerPattern.class);
public static final IProperty<EnumFillerPattern> FILLER_PATTERN = PropertyEnum.create("pattern", EnumFillerPattern.class);
// Block state setting flags -these are used by World.markAndNotifyBlock and World.setBlockState. These flags can be
// added together to pass the additions
@@ -69,7 +73,7 @@ public final class BuildCraftProperties {
public static final int UPDATE_ALL = UPDATE_NEIGHBOURS + MARK_BLOCK_FOR_UPDATE + UPDATE_EVEN_CLIENT;
static {
Map<EnumFacing, BuildCraftProperty<Boolean>> map = Maps.newEnumMap(EnumFacing.class);
Map<EnumFacing, IProperty<Boolean>> map = Maps.newEnumMap(EnumFacing.class);
map.put(EnumFacing.DOWN, CONNECTED_DOWN);
map.put(EnumFacing.UP, CONNECTED_UP);
map.put(EnumFacing.EAST, CONNECTED_EAST);
@@ -1,147 +0,0 @@
package buildcraft.api.properties;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import com.google.common.base.Optional;
import net.minecraft.block.properties.PropertyHelper;
import net.minecraft.util.IStringSerializable;
import net.minecraft.util.math.MathHelper;
/** This class exists primarily to allow for a property to be used as either a normal IProperty, or an
* IUnlistedProperty. It also exists to give IProperty's generic types. */
public class BuildCraftProperty<T extends Comparable<T>> extends PropertyHelper<T> {
private final String name;
private final Class<T> clazz;
protected final List<T> values;
public BuildCraftProperty(String name, Class<T> clazz, T[] values) {
this(name, clazz, Arrays.asList(values));
}
public BuildCraftProperty(String name, Class<T> clazz, List<T> values) {
super(name, clazz);
this.name = name;
this.clazz = clazz;
this.values = values;
}
/** Used for BuildCraftInifiniteProperty */
protected BuildCraftProperty(String name, Class<T> clazz) {
super(name, clazz);
this.name = name;
this.clazz = clazz;
this.values = Collections.emptyList();
}
public static <E extends Enum<E>> BuildCraftProperty<E> create(String name, Class<E> enumeration) {
List<E> values = Arrays.asList(enumeration.getEnumConstants());
return new BuildCraftProperty<E>(name, enumeration, values);
}
public static <E extends Enum<E>> BuildCraftProperty<E> create(String name, E... values) {
Class<E> clazz = values[0].getDeclaringClass();
List<E> list = Arrays.asList(values);
return new BuildCraftProperty<E>(name, clazz, list);
}
public static BuildCraftProperty<Boolean> create(String name, boolean first) {
return new BuildCraftProperty<Boolean>(name, Boolean.class, new Boolean[] { first, !first });
}
/** first and last are both inclusive values (use 0, 4 to create an array of [0, 1, 2, 3, 4]) */
public static BuildCraftProperty<Integer> create(String name, int first, int last) {
return create(name, first, last, 1);
}
/** first and last are both inclusive values (use 0, 12, 3 to create an array of [0, 3, 6, 9, 12]) */
public static BuildCraftProperty<Integer> create(String name, int first, int last, int difference) {
int actualDiff = Math.abs(difference);
int number = MathHelper.floor(Math.abs(first - last) / (float) actualDiff + 1);
Integer[] array = new Integer[number];
int addedDiff = actualDiff * (first > last ? -1 : 1);
int current = first;
for (int i = 0; i < array.length; i++) {
array[i] = current;
current += addedDiff;
}
return new BuildCraftProperty<Integer>(name, Integer.class, array);
}
public static BuildCraftProperty<Double> create(String name, double first, double last) {
return create(name, first, last, 1);
}
public static BuildCraftProperty<Double> create(String name, double first, double last, double difference) {
double actualDiff = Math.abs(difference);
Double[] array = new Double[(int) (Math.abs(first - last) / actualDiff)];
double addedDiff = actualDiff * (first > last ? -1 : 1);
for (int i = 0; i <= array.length; i++) {
array[i] = first + (first - last) / addedDiff * i;
}
return new BuildCraftProperty<Double>(name, Double.class, array);
}
@Override
public String getName() {
return name;
}
@Override
public List<T> getAllowedValues() {
return values;
}
@Override
public Class<T> getValueClass() {
return clazz;
}
@Override
public String getName(@SuppressWarnings("rawtypes") Comparable value) {
return valueName(value);
}
protected String valueName(Object value) {
if (value == null) {
return "null";
} else if (value instanceof IStringSerializable) {
return ((IStringSerializable) value).getName();
} else if (value instanceof Enum) {
return ((Enum<?>) value).name().toLowerCase(Locale.ROOT);
} else {
return value.toString().toLowerCase(Locale.ROOT);
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("BuildCraftProperty [name=");
builder.append(name);
builder.append(", clazz=");
builder.append(clazz);
builder.append(", values=");
builder.append(values);
builder.append("]");
return builder.toString();
}
@Override
public Optional<T> parseValue(String value) {
if (clazz.isEnum()) {
return parseEnum(value, (BuildCraftProperty) this);
}
return Optional.absent();
}
public static <E extends Enum<E>> Optional<E> parseEnum(String name, BuildCraftProperty<E> prop) {
for (E e : prop.values) {
if (e.name().equalsIgnoreCase(name)) return Optional.of(e);
}
return Optional.absent();
}
}
@@ -1,109 +1,72 @@
package buildcraft.api.recipes;
import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.common.collect.ImmutableSet;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.util.Constants;
import buildcraft.api.core.BuildCraftAPI;
/** Provides an immutable assembly recipe */
public final class AssemblyRecipe {
public final class AssemblyRecipe implements Comparable<AssemblyRecipe> {
public final ResourceLocation name;
public final long requiredMicroJoules;
public final ImmutableSet<ItemStack> requiredStacks;
public final ItemStack output;
public final ImmutableSet<StackDefinition> requiredStacks;
public final @Nonnull ItemStack output;
/**
* Additional tag used to restore network-transmitted recipe to same state.<br>
* You need to register own {@link IAssemblyRecipeProvider} using {@link IAssemblyRecipeRegistry#addRecipeProvider(IAssemblyRecipeProvider)}
* to handle this and declare {@link IAssemblyRecipeProvider#getRecipe(ResourceLocation, NBTTagCompound)} method
*/
public final @Nullable NBTTagCompound recipeTag;
public AssemblyRecipe(long requiredMicroJoules, ImmutableSet<ItemStack> requiredStacks, ItemStack output) {
public AssemblyRecipe(ResourceLocation name, long requiredMicroJoules, Set<StackDefinition> requiredStacks, @Nonnull ItemStack output, @Nullable NBTTagCompound recipeTag) {
this.name = name;
this.requiredMicroJoules = requiredMicroJoules;
this.requiredStacks = requiredStacks;
this.requiredStacks = ImmutableSet.copyOf(requiredStacks);
this.output = output;
this.recipeTag = recipeTag;
}
public AssemblyRecipe(NBTTagCompound nbt) {
requiredMicroJoules = nbt.getLong("required_micro_joules");
NBTTagList requiredStacksTag = nbt.getTagList("required_stacks", Constants.NBT.TAG_COMPOUND);
NonNullList<ItemStack> requiredStacksArray = NonNullList.withSize(requiredStacksTag.tagCount(), ItemStack.EMPTY);
for(int i = 0; i < requiredStacksTag.tagCount(); i++) {
requiredStacksArray.set(i, new ItemStack(requiredStacksTag.getCompoundTagAt(i)));
}
requiredStacks = ImmutableSet.copyOf(requiredStacksArray);
output = new ItemStack(nbt.getCompoundTag("output"));
public AssemblyRecipe(String name, long requiredMicroJoules, Set<StackDefinition> requiredStacks, @Nonnull ItemStack output, @Nullable NBTTagCompound recipeTag) {
this(BuildCraftAPI.nameToResourceLocation(name), requiredMicroJoules, requiredStacks, output, recipeTag);
}
public AssemblyRecipe(PacketBuffer buffer) throws IOException {
requiredMicroJoules = buffer.readLong();
int count = buffer.readInt();
NonNullList<ItemStack> requiredStacksArray = NonNullList.withSize(count, ItemStack.EMPTY);
for(int i = 0; i < count; i++) {
requiredStacksArray.set(i, buffer.readItemStack());
}
requiredStacks = ImmutableSet.copyOf(requiredStacksArray);
output = buffer.readItemStack();
public AssemblyRecipe(ResourceLocation name, long requiredMicroJoules, Set<StackDefinition> requiredStacks, @Nonnull ItemStack output) {
this(name, requiredMicroJoules, requiredStacks, output, null);
}
public NBTTagCompound writeToNBT() {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setLong("required_micro_joules", requiredMicroJoules);
NBTTagList requiredStacksTag = new NBTTagList();
for(ItemStack requiredStack : requiredStacks) {
requiredStacksTag.appendTag(requiredStack.serializeNBT());
}
nbt.setTag("required_stacks", requiredStacksTag);
nbt.setTag("output", output.serializeNBT());
return nbt;
}
public void writeToBuffer(PacketBuffer buffer) {
buffer.writeLong(requiredMicroJoules);
buffer.writeInt(requiredStacks.size());
requiredStacks.forEach(buffer::writeItemStack);
buffer.writeItemStack(output);
public AssemblyRecipe(String name, long requiredMicroJoules, Set<StackDefinition> requiredStacks, @Nonnull ItemStack output) {
this(name, requiredMicroJoules, requiredStacks, output, null);
}
@Override
public boolean equals(Object o) {
if(this == o) {
if (this == o) {
return true;
}
if(o == null || getClass() != o.getClass()) {
if (o == null || getClass() != o.getClass()) {
return false;
}
AssemblyRecipe that = (AssemblyRecipe) o;
if(requiredMicroJoules != that.requiredMicroJoules) {
return false;
}
if(requiredStacks != null && that.requiredStacks != null) {
Iterator<ItemStack> iterator1 = requiredStacks.iterator();
Iterator<ItemStack> iterator2 = that.requiredStacks.iterator();
while(iterator1.hasNext()) {
if (!iterator2.hasNext()) {
return false;
}
ItemStack o1 = iterator1.next();
ItemStack o2 = iterator2.next();
if (!ItemStack.areItemStacksEqual(o1, o2)) {
return false;
}
}
return !iterator2.hasNext() && output != null ? ItemStack.areItemStacksEqual(output, that.output) : that.output == null;
} else {
return requiredStacks == null && that.requiredStacks == null && output != null ? ItemStack.areItemStacksEqual(output, that.output) : that.output == null;
}
return name.equals(that.name);
}
@Override
public int hashCode() {
int result = (int) (requiredMicroJoules ^ (requiredMicroJoules >>> 32));
result = 31 * result + (requiredStacks != null ? requiredStacks.hashCode() : 0);
result = 31 * result + (output != null ? output.hashCode() : 0);
return result;
return name.hashCode();
}
@Override
public int compareTo(AssemblyRecipe o) {
return name.toString().compareTo(o.name.toString());
}
}
@@ -8,7 +8,7 @@ public final class BuildcraftRecipeRegistry {
public static IAssemblyRecipeRegistry assemblyRecipes;
public static IIntegrationRecipeRegistry integrationRecipes;
public static IComplexRefineryRecipeManager complexRefinery;
public static IRefineryRecipeManager refineryRecipes;
private BuildcraftRecipeRegistry() {}
}
@@ -1,20 +1,32 @@
package buildcraft.api.recipes;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
/** Provides a way of registering complex recipes without needing to register every possible variant. If you want the
* recipes to be viewable in JEI and the guide book then you will *also* need to implement the bc lib class
* IAssemblyRecipeViewable. */
* IRecipeViewable. */
public interface IAssemblyRecipeProvider {
/** Should return a list of all the valid recipes given the input items. The list may be empty, but must not be
* null. Note that this will *most likely* be slow to check everything, so you should cache the return value and
* re-use it when you can. */
@Nonnull
List<AssemblyRecipe> getRecipesFor(@Nonnull NonNullList<ItemStack> possibleIn);
List<AssemblyRecipe> getRecipesFor(@Nonnull NonNullList<ItemStack> possible);
/**
* Returns recipe by it's name
* @param recipeTag Additional tag attached to network-transmitted recipe definition
*/
default Optional<AssemblyRecipe> getRecipe(@Nonnull ResourceLocation name, @Nullable NBTTagCompound recipeTag) {
return Optional.empty();
}
}
@@ -1,66 +0,0 @@
package buildcraft.api.recipes;
import java.util.Set;
import com.google.common.base.Predicate;
import net.minecraftforge.fluids.FluidStack;
public interface IComplexRefineryRecipeManager {
IHeatableRecipe createHeatingRecipe(FluidStack in, FluidStack out, int heatFrom, int heatTo, int ticks);
IHeatableRecipe addHeatableRecipe(FluidStack in, FluidStack out, int heatFrom, int heatTo, int ticks, boolean replaceExisting);
ICoolableRecipe createCoolableRecipe(FluidStack in, FluidStack out, int heatFrom, int heatTo, int ticks);
ICoolableRecipe addCoolableRecipe(FluidStack in, FluidStack out, int heatFrom, int heatTo, int ticks, boolean replaceExisting);
IDistilationRecipe createDistilationRecipe(FluidStack in, FluidStack outGas, FluidStack outLiquid, int ticks);
IDistilationRecipe addDistilationRecipe(FluidStack in, FluidStack outGas, FluidStack outLiquid, int ticks, boolean replaceExisting);
IComplexRefineryRegistry<IHeatableRecipe> getHeatableRegistry();
IComplexRefineryRegistry<ICoolableRecipe> getCoolableRegistry();
IComplexRefineryRegistry<IDistilationRecipe> getDistilationRegistry();
public interface IComplexRefineryRegistry<R extends IComplexRefineryRecipe> {
/** @return an unmodifiable set containing all of the distilation recipies that satisfy the given predicate. All
* of the recipe objects are guarenteed to never be null. */
Set<R> getRecipes(Predicate<R> toReturn);
/** @return an unmodifiable set containing all of the distilation recipies. */
Set<R> getAllRecipes();
R getRecipeForInput(FluidStack fluid);
Set<R> removeRecipes(Predicate<R> toRemove);
R addRecipe(R recipe, boolean replaceExisting);
}
public interface IComplexRefineryRecipe {
int ticks();
FluidStack in();
}
public interface IHeatExchangerRecipe extends IComplexRefineryRecipe {
FluidStack out();
int heatFrom();
int heatTo();
}
public interface IHeatableRecipe extends IHeatExchangerRecipe {}
public interface ICoolableRecipe extends IHeatExchangerRecipe {}
public interface IDistilationRecipe extends IComplexRefineryRecipe {
FluidStack outGas();
FluidStack outLiquid();
}
}
@@ -1,10 +1,14 @@
package buildcraft.api.recipes;
import java.util.Optional;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
/** Provides a way of registering complex recipes without needing to register every possible variant. If you want the
* recipes to be viewable in JEI and the guide book then you will *also* need to implement the bc lib class
@@ -17,4 +21,12 @@ public interface IIntegrationRecipeProvider {
* @return */
@Nullable
IntegrationRecipe getRecipeFor(@Nonnull ItemStack target, @Nonnull NonNullList<ItemStack> toIntegrate);
/**
* Returns recipe by it's name
* @param recipeTag Additional tag attached to network-transmitted recipe definition
*/
default Optional<IntegrationRecipe> getRecipe(@Nonnull ResourceLocation name, @Nullable NBTTagCompound recipeTag) {
return Optional.empty();
}
}
@@ -0,0 +1,81 @@
package buildcraft.api.recipes;
import java.util.Collection;
import java.util.function.Predicate;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import net.minecraftforge.fluids.FluidStack;
public interface IRefineryRecipeManager {
IHeatableRecipe createHeatingRecipe(FluidStack in, FluidStack out, int heatFrom, int heatTo);
default IHeatableRecipe addHeatableRecipe(FluidStack in, FluidStack out, int heatFrom, int heatTo) {
return getHeatableRegistry().addRecipe(createHeatingRecipe(in, out, heatFrom, heatTo));
}
ICoolableRecipe createCoolableRecipe(FluidStack in, FluidStack out, int heatFrom, int heatTo);
default ICoolableRecipe addCoolableRecipe(FluidStack in, FluidStack out, int heatFrom, int heatTo) {
return getCoolableRegistry().addRecipe(createCoolableRecipe(in, out, heatFrom, heatTo));
}
IDistillationRecipe createDistillationRecipe(FluidStack in, FluidStack outGas, FluidStack outLiquid, long powerRequired);
default IDistillationRecipe addDistillationRecipe(FluidStack in, FluidStack outGas, FluidStack outLiquid, long powerRequired) {
return getDistillationRegistry().addRecipe(createDistillationRecipe(in, outGas, outLiquid, powerRequired));
}
IRefineryRegistry<IHeatableRecipe> getHeatableRegistry();
IRefineryRegistry<ICoolableRecipe> getCoolableRegistry();
IRefineryRegistry<IDistillationRecipe> getDistillationRegistry();
interface IRefineryRegistry<R extends IRefineryRecipe> {
/** @return an unmodifiable collection containing all of the distillation recipes that satisfy the given
* predicate. All of the recipe objects are guaranteed to never be null. */
Stream<R> getRecipes(Predicate<R> toReturn);
/** @return an unmodifiable set containing all of the distillation recipes. */
Collection<R> getAllRecipes();
@Nullable
R getRecipeForInput(@Nullable FluidStack fluid);
Collection<R> removeRecipes(Predicate<R> toRemove);
/** Adds the given recipe to the registry. Note that this will remove any existing recipes for the passed
* recipe's {@link IRefineryRecipe#in()}
*
* @param recipe The recipe to add.
* @return The input recipe. */
R addRecipe(R recipe);
}
interface IRefineryRecipe {
FluidStack in();
}
interface IHeatExchangerRecipe extends IRefineryRecipe {
@Nullable
FluidStack out();
int heatFrom();
int heatTo();
}
interface IHeatableRecipe extends IHeatExchangerRecipe {}
interface ICoolableRecipe extends IHeatExchangerRecipe {}
interface IDistillationRecipe extends IRefineryRecipe {
long powerRequired();
FluidStack outGas();
FluidStack outLiquid();
}
}
@@ -1,76 +1,50 @@
package buildcraft.api.recipes;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.common.collect.ImmutableList;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.util.Constants;
import buildcraft.api.core.BuildCraftAPI;
public final class IntegrationRecipe {
public final ResourceLocation name;
public final long requiredMicroJoules;
public final @Nonnull ItemStack target;
public final NonNullList<ItemStack> toIntegrate;
public final ItemStack output;
public final StackDefinition target;
public final ImmutableList<StackDefinition> toIntegrate;
public final @Nonnull ItemStack output;
/**
* Additional tag used to restore network-transmitted recipe to same state
* You need to register own {@link IIntegrationRecipeProvider} using {@link IIntegrationRecipeRegistry#addRecipeProvider(IIntegrationRecipeProvider)}
* to handle this and declare {@link IIntegrationRecipeProvider#getRecipe(ResourceLocation, NBTTagCompound)} method
*/
public final @Nullable NBTTagCompound recipeTag;
public IntegrationRecipe(long requiredMicroJoules, @Nonnull ItemStack target, NonNullList<ItemStack> toIntegrate, ItemStack output) {
public IntegrationRecipe(ResourceLocation name, long requiredMicroJoules, StackDefinition target, List<StackDefinition> toIntegrate, @Nonnull ItemStack output, @Nullable NBTTagCompound recipeTag) {
this.name = name;
this.requiredMicroJoules = requiredMicroJoules;
this.target = target;
this.toIntegrate = toIntegrate;
this.toIntegrate = ImmutableList.copyOf(toIntegrate);
this.output = output;
this.recipeTag = recipeTag;
}
public IntegrationRecipe(NBTTagCompound nbt) {
requiredMicroJoules = nbt.getLong("required_micro_joules");
target = new ItemStack(nbt.getCompoundTag("target"));
NBTTagList toIntegrateTag = nbt.getTagList("to_integrate", Constants.NBT.TAG_COMPOUND);
toIntegrate = NonNullList.withSize(toIntegrateTag.tagCount(), ItemStack.EMPTY);
for (int i = 0; i < toIntegrateTag.tagCount(); i++) {
toIntegrate.set(i, new ItemStack(toIntegrateTag.getCompoundTagAt(i)));
}
output = new ItemStack(nbt.getCompoundTag("output"));
public IntegrationRecipe(String name, long requiredMicroJoules, StackDefinition target, List<StackDefinition> toIntegrate, @Nonnull ItemStack output, @Nullable NBTTagCompound recipeTag) {
this(BuildCraftAPI.nameToResourceLocation(name), requiredMicroJoules, target, toIntegrate, output, recipeTag);
}
public IntegrationRecipe(PacketBuffer buffer) throws IOException {
requiredMicroJoules = buffer.readLong();
ItemStack stack = buffer.readItemStack();
if (stack == null) throw new NullPointerException("stack");// should never happen
target = stack;
int count = buffer.readInt();
toIntegrate = NonNullList.withSize(count, ItemStack.EMPTY);
for (int i = 0; i < count; i++) {
toIntegrate.set(i, buffer.readItemStack());
}
output = buffer.readItemStack();
public IntegrationRecipe(ResourceLocation name, long requiredMicroJoules, StackDefinition target, List<StackDefinition> toIntegrate, @Nonnull ItemStack output) {
this(name, requiredMicroJoules, target, toIntegrate, output, null);
}
public NBTTagCompound writeToNBT() {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setLong("required_micro_joules", requiredMicroJoules);
nbt.setTag("target", target.serializeNBT());
NBTTagList toIntegrateTag = new NBTTagList();
for (ItemStack toIntegrateElement : toIntegrate) {
toIntegrateTag.appendTag(toIntegrateElement.serializeNBT());
}
nbt.setTag("to_integrate", toIntegrateTag);
nbt.setTag("output", output.serializeNBT());
return nbt;
}
public void writeToBuffer(PacketBuffer buffer) {
buffer.writeLong(requiredMicroJoules);
buffer.writeItemStack(target);
buffer.writeInt(toIntegrate.size());
for (ItemStack stack : toIntegrate) {
buffer.writeItemStack(stack);
}
buffer.writeItemStack(output);
public IntegrationRecipe(String name, long requiredMicroJoules, StackDefinition target, List<StackDefinition> toIntegrate, @Nonnull ItemStack output) {
this(name, requiredMicroJoules, target, toIntegrate, output, null);
}
@Override
@@ -84,37 +58,11 @@ public final class IntegrationRecipe {
IntegrationRecipe that = (IntegrationRecipe) o;
if (requiredMicroJoules != that.requiredMicroJoules) {
return false;
}
if (!ItemStack.areItemStacksEqual(target, that.target)) {
return false;
}
if (toIntegrate != null && that.toIntegrate != null) {
Iterator<ItemStack> iterator1 = toIntegrate.iterator();
Iterator<ItemStack> iterator2 = that.toIntegrate.iterator();
while (iterator1.hasNext()) {
if (!iterator2.hasNext()) {
return false;
}
ItemStack o1 = iterator1.next();
ItemStack o2 = iterator2.next();
if (!ItemStack.areItemStacksEqual(o1, o2)) {
return false;
}
}
return !iterator2.hasNext() && output != null ? ItemStack.areItemStacksEqual(output, that.output) : that.output == null;
} else {
return toIntegrate == null && that.toIntegrate == null && output != null ? ItemStack.areItemStacksEqual(output, that.output) : that.output == null;
}
return name.equals(that.name);
}
@Override
public int hashCode() {
int result = (int) (requiredMicroJoules ^ (requiredMicroJoules >>> 32));
result = 31 * result + (target != null ? target.hashCode() : 0);
result = 31 * result + (toIntegrate != null ? toIntegrate.hashCode() : 0);
result = 31 * result + (output != null ? output.hashCode() : 0);
return result;
return name.hashCode();
}
}
@@ -0,0 +1,20 @@
package buildcraft.api.recipes;
import buildcraft.api.core.IStackFilter;
/**
* Stack definition for recipe input
*/
public final class StackDefinition {
public final IStackFilter filter;
public final int count;
public StackDefinition(IStackFilter filter, int count) {
this.filter = filter;
this.count = count;
}
public StackDefinition(IStackFilter filter) {
this(filter, 1);
}
}
@@ -4,6 +4,8 @@
* of the license located in http://www.mod-buildcraft.com/MMPL-1.0.txt */
package buildcraft.api.robots;
import java.util.Arrays;
import net.minecraft.inventory.IInventory;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
@@ -134,7 +136,7 @@ public abstract class DockingStation {
if (array.length == 3) {
pos = new BlockPos(array[0], array[1], array[2]);
} else if (array.length != 0) {
BCLog.logger.warn("Found an integer array that wwas not the right length! (" + array + ")");
BCLog.logger.warn("Found an integer array that was not the right length! (" + Arrays.toString(array) + ")");
} else {
BCLog.logger.warn("Did not find any integer positions! This is a bug!");
}
@@ -12,17 +12,17 @@ import buildcraft.api.core.BCLog;
public abstract class RobotManager {
public static IRobotRegistryProvider registryProvider;
public static ArrayList<Class<? extends AIRobot>> aiRobots = new ArrayList<Class<? extends AIRobot>>();
public static ArrayList<Class<? extends AIRobot>> aiRobots = new ArrayList<>();
static {
aiRobotsByNames = new HashMap<String, Class<? extends AIRobot>>();
aiRobotsNames = new HashMap<Class<? extends AIRobot>, String>();
aiRobotsByLegacyClassNames = new HashMap<String, Class<? extends AIRobot>>();
resourceIdNames = new HashMap<Class<? extends ResourceId>, String>();
resourceIdByNames = new HashMap<String, Class<? extends ResourceId>>();
resourceIdLegacyClassNames = new HashMap<String, Class<? extends ResourceId>>();
dockingStationNames = new HashMap<Class<? extends DockingStation>, String>();
dockingStationByNames = new HashMap<String, Class<? extends DockingStation>>();
aiRobotsByNames = new HashMap<>();
aiRobotsNames = new HashMap<>();
aiRobotsByLegacyClassNames = new HashMap<>();
resourceIdNames = new HashMap<>();
resourceIdByNames = new HashMap<>();
resourceIdLegacyClassNames = new HashMap<>();
dockingStationNames = new HashMap<>();
dockingStationByNames = new HashMap<>();
registerResourceId(ResourceIdBlock.class, "resourceIdBlock", "buildcraft.core.robots.ResourceIdBlock");
registerResourceId(ResourceIdRequest.class, "resourceIdRequest", "buildcraft.core.robots.ResourceIdRequest");
@@ -52,7 +52,7 @@ public abstract class RobotManager {
try {
aiRobot.getConstructor(EntityRobotBase.class);
} catch (NoSuchMethodException e) {
throw new RuntimeException("AI class " + aiRobot.getName() + " lacks NBT load construtor! This is a bug!");
throw new RuntimeException("AI class " + aiRobot.getName() + " lacks NBT load constructor! This is a bug!");
}
aiRobots.add(aiRobot);
@@ -91,8 +91,8 @@ public abstract class RobotManager {
return resourceIdByNames.get(resourceIdName);
}
public static String getResourceIdName(Class<? extends ResourceId> resouceIdClass) {
return resourceIdNames.get(resouceIdClass);
public static String getResourceIdName(Class<? extends ResourceId> resourceIdClass) {
return resourceIdNames.get(resourceIdClass);
}
public static Class<?> getResourceIdByLegacyClassName(String resourceIdLegacyClassName) {
@@ -0,0 +1,46 @@
package buildcraft.api.schematics;
import java.util.List;
import java.util.Set;
import javax.annotation.Nonnull;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.Rotation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fluids.FluidStack;
import buildcraft.api.core.InvalidInputDataException;
public interface ISchematicBlock<S extends ISchematicBlock<S>> {
void init(SchematicBlockContext context);
boolean isAir();
@Nonnull
Set<BlockPos> getRequiredBlockOffsets();
@Nonnull
List<ItemStack> computeRequiredItems(SchematicBlockContext context);
@Nonnull
List<FluidStack> computeRequiredFluids(SchematicBlockContext context);
S getRotated(Rotation rotation);
boolean canBuild(World world, BlockPos blockPos);
boolean build(World world, BlockPos blockPos);
boolean buildWithoutChecks(World world, BlockPos blockPos);
boolean isBuilt(World world, BlockPos blockPos);
NBTTagCompound serializeNBT();
/** @throws InvalidInputDataException If the input data wasn't correct or didn't make sense. */
void deserializeNBT(NBTTagCompound nbt) throws InvalidInputDataException;
}
@@ -0,0 +1,40 @@
package buildcraft.api.schematics;
import java.util.List;
import javax.annotation.Nonnull;
import net.minecraft.entity.Entity;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.Rotation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.fluids.FluidStack;
import buildcraft.api.core.InvalidInputDataException;
public interface ISchematicEntity<S extends ISchematicEntity<S>> {
void init(SchematicEntityContext context);
Vec3d getPos();
@Nonnull
List<ItemStack> computeRequiredItems(SchematicEntityContext context);
@Nonnull
List<FluidStack> computeRequiredFluids(SchematicEntityContext context);
S getRotated(Rotation rotation);
Entity build(World world, BlockPos basePos);
Entity buildWithoutChecks(World world, BlockPos basePos);
NBTTagCompound serializeNBT();
/** @throws InvalidInputDataException If the input data wasn't correct or didn't make sense. */
void deserializeNBT(NBTTagCompound nbt) throws InvalidInputDataException;
}
@@ -0,0 +1,33 @@
package buildcraft.api.schematics;
import javax.annotation.Nonnull;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public class SchematicBlockContext {
@Nonnull
public final World world;
@Nonnull
public final BlockPos basePos;
@Nonnull
public final BlockPos pos;
@Nonnull
public final IBlockState blockState;
@Nonnull
public final Block block;
public SchematicBlockContext(@Nonnull World world,
@Nonnull BlockPos basePos,
@Nonnull BlockPos pos,
@Nonnull IBlockState blockState,
@Nonnull Block block) {
this.world = world;
this.basePos = basePos;
this.pos = pos;
this.blockState = blockState;
this.block = block;
}
}
@@ -0,0 +1,39 @@
package buildcraft.api.schematics;
import java.util.function.Predicate;
import java.util.function.Supplier;
import javax.annotation.Nonnull;
import net.minecraft.util.ResourceLocation;
public class SchematicBlockFactory<S extends ISchematicBlock<S>> implements Comparable<SchematicBlockFactory> {
@Nonnull
public final ResourceLocation name;
public final int priority;
@Nonnull
public final Predicate<SchematicBlockContext> predicate;
@Nonnull
public final Supplier<S> supplier;
@Nonnull
public final Class<S> clazz;
@SuppressWarnings("unchecked")
public SchematicBlockFactory(@Nonnull ResourceLocation name,
int priority,
@Nonnull Predicate<SchematicBlockContext> predicate,
@Nonnull Supplier<S> supplier) {
this.name = name;
this.priority = priority;
this.predicate = predicate;
this.supplier = supplier;
clazz = (Class<S>) supplier.get().getClass();
}
@Override
public int compareTo(@Nonnull SchematicBlockFactory o) {
return priority != o.priority
? Integer.compare(priority, o.priority)
: name.toString().compareTo(o.name.toString());
}
}
@@ -0,0 +1,65 @@
package buildcraft.api.schematics;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Predicate;
import java.util.function.Supplier;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.common.collect.ImmutableList;
import net.minecraft.block.Block;
import net.minecraft.util.ResourceLocation;
import buildcraft.api.core.BuildCraftAPI;
public class SchematicBlockFactoryRegistry {
private static final Set<SchematicBlockFactory<?>> FACTORIES = new TreeSet<>();
public static <S extends ISchematicBlock<S>> void registerFactory(String name,
int priority,
Predicate<SchematicBlockContext> predicate,
Supplier<S> supplier) {
FACTORIES.add(new SchematicBlockFactory<>(
BuildCraftAPI.nameToResourceLocation(name),
priority,
predicate,
supplier
));
}
public static <S extends ISchematicBlock<S>> void registerFactory(String name,
int priority,
List<Block> blocks,
Supplier<S> supplier) {
registerFactory(
name,
priority,
context -> blocks.contains(context.block),
supplier
);
}
public static List<SchematicBlockFactory<?>> getFactories() {
return ImmutableList.copyOf(FACTORIES);
}
@Nonnull
public static SchematicBlockFactory<?> getFactoryByInstance(ISchematicBlock<?> instance) {
return FACTORIES.stream()
.filter(schematicBlockFactory -> schematicBlockFactory.clazz == instance.getClass())
.findFirst()
.orElseThrow(() -> new IllegalStateException("Didn't find a factory for " + instance.getClass()));
}
@Nullable
public static SchematicBlockFactory<?> getFactoryByName(ResourceLocation name) {
return FACTORIES.stream()
.filter(schematicBlockFactory -> schematicBlockFactory.name.equals(name))
.findFirst()
.orElse(null);
}
}
@@ -0,0 +1,24 @@
package buildcraft.api.schematics;
import javax.annotation.Nonnull;
import net.minecraft.entity.Entity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public class SchematicEntityContext {
@Nonnull
public final World world;
@Nonnull
public final BlockPos basePos;
@Nonnull
public final Entity entity;
public SchematicEntityContext(@Nonnull World world,
@Nonnull BlockPos basePos,
@Nonnull Entity entity) {
this.world = world;
this.basePos = basePos;
this.entity = entity;
}
}
@@ -0,0 +1,39 @@
package buildcraft.api.schematics;
import java.util.function.Predicate;
import java.util.function.Supplier;
import javax.annotation.Nonnull;
import net.minecraft.util.ResourceLocation;
public class SchematicEntityFactory<S extends ISchematicEntity<S>> implements Comparable<SchematicEntityFactory> {
@Nonnull
public final ResourceLocation name;
public final int priority;
@Nonnull
public final Predicate<SchematicEntityContext> predicate;
@Nonnull
public final Supplier<S> supplier;
@Nonnull
public final Class<S> clazz;
@SuppressWarnings("unchecked")
public SchematicEntityFactory(@Nonnull ResourceLocation name,
int priority,
@Nonnull Predicate<SchematicEntityContext> predicate,
@Nonnull Supplier<S> supplier) {
this.name = name;
this.priority = priority;
this.predicate = predicate;
this.supplier = supplier;
clazz = (Class<S>) supplier.get().getClass();
}
@Override
public int compareTo(@Nonnull SchematicEntityFactory o) {
return priority != o.priority
? Integer.compare(priority, o.priority)
: name.toString().compareTo(o.name.toString());
}
}
@@ -0,0 +1,65 @@
package buildcraft.api.schematics;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Predicate;
import java.util.function.Supplier;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.common.collect.ImmutableList;
import net.minecraft.entity.EntityList;
import net.minecraft.util.ResourceLocation;
import buildcraft.api.core.BuildCraftAPI;
public class SchematicEntityFactoryRegistry {
private static final Set<SchematicEntityFactory<?>> FACTORIES = new TreeSet<>();
public static <S extends ISchematicEntity<S>> void registerFactory(String name,
int priority,
Predicate<SchematicEntityContext> predicate,
Supplier<S> supplier) {
FACTORIES.add(new SchematicEntityFactory<>(
BuildCraftAPI.nameToResourceLocation(name),
priority,
predicate,
supplier
));
}
public static <S extends ISchematicEntity<S>> void registerFactory(String name,
int priority,
List<ResourceLocation> entities,
Supplier<S> supplier) {
registerFactory(
name,
priority,
context -> entities.contains(EntityList.getKey(context.entity)),
supplier
);
}
public static List<SchematicEntityFactory<?>> getFactories() {
return ImmutableList.copyOf(FACTORIES);
}
@Nonnull
public static SchematicEntityFactory<?> getFactoryByInstance(ISchematicEntity<?> instance) {
return FACTORIES.stream()
.filter(schematicEntityFactory -> schematicEntityFactory.clazz == instance.getClass())
.findFirst()
.orElseThrow(() -> new IllegalStateException("Didn't find a factory for " + instance.getClass()));
}
@Nullable
public static SchematicEntityFactory<?> getFactoryByName(ResourceLocation name) {
return FACTORIES.stream()
.filter(schematicEntityFactory -> schematicEntityFactory.name.equals(name))
.findFirst()
.orElse(null);
}
}
@@ -14,7 +14,8 @@ public interface IGuiSlot {
/** Return the parameter description in the UI */
String getDescription();
/** @return A sprite to show in a GUI, or null if this should not render a sprite. */
/** @return A sprite to show in a GUI or in-world (so this must be stitched into the block texture atlas), or null
* if this should not render a sprite. */
@SideOnly(Side.CLIENT)
TextureAtlasSprite getGuiSprite();
}
@@ -4,6 +4,8 @@
* should be located as "LICENSE.API" in the BuildCraft source code distribution. */
package buildcraft.api.statements;
import javax.annotation.Nullable;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
@@ -11,5 +13,6 @@ import net.minecraft.util.EnumFacing;
public interface IStatementContainer {
TileEntity getTile();
@Nullable
TileEntity getNeighbourTile(EnumFacing side);
}
@@ -6,7 +6,7 @@ import net.minecraft.util.EnumFacing;
*
* Please use wisely. */
public interface ITriggerExternalOverride {
public enum Result {
enum Result {
TRUE,
FALSE,
IGNORE
@@ -4,7 +4,12 @@
* should be located as "LICENSE.API" in the BuildCraft source code distribution. */
package buildcraft.api.statements;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
@@ -13,10 +18,10 @@ import buildcraft.api.core.BCLog;
public final class StatementManager {
public static Map<String, IStatement> statements = new HashMap<String, IStatement>();
public static Map<String, Class<? extends IStatementParameter>> parameters = new HashMap<String, Class<? extends IStatementParameter>>();
private static List<ITriggerProvider> triggerProviders = new LinkedList<ITriggerProvider>();
private static List<IActionProvider> actionProviders = new LinkedList<IActionProvider>();
public static Map<String, IStatement> statements = new HashMap<>();
public static Map<String, Class<? extends IStatementParameter>> parameters = new HashMap<>();
private static List<ITriggerProvider> triggerProviders = new LinkedList<>();
private static List<IActionProvider> actionProviders = new LinkedList<>();
static {
registerParameterClass(StatementParameterItemStack.class);
@@ -53,13 +58,13 @@ public final class StatementManager {
}
}
LinkedHashSet<ITriggerExternal> triggers = new LinkedHashSet<ITriggerExternal>();
LinkedHashSet<ITriggerExternal> triggers = new LinkedHashSet<>();
for (ITriggerProvider provider : triggerProviders) {
provider.addExternalTriggers(triggers, side, entity);
}
return new ArrayList<ITriggerExternal>(triggers);
return new ArrayList<>(triggers);
}
public static List<IActionExternal> getExternalActions(EnumFacing side, TileEntity entity) {
@@ -70,53 +75,53 @@ public final class StatementManager {
}
}
LinkedHashSet<IActionExternal> actions = new LinkedHashSet<IActionExternal>();
LinkedHashSet<IActionExternal> actions = new LinkedHashSet<>();
for (IActionProvider provider : actionProviders) {
provider.addExternalActions(actions, side, entity);
}
return new ArrayList<IActionExternal>(actions);
return new ArrayList<>(actions);
}
public static List<ITriggerInternal> getInternalTriggers(IStatementContainer container) {
LinkedHashSet<ITriggerInternal> triggers = new LinkedHashSet<ITriggerInternal>();
LinkedHashSet<ITriggerInternal> triggers = new LinkedHashSet<>();
for (ITriggerProvider provider : triggerProviders) {
provider.addInternalTriggers(triggers, container);
}
return new ArrayList<ITriggerInternal>(triggers);
return new ArrayList<>(triggers);
}
public static List<IActionInternal> getInternalActions(IStatementContainer container) {
LinkedHashSet<IActionInternal> actions = new LinkedHashSet<IActionInternal>();
LinkedHashSet<IActionInternal> actions = new LinkedHashSet<>();
for (IActionProvider provider : actionProviders) {
provider.addInternalActions(actions, container);
}
return new ArrayList<IActionInternal>(actions);
return new ArrayList<>(actions);
}
public static List<ITriggerInternalSided> getInternalSidedTriggers(IStatementContainer container, EnumFacing side) {
LinkedHashSet<ITriggerInternalSided> triggers = new LinkedHashSet<ITriggerInternalSided>();
LinkedHashSet<ITriggerInternalSided> triggers = new LinkedHashSet<>();
for (ITriggerProvider provider : triggerProviders) {
provider.addInternalSidedTriggers(triggers, container, side);
}
return new ArrayList<ITriggerInternalSided>(triggers);
return new ArrayList<>(triggers);
}
public static List<IActionInternalSided> getInternalSidedActions(IStatementContainer container, EnumFacing side) {
LinkedHashSet<IActionInternalSided> actions = new LinkedHashSet<IActionInternalSided>();
LinkedHashSet<IActionInternalSided> actions = new LinkedHashSet<>();
for (IActionProvider provider : actionProviders) {
provider.addInternalSidedActions(actions, container, side);
}
return new ArrayList<IActionInternalSided>(actions);
return new ArrayList<>(actions);
}
public static IStatementParameter createParameter(String kind) {
@@ -130,9 +135,7 @@ public final class StatementManager {
try {
return param.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
} catch (Error error) {
BCLog.logErrorAPI(error, IStatementParameter.class);
@@ -31,6 +31,7 @@ public class StatementParameterItemStack implements IStatementParameter {
return null;
}
@Nonnull
@Override
public ItemStack getItemStack() {
return stack;
@@ -4,7 +4,7 @@ import java.util.HashMap;
import java.util.Map;
public final class TabletAPI {
private static final Map<String, TabletProgramFactory> programs = new HashMap<String, TabletProgramFactory>();
private static final Map<String, TabletProgramFactory> programs = new HashMap<>();
private TabletAPI() {
@@ -0,0 +1,16 @@
/*
* Copyright (c) 2017 SpaceToad and the BuildCraft team
* The BuildCraft API is distributed under the terms of the MIT License. Please check the contents of the license, which
* should be located as "LICENSE.API" in the BuildCraft source code distribution.
*/
package buildcraft.api.template;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public interface ITemplateHandler {
boolean handle(World world, BlockPos pos, EntityPlayer player, ItemStack stack);
}
@@ -0,0 +1,25 @@
/*
* Copyright (c) 2017 SpaceToad and the BuildCraft team
* The BuildCraft API is distributed under the terms of the MIT License. Please check the contents of the license, which
* should be located as "LICENSE.API" in the BuildCraft source code distribution.
*/
package buildcraft.api.template;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import buildcraft.api.core.EnumHandlerPriority;
public interface ITemplateRegistry {
/** Adds a handler with a {@link EnumHandlerPriority} of {@linkplain EnumHandlerPriority#NORMAL} */
default void addHandler(ITemplateHandler handler) {
addHandler(handler, EnumHandlerPriority.NORMAL);
}
void addHandler(ITemplateHandler handler, EnumHandlerPriority priority);
boolean handle(World world, BlockPos pos, EntityPlayer player, ItemStack stack);
}
Loaded 100 of 127 files, more files were not shown because too many files have changed in this diff. Show more