From e860089535a995c56dacda5225cdacc7745d4278 Mon Sep 17 00:00:00 2001 From: Tom Elfring Date: Mon, 10 Jul 2017 18:19:00 +0200 Subject: [PATCH] Update BuildCraft API to 218FB4A --- src/api/java/buildcraft/api/BCBlocks.java | 122 +++++ src/api/java/buildcraft/api/BCItems.java | 167 +++++++ src/api/java/buildcraft/api/BCModules.java | 67 +++ .../api/blueprints/BlueprintDeployer.java | 30 -- .../buildcraft/api/blueprints/BuilderAPI.java | 16 - .../api/blueprints/BuildingPermission.java | 21 - .../api/blueprints/IBuilderContext.java | 22 - .../api/blueprints/ISchematicHelper.java | 7 - .../api/blueprints/ISchematicRegistry.java | 19 - .../api/blueprints/ITileBuilder.java | 13 - .../blueprints/MappingNotFoundException.java | 13 - .../api/blueprints/MappingRegistry.java | 422 ------------------ .../buildcraft/api/blueprints/Schematic.java | 196 -------- .../api/blueprints/SchematicBlock.java | 193 -------- .../api/blueprints/SchematicBlockBase.java | 9 - .../api/blueprints/SchematicEntity.java | 193 -------- .../api/blueprints/SchematicFactory.java | 51 --- .../api/blueprints/SchematicFluid.java | 83 ---- .../api/blueprints/SchematicMask.java | 83 ---- .../api/blueprints/SchematicTile.java | 109 ----- .../api/blueprints/package-info.java | 8 - .../java/buildcraft/api/core/APIHelper.java | 81 ---- .../java/buildcraft/api/core/BCDebugging.java | 4 +- .../buildcraft/api/core/BuildCraftAPI.java | 29 +- .../api/core/CapabilitiesHelper.java | 37 ++ .../buildcraft/api/core/ConfigAccessor.java | 48 -- .../api/core/EnumHandlerPriority.java | 17 + .../buildcraft/api/core/EnumPipePart.java | 53 ++- .../buildcraft/api/core/IBCFakePlayer.java | 25 -- .../buildcraft/api/core/IBuildCraftMod.java | 8 - .../java/buildcraft/api/core/IEngineType.java | 5 + .../api/core/IFakePlayerProvider.java | 40 ++ .../buildcraft/api/core/INBTLoadable_BC8.java | 14 - .../buildcraft/api/core/INBTStoreable.java | 12 - .../api/core/INetworkLoadable_BC8.java | 10 - .../{permission => core}/IPlayerOwned.java | 2 +- .../buildcraft/api/core/ISerializable.java | 21 - .../buildcraft/api/core/IStackFilter.java | 8 + .../api/core/InvalidInputDataException.java | 29 ++ .../buildcraft/api/core/render/ICullable.java | 27 -- .../api/core/render/ITextureStateManager.java | 7 - .../api/core/render/ITextureStates.java | 18 - .../buildcraft/api/crops/CropManager.java | 2 +- .../buildcraft/api/crops/ICropHandler.java | 2 - .../api/data/NbtSquishConstants.java | 50 +++ .../api/enums/EnumBlueprintType.java | 29 -- .../api/enums/EnumDecoratedBlock.java | 2 +- .../buildcraft/api/enums/EnumEngineType.java | 11 +- .../api/enums/EnumMachineState.java | 2 +- .../api/enums/EnumOptionalSnapshotType.java | 36 ++ .../api/enums/EnumRedstoneChipset.java | 23 +- .../api/enums/EnumSnapshotType.java | 12 + .../java/buildcraft/api/enums/EnumSpring.java | 9 +- .../buildcraft/api/facades/FacadeAPI.java | 26 ++ .../buildcraft/api/facades/IFacadeItem.java | 7 +- .../java/buildcraft/api/fuels/ICoolant.java | 9 +- .../buildcraft/api/fuels/ICoolantManager.java | 12 +- src/api/java/buildcraft/api/fuels/IFuel.java | 5 +- .../buildcraft/api/fuels/IFuelManager.java | 20 +- .../api/inventory/IItemTransactor.java | 72 +++ .../buildcraft/api/items/IBlueprintItem.java | 9 - .../buildcraft/api/items/IMapLocation.java | 2 +- .../buildcraft/api/library/LibraryAPI.java | 2 +- .../buildcraft/api/lists/ListRegistry.java | 4 +- .../java/buildcraft/api/mj/ILaserTarget.java | 11 +- .../java/buildcraft/api/mj/IMjReceiver.java | 11 + src/api/java/buildcraft/api/mj/MjAPI.java | 149 ++----- src/api/java/buildcraft/api/mj/MjBattery.java | 4 +- .../buildcraft/api/mj/MjCapabilityHelper.java | 32 +- .../java/buildcraft/api/mj/package-info.java | 4 +- .../buildcraft/api/permission/IOwner.java | 24 - .../BuildCraftExtendedProperty.java | 65 --- .../api/properties/BuildCraftProperties.java | 72 +-- .../api/properties/BuildCraftProperty.java | 147 ------ .../api/recipes/AssemblyRecipe.java | 107 ++--- .../api/recipes/BuildcraftRecipeRegistry.java | 2 +- .../api/recipes/IAssemblyRecipeProvider.java | 16 +- .../IComplexRefineryRecipeManager.java | 66 --- .../recipes/IIntegrationRecipeProvider.java | 12 + .../api/recipes/IRefineryRecipeManager.java | 81 ++++ .../api/recipes/IntegrationRecipe.java | 108 ++--- .../api/recipes/StackDefinition.java | 20 + .../buildcraft/api/robots/DockingStation.java | 4 +- .../buildcraft/api/robots/RobotManager.java | 24 +- .../api/schematics/ISchematicBlock.java | 46 ++ .../api/schematics/ISchematicEntity.java | 40 ++ .../api/schematics/SchematicBlockContext.java | 33 ++ .../api/schematics/SchematicBlockFactory.java | 39 ++ .../SchematicBlockFactoryRegistry.java | 65 +++ .../schematics/SchematicEntityContext.java | 24 + .../schematics/SchematicEntityFactory.java | 39 ++ .../SchematicEntityFactoryRegistry.java | 65 +++ .../buildcraft/api/statements/IGuiSlot.java | 3 +- .../api/statements/IStatementContainer.java | 3 + .../statements/ITriggerExternalOverride.java | 2 +- .../api/statements/StatementManager.java | 43 +- .../StatementParameterItemStack.java | 1 + .../java/buildcraft/api/tablet/TabletAPI.java | 2 +- .../api/template/ITemplateHandler.java | 16 + .../api/template/ITemplateRegistry.java | 25 ++ .../buildcraft/api/template/TemplateApi.java | 11 + .../buildcraft/api/tiles/IControllable.java | 21 +- .../java/buildcraft/api/tiles/IHeatable.java | 2 +- .../java/buildcraft/api/tiles/TilesAPI.java | 46 ++ .../api/transport/EnumWirePart.java | 15 +- .../buildcraft/api/transport/IInjectable.java | 1 - .../api/transport/IItemPluggable.java | 6 +- .../api/transport/IStripesRegistry.java | 41 +- .../transport/pipe/ICustomPipeConnection.java | 6 +- .../api/transport/pipe/IFlowFluid.java | 11 +- .../api/transport/pipe/IItemPipe.java | 2 +- .../buildcraft/api/transport/pipe/IPipe.java | 4 +- .../api/transport/pipe/IPipeHolder.java | 21 +- .../api/transport/pipe/PipeApi.java | 103 ++++- .../api/transport/pipe/PipeBehaviour.java | 11 +- .../api/transport/pipe/PipeConnectionAPI.java | 11 +- .../api/transport/pipe/PipeDefinition.java | 2 +- .../api/transport/pipe/PipeEvent.java | 15 +- .../api/transport/pipe/PipeEventFluid.java | 97 +++- .../api/transport/pipe/PipeEventHandler.java | 11 +- .../api/transport/pipe/PipeEventItem.java | 38 +- .../api/transport/pipe/PipeEventPriority.java | 2 +- .../api/transport/pipe/PipeFlow.java | 17 +- .../transport/pluggable/PipePluggable.java | 51 ++- .../pluggable/PluggableDefinition.java | 2 +- .../java/mekanism/common/FuelHandler.java | 6 +- .../generators/common/MekanismGenerators.java | 6 +- 127 files changed, 2015 insertions(+), 2634 deletions(-) create mode 100644 src/api/java/buildcraft/api/BCBlocks.java create mode 100644 src/api/java/buildcraft/api/BCItems.java create mode 100644 src/api/java/buildcraft/api/BCModules.java delete mode 100755 src/api/java/buildcraft/api/blueprints/BlueprintDeployer.java delete mode 100755 src/api/java/buildcraft/api/blueprints/BuilderAPI.java delete mode 100755 src/api/java/buildcraft/api/blueprints/BuildingPermission.java delete mode 100755 src/api/java/buildcraft/api/blueprints/IBuilderContext.java delete mode 100755 src/api/java/buildcraft/api/blueprints/ISchematicHelper.java delete mode 100755 src/api/java/buildcraft/api/blueprints/ISchematicRegistry.java delete mode 100755 src/api/java/buildcraft/api/blueprints/ITileBuilder.java delete mode 100755 src/api/java/buildcraft/api/blueprints/MappingNotFoundException.java delete mode 100755 src/api/java/buildcraft/api/blueprints/MappingRegistry.java delete mode 100755 src/api/java/buildcraft/api/blueprints/Schematic.java delete mode 100755 src/api/java/buildcraft/api/blueprints/SchematicBlock.java delete mode 100755 src/api/java/buildcraft/api/blueprints/SchematicBlockBase.java delete mode 100755 src/api/java/buildcraft/api/blueprints/SchematicEntity.java delete mode 100755 src/api/java/buildcraft/api/blueprints/SchematicFactory.java delete mode 100755 src/api/java/buildcraft/api/blueprints/SchematicFluid.java delete mode 100755 src/api/java/buildcraft/api/blueprints/SchematicMask.java delete mode 100755 src/api/java/buildcraft/api/blueprints/SchematicTile.java delete mode 100755 src/api/java/buildcraft/api/blueprints/package-info.java delete mode 100755 src/api/java/buildcraft/api/core/APIHelper.java create mode 100644 src/api/java/buildcraft/api/core/CapabilitiesHelper.java delete mode 100755 src/api/java/buildcraft/api/core/ConfigAccessor.java create mode 100644 src/api/java/buildcraft/api/core/EnumHandlerPriority.java delete mode 100755 src/api/java/buildcraft/api/core/IBCFakePlayer.java delete mode 100755 src/api/java/buildcraft/api/core/IBuildCraftMod.java create mode 100644 src/api/java/buildcraft/api/core/IEngineType.java create mode 100644 src/api/java/buildcraft/api/core/IFakePlayerProvider.java delete mode 100755 src/api/java/buildcraft/api/core/INBTLoadable_BC8.java delete mode 100755 src/api/java/buildcraft/api/core/INBTStoreable.java delete mode 100755 src/api/java/buildcraft/api/core/INetworkLoadable_BC8.java rename src/api/java/buildcraft/api/{permission => core}/IPlayerOwned.java (83%) mode change 100755 => 100644 delete mode 100755 src/api/java/buildcraft/api/core/ISerializable.java create mode 100644 src/api/java/buildcraft/api/core/InvalidInputDataException.java delete mode 100755 src/api/java/buildcraft/api/core/render/ICullable.java delete mode 100755 src/api/java/buildcraft/api/core/render/ITextureStateManager.java delete mode 100755 src/api/java/buildcraft/api/core/render/ITextureStates.java create mode 100644 src/api/java/buildcraft/api/data/NbtSquishConstants.java delete mode 100755 src/api/java/buildcraft/api/enums/EnumBlueprintType.java create mode 100644 src/api/java/buildcraft/api/enums/EnumOptionalSnapshotType.java create mode 100644 src/api/java/buildcraft/api/enums/EnumSnapshotType.java create mode 100644 src/api/java/buildcraft/api/inventory/IItemTransactor.java delete mode 100755 src/api/java/buildcraft/api/items/IBlueprintItem.java delete mode 100755 src/api/java/buildcraft/api/permission/IOwner.java delete mode 100755 src/api/java/buildcraft/api/properties/BuildCraftExtendedProperty.java delete mode 100755 src/api/java/buildcraft/api/properties/BuildCraftProperty.java delete mode 100755 src/api/java/buildcraft/api/recipes/IComplexRefineryRecipeManager.java create mode 100644 src/api/java/buildcraft/api/recipes/IRefineryRecipeManager.java create mode 100644 src/api/java/buildcraft/api/recipes/StackDefinition.java create mode 100644 src/api/java/buildcraft/api/schematics/ISchematicBlock.java create mode 100644 src/api/java/buildcraft/api/schematics/ISchematicEntity.java create mode 100644 src/api/java/buildcraft/api/schematics/SchematicBlockContext.java create mode 100644 src/api/java/buildcraft/api/schematics/SchematicBlockFactory.java create mode 100644 src/api/java/buildcraft/api/schematics/SchematicBlockFactoryRegistry.java create mode 100644 src/api/java/buildcraft/api/schematics/SchematicEntityContext.java create mode 100644 src/api/java/buildcraft/api/schematics/SchematicEntityFactory.java create mode 100644 src/api/java/buildcraft/api/schematics/SchematicEntityFactoryRegistry.java create mode 100644 src/api/java/buildcraft/api/template/ITemplateHandler.java create mode 100644 src/api/java/buildcraft/api/template/ITemplateRegistry.java create mode 100644 src/api/java/buildcraft/api/template/TemplateApi.java create mode 100644 src/api/java/buildcraft/api/tiles/TilesAPI.java diff --git a/src/api/java/buildcraft/api/BCBlocks.java b/src/api/java/buildcraft/api/BCBlocks.java new file mode 100644 index 000000000..c864fd797 --- /dev/null +++ b/src/api/java/buildcraft/api/BCBlocks.java @@ -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 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; + } +} diff --git a/src/api/java/buildcraft/api/BCItems.java b/src/api/java/buildcraft/api/BCItems.java new file mode 100644 index 000000000..2497aff15 --- /dev/null +++ b/src/api/java/buildcraft/api/BCItems.java @@ -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 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; + } +} diff --git a/src/api/java/buildcraft/api/BCModules.java b/src/api/java/buildcraft/api/BCModules.java new file mode 100644 index 000000000..73e769690 --- /dev/null +++ b/src/api/java/buildcraft/api/BCModules.java @@ -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!"); + } + } + } +} diff --git a/src/api/java/buildcraft/api/blueprints/BlueprintDeployer.java b/src/api/java/buildcraft/api/blueprints/BlueprintDeployer.java deleted file mode 100755 index dad91b98f..000000000 --- a/src/api/java/buildcraft/api/blueprints/BlueprintDeployer.java +++ /dev/null @@ -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); - -} diff --git a/src/api/java/buildcraft/api/blueprints/BuilderAPI.java b/src/api/java/buildcraft/api/blueprints/BuilderAPI.java deleted file mode 100755 index ac15b474b..000000000 --- a/src/api/java/buildcraft/api/blueprints/BuilderAPI.java +++ /dev/null @@ -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() {} -} diff --git a/src/api/java/buildcraft/api/blueprints/BuildingPermission.java b/src/api/java/buildcraft/api/blueprints/BuildingPermission.java deleted file mode 100755 index 8661240c4..000000000 --- a/src/api/java/buildcraft/api/blueprints/BuildingPermission.java +++ /dev/null @@ -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, -} diff --git a/src/api/java/buildcraft/api/blueprints/IBuilderContext.java b/src/api/java/buildcraft/api/blueprints/IBuilderContext.java deleted file mode 100755 index e5eb8900b..000000000 --- a/src/api/java/buildcraft/api/blueprints/IBuilderContext.java +++ /dev/null @@ -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(); -} diff --git a/src/api/java/buildcraft/api/blueprints/ISchematicHelper.java b/src/api/java/buildcraft/api/blueprints/ISchematicHelper.java deleted file mode 100755 index 7327f2e20..000000000 --- a/src/api/java/buildcraft/api/blueprints/ISchematicHelper.java +++ /dev/null @@ -1,7 +0,0 @@ -package buildcraft.api.blueprints; - -import net.minecraft.item.ItemStack; - -public interface ISchematicHelper { - boolean isEqualItem(ItemStack a, ItemStack b); -} diff --git a/src/api/java/buildcraft/api/blueprints/ISchematicRegistry.java b/src/api/java/buildcraft/api/blueprints/ISchematicRegistry.java deleted file mode 100755 index 503c315d5..000000000 --- a/src/api/java/buildcraft/api/blueprints/ISchematicRegistry.java +++ /dev/null @@ -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 clazz, Object... params); - - void registerSchematicBlock(IBlockState state, Class clazz, Object... params); - - void registerSchematicEntity(Class entityClass, Class schematicClass, Object... params); - - boolean isSupported(IBlockState state); -} diff --git a/src/api/java/buildcraft/api/blueprints/ITileBuilder.java b/src/api/java/buildcraft/api/blueprints/ITileBuilder.java deleted file mode 100755 index 2c06f64c3..000000000 --- a/src/api/java/buildcraft/api/blueprints/ITileBuilder.java +++ /dev/null @@ -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); - -} diff --git a/src/api/java/buildcraft/api/blueprints/MappingNotFoundException.java b/src/api/java/buildcraft/api/blueprints/MappingNotFoundException.java deleted file mode 100755 index f84cee627..000000000 --- a/src/api/java/buildcraft/api/blueprints/MappingNotFoundException.java +++ /dev/null @@ -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); - } -} diff --git a/src/api/java/buildcraft/api/blueprints/MappingRegistry.java b/src/api/java/buildcraft/api/blueprints/MappingRegistry.java deleted file mode 100755 index d2d9b9060..000000000 --- a/src/api/java/buildcraft/api/blueprints/MappingRegistry.java +++ /dev/null @@ -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 blockToId = new HashMap(); - public ArrayList idToBlock = new ArrayList(); - - public HashMap itemToId = new HashMap(); - public ArrayList idToItem = new ArrayList(); - - public HashMap, Integer> entityToId = new HashMap, Integer>(); - public ArrayList> idToEntity = new ArrayList>(); - - 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 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 getEntityForId(int id) throws MappingNotFoundException { - if (id >= idToEntity.size()) { - throw new MappingNotFoundException("no entity mapping at position " + id); - } - - Class result = idToEntity.get(id); - - if (result == null) { - throw new MappingNotFoundException("no entity mapping at position " + id); - } else { - return result; - } - } - - public int getIdForEntity(Class 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) 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 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 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 e = null; - - try { - e = (Class) 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 e : itemToId.entrySet()) { - cat.addCrashSection(" - ID " + e.getValue(), Item.REGISTRY.getNameForObject(e.getKey())); - } - - cat.addCrashSection("Block Map Count", blockToId.size()); - for (Entry e : blockToId.entrySet()) { - cat.addCrashSection(" - ID " + e.getValue(), Block.REGISTRY.getNameForObject(e.getKey())); - } - - cat.addCrashSection("Entity Map Count", entityToId.size()); - for (Entry, Integer> e : entityToId.entrySet()) { - cat.addCrashSection(" - ID " + e.getValue(), e.getKey()); - } - } -} diff --git a/src/api/java/buildcraft/api/blueprints/Schematic.java b/src/api/java/buildcraft/api/blueprints/Schematic.java deleted file mode 100755 index a0bb497b9..000000000 --- a/src/api/java/buildcraft/api/blueprints/Schematic.java +++ /dev/null @@ -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 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 requirements) {} - - /** Returns the amount of energy required to build this slot, depends on the stacks selected for the build. */ - public int getEnergyRequirement(NonNullList 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 getStacksToDisplay(NonNullList 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; - } -} diff --git a/src/api/java/buildcraft/api/blueprints/SchematicBlock.java b/src/api/java/buildcraft/api/blueprints/SchematicBlock.java deleted file mode 100755 index fe3af0acf..000000000 --- a/src/api/java/buildcraft/api/blueprints/SchematicBlock.java +++ /dev/null @@ -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 storedRequirements = NonNullList.create(); - - private boolean doNotUse = false; - - @Override - public void getRequirementsForPlacement(IBuilderContext context, NonNullList 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 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 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 getPrerequisiteBlocks(IBuilderContext context) { - Set indexes = new HashSet(); - 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); - } -} diff --git a/src/api/java/buildcraft/api/blueprints/SchematicBlockBase.java b/src/api/java/buildcraft/api/blueprints/SchematicBlockBase.java deleted file mode 100755 index 69f18a2eb..000000000 --- a/src/api/java/buildcraft/api/blueprints/SchematicBlockBase.java +++ /dev/null @@ -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 { - -} diff --git a/src/api/java/buildcraft/api/blueprints/SchematicEntity.java b/src/api/java/buildcraft/api/blueprints/SchematicEntity.java deleted file mode 100755 index 5d856c71d..000000000 --- a/src/api/java/buildcraft/api/blueprints/SchematicEntity.java +++ /dev/null @@ -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 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 storedRequirements = NonNullList.withSize(0, null); - public BuildingPermission defaultPermission = BuildingPermission.ALL; - - @Override - public void getRequirementsForPlacement(IBuilderContext context, NonNullList 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 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; - } -} diff --git a/src/api/java/buildcraft/api/blueprints/SchematicFactory.java b/src/api/java/buildcraft/api/blueprints/SchematicFactory.java deleted file mode 100755 index 878b15714..000000000 --- a/src/api/java/buildcraft/api/blueprints/SchematicFactory.java +++ /dev/null @@ -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 { - - private static final HashMap> factories = new HashMap>(); - - private static final HashMap, SchematicFactory> schematicToFactory = - new HashMap, 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 clas, SchematicFactory factory) { - schematicToFactory.put(clas, factory); - factories.put(factory.getClass().getCanonicalName(), factory); - } - - public static SchematicFactory getFactory(Class clas) { - Class superClass = clas.getSuperclass(); - - if (schematicToFactory.containsKey(clas)) { - return schematicToFactory.get(clas); - } else if (superClass != null) { - return getFactory(superClass); - } else { - return null; - } - } - -} diff --git a/src/api/java/buildcraft/api/blueprints/SchematicFluid.java b/src/api/java/buildcraft/api/blueprints/SchematicFluid.java deleted file mode 100755 index f044bf021..000000000 --- a/src/api/java/buildcraft/api/blueprints/SchematicFluid.java +++ /dev/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 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 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 getStacksToDisplay(NonNullList stackConsumed) { - NonNullList result = NonNullList.create(); - result.add(fluidItem); - return result; - } - - @Override - public int getEnergyRequirement(NonNullList stacksUsed) { - return 1;// * BuilderAPI.BUILD_ENERGY; - } - - public int getLevel() { - return state.getValue(BlockLiquid.LEVEL); - } -} diff --git a/src/api/java/buildcraft/api/blueprints/SchematicMask.java b/src/api/java/buildcraft/api/blueprints/SchematicMask.java deleted file mode 100755 index 3d811bce4..000000000 --- a/src/api/java/buildcraft/api/blueprints/SchematicMask.java +++ /dev/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.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 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"); - } -} diff --git a/src/api/java/buildcraft/api/blueprints/SchematicTile.java b/src/api/java/buildcraft/api/blueprints/SchematicTile.java deleted file mode 100755 index 318e27eb3..000000000 --- a/src/api/java/buildcraft/api/blueprints/SchematicTile.java +++ /dev/null @@ -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 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; - } -} diff --git a/src/api/java/buildcraft/api/blueprints/package-info.java b/src/api/java/buildcraft/api/blueprints/package-info.java deleted file mode 100755 index 3b3632424..000000000 --- a/src/api/java/buildcraft/api/blueprints/package-info.java +++ /dev/null @@ -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; diff --git a/src/api/java/buildcraft/api/core/APIHelper.java b/src/api/java/buildcraft/api/core/APIHelper.java deleted file mode 100755 index 9d8613201..000000000 --- a/src/api/java/buildcraft/api/core/APIHelper.java +++ /dev/null @@ -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 getInstance(String clsName, Class baseVersion) { - return getNamedInstance(clsName, "INSTANCE", baseVersion); - } - - public static T getInstance(String clsName, Class baseVersion, T nullVersion) { - return getNamedInstance(clsName, "INSTANCE", baseVersion, nullVersion); - } - - @SuppressWarnings("unchecked") - public static T getNamedInstance(String clsName, String enumName, Class 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>) voidType).getEnumConstants(); - for (Enum e : eArr) { - if (e.name().equals(enumName) && baseVersion.isInstance(e)) return (T) e; - } - } - return null; - } - - @SuppressWarnings("unchecked") - public static T getNamedInstance(String clsName, String enumName, Class 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>) 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 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; - } -} diff --git a/src/api/java/buildcraft/api/core/BCDebugging.java b/src/api/java/buildcraft/api/core/BCDebugging.java index 3badeb901..732be03d0 100755 --- a/src/api/java/buildcraft/api/core/BCDebugging.java +++ b/src/api/java/buildcraft/api/core/BCDebugging.java @@ -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; diff --git a/src/api/java/buildcraft/api/core/BuildCraftAPI.java b/src/api/java/buildcraft/api/core/BuildCraftAPI.java index 19e9e9c79..f7f24c0cb 100755 --- a/src/api/java/buildcraft/api/core/BuildCraftAPI.java +++ b/src/api/java/buildcraft/api/core/BuildCraftAPI.java @@ -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 softBlocks = Sets.newHashSet(); public static final HashMap 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); + } } diff --git a/src/api/java/buildcraft/api/core/CapabilitiesHelper.java b/src/api/java/buildcraft/api/core/CapabilitiesHelper.java new file mode 100644 index 000000000..d5795c935 --- /dev/null +++ b/src/api/java/buildcraft/api/core/CapabilitiesHelper.java @@ -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 void registerCapability(Class clazz) { + CapabilityManager.INSTANCE.register(clazz, new VoidStorage<>(), () -> { + throw new IllegalStateException("You must create your own instances!"); + }); + } + + @Nonnull + public static Capability ensureRegistration(Capability cap, Class clazz) { + if (cap == null) { + throw new Error("Capability registration failed for " + clazz); + } + return cap; + } + + public static class VoidStorage implements Capability.IStorage { + @Override + public NBTBase writeNBT(Capability capability, T instance, EnumFacing side) { + throw new IllegalStateException("You must create your own instances!"); + } + + @Override + public void readNBT(Capability capability, T instance, EnumFacing side, NBTBase nbt) { + throw new IllegalStateException("You must create your own instances!"); + } + } +} diff --git a/src/api/java/buildcraft/api/core/ConfigAccessor.java b/src/api/java/buildcraft/api/core/ConfigAccessor.java deleted file mode 100755 index a66346ac5..000000000 --- a/src/api/java/buildcraft/api/core/ConfigAccessor.java +++ /dev/null @@ -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 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); - } -} diff --git a/src/api/java/buildcraft/api/core/EnumHandlerPriority.java b/src/api/java/buildcraft/api/core/EnumHandlerPriority.java new file mode 100644 index 000000000..66145a2f5 --- /dev/null +++ b/src/api/java/buildcraft/api/core/EnumHandlerPriority.java @@ -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 { + HIGHEST, + HIGH, + NORMAL, + LOW, + LOWEST; + + public static final EnumHandlerPriority[] VALUES = values(); +} diff --git a/src/api/java/buildcraft/api/core/EnumPipePart.java b/src/api/java/buildcraft/api/core/EnumPipePart.java index 13b1ffc3f..3eb3731b0 100755 --- a/src/api/java/buildcraft/api/core/EnumPipePart.java +++ b/src/api/java/buildcraft/api/core/EnumPipePart.java @@ -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 { +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 facingMap = Maps.newEnumMap(EnumFacing.class); private static final Map nameMap = Maps.newHashMap(); private static final int MAX_VALUES = values().length; @@ -36,6 +36,16 @@ public enum EnumPipePart implements IStringSerializable, INetworkLoadable_BC8= 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 6) return CENTER; + if (ord < 0 || ord > 6) { + return CENTER; + } return values()[ord]; } } @@ -110,15 +130,4 @@ public enum EnumPipePart implements IStringSerializable, INetworkLoadable_BC8 + * 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); +} diff --git a/src/api/java/buildcraft/api/core/INBTLoadable_BC8.java b/src/api/java/buildcraft/api/core/INBTLoadable_BC8.java deleted file mode 100755 index 8005bcf53..000000000 --- a/src/api/java/buildcraft/api/core/INBTLoadable_BC8.java +++ /dev/null @@ -1,14 +0,0 @@ -package buildcraft.api.core; - -import net.minecraft.nbt.NBTBase; - -/** @param 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 { - /** @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(); -} diff --git a/src/api/java/buildcraft/api/core/INBTStoreable.java b/src/api/java/buildcraft/api/core/INBTStoreable.java deleted file mode 100755 index c34c134ac..000000000 --- a/src/api/java/buildcraft/api/core/INBTStoreable.java +++ /dev/null @@ -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); -} diff --git a/src/api/java/buildcraft/api/core/INetworkLoadable_BC8.java b/src/api/java/buildcraft/api/core/INetworkLoadable_BC8.java deleted file mode 100755 index 42d0d2469..000000000 --- a/src/api/java/buildcraft/api/core/INetworkLoadable_BC8.java +++ /dev/null @@ -1,10 +0,0 @@ -package buildcraft.api.core; - -import io.netty.buffer.ByteBuf; - -@Deprecated -public interface INetworkLoadable_BC8 { - T readFromByteBuf(ByteBuf buf); - - void writeToByteBuf(ByteBuf buf); -} diff --git a/src/api/java/buildcraft/api/permission/IPlayerOwned.java b/src/api/java/buildcraft/api/core/IPlayerOwned.java old mode 100755 new mode 100644 similarity index 83% rename from src/api/java/buildcraft/api/permission/IPlayerOwned.java rename to src/api/java/buildcraft/api/core/IPlayerOwned.java index b6c4350bb..8aa80fe4f --- a/src/api/java/buildcraft/api/permission/IPlayerOwned.java +++ b/src/api/java/buildcraft/api/core/IPlayerOwned.java @@ -1,4 +1,4 @@ -package buildcraft.api.permission; +package buildcraft.api.core; import com.mojang.authlib.GameProfile; diff --git a/src/api/java/buildcraft/api/core/ISerializable.java b/src/api/java/buildcraft/api/core/ISerializable.java deleted file mode 100755 index 77d56d541..000000000 --- a/src/api/java/buildcraft/api/core/ISerializable.java +++ /dev/null @@ -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); -} diff --git a/src/api/java/buildcraft/api/core/IStackFilter.java b/src/api/java/buildcraft/api/core/IStackFilter.java index 815861c44..2c810c9f6 100755 --- a/src/api/java/buildcraft/api/core/IStackFilter.java +++ b/src/api/java/buildcraft/api/core/IStackFilter.java @@ -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 getExamples() { + return NonNullList.withSize(0, ItemStack.EMPTY); + } } diff --git a/src/api/java/buildcraft/api/core/InvalidInputDataException.java b/src/api/java/buildcraft/api/core/InvalidInputDataException.java new file mode 100644 index 000000000..866c36cb1 --- /dev/null +++ b/src/api/java/buildcraft/api/core/InvalidInputDataException.java @@ -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); + } +} diff --git a/src/api/java/buildcraft/api/core/render/ICullable.java b/src/api/java/buildcraft/api/core/render/ICullable.java deleted file mode 100755 index 2399a6927..000000000 --- a/src/api/java/buildcraft/api/core/render/ICullable.java +++ /dev/null @@ -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); - -} diff --git a/src/api/java/buildcraft/api/core/render/ITextureStateManager.java b/src/api/java/buildcraft/api/core/render/ITextureStateManager.java deleted file mode 100755 index e401b3e2e..000000000 --- a/src/api/java/buildcraft/api/core/render/ITextureStateManager.java +++ /dev/null @@ -1,7 +0,0 @@ -package buildcraft.api.core.render; - -import net.minecraft.client.renderer.texture.TextureAtlasSprite; - -public interface ITextureStateManager { - void set(TextureAtlasSprite icon); -} diff --git a/src/api/java/buildcraft/api/core/render/ITextureStates.java b/src/api/java/buildcraft/api/core/render/ITextureStates.java deleted file mode 100755 index 593534f6c..000000000 --- a/src/api/java/buildcraft/api/core/render/ITextureStates.java +++ /dev/null @@ -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(); - -} diff --git a/src/api/java/buildcraft/api/crops/CropManager.java b/src/api/java/buildcraft/api/crops/CropManager.java index 97879829f..68a430201 100755 --- a/src/api/java/buildcraft/api/crops/CropManager.java +++ b/src/api/java/buildcraft/api/crops/CropManager.java @@ -12,7 +12,7 @@ import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; public final class CropManager { - private static List handlers = new ArrayList(); + private static List handlers = new ArrayList<>(); private static ICropHandler defaultHandler; private CropManager() { diff --git a/src/api/java/buildcraft/api/crops/ICropHandler.java b/src/api/java/buildcraft/api/crops/ICropHandler.java index 6b2324ac8..845108fe0 100755 --- a/src/api/java/buildcraft/api/crops/ICropHandler.java +++ b/src/api/java/buildcraft/api/crops/ICropHandler.java @@ -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; diff --git a/src/api/java/buildcraft/api/data/NbtSquishConstants.java b/src/api/java/buildcraft/api/data/NbtSquishConstants.java new file mode 100644 index 000000000..942f0a8e4 --- /dev/null +++ b/src/api/java/buildcraft/api/data/NbtSquishConstants.java @@ -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; +} diff --git a/src/api/java/buildcraft/api/enums/EnumBlueprintType.java b/src/api/java/buildcraft/api/enums/EnumBlueprintType.java deleted file mode 100755 index 8d6217797..000000000 --- a/src/api/java/buildcraft/api/enums/EnumBlueprintType.java +++ /dev/null @@ -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; - } - } -} diff --git a/src/api/java/buildcraft/api/enums/EnumDecoratedBlock.java b/src/api/java/buildcraft/api/enums/EnumDecoratedBlock.java index f161e2ba8..0a6b53feb 100755 --- a/src/api/java/buildcraft/api/enums/EnumDecoratedBlock.java +++ b/src/api/java/buildcraft/api/enums/EnumDecoratedBlock.java @@ -16,7 +16,7 @@ public enum EnumDecoratedBlock implements IStringSerializable { public final int lightValue; - private EnumDecoratedBlock(int lightValue) { + EnumDecoratedBlock(int lightValue) { this.lightValue = lightValue; } diff --git a/src/api/java/buildcraft/api/enums/EnumEngineType.java b/src/api/java/buildcraft/api/enums/EnumEngineType.java index 16e2714b7..38cdc62f7 100755 --- a/src/api/java/buildcraft/api/enums/EnumEngineType.java +++ b/src/api/java/buildcraft/api/enums/EnumEngineType.java @@ -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 diff --git a/src/api/java/buildcraft/api/enums/EnumMachineState.java b/src/api/java/buildcraft/api/enums/EnumMachineState.java index 6a215c235..7b7caf740 100755 --- a/src/api/java/buildcraft/api/enums/EnumMachineState.java +++ b/src/api/java/buildcraft/api/enums/EnumMachineState.java @@ -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 diff --git a/src/api/java/buildcraft/api/enums/EnumOptionalSnapshotType.java b/src/api/java/buildcraft/api/enums/EnumOptionalSnapshotType.java new file mode 100644 index 000000000..283ca0b02 --- /dev/null +++ b/src/api/java/buildcraft/api/enums/EnumOptionalSnapshotType.java @@ -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); + } +} diff --git a/src/api/java/buildcraft/api/enums/EnumRedstoneChipset.java b/src/api/java/buildcraft/api/enums/EnumRedstoneChipset.java index 68ecb2515..95c648fe1 100755 --- a/src/api/java/buildcraft/api/enums/EnumRedstoneChipset.java +++ b/src/api/java/buildcraft/api/enums/EnumRedstoneChipset.java @@ -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; + } } diff --git a/src/api/java/buildcraft/api/enums/EnumSnapshotType.java b/src/api/java/buildcraft/api/enums/EnumSnapshotType.java new file mode 100644 index 000000000..b3c21245c --- /dev/null +++ b/src/api/java/buildcraft/api/enums/EnumSnapshotType.java @@ -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; + } +} diff --git a/src/api/java/buildcraft/api/enums/EnumSpring.java b/src/api/java/buildcraft/api/enums/EnumSpring.java index 478b5cae8..21e4cf21c 100755 --- a/src/api/java/buildcraft/api/enums/EnumSpring.java +++ b/src/api/java/buildcraft/api/enums/EnumSpring.java @@ -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 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; diff --git a/src/api/java/buildcraft/api/facades/FacadeAPI.java b/src/api/java/buildcraft/api/facades/FacadeAPI.java index b3e214ea8..ce4cb8f06 100755 --- a/src/api/java/buildcraft/api/facades/FacadeAPI.java +++ b/src/api/java/buildcraft/api/facades/FacadeAPI.java @@ -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); + } } diff --git a/src/api/java/buildcraft/api/facades/IFacadeItem.java b/src/api/java/buildcraft/api/facades/IFacadeItem.java index 1fe981a3b..7f4362b49 100755 --- a/src/api/java/buildcraft/api/facades/IFacadeItem.java +++ b/src/api/java/buildcraft/api/facades/IFacadeItem.java @@ -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); } diff --git a/src/api/java/buildcraft/api/fuels/ICoolant.java b/src/api/java/buildcraft/api/fuels/ICoolant.java index 5d038c8d5..f81a863e0 100755 --- a/src/api/java/buildcraft/api/fuels/ICoolant.java +++ b/src/api/java/buildcraft/api/fuels/ICoolant.java @@ -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); } diff --git a/src/api/java/buildcraft/api/fuels/ICoolantManager.java b/src/api/java/buildcraft/api/fuels/ICoolantManager.java index fb535c438..dfcf78b6d 100755 --- a/src/api/java/buildcraft/api/fuels/ICoolantManager.java +++ b/src/api/java/buildcraft/api/fuels/ICoolantManager.java @@ -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 getSolidCoolants(); - ICoolant getCoolant(Fluid fluid); + ICoolant getCoolant(FluidStack fluid); + + float getDegreesPerMb(FluidStack fluid, float heat); ISolidCoolant getSolidCoolant(ItemStack solid); } diff --git a/src/api/java/buildcraft/api/fuels/IFuel.java b/src/api/java/buildcraft/api/fuels/IFuel.java index 65891f75a..382eb2a28 100755 --- a/src/api/java/buildcraft/api/fuels/IFuel.java +++ b/src/api/java/buildcraft/api/fuels/IFuel.java @@ -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(); diff --git a/src/api/java/buildcraft/api/fuels/IFuelManager.java b/src/api/java/buildcraft/api/fuels/IFuelManager.java index 137882139..cb02063e0 100755 --- a/src/api/java/buildcraft/api/fuels/IFuelManager.java +++ b/src/api/java/buildcraft/api/fuels/IFuelManager.java @@ -10,17 +10,27 @@ import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; public interface IFuelManager { - IFuel addFuel(IFuel fuel); + 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 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(); } diff --git a/src/api/java/buildcraft/api/inventory/IItemTransactor.java b/src/api/java/buildcraft/api/inventory/IItemTransactor.java new file mode 100644 index 000000000..212d2e35f --- /dev/null +++ b/src/api/java/buildcraft/api/inventory/IItemTransactor.java @@ -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 insert(NonNullList stacks, boolean simulate) { + NonNullList 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; + } + } +} diff --git a/src/api/java/buildcraft/api/items/IBlueprintItem.java b/src/api/java/buildcraft/api/items/IBlueprintItem.java deleted file mode 100755 index d67bc39fd..000000000 --- a/src/api/java/buildcraft/api/items/IBlueprintItem.java +++ /dev/null @@ -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); -} diff --git a/src/api/java/buildcraft/api/items/IMapLocation.java b/src/api/java/buildcraft/api/items/IMapLocation.java index b10adecd0..cb5dba538 100755 --- a/src/api/java/buildcraft/api/items/IMapLocation.java +++ b/src/api/java/buildcraft/api/items/IMapLocation.java @@ -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, diff --git a/src/api/java/buildcraft/api/library/LibraryAPI.java b/src/api/java/buildcraft/api/library/LibraryAPI.java index b3b1e84f8..b8997930a 100755 --- a/src/api/java/buildcraft/api/library/LibraryAPI.java +++ b/src/api/java/buildcraft/api/library/LibraryAPI.java @@ -5,7 +5,7 @@ import java.util.Set; @Deprecated public final class LibraryAPI { - private static final Set handlers = new HashSet(); + private static final Set handlers = new HashSet<>(); private LibraryAPI() { diff --git a/src/api/java/buildcraft/api/lists/ListRegistry.java b/src/api/java/buildcraft/api/lists/ListRegistry.java index 1f3655244..38a916694 100755 --- a/src/api/java/buildcraft/api/lists/ListRegistry.java +++ b/src/api/java/buildcraft/api/lists/ListRegistry.java @@ -7,8 +7,8 @@ import java.util.List; import net.minecraft.item.Item; public final class ListRegistry { - public static final List> itemClassAsType = new ArrayList>(); - private static final List handlers = new ArrayList(); + public static final List> itemClassAsType = new ArrayList<>(); + private static final List handlers = new ArrayList<>(); private ListRegistry() { diff --git a/src/api/java/buildcraft/api/mj/ILaserTarget.java b/src/api/java/buildcraft/api/mj/ILaserTarget.java index 26adb399c..e1fbfb48f 100755 --- a/src/api/java/buildcraft/api/mj/ILaserTarget.java +++ b/src/api/java/buildcraft/api/mj/ILaserTarget.java @@ -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. * diff --git a/src/api/java/buildcraft/api/mj/IMjReceiver.java b/src/api/java/buildcraft/api/mj/IMjReceiver.java index fe9eadd0b..a8cecd7d4 100755 --- a/src/api/java/buildcraft/api/mj/IMjReceiver.java +++ b/src/api/java/buildcraft/api/mj/IMjReceiver.java @@ -12,8 +12,19 @@ public interface IMjReceiver extends IMjConnector { *
  • Refuse all power (if you have no more work to do or your {@link MjBattery} is full). * * + * 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; + } } diff --git a/src/api/java/buildcraft/api/mj/MjAPI.java b/src/api/java/buildcraft/api/mj/MjAPI.java index 8bf317e1f..87d74e897 100755 --- a/src/api/java/buildcraft/api/mj/MjAPI.java +++ b/src/api/java/buildcraft/api/mj/MjAPI.java @@ -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 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 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 void registerCapability(Class clazz) { - CapabilityManager.INSTANCE.register(clazz, new VoidStorage(), new Callable() { - // No lambda because of java 6... :( - @Override - public T call() throws Exception { - throw new IllegalStateException("You must create your own instances!"); - } - }); - } - - @Nonnull - private static Capability ensureRegistration(Capability cap, Class clazz) { - if (cap == null) { - throw new Error("Capability registration failed for " + clazz); - } - return cap; - } - - private static class VoidStorage implements Capability.IStorage { - @Override - public NBTBase writeNBT(Capability capability, T instance, EnumFacing side) { - throw new IllegalStateException("You must create your own instances!"); - } - - @Override - public void readNBT(Capability 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); } } diff --git a/src/api/java/buildcraft/api/mj/MjBattery.java b/src/api/java/buildcraft/api/mj/MjBattery.java index ca86ce1f3..68c2ea12e 100755 --- a/src/api/java/buildcraft/api/mj/MjBattery.java +++ b/src/api/java/buildcraft/api/mj/MjBattery.java @@ -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 { diff --git a/src/api/java/buildcraft/api/mj/MjCapabilityHelper.java b/src/api/java/buildcraft/api/mj/MjCapabilityHelper.java index 41f78747d..c70c74cb2 100755 --- a/src/api/java/buildcraft/api/mj/MjCapabilityHelper.java +++ b/src/api/java/buildcraft/api/mj/MjCapabilityHelper.java @@ -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 getCapability(Capability 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 getCapability(@Nonnull Capability 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; } - } diff --git a/src/api/java/buildcraft/api/mj/package-info.java b/src/api/java/buildcraft/api/mj/package-info.java index c2670e4cf..8afa7544e 100755 --- a/src/api/java/buildcraft/api/mj/package-info.java +++ b/src/api/java/buildcraft/api/mj/package-info.java @@ -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. *

    - * 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)} *

    *

    Capability's

    *

    diff --git a/src/api/java/buildcraft/api/permission/IOwner.java b/src/api/java/buildcraft/api/permission/IOwner.java deleted file mode 100755 index 0fa178d2b..000000000 --- a/src/api/java/buildcraft/api/permission/IOwner.java +++ /dev/null @@ -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(); -} diff --git a/src/api/java/buildcraft/api/properties/BuildCraftExtendedProperty.java b/src/api/java/buildcraft/api/properties/BuildCraftExtendedProperty.java deleted file mode 100755 index e0ba3a62d..000000000 --- a/src/api/java/buildcraft/api/properties/BuildCraftExtendedProperty.java +++ /dev/null @@ -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> extends BuildCraftProperty implements IUnlistedProperty { - private final Predicate function; - - public BuildCraftExtendedProperty(String name, Class clazz, Predicate allowingFunction) { - super(name, clazz); - function = allowingFunction; - } - - public BuildCraftExtendedProperty(String name, Class clazz, List allowedValues) { - super(name, clazz, allowedValues); - function = null; - } - - public static BuildCraftExtendedProperty create(String name, final double min, final double max) { - return new BuildCraftExtendedProperty(name, Double.class, new Predicate() { - @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 > BuildCraftExtendedProperty createExtended(String name, Class clazz) { - return new BuildCraftExtendedProperty(name, clazz, Predicates. alwaysTrue()); - } - - @Override - public boolean isValid(T value) { - if (function == null) { - return values.contains(value); - } - return function.apply(value); - } - - @Override - public Class 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 asUnlistedProperty() { - return this; - } -} diff --git a/src/api/java/buildcraft/api/properties/BuildCraftProperties.java b/src/api/java/buildcraft/api/properties/BuildCraftProperties.java index d7f883b7b..63a519ad0 100755 --- a/src/api/java/buildcraft/api/properties/BuildCraftProperties.java +++ b/src/api/java/buildcraft/api/properties/BuildCraftProperties.java @@ -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 BLOCK_FACING = BuildCraftProperty.create("facing", EnumFacing.Plane.HORIZONTAL.facings()); - public static final BuildCraftProperty BLOCK_FACING_6 = BuildCraftProperty.create("facing", EnumFacing.class); + public static final IProperty BLOCK_FACING = PropertyEnum.create("facing", EnumFacing.class, EnumFacing.Plane.HORIZONTAL.facings()); + public static final IProperty BLOCK_FACING_6 = PropertyEnum.create("facing", EnumFacing.class); - public static final BuildCraftProperty BLOCK_COLOR = BuildCraftProperty.create("color", EnumDyeColor.class); - public static final BuildCraftProperty SPRING_TYPE = BuildCraftProperty.create("type", EnumSpring.class); - public static final BuildCraftProperty ENGINE_TYPE = BuildCraftProperty.create("type", EnumEngineType.class); - public static final BuildCraftProperty LASER_TABLE_TYPE = BuildCraftProperty.create("type", EnumLaserTableType.class); - public static final BuildCraftProperty MACHINE_STATE = BuildCraftProperty.create("state", EnumMachineState.class); - public static final BuildCraftProperty ENERGY_STAGE = BuildCraftProperty.create("stage", EnumPowerStage.class); - public static final BuildCraftProperty BLUEPRINT_TYPE = BuildCraftProperty.create("blueprint_type", EnumBlueprintType.class); - public static final BuildCraftProperty DECORATED_BLOCK = BuildCraftProperty.create("decoration_type", EnumDecoratedBlock.class); + public static final IProperty BLOCK_COLOR = PropertyEnum.create("color", EnumDyeColor.class); + public static final IProperty SPRING_TYPE = PropertyEnum.create("type", EnumSpring.class); + public static final IProperty ENGINE_TYPE = PropertyEnum.create("type", EnumEngineType.class); + public static final IProperty LASER_TABLE_TYPE = PropertyEnum.create("type", EnumLaserTableType.class); + public static final IProperty MACHINE_STATE = PropertyEnum.create("state", EnumMachineState.class); + public static final IProperty ENERGY_STAGE = PropertyEnum.create("stage", EnumPowerStage.class); + public static final IProperty SNAPSHOT_TYPE = PropertyEnum.create("snapshot_type", EnumOptionalSnapshotType.class); + public static final IProperty DECORATED_BLOCK = PropertyEnum.create("decoration_type", EnumDecoratedBlock.class); - public static final BuildCraftProperty GENERIC_PIPE_DATA = BuildCraftProperty.create("pipe_data", 0, 15); - public static final BuildCraftProperty LED_POWER = BuildCraftProperty.create("led_power", 0, 3); + public static final IProperty GENERIC_PIPE_DATA = PropertyInteger.create("pipe_data", 0, 15); + public static final IProperty LED_POWER = PropertyInteger.create("led_power", 0, 3); - public static final BuildCraftProperty JOINED_BELOW = BuildCraftProperty.create("joined_below", false); - public static final BuildCraftProperty MOVING = BuildCraftProperty.create("moving", false); - public static final BuildCraftProperty LED_DONE = BuildCraftProperty.create("led_done", false); - public static final BuildCraftProperty ACTIVE = BuildCraftProperty.create("active", false); - public static final BuildCraftProperty VALID = BuildCraftProperty.create("valid", false); + public static final IProperty JOINED_BELOW = PropertyBool.create("joined_below"); + public static final IProperty MOVING = PropertyBool.create("moving"); + public static final IProperty LED_DONE = PropertyBool.create("led_done"); + public static final IProperty ACTIVE = PropertyBool.create("active"); + public static final IProperty VALID = PropertyBool.create("valid"); - public static final BuildCraftProperty CONNECTED_UP = BuildCraftProperty.create("connected_up", false); - public static final BuildCraftProperty CONNECTED_DOWN = BuildCraftProperty.create("connected_down", false); - public static final BuildCraftProperty CONNECTED_EAST = BuildCraftProperty.create("connected_east", false); - public static final BuildCraftProperty CONNECTED_WEST = BuildCraftProperty.create("connected_west", false); - public static final BuildCraftProperty CONNECTED_NORTH = BuildCraftProperty.create("connected_north", false); - public static final BuildCraftProperty CONNECTED_SOUTH = BuildCraftProperty.create("connected_south", false); + public static final IProperty CONNECTED_UP = PropertyBool.create("connected_up"); + public static final IProperty CONNECTED_DOWN = PropertyBool.create("connected_down"); + public static final IProperty CONNECTED_EAST = PropertyBool.create("connected_east"); + public static final IProperty CONNECTED_WEST = PropertyBool.create("connected_west"); + public static final IProperty CONNECTED_NORTH = PropertyBool.create("connected_north"); + public static final IProperty CONNECTED_SOUTH = PropertyBool.create("connected_south"); - public static final Map> CONNECTED_MAP; + public static final Map> 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 FILLER_PATTERN = BuildCraftProperty.create("pattern", EnumFillerPattern.class); + public static final IProperty 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> map = Maps.newEnumMap(EnumFacing.class); + Map> map = Maps.newEnumMap(EnumFacing.class); map.put(EnumFacing.DOWN, CONNECTED_DOWN); map.put(EnumFacing.UP, CONNECTED_UP); map.put(EnumFacing.EAST, CONNECTED_EAST); diff --git a/src/api/java/buildcraft/api/properties/BuildCraftProperty.java b/src/api/java/buildcraft/api/properties/BuildCraftProperty.java deleted file mode 100755 index f13f82c5b..000000000 --- a/src/api/java/buildcraft/api/properties/BuildCraftProperty.java +++ /dev/null @@ -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> extends PropertyHelper { - private final String name; - private final Class clazz; - protected final List values; - - public BuildCraftProperty(String name, Class clazz, T[] values) { - this(name, clazz, Arrays.asList(values)); - } - - public BuildCraftProperty(String name, Class clazz, List values) { - super(name, clazz); - this.name = name; - this.clazz = clazz; - this.values = values; - } - - /** Used for BuildCraftInifiniteProperty */ - protected BuildCraftProperty(String name, Class clazz) { - super(name, clazz); - this.name = name; - this.clazz = clazz; - this.values = Collections.emptyList(); - } - - public static > BuildCraftProperty create(String name, Class enumeration) { - List values = Arrays.asList(enumeration.getEnumConstants()); - return new BuildCraftProperty(name, enumeration, values); - } - - public static > BuildCraftProperty create(String name, E... values) { - Class clazz = values[0].getDeclaringClass(); - List list = Arrays.asList(values); - return new BuildCraftProperty(name, clazz, list); - } - - public static BuildCraftProperty create(String name, boolean first) { - return new BuildCraftProperty(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 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 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(name, Integer.class, array); - } - - public static BuildCraftProperty create(String name, double first, double last) { - return create(name, first, last, 1); - } - - public static BuildCraftProperty 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(name, Double.class, array); - } - - @Override - public String getName() { - return name; - } - - @Override - public List getAllowedValues() { - return values; - } - - @Override - public Class 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 parseValue(String value) { - if (clazz.isEnum()) { - return parseEnum(value, (BuildCraftProperty) this); - } - return Optional.absent(); - } - - public static > Optional parseEnum(String name, BuildCraftProperty prop) { - for (E e : prop.values) { - if (e.name().equalsIgnoreCase(name)) return Optional.of(e); - } - return Optional.absent(); - } -} diff --git a/src/api/java/buildcraft/api/recipes/AssemblyRecipe.java b/src/api/java/buildcraft/api/recipes/AssemblyRecipe.java index 0baba21c0..44a2b01ff 100755 --- a/src/api/java/buildcraft/api/recipes/AssemblyRecipe.java +++ b/src/api/java/buildcraft/api/recipes/AssemblyRecipe.java @@ -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 { + public final ResourceLocation name; public final long requiredMicroJoules; - public final ImmutableSet requiredStacks; - public final ItemStack output; + public final ImmutableSet requiredStacks; + public final @Nonnull ItemStack output; + /** + * Additional tag used to restore network-transmitted recipe to same state.
    + * 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 requiredStacks, ItemStack output) { + public AssemblyRecipe(ResourceLocation name, long requiredMicroJoules, Set 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 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 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 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 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 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 iterator1 = requiredStacks.iterator(); - Iterator 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()); } } diff --git a/src/api/java/buildcraft/api/recipes/BuildcraftRecipeRegistry.java b/src/api/java/buildcraft/api/recipes/BuildcraftRecipeRegistry.java index fd0838ab5..1c074e9db 100755 --- a/src/api/java/buildcraft/api/recipes/BuildcraftRecipeRegistry.java +++ b/src/api/java/buildcraft/api/recipes/BuildcraftRecipeRegistry.java @@ -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() {} } diff --git a/src/api/java/buildcraft/api/recipes/IAssemblyRecipeProvider.java b/src/api/java/buildcraft/api/recipes/IAssemblyRecipeProvider.java index 4e051d78d..f98567653 100755 --- a/src/api/java/buildcraft/api/recipes/IAssemblyRecipeProvider.java +++ b/src/api/java/buildcraft/api/recipes/IAssemblyRecipeProvider.java @@ -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 getRecipesFor(@Nonnull NonNullList possibleIn); + List getRecipesFor(@Nonnull NonNullList possible); + + /** + * Returns recipe by it's name + * @param recipeTag Additional tag attached to network-transmitted recipe definition + */ + default Optional getRecipe(@Nonnull ResourceLocation name, @Nullable NBTTagCompound recipeTag) { + return Optional.empty(); + } } diff --git a/src/api/java/buildcraft/api/recipes/IComplexRefineryRecipeManager.java b/src/api/java/buildcraft/api/recipes/IComplexRefineryRecipeManager.java deleted file mode 100755 index 5623b5eaa..000000000 --- a/src/api/java/buildcraft/api/recipes/IComplexRefineryRecipeManager.java +++ /dev/null @@ -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 getHeatableRegistry(); - - IComplexRefineryRegistry getCoolableRegistry(); - - IComplexRefineryRegistry getDistilationRegistry(); - - public interface IComplexRefineryRegistry { - /** @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 getRecipes(Predicate toReturn); - - /** @return an unmodifiable set containing all of the distilation recipies. */ - Set getAllRecipes(); - - R getRecipeForInput(FluidStack fluid); - - Set removeRecipes(Predicate 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(); - } -} diff --git a/src/api/java/buildcraft/api/recipes/IIntegrationRecipeProvider.java b/src/api/java/buildcraft/api/recipes/IIntegrationRecipeProvider.java index 77b1cfc22..5c3d6446f 100755 --- a/src/api/java/buildcraft/api/recipes/IIntegrationRecipeProvider.java +++ b/src/api/java/buildcraft/api/recipes/IIntegrationRecipeProvider.java @@ -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 toIntegrate); + + /** + * Returns recipe by it's name + * @param recipeTag Additional tag attached to network-transmitted recipe definition + */ + default Optional getRecipe(@Nonnull ResourceLocation name, @Nullable NBTTagCompound recipeTag) { + return Optional.empty(); + } } diff --git a/src/api/java/buildcraft/api/recipes/IRefineryRecipeManager.java b/src/api/java/buildcraft/api/recipes/IRefineryRecipeManager.java new file mode 100644 index 000000000..65b523bd8 --- /dev/null +++ b/src/api/java/buildcraft/api/recipes/IRefineryRecipeManager.java @@ -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 getHeatableRegistry(); + + IRefineryRegistry getCoolableRegistry(); + + IRefineryRegistry getDistillationRegistry(); + + interface IRefineryRegistry { + /** @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 getRecipes(Predicate toReturn); + + /** @return an unmodifiable set containing all of the distillation recipes. */ + Collection getAllRecipes(); + + @Nullable + R getRecipeForInput(@Nullable FluidStack fluid); + + Collection removeRecipes(Predicate 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(); + } +} diff --git a/src/api/java/buildcraft/api/recipes/IntegrationRecipe.java b/src/api/java/buildcraft/api/recipes/IntegrationRecipe.java index afaac2dd8..b2e36aad2 100755 --- a/src/api/java/buildcraft/api/recipes/IntegrationRecipe.java +++ b/src/api/java/buildcraft/api/recipes/IntegrationRecipe.java @@ -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 toIntegrate; - public final ItemStack output; + public final StackDefinition target; + public final ImmutableList 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 toIntegrate, ItemStack output) { + public IntegrationRecipe(ResourceLocation name, long requiredMicroJoules, StackDefinition target, List 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 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 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 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 iterator1 = toIntegrate.iterator(); - Iterator 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(); } } diff --git a/src/api/java/buildcraft/api/recipes/StackDefinition.java b/src/api/java/buildcraft/api/recipes/StackDefinition.java new file mode 100644 index 000000000..ae1a6b3b8 --- /dev/null +++ b/src/api/java/buildcraft/api/recipes/StackDefinition.java @@ -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); + } +} diff --git a/src/api/java/buildcraft/api/robots/DockingStation.java b/src/api/java/buildcraft/api/robots/DockingStation.java index 28ecb0830..d3237a018 100755 --- a/src/api/java/buildcraft/api/robots/DockingStation.java +++ b/src/api/java/buildcraft/api/robots/DockingStation.java @@ -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!"); } diff --git a/src/api/java/buildcraft/api/robots/RobotManager.java b/src/api/java/buildcraft/api/robots/RobotManager.java index aa59fc4d7..7c712c91f 100755 --- a/src/api/java/buildcraft/api/robots/RobotManager.java +++ b/src/api/java/buildcraft/api/robots/RobotManager.java @@ -12,17 +12,17 @@ import buildcraft.api.core.BCLog; public abstract class RobotManager { public static IRobotRegistryProvider registryProvider; - public static ArrayList> aiRobots = new ArrayList>(); + public static ArrayList> aiRobots = new ArrayList<>(); static { - aiRobotsByNames = new HashMap>(); - aiRobotsNames = new HashMap, String>(); - aiRobotsByLegacyClassNames = new HashMap>(); - resourceIdNames = new HashMap, String>(); - resourceIdByNames = new HashMap>(); - resourceIdLegacyClassNames = new HashMap>(); - dockingStationNames = new HashMap, String>(); - dockingStationByNames = new HashMap>(); + 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 resouceIdClass) { - return resourceIdNames.get(resouceIdClass); + public static String getResourceIdName(Class resourceIdClass) { + return resourceIdNames.get(resourceIdClass); } public static Class getResourceIdByLegacyClassName(String resourceIdLegacyClassName) { diff --git a/src/api/java/buildcraft/api/schematics/ISchematicBlock.java b/src/api/java/buildcraft/api/schematics/ISchematicBlock.java new file mode 100644 index 000000000..01475eb48 --- /dev/null +++ b/src/api/java/buildcraft/api/schematics/ISchematicBlock.java @@ -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> { + void init(SchematicBlockContext context); + + boolean isAir(); + + @Nonnull + Set getRequiredBlockOffsets(); + + @Nonnull + List computeRequiredItems(SchematicBlockContext context); + + @Nonnull + List 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; +} diff --git a/src/api/java/buildcraft/api/schematics/ISchematicEntity.java b/src/api/java/buildcraft/api/schematics/ISchematicEntity.java new file mode 100644 index 000000000..1f087ca68 --- /dev/null +++ b/src/api/java/buildcraft/api/schematics/ISchematicEntity.java @@ -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> { + void init(SchematicEntityContext context); + + Vec3d getPos(); + + @Nonnull + List computeRequiredItems(SchematicEntityContext context); + + @Nonnull + List 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; +} diff --git a/src/api/java/buildcraft/api/schematics/SchematicBlockContext.java b/src/api/java/buildcraft/api/schematics/SchematicBlockContext.java new file mode 100644 index 000000000..0ca98532a --- /dev/null +++ b/src/api/java/buildcraft/api/schematics/SchematicBlockContext.java @@ -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; + } +} diff --git a/src/api/java/buildcraft/api/schematics/SchematicBlockFactory.java b/src/api/java/buildcraft/api/schematics/SchematicBlockFactory.java new file mode 100644 index 000000000..e88d6cd4f --- /dev/null +++ b/src/api/java/buildcraft/api/schematics/SchematicBlockFactory.java @@ -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> implements Comparable { + @Nonnull + public final ResourceLocation name; + public final int priority; + @Nonnull + public final Predicate predicate; + @Nonnull + public final Supplier supplier; + @Nonnull + public final Class clazz; + + @SuppressWarnings("unchecked") + public SchematicBlockFactory(@Nonnull ResourceLocation name, + int priority, + @Nonnull Predicate predicate, + @Nonnull Supplier supplier) { + this.name = name; + this.priority = priority; + this.predicate = predicate; + this.supplier = supplier; + clazz = (Class) 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()); + } +} diff --git a/src/api/java/buildcraft/api/schematics/SchematicBlockFactoryRegistry.java b/src/api/java/buildcraft/api/schematics/SchematicBlockFactoryRegistry.java new file mode 100644 index 000000000..541c2777e --- /dev/null +++ b/src/api/java/buildcraft/api/schematics/SchematicBlockFactoryRegistry.java @@ -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> FACTORIES = new TreeSet<>(); + + public static > void registerFactory(String name, + int priority, + Predicate predicate, + Supplier supplier) { + FACTORIES.add(new SchematicBlockFactory<>( + BuildCraftAPI.nameToResourceLocation(name), + priority, + predicate, + supplier + )); + } + + public static > void registerFactory(String name, + int priority, + List blocks, + Supplier supplier) { + registerFactory( + name, + priority, + context -> blocks.contains(context.block), + supplier + ); + } + + public static List> 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); + } +} diff --git a/src/api/java/buildcraft/api/schematics/SchematicEntityContext.java b/src/api/java/buildcraft/api/schematics/SchematicEntityContext.java new file mode 100644 index 000000000..b812556a0 --- /dev/null +++ b/src/api/java/buildcraft/api/schematics/SchematicEntityContext.java @@ -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; + } +} diff --git a/src/api/java/buildcraft/api/schematics/SchematicEntityFactory.java b/src/api/java/buildcraft/api/schematics/SchematicEntityFactory.java new file mode 100644 index 000000000..285f05819 --- /dev/null +++ b/src/api/java/buildcraft/api/schematics/SchematicEntityFactory.java @@ -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> implements Comparable { + @Nonnull + public final ResourceLocation name; + public final int priority; + @Nonnull + public final Predicate predicate; + @Nonnull + public final Supplier supplier; + @Nonnull + public final Class clazz; + + @SuppressWarnings("unchecked") + public SchematicEntityFactory(@Nonnull ResourceLocation name, + int priority, + @Nonnull Predicate predicate, + @Nonnull Supplier supplier) { + this.name = name; + this.priority = priority; + this.predicate = predicate; + this.supplier = supplier; + clazz = (Class) 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()); + } +} diff --git a/src/api/java/buildcraft/api/schematics/SchematicEntityFactoryRegistry.java b/src/api/java/buildcraft/api/schematics/SchematicEntityFactoryRegistry.java new file mode 100644 index 000000000..7bfc97cb0 --- /dev/null +++ b/src/api/java/buildcraft/api/schematics/SchematicEntityFactoryRegistry.java @@ -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> FACTORIES = new TreeSet<>(); + + public static > void registerFactory(String name, + int priority, + Predicate predicate, + Supplier supplier) { + FACTORIES.add(new SchematicEntityFactory<>( + BuildCraftAPI.nameToResourceLocation(name), + priority, + predicate, + supplier + )); + } + + public static > void registerFactory(String name, + int priority, + List entities, + Supplier supplier) { + registerFactory( + name, + priority, + context -> entities.contains(EntityList.getKey(context.entity)), + supplier + ); + } + + public static List> 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); + } +} diff --git a/src/api/java/buildcraft/api/statements/IGuiSlot.java b/src/api/java/buildcraft/api/statements/IGuiSlot.java index c7386dd69..0dec933c1 100755 --- a/src/api/java/buildcraft/api/statements/IGuiSlot.java +++ b/src/api/java/buildcraft/api/statements/IGuiSlot.java @@ -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(); } diff --git a/src/api/java/buildcraft/api/statements/IStatementContainer.java b/src/api/java/buildcraft/api/statements/IStatementContainer.java index 2e7652fd8..e08a7e85b 100755 --- a/src/api/java/buildcraft/api/statements/IStatementContainer.java +++ b/src/api/java/buildcraft/api/statements/IStatementContainer.java @@ -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); } diff --git a/src/api/java/buildcraft/api/statements/ITriggerExternalOverride.java b/src/api/java/buildcraft/api/statements/ITriggerExternalOverride.java index 5b8ce9ee2..9b1fd1e19 100755 --- a/src/api/java/buildcraft/api/statements/ITriggerExternalOverride.java +++ b/src/api/java/buildcraft/api/statements/ITriggerExternalOverride.java @@ -6,7 +6,7 @@ import net.minecraft.util.EnumFacing; * * Please use wisely. */ public interface ITriggerExternalOverride { - public enum Result { + enum Result { TRUE, FALSE, IGNORE diff --git a/src/api/java/buildcraft/api/statements/StatementManager.java b/src/api/java/buildcraft/api/statements/StatementManager.java index 61266e583..1cd30f130 100755 --- a/src/api/java/buildcraft/api/statements/StatementManager.java +++ b/src/api/java/buildcraft/api/statements/StatementManager.java @@ -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 statements = new HashMap(); - public static Map> parameters = new HashMap>(); - private static List triggerProviders = new LinkedList(); - private static List actionProviders = new LinkedList(); + public static Map statements = new HashMap<>(); + public static Map> parameters = new HashMap<>(); + private static List triggerProviders = new LinkedList<>(); + private static List actionProviders = new LinkedList<>(); static { registerParameterClass(StatementParameterItemStack.class); @@ -53,13 +58,13 @@ public final class StatementManager { } } - LinkedHashSet triggers = new LinkedHashSet(); + LinkedHashSet triggers = new LinkedHashSet<>(); for (ITriggerProvider provider : triggerProviders) { provider.addExternalTriggers(triggers, side, entity); } - return new ArrayList(triggers); + return new ArrayList<>(triggers); } public static List getExternalActions(EnumFacing side, TileEntity entity) { @@ -70,53 +75,53 @@ public final class StatementManager { } } - LinkedHashSet actions = new LinkedHashSet(); + LinkedHashSet actions = new LinkedHashSet<>(); for (IActionProvider provider : actionProviders) { provider.addExternalActions(actions, side, entity); } - return new ArrayList(actions); + return new ArrayList<>(actions); } public static List getInternalTriggers(IStatementContainer container) { - LinkedHashSet triggers = new LinkedHashSet(); + LinkedHashSet triggers = new LinkedHashSet<>(); for (ITriggerProvider provider : triggerProviders) { provider.addInternalTriggers(triggers, container); } - return new ArrayList(triggers); + return new ArrayList<>(triggers); } public static List getInternalActions(IStatementContainer container) { - LinkedHashSet actions = new LinkedHashSet(); + LinkedHashSet actions = new LinkedHashSet<>(); for (IActionProvider provider : actionProviders) { provider.addInternalActions(actions, container); } - return new ArrayList(actions); + return new ArrayList<>(actions); } public static List getInternalSidedTriggers(IStatementContainer container, EnumFacing side) { - LinkedHashSet triggers = new LinkedHashSet(); + LinkedHashSet triggers = new LinkedHashSet<>(); for (ITriggerProvider provider : triggerProviders) { provider.addInternalSidedTriggers(triggers, container, side); } - return new ArrayList(triggers); + return new ArrayList<>(triggers); } public static List getInternalSidedActions(IStatementContainer container, EnumFacing side) { - LinkedHashSet actions = new LinkedHashSet(); + LinkedHashSet actions = new LinkedHashSet<>(); for (IActionProvider provider : actionProviders) { provider.addInternalSidedActions(actions, container, side); } - return new ArrayList(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); diff --git a/src/api/java/buildcraft/api/statements/StatementParameterItemStack.java b/src/api/java/buildcraft/api/statements/StatementParameterItemStack.java index 5ed9c4088..ad55c9909 100755 --- a/src/api/java/buildcraft/api/statements/StatementParameterItemStack.java +++ b/src/api/java/buildcraft/api/statements/StatementParameterItemStack.java @@ -31,6 +31,7 @@ public class StatementParameterItemStack implements IStatementParameter { return null; } + @Nonnull @Override public ItemStack getItemStack() { return stack; diff --git a/src/api/java/buildcraft/api/tablet/TabletAPI.java b/src/api/java/buildcraft/api/tablet/TabletAPI.java index 529862790..3d669838f 100755 --- a/src/api/java/buildcraft/api/tablet/TabletAPI.java +++ b/src/api/java/buildcraft/api/tablet/TabletAPI.java @@ -4,7 +4,7 @@ import java.util.HashMap; import java.util.Map; public final class TabletAPI { - private static final Map programs = new HashMap(); + private static final Map programs = new HashMap<>(); private TabletAPI() { diff --git a/src/api/java/buildcraft/api/template/ITemplateHandler.java b/src/api/java/buildcraft/api/template/ITemplateHandler.java new file mode 100644 index 000000000..e0dac1bf8 --- /dev/null +++ b/src/api/java/buildcraft/api/template/ITemplateHandler.java @@ -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); +} diff --git a/src/api/java/buildcraft/api/template/ITemplateRegistry.java b/src/api/java/buildcraft/api/template/ITemplateRegistry.java new file mode 100644 index 000000000..ec6d25049 --- /dev/null +++ b/src/api/java/buildcraft/api/template/ITemplateRegistry.java @@ -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); +} diff --git a/src/api/java/buildcraft/api/template/TemplateApi.java b/src/api/java/buildcraft/api/template/TemplateApi.java new file mode 100644 index 000000000..423c70eaf --- /dev/null +++ b/src/api/java/buildcraft/api/template/TemplateApi.java @@ -0,0 +1,11 @@ +/* + * 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; + +public class TemplateApi { + public static ITemplateRegistry templateRegistry; +} diff --git a/src/api/java/buildcraft/api/tiles/IControllable.java b/src/api/java/buildcraft/api/tiles/IControllable.java index 633d1fc28..ac9483635 100755 --- a/src/api/java/buildcraft/api/tiles/IControllable.java +++ b/src/api/java/buildcraft/api/tiles/IControllable.java @@ -7,31 +7,22 @@ package buildcraft.api.tiles; /** This interface should be implemented by any Tile Entity which wishes to have non-redstone automation (for example, * BuildCraft Gates, but also other mods which implement it, e.g. OpenComputers). */ public interface IControllable { - public enum Mode { - Unknown, - On, - Off, - Mode, - Loop; + enum Mode { + ON, + OFF, + LOOP; public static final Mode[] VALUES = values(); - public static final Mode[] VALID_VALUES = { On, Off, Loop }; } /** Get the current control mode of the Tile Entity. - * + * * @return */ Mode getControlMode(); /** Set the mode of the Tile Entity. - * - * @param mode */ - void setControlMode(Mode mode); - - /** Check if a given control mode is accepted. If you query IControllable tiles, you MUST check with - * acceptsControlMode first. * * @param mode * @return True if this control mode is accepted. */ - boolean acceptsControlMode(Mode mode); + boolean setControlMode(Mode mode, boolean simulate); } diff --git a/src/api/java/buildcraft/api/tiles/IHeatable.java b/src/api/java/buildcraft/api/tiles/IHeatable.java index 1af6d6b59..d789ab564 100755 --- a/src/api/java/buildcraft/api/tiles/IHeatable.java +++ b/src/api/java/buildcraft/api/tiles/IHeatable.java @@ -12,7 +12,7 @@ public interface IHeatable { /** @return The preferred heat value, in degrees. */ double getIdealHeatValue(); - /** @return The maxmimum heat value, in degrees. */ + /** @return The maximum heat value, in degrees. */ double getMaxHeatValue(); /** @return The current heat value, in degrees. */ diff --git a/src/api/java/buildcraft/api/tiles/TilesAPI.java b/src/api/java/buildcraft/api/tiles/TilesAPI.java new file mode 100644 index 000000000..38478d512 --- /dev/null +++ b/src/api/java/buildcraft/api/tiles/TilesAPI.java @@ -0,0 +1,46 @@ +package buildcraft.api.tiles; + +import javax.annotation.Nonnull; + +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.common.capabilities.CapabilityInject; + +import buildcraft.api.core.CapabilitiesHelper; + +public class TilesAPI { + @Nonnull + public static final Capability CAP_CONTROLLABLE; + + @Nonnull + public static final Capability CAP_HAS_WORK; + + @Nonnull + public static final Capability CAP_HEATABLE; + + @Nonnull + public static final Capability CAP_TILE_AREA_PROVIDER; + + @CapabilityInject(IControllable.class) + private static final Capability CAP_CONTROLLABLE_FIRST = null; + + @CapabilityInject(IHasWork.class) + private static final Capability CAP_HAS_WORK_FIRST = null; + + @CapabilityInject(IHeatable.class) + private static final Capability CAP_HEATABLE_FIRST = null; + + @CapabilityInject(ITileAreaProvider.class) + private static final Capability CAP_TILE_AREA_PROVIDER_FIRST = null; + + static { + CapabilitiesHelper.registerCapability(IControllable.class); + CapabilitiesHelper.registerCapability(IHasWork.class); + CapabilitiesHelper.registerCapability(IHeatable.class); + CapabilitiesHelper.registerCapability(ITileAreaProvider.class); + + CAP_CONTROLLABLE = CapabilitiesHelper.ensureRegistration(CAP_CONTROLLABLE_FIRST, IControllable.class); + CAP_HAS_WORK = CapabilitiesHelper.ensureRegistration(CAP_HAS_WORK_FIRST, IHasWork.class); + CAP_HEATABLE = CapabilitiesHelper.ensureRegistration(CAP_HEATABLE_FIRST, IHeatable.class); + CAP_TILE_AREA_PROVIDER = CapabilitiesHelper.ensureRegistration(CAP_TILE_AREA_PROVIDER_FIRST, ITileAreaProvider.class); + } +} diff --git a/src/api/java/buildcraft/api/transport/EnumWirePart.java b/src/api/java/buildcraft/api/transport/EnumWirePart.java index 6b9e983d2..f05ff8e44 100755 --- a/src/api/java/buildcraft/api/transport/EnumWirePart.java +++ b/src/api/java/buildcraft/api/transport/EnumWirePart.java @@ -39,7 +39,8 @@ public enum EnumWirePart { Vec3d center = new Vec3d(0.5, 0.5, 0.5); Vec3d edge = new Vec3d(x ? 0.75 : 0.25, y ? 0.75 : 0.25, z ? 0.75 : 0.25); - this.boundingBoxPossible = new AxisAlignedBB(center.xCoord, center.yCoord, center.zCoord, edge.xCoord, edge.yCoord, edge.zCoord); + this.boundingBoxPossible = new AxisAlignedBB(center.xCoord, center.yCoord, center.zCoord, edge.xCoord, + edge.yCoord, edge.zCoord); } public AxisDirection getDirection(EnumFacing.Axis axis) { @@ -50,16 +51,16 @@ public enum EnumWirePart { return y; case Z: return z; + default: + return null; } - return null; } public static EnumWirePart get(int x, int y, int z) { - return get(// - (x % 2 + 2) % 2 == 1,// - (y % 2 + 2) % 2 == 1,// - (z % 2 + 2) % 2 == 1 // - ); + boolean bx = (x % 2 + 2) % 2 == 1; + boolean by = (y % 2 + 2) % 2 == 1; + boolean bz = (z % 2 + 2) % 2 == 1; + return get(bx, by, bz); } public static EnumWirePart get(boolean x, boolean y, boolean z) { diff --git a/src/api/java/buildcraft/api/transport/IInjectable.java b/src/api/java/buildcraft/api/transport/IInjectable.java index 0292ae2ef..2aeebd671 100755 --- a/src/api/java/buildcraft/api/transport/IInjectable.java +++ b/src/api/java/buildcraft/api/transport/IInjectable.java @@ -7,7 +7,6 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; /** Interface for pipes to implement if they can accept items in a similar fashion to BC pipes. */ -// TODO: Forge Capability! public interface IInjectable { /** Tests to see if this pipe can accept items from the given direction. Useless to call this if you are going to * call {@link #injectItem(ItemStack, boolean, EnumFacing, EnumDyeColor, double)} straight after. */ diff --git a/src/api/java/buildcraft/api/transport/IItemPluggable.java b/src/api/java/buildcraft/api/transport/IItemPluggable.java index f18df6344..704318e67 100755 --- a/src/api/java/buildcraft/api/transport/IItemPluggable.java +++ b/src/api/java/buildcraft/api/transport/IItemPluggable.java @@ -2,8 +2,10 @@ package buildcraft.api.transport; import javax.annotation.Nonnull; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; +import net.minecraft.util.EnumHand; import buildcraft.api.transport.pipe.IPipeHolder; import buildcraft.api.transport.pluggable.PipePluggable; @@ -11,12 +13,12 @@ import buildcraft.api.transport.pluggable.PipePluggable; /** Designates an item that can be placed onto a pipe as a {@link PipePluggable}. */ public interface IItemPluggable { /** Called when this item is placed onto a pipe holder. This can return null if this item does not make a valid - * pluggable. Note that if you return a non-null pluggable then it will *definatly* be added to the pipe, and you + * pluggable. Note that if you return a non-null pluggable then it will *definitely* be added to the pipe, and you * are responsible for making all the effects yourself (like the sound effect). * * @param stack The stack that holds this item * @param holder The pipe holder * @param side The side that the pluggable should be placed on * @return A pluggable to place onto the pipe */ - PipePluggable onPlace(@Nonnull ItemStack stack, IPipeHolder holder, EnumFacing side); + PipePluggable onPlace(@Nonnull ItemStack stack, IPipeHolder holder, EnumFacing side, EntityPlayer player, EnumHand hand); } diff --git a/src/api/java/buildcraft/api/transport/IStripesRegistry.java b/src/api/java/buildcraft/api/transport/IStripesRegistry.java index 73e881993..ae6980603 100755 --- a/src/api/java/buildcraft/api/transport/IStripesRegistry.java +++ b/src/api/java/buildcraft/api/transport/IStripesRegistry.java @@ -6,31 +6,36 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; +import buildcraft.api.core.EnumHandlerPriority; + public interface IStripesRegistry { + /** Adds a handler with a {@link EnumHandlerPriority} of {@linkplain EnumHandlerPriority#NORMAL} */ + default void addHandler(IStripesHandlerItem handler) { + addHandler(handler, EnumHandlerPriority.NORMAL); + } - /** Adds a handler with a {@link HandlerPriority} of {@linkplain HandlerPriority#NORMAL NORMAL} */ - void addHandler(IStripesHandlerItem handler); + void addHandler(IStripesHandlerItem handler, EnumHandlerPriority priority); - void addHandler(IStripesHandlerItem handler, HandlerPriority priority); + /** Adds a handler with a {@link EnumHandlerPriority} of {@linkplain EnumHandlerPriority#NORMAL NORMAL} */ + default void addHandler(IStripesHandlerBlock handler) { + addHandler(handler, EnumHandlerPriority.NORMAL); + } - /** Adds a handler with a {@link HandlerPriority} of {@linkplain HandlerPriority#NORMAL NORMAL} */ - void addHandler(IStripesHandlerBlock handler); - - void addHandler(IStripesHandlerBlock handler, HandlerPriority priority); + void addHandler(IStripesHandlerBlock handler, EnumHandlerPriority priority); /** @param pos The position of the stripes pipe. * @return True if a handler handled the itemstack, false otherwise (and so nothing has been done) */ - boolean handleItem(World world, BlockPos pos, EnumFacing direction, ItemStack stack, EntityPlayer player, IStripesActivator activator); + boolean handleItem(World world, + BlockPos pos, + EnumFacing direction, + ItemStack stack, + EntityPlayer player, + IStripesActivator activator); /** @return True if a handler broke a block, false otherwise (and so nothing has been done) */ - boolean handleBlock(World world, BlockPos pos, EnumFacing direction, EntityPlayer player, IStripesActivator activator); - - // TODO: Ensure that this method really will work better than an integer for priorities. - public enum HandlerPriority { - HIGHEST, - HIGH, - NORMAL, - LOW, - LOWEST - } + boolean handleBlock(World world, + BlockPos pos, + EnumFacing direction, + EntityPlayer player, + IStripesActivator activator); } diff --git a/src/api/java/buildcraft/api/transport/pipe/ICustomPipeConnection.java b/src/api/java/buildcraft/api/transport/pipe/ICustomPipeConnection.java index ded7b2e22..d4ca9ab26 100755 --- a/src/api/java/buildcraft/api/transport/pipe/ICustomPipeConnection.java +++ b/src/api/java/buildcraft/api/transport/pipe/ICustomPipeConnection.java @@ -7,7 +7,7 @@ import net.minecraft.world.World; public interface ICustomPipeConnection { /** @return How long the connecting pipe should extend for, in addition to its normal 4/16f connection. Values less - * than or equal to -4/16 indicate that the pipe will not connect at all, and will render as it it was not - * connected. */ - public float getExtension(World world, BlockPos pos, EnumFacing face, IBlockState state); + * than or equal to -4 / 16.0f indicate that the pipe will not connect at all, and will render + * as it it was not connected. */ + float getExtension(World world, BlockPos pos, EnumFacing face, IBlockState state); } diff --git a/src/api/java/buildcraft/api/transport/pipe/IFlowFluid.java b/src/api/java/buildcraft/api/transport/pipe/IFlowFluid.java index 25bc329ca..bded1911d 100755 --- a/src/api/java/buildcraft/api/transport/pipe/IFlowFluid.java +++ b/src/api/java/buildcraft/api/transport/pipe/IFlowFluid.java @@ -1,11 +1,14 @@ package buildcraft.api.transport.pipe; +import net.minecraft.util.ActionResult; +import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.capability.IFluidHandler; import buildcraft.api.core.IFluidFilter; +import buildcraft.api.core.IFluidHandlerAdv; public interface IFlowFluid { /** @param millibuckets @@ -15,11 +18,13 @@ public interface IFlowFluid { FluidStack tryExtractFluid(int millibuckets, EnumFacing from, FluidStack filter); /** Advanced version of {@link #tryExtractFluid(int, EnumFacing, FluidStack)}. Note that this only works for - * instances of {@link IFluidHandler} that ALSO extends IFluidHandlerAdv + * instances of {@link IFluidHandler} that ALSO extends {@link IFluidHandlerAdv} * * @param millibuckets * @param from * @param filter A filter to try and match fluids. - * @return The fluidstack extracted and inserted into the pipe. */ - FluidStack tryExtractFluidAdv(int millibuckets, EnumFacing from, IFluidFilter filter); + * @return The fluidstack extracted and inserted into the pipe. If {@link ActionResult#getType()} equals + * {@link EnumActionResult#PASS} then it means that the {@link IFluidHandler} didn't implement + * {@link IFluidHandlerAdv} and you should call the basic version, if you can. */ + ActionResult tryExtractFluidAdv(int millibuckets, EnumFacing from, IFluidFilter filter); } diff --git a/src/api/java/buildcraft/api/transport/pipe/IItemPipe.java b/src/api/java/buildcraft/api/transport/pipe/IItemPipe.java index fbff67747..1d2d37700 100755 --- a/src/api/java/buildcraft/api/transport/pipe/IItemPipe.java +++ b/src/api/java/buildcraft/api/transport/pipe/IItemPipe.java @@ -3,5 +3,5 @@ package buildcraft.api.transport.pipe; /** To be implemented by the real item pipe in Transport mod, but leaves knowledge for classes that do not have direct * dependency on transport. */ public interface IItemPipe { - PipeDefinition getDefiniton(); + PipeDefinition getDefinition(); } diff --git a/src/api/java/buildcraft/api/transport/pipe/IPipe.java b/src/api/java/buildcraft/api/transport/pipe/IPipe.java index 2a7a15c30..8f3d51e15 100755 --- a/src/api/java/buildcraft/api/transport/pipe/IPipe.java +++ b/src/api/java/buildcraft/api/transport/pipe/IPipe.java @@ -29,8 +29,8 @@ public interface IPipe extends ICapabilityProvider { ConnectedType getConnectedType(EnumFacing side); - public enum ConnectedType { + enum ConnectedType { TILE, - PIPE; + PIPE } } diff --git a/src/api/java/buildcraft/api/transport/pipe/IPipeHolder.java b/src/api/java/buildcraft/api/transport/pipe/IPipeHolder.java index 5ce5173b4..9d75f8777 100755 --- a/src/api/java/buildcraft/api/transport/pipe/IPipeHolder.java +++ b/src/api/java/buildcraft/api/transport/pipe/IPipeHolder.java @@ -1,5 +1,8 @@ package buildcraft.api.transport.pipe; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + import com.mojang.authlib.GameProfile; import net.minecraft.entity.player.EntityPlayer; @@ -9,6 +12,8 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; +import net.minecraftforge.common.capabilities.Capability; + import buildcraft.api.statements.containers.IRedstoneStatementContainer; import buildcraft.api.transport.IWireManager; import buildcraft.api.transport.pluggable.PipePluggable; @@ -23,11 +28,19 @@ public interface IPipeHolder extends IRedstoneStatementContainer { IPipe getPipe(); + @Nullable PipePluggable getPluggable(EnumFacing side); - TileEntity getNeighbouringTile(EnumFacing side); + @Nullable + TileEntity getNeighbourTile(EnumFacing side); - IPipe getNeighbouringPipe(EnumFacing side); + @Nullable + IPipe getNeighbourPipe(EnumFacing side); + + /** Gets the given capability going outwards from the pipe. This will test the + * {@link PipePluggable#getInternalCapability(Capability)} first, and the look at the neighbouring tile. */ + @Nullable + T getCapabilityFromPipe(EnumFacing side, @Nonnull Capability capability); IWireManager getWireManager(); @@ -59,7 +72,7 @@ public interface IPipeHolder extends IRedstoneStatementContainer { /** Called on the server whenever a gui container object is closed. */ void onPlayerClose(EntityPlayer player); - public enum PipeMessageReceiver { + enum PipeMessageReceiver { BEHAVIOUR(null), FLOW(null), PLUGGABLE_DOWN(EnumFacing.DOWN), @@ -89,7 +102,7 @@ public interface IPipeHolder extends IRedstoneStatementContainer { } } - public interface IWriter { + interface IWriter { void write(PacketBuffer buffer); } } diff --git a/src/api/java/buildcraft/api/transport/pipe/PipeApi.java b/src/api/java/buildcraft/api/transport/pipe/PipeApi.java index f401dc48f..7fffadd16 100755 --- a/src/api/java/buildcraft/api/transport/pipe/PipeApi.java +++ b/src/api/java/buildcraft/api/transport/pipe/PipeApi.java @@ -3,8 +3,17 @@ package buildcraft.api.transport.pipe; import java.util.IdentityHashMap; import java.util.Map; +import javax.annotation.Nonnull; + +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.common.capabilities.CapabilityInject; + +import buildcraft.api.core.CapabilitiesHelper; +import buildcraft.api.mj.MjAPI; +import buildcraft.api.transport.IInjectable; import buildcraft.api.transport.IStripesRegistry; import buildcraft.api.transport.pluggable.IPluggableRegistry; +import buildcraft.api.transport.pluggable.PipePluggable; /** The central holding class for all pipe related registers and methods. */ public final class PipeApi { @@ -18,21 +27,47 @@ public final class PipeApi { /** The default transfer information used if a pipe definition has not been registered. Note that this is replaced * by BuildCraft Transport to config-defined values. */ - public static FluidTransferInfo transferInfoDefault = new FluidTransferInfo(20, 10); + public static FluidTransferInfo fluidInfoDefault = new FluidTransferInfo(20, 10); + + /** The default transfer information used if a pipe definition has not been registered. Note that this is replaced + * by BuildCraft Transport to config-defined values. */ + public static PowerTransferInfo powerInfoDefault = PowerTransferInfo.createFromResistance(8 * MjAPI.MJ, MjAPI.MJ / 32, false); public static final Map fluidTransferData = new IdentityHashMap<>(); + public static final Map powerTransferData = new IdentityHashMap<>(); + + @Nonnull + public static final Capability CAP_PIPE_HOLDER; + + @Nonnull + public static final Capability CAP_PIPE; + + @Nonnull + public static final Capability CAP_PLUG; + + @Nonnull + public static final Capability CAP_INJECTABLE; public static FluidTransferInfo getFluidTransferInfo(PipeDefinition def) { FluidTransferInfo info = fluidTransferData.get(def); if (info == null) { - return transferInfoDefault; + return fluidInfoDefault; + } else { + return info; + } + } + + public static PowerTransferInfo getPowerTransferInfo(PipeDefinition def) { + PowerTransferInfo info = powerTransferData.get(def); + if (info == null) { + return powerInfoDefault; } else { return info; } } public static class FluidTransferInfo { - /** Controls the maximum amount of fluid that can be transfered around and out of a pipe per tick. Note that + /** Controls the maximum amount of fluid that can be transferred around and out of a pipe per tick. Note that * this does not affect the flow rate coming into the pipe. */ public final int transferPerTick; @@ -49,4 +84,66 @@ public final class PipeApi { this.transferDelayMultiplier = transferDelay; } } + + public static class PowerTransferInfo { + public final long transferPerTick; + public final long lossPerTick; + /** The percentage resistance per tick. Should be a value between 0 and {@link MjAPI#MJ} */ + public final long resistancePerTick; + public final boolean isReceiver; + + /** Sets resistancePerTick to be equal to lossPerTick when full power is being transferred, scaling down to 0. + * + * @param transferPerTick + * @param lossPerTick + * @param isReceiver */ + public static PowerTransferInfo createFromLoss(long transferPerTick, long lossPerTick, boolean isReceiver) { + return new PowerTransferInfo(transferPerTick, lossPerTick, lossPerTick * MjAPI.MJ / transferPerTick, isReceiver); + } + + /** Sets lossPerTick to be equal to resistancePerTick when full power is being transferred. + * + * @param transferPerTick + * @param resistancePerTick + * @param isReceiver */ + public static PowerTransferInfo createFromResistance(long transferPerTick, long resistancePerTick, boolean isReceiver) { + return new PowerTransferInfo(transferPerTick, resistancePerTick, resistancePerTick * transferPerTick / MjAPI.MJ, isReceiver); + } + + public PowerTransferInfo(long transferPerTick, long lossPerTick, long resistancePerTick, boolean isReceiver) { + if (transferPerTick < 10) { + transferPerTick = 10; + } + this.transferPerTick = transferPerTick; + this.lossPerTick = lossPerTick; + this.resistancePerTick = resistancePerTick; + this.isReceiver = isReceiver; + } + } + + // Internals + + @CapabilityInject(IPipeHolder.class) + private static Capability capPipeHolder; + + @CapabilityInject(IPipe.class) + private static Capability capPipe; + + @CapabilityInject(PipePluggable.class) + private static Capability capPlug; + + @CapabilityInject(IInjectable.class) + private static Capability capInjectable; + + static { + CapabilitiesHelper.registerCapability(IPipe.class); + CapabilitiesHelper.registerCapability(IPipeHolder.class); + CapabilitiesHelper.registerCapability(IInjectable.class); + CapabilitiesHelper.registerCapability(PipePluggable.class); + + CAP_PIPE = CapabilitiesHelper.ensureRegistration(capPipe, IPipe.class); + CAP_PLUG = CapabilitiesHelper.ensureRegistration(capPlug, PipePluggable.class); + CAP_PIPE_HOLDER = CapabilitiesHelper.ensureRegistration(capPipeHolder, IPipeHolder.class); + CAP_INJECTABLE = CapabilitiesHelper.ensureRegistration(capInjectable, IInjectable.class); + } } diff --git a/src/api/java/buildcraft/api/transport/pipe/PipeBehaviour.java b/src/api/java/buildcraft/api/transport/pipe/PipeBehaviour.java index 624d75b99..2e919038f 100755 --- a/src/api/java/buildcraft/api/transport/pipe/PipeBehaviour.java +++ b/src/api/java/buildcraft/api/transport/pipe/PipeBehaviour.java @@ -1,5 +1,8 @@ package buildcraft.api.transport.pipe; +import javax.annotation.Nonnull; + +import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.PacketBuffer; @@ -53,15 +56,17 @@ public abstract class PipeBehaviour implements ICapabilityProvider { return false; } + public void onEntityCollide(Entity entity) {} + public void onTick() {} @Override - public boolean hasCapability(Capability capability, EnumFacing facing) { - return false; + public boolean hasCapability(@Nonnull Capability capability, EnumFacing facing) { + return getCapability(capability, facing) != null; } @Override - public T getCapability(Capability capability, EnumFacing facing) { + public T getCapability(@Nonnull Capability capability, EnumFacing facing) { return null; } } diff --git a/src/api/java/buildcraft/api/transport/pipe/PipeConnectionAPI.java b/src/api/java/buildcraft/api/transport/pipe/PipeConnectionAPI.java index 336ce551a..987203442 100755 --- a/src/api/java/buildcraft/api/transport/pipe/PipeConnectionAPI.java +++ b/src/api/java/buildcraft/api/transport/pipe/PipeConnectionAPI.java @@ -5,22 +5,13 @@ import java.util.Map; import com.google.common.collect.Maps; import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; /** Use this class to register blocks with custom block sizes so that pipes can connect to them properly. Note that you * do not need to register a custom pipe connection if your block implements ICustomPipeConnection. The registered * version does not override your own implementation. */ public final class PipeConnectionAPI { private static final Map connections = Maps.newHashMap(); - private static final ICustomPipeConnection NOTHING = new ICustomPipeConnection() { - @Override - public float getExtension(World world, BlockPos pos, EnumFacing face, IBlockState state) { - return 0; - } - }; + private static final ICustomPipeConnection NOTHING = (world, pos, face, state) -> 0; /** Register a block with a custom connection. Useful if you don't own the block class or are adding it for some-one * else. diff --git a/src/api/java/buildcraft/api/transport/pipe/PipeDefinition.java b/src/api/java/buildcraft/api/transport/pipe/PipeDefinition.java index 845d6b70b..6e223512d 100755 --- a/src/api/java/buildcraft/api/transport/pipe/PipeDefinition.java +++ b/src/api/java/buildcraft/api/transport/pipe/PipeDefinition.java @@ -69,7 +69,7 @@ public final class PipeDefinition { private static String getActiveModId() { ModContainer mod = Loader.instance().activeModContainer(); if (mod == null) { - throw new IllegalStateException("Cannot interact with PipeDefinition outside of an activly scoped mod!"); + throw new IllegalStateException("Cannot interact with PipeDefinition outside of an actively scoped mod!"); } return mod.getModId(); } diff --git a/src/api/java/buildcraft/api/transport/pipe/PipeEvent.java b/src/api/java/buildcraft/api/transport/pipe/PipeEvent.java index a5c41062c..1c6935e5e 100755 --- a/src/api/java/buildcraft/api/transport/pipe/PipeEvent.java +++ b/src/api/java/buildcraft/api/transport/pipe/PipeEvent.java @@ -1,7 +1,8 @@ package buildcraft.api.transport.pipe; /** The base class for all pipe events. Some event classes can be cancelled with {@link #cancel()}, however this will - * only have an effect if {@link #canBeCancelled} is true. Refer to indervidual classes for information on what*/ + * only have an effect if {@link #canBeCancelled} is true. Refer to individual classes for information on if they can + * be cancelled, and what cancelling the event does. */ public abstract class PipeEvent { public final boolean canBeCancelled; public final IPipeHolder holder; @@ -25,4 +26,16 @@ public abstract class PipeEvent { public boolean isCanceled() { return canceled; } + + /** Called after every event handler has received this pipe event, to pick up simple mistakes when implementing pipe + * event handlers. + * + * @return Null if there are no state errors, or a message containing information about what is wrong (although this + * may be incomplete) */ + public String checkStateForErrors() { + if (canceled & !canBeCancelled) { + return "Somehow cancelled an event that isn't marked as such!"; + } + return null; + } } diff --git a/src/api/java/buildcraft/api/transport/pipe/PipeEventFluid.java b/src/api/java/buildcraft/api/transport/pipe/PipeEventFluid.java index f31714203..e557bccfd 100755 --- a/src/api/java/buildcraft/api/transport/pipe/PipeEventFluid.java +++ b/src/api/java/buildcraft/api/transport/pipe/PipeEventFluid.java @@ -4,6 +4,8 @@ import java.util.Arrays; import java.util.Collection; import java.util.EnumSet; +import javax.annotation.Nonnull; + import com.google.common.collect.Lists; import net.minecraft.util.EnumFacing; @@ -24,6 +26,100 @@ public abstract class PipeEventFluid extends PipeEvent { this.flow = flow; } + public static class TryInsert extends PipeEventFluid { + public final EnumFacing from; + /** The incoming fluidstack. Currently changing this does nothing. */ + @Nonnull + public final FluidStack fluid; + + public TryInsert(IPipeHolder holder, IFlowFluid flow, EnumFacing from, @Nonnull FluidStack fluid) { + super(true, holder, flow); + this.from = from; + this.fluid = fluid; + } + } + + /** Fired after collecting the amounts of fluid that can be moved from each pipe part into the centre. */ + public static class PreMoveToCentre extends PipeEventFluid { + /** The fluid that is being moved. Future versions of BC *might* allow more than one fluid type per pipe, but + * for the moment the API doesn't allow pipes to do this. */ + public final FluidStack fluid; + + /** The maximum amount of fluid that the centre pipe could accept. */ + public final int totalAcceptable; + + /** Array of {@link EnumFacing#getIndex()} to the maximum amount of fluid that a given side can offer. DO NOT + * CHANGE THIS! */ + public final int[] totalOffered; + + // Used for checking the state + private final int[] totalOfferedCheck; + + /** Array of {@link EnumFacing#getIndex()} to the amount of fluid that the given side will actually offer to the + * centre. This should *never* be larger than */ + public final int[] actuallyOffered; + + public PreMoveToCentre(IPipeHolder holder, IFlowFluid flow, FluidStack fluid, int totalAcceptable, int[] totalOffered, int[] actuallyOffered) { + super(holder, flow); + this.fluid = fluid; + this.totalAcceptable = totalAcceptable; + this.totalOffered = totalOffered; + totalOfferedCheck = Arrays.copyOf(totalOffered, totalOffered.length); + this.actuallyOffered = actuallyOffered; + } + + @Override + public String checkStateForErrors() { + for (int i = 0; i < totalOffered.length; i++) { + if (totalOffered[i] != totalOfferedCheck[i]) { + return "Changed totalOffered"; + } + if (actuallyOffered[i] > totalOffered[i]) { + return "actuallyOffered[" + i + "](=" + actuallyOffered[i] + ") shouldn't be greater than totalOffered[" + i + "](=" + totalOffered[i] + ")"; + } + } + return super.checkStateForErrors(); + } + } + + /** Fired after {@link PreMoveToCentre} when all of the amounts have been totalled up. */ + public static class OnMoveToCentre extends PipeEventFluid { + /** The fluid that is being moved. Future versions of BC *might* allow more than one fluid type per pipe, but + * for the moment the API doesn't allow pipes to do this. */ + public final FluidStack fluid; + + public final int[] fluidLeavingSide; + public final int[] fluidEnteringCentre; + + // Used for checking the state maximums + private final int[] fluidLeaveCheck, fluidEnterCheck; + + public OnMoveToCentre(IPipeHolder holder, IFlowFluid flow, FluidStack fluid, int[] fluidLeavingSide, int[] fluidEnteringCentre) { + super(holder, flow); + this.fluid = fluid; + this.fluidLeavingSide = fluidLeavingSide; + this.fluidEnteringCentre = fluidEnteringCentre; + fluidLeaveCheck = Arrays.copyOf(fluidLeavingSide, fluidLeavingSide.length); + fluidEnterCheck = Arrays.copyOf(fluidEnteringCentre, fluidEnteringCentre.length); + } + + @Override + public String checkStateForErrors() { + for (int i = 0; i < fluidLeavingSide.length; i++) { + if (fluidLeavingSide[i] > fluidLeaveCheck[i]) { + return "fluidLeavingSide[" + i + "](=" + fluidLeavingSide[i] + ") shouldn't be bigger than its original value!(=" + fluidLeaveCheck[i] + ")"; + } + if (fluidEnteringCentre[i] > fluidEnterCheck[i]) { + return "fluidEnteringCentre[" + i + "](=" + fluidEnteringCentre[i] + ") shouldn't be bigger than its original value!(=" + fluidEnterCheck[i] + ")"; + } + if (fluidEnteringCentre[i] > fluidLeavingSide[i]) { + return "fluidEnteringCentre[" + i + "](=" + fluidEnteringCentre[i] + ") shouldn't be bigger than fluidLeavingSide[" + i + "](=" + fluidLeavingSide[i] + ")"; + } + } + return super.checkStateForErrors(); + } + } + public static class SideCheck extends PipeEventFluid { public final FluidStack fluid; @@ -126,5 +222,4 @@ public abstract class PipeEventFluid extends PipeEvent { return EnumSet.noneOf(EnumFacing.class); } } - } diff --git a/src/api/java/buildcraft/api/transport/pipe/PipeEventHandler.java b/src/api/java/buildcraft/api/transport/pipe/PipeEventHandler.java index 1ef3667a6..15eaecaf5 100755 --- a/src/api/java/buildcraft/api/transport/pipe/PipeEventHandler.java +++ b/src/api/java/buildcraft/api/transport/pipe/PipeEventHandler.java @@ -1,9 +1,8 @@ package buildcraft.api.transport.pipe; -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - +import java.lang.annotation.ElementType; import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** Designates a method that will receive a pipe event. The method must be public and take a single parameter that @@ -12,12 +11,12 @@ import java.lang.annotation.Target; * @PipeEventHandler
    public void sideCheck(PipeEventItem.SideCheck sideCheck) {
    - // Logic ommited
    + // Logic omitted
    } * *
    */ -@Retention(RUNTIME) -@Target(METHOD) +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) public @interface PipeEventHandler { /** Designates the priority that the handler will be given. All handlers in vanilla BuildCraft use * {@link PipeEventPriority#NORMAL}, so this is given for other pipe mods to fire before or after all BC logic has diff --git a/src/api/java/buildcraft/api/transport/pipe/PipeEventItem.java b/src/api/java/buildcraft/api/transport/pipe/PipeEventItem.java index 6e1d44820..ab33955d9 100755 --- a/src/api/java/buildcraft/api/transport/pipe/PipeEventItem.java +++ b/src/api/java/buildcraft/api/transport/pipe/PipeEventItem.java @@ -1,12 +1,19 @@ package buildcraft.api.transport.pipe; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.EnumSet; +import java.util.List; import javax.annotation.Nonnull; +import javax.annotation.Nullable; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; +import net.minecraft.entity.item.EntityItem; import net.minecraft.item.EnumDyeColor; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; @@ -245,26 +252,32 @@ public abstract class PipeEventItem extends PipeEvent { } public static class Drop extends PipeEventItem { - @Nonnull - private ItemStack stack; + private final EntityItem entity; - public Drop(IPipeHolder holder, IFlowItems flow, @Nonnull ItemStack stack) { + public Drop(IPipeHolder holder, IFlowItems flow, EntityItem entity) { super(holder, flow); - this.stack = stack; + this.entity = entity; } @Nonnull public ItemStack getStack() { - return this.stack; + ItemStack item = entity.getEntityItem(); + return item.isEmpty() ? ItemStack.EMPTY : item; } public void setStack(ItemStack stack) { if (stack == null) { throw new NullPointerException("stack"); + } else if (stack.isEmpty()) { + entity.setEntityItemStack(ItemStack.EMPTY); } else { - this.stack = stack; + entity.setEntityItemStack(stack); } } + + public EntityItem getEntity() { + return this.entity; + } } /** Base class for {@link Split} and {@link FindDest}. Do not listen to this directly! */ @@ -276,6 +289,14 @@ public abstract class PipeEventItem extends PipeEvent { this.orderedDestinations = orderedDestinations; } + public EnumSet getAllPossibleDestinations() { + EnumSet set = EnumSet.noneOf(EnumFacing.class); + for (EnumSet e : orderedDestinations) { + set.addAll(e); + } + return set; + } + public ImmutableList generateRandomOrder() { ImmutableList.Builder builder = ImmutableList.builder(); for (EnumSet set : orderedDestinations) { @@ -337,7 +358,8 @@ public abstract class PipeEventItem extends PipeEvent { @Nonnull public final ItemStack stack; public final EnumFacing from; - /** An list of the destinations to try, in order. */ + /** The list of the destinations to try, in order. */ + @Nullable public List to; public ItemEntry(EnumDyeColor colour, @Nonnull ItemStack stack, EnumFacing from) { diff --git a/src/api/java/buildcraft/api/transport/pipe/PipeEventPriority.java b/src/api/java/buildcraft/api/transport/pipe/PipeEventPriority.java index cedaaa83f..21f78937a 100755 --- a/src/api/java/buildcraft/api/transport/pipe/PipeEventPriority.java +++ b/src/api/java/buildcraft/api/transport/pipe/PipeEventPriority.java @@ -3,5 +3,5 @@ package buildcraft.api.transport.pipe; public enum PipeEventPriority { PRE, NORMAL, - POST; + POST } diff --git a/src/api/java/buildcraft/api/transport/pipe/PipeFlow.java b/src/api/java/buildcraft/api/transport/pipe/PipeFlow.java index d35e34a22..b941b4e73 100755 --- a/src/api/java/buildcraft/api/transport/pipe/PipeFlow.java +++ b/src/api/java/buildcraft/api/transport/pipe/PipeFlow.java @@ -2,6 +2,8 @@ package buildcraft.api.transport.pipe; import java.io.IOException; +import javax.annotation.Nonnull; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.PacketBuffer; @@ -50,13 +52,10 @@ public abstract class PipeFlow implements ICapabilityProvider { } public final void sendCustomPayload(int id, IWriter writer) { - pipe.getHolder().sendMessage(PipeMessageReceiver.FLOW, new IWriter() { - @Override - public void write(PacketBuffer buffer) { - buffer.writeBoolean(true); - buffer.writeShort(id); - writer.write(buffer); - } + pipe.getHolder().sendMessage(PipeMessageReceiver.FLOW, buffer -> { + buffer.writeBoolean(true); + buffer.writeShort(id); + writer.write(buffer); }); } @@ -71,12 +70,12 @@ public abstract class PipeFlow implements ICapabilityProvider { } @Override - public final boolean hasCapability(Capability capability, EnumFacing facing) { + public final boolean hasCapability(@Nonnull Capability capability, EnumFacing facing) { return getCapability(capability, facing) != null; } @Override - public T getCapability(Capability capability, EnumFacing facing) { + public T getCapability(@Nonnull Capability capability, EnumFacing facing) { return null; } } diff --git a/src/api/java/buildcraft/api/transport/pluggable/PipePluggable.java b/src/api/java/buildcraft/api/transport/pluggable/PipePluggable.java index a1b180519..8ddb478bf 100755 --- a/src/api/java/buildcraft/api/transport/pluggable/PipePluggable.java +++ b/src/api/java/buildcraft/api/transport/pluggable/PipePluggable.java @@ -5,6 +5,8 @@ import java.io.IOException; import javax.annotation.Nonnull; import javax.annotation.Nullable; +import net.minecraft.block.Block; +import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -13,12 +15,16 @@ import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.EnumFacing; import net.minecraft.util.NonNullList; import net.minecraft.util.math.AxisAlignedBB; +import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; +import net.minecraft.world.Explosion; +import net.minecraft.world.World; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; import buildcraft.api.transport.pipe.IPipeHolder; import buildcraft.api.transport.pipe.IPipeHolder.PipeMessageReceiver; @@ -76,10 +82,19 @@ public abstract class PipePluggable { return null; } - /** Called whenever this pluggable is removed from the pipe. + /** Gets the {@link Capability} that is accessible from the pipe that this is attached to. * - * @param toDrop A list containing all the items to drop (so you should add your items to this list) */ - public void onRemove(NonNullList toDrop) { + * @param cap + * @return */ + public T getInternalCapability(@Nonnull Capability cap) { + return null; + } + + /** Called whenever this pluggable is removed from the pipe. */ + public void onRemove() {} + + /** @param toDrop A list containing all the items to drop (so you should add your items to this list) * */ + public void getDrops(NonNullList toDrop) { ItemStack stack = getPickStack(); if (!stack.isEmpty()) { toDrop.add(stack); @@ -101,4 +116,34 @@ public abstract class PipePluggable { public PluggableModelKey getModelRenderKey(BlockRenderLayer layer) { return null; } + + /** Called if the {@link IPluggableStaticBaker} returns quads with tint indexes set to + * data * 6 + key.side.ordinal(). "data" is passed in here as "tintIndex". + * + * @return The tint index to render the quad with, or -1 for default. */ + @SideOnly(Side.CLIENT) + public int getBlockColor(int tintIndex) { + return -1; + } + + /** PipePluggable version of + * {@link Block#canBeConnectedTo(net.minecraft.world.IBlockAccess, net.minecraft.util.math.BlockPos, EnumFacing)}. */ + public boolean canBeConnected() { + return false; + } + + /** PipePluggable version of + * {@link Block#isBlockSolid(net.minecraft.world.IBlockAccess, net.minecraft.util.math.BlockPos, EnumFacing)} */ + public boolean isSideSolid() { + return false; + } + + /** PipePluggable version of {@link Block#getExplosionResistance(World, BlockPos, Entity, Explosion)} */ + public float getExplosionResistance(@Nullable Entity exploder, Explosion explosion) { + return 0; + } + + public boolean canConnectToRedstone(@Nullable EnumFacing to) { + return false; + } } diff --git a/src/api/java/buildcraft/api/transport/pluggable/PluggableDefinition.java b/src/api/java/buildcraft/api/transport/pluggable/PluggableDefinition.java index f6e371c3d..61884a668 100755 --- a/src/api/java/buildcraft/api/transport/pluggable/PluggableDefinition.java +++ b/src/api/java/buildcraft/api/transport/pluggable/PluggableDefinition.java @@ -25,7 +25,7 @@ public final class PluggableDefinition { this.creator = null; } - public PluggableDefinition(ResourceLocation identifier, IPluggableCreator creator) { + public PluggableDefinition(ResourceLocation identifier, @Nullable IPluggableCreator creator) { this.identifier = identifier; this.reader = creator; this.loader = creator; diff --git a/src/main/java/mekanism/common/FuelHandler.java b/src/main/java/mekanism/common/FuelHandler.java index d4fded57b..5c5e954a6 100644 --- a/src/main/java/mekanism/common/FuelHandler.java +++ b/src/main/java/mekanism/common/FuelHandler.java @@ -2,10 +2,12 @@ package mekanism.common; import java.util.HashMap; +import buildcraft.api.mj.MjAPI; import mekanism.api.gas.Gas; import mekanism.common.config.MekanismConfig.general; import mekanism.common.util.MekanismUtils; import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fml.common.ModAPIManager; import buildcraft.api.fuels.BuildcraftFuelRegistry; import buildcraft.api.fuels.IFuel; @@ -28,7 +30,7 @@ public class FuelHandler if(BCPresent() && gas.hasFluid() && BuildcraftFuelRegistry.fuel != null) { - IFuel bcFuel = BuildcraftFuelRegistry.fuel.getFuel(gas.getFluid()); + IFuel bcFuel = BuildcraftFuelRegistry.fuel.getFuel(new FluidStack(gas.getFluid(), 1)); if(bcFuel != null) { @@ -56,7 +58,7 @@ public class FuelHandler public FuelGas(IFuel bcFuel) { burnTicks = bcFuel.getTotalBurningTime() / Fluid.BUCKET_VOLUME; - energyPerTick = bcFuel.getPowerPerCycle() * general.FROM_RF; + energyPerTick = bcFuel.getPowerPerCycle() * MjAPI.MJ; } } diff --git a/src/main/java/mekanism/generators/common/MekanismGenerators.java b/src/main/java/mekanism/generators/common/MekanismGenerators.java index b06fb7bc0..9e84541cf 100644 --- a/src/main/java/mekanism/generators/common/MekanismGenerators.java +++ b/src/main/java/mekanism/generators/common/MekanismGenerators.java @@ -101,13 +101,13 @@ public class MekanismGenerators implements IModule { for(IFuel s : BuildcraftFuelRegistry.fuel.getFuels()) { - if(!(s.getFluid() == null || GasRegistry.containsGas(s.getFluid().getName()))) + if(!(s.getFluid() == null || GasRegistry.containsGas(s.getFluid().getFluid().getName()))) { - GasRegistry.register(new Gas(s.getFluid())); + GasRegistry.register(new Gas(s.getFluid().getFluid())); } } - BuildcraftFuelRegistry.fuel.addFuel(MekanismFluids.Ethene.getFluid(), (int)(240 * general.TO_RF), 40 * Fluid.BUCKET_VOLUME); + BuildcraftFuelRegistry.fuel.addFuel(MekanismFluids.Ethene.getFluid(), 240, 40 * Fluid.BUCKET_VOLUME); } //Update the config-dependent recipes after the recipes have actually been added in the first place