Merge branch '1.8'

Conflicts:
	build.gradle
	build.properties
	src/mantle/Mantle.java
	src/mantle/blocks/abstracts/AdaptiveInventoryLogic.java
	src/mantle/blocks/abstracts/InventoryBlock.java
	src/mantle/blocks/abstracts/MultiItemBlock.java
	src/mantle/blocks/abstracts/MultiServantLogic.java
	src/mantle/client/RenderItemCopy.java
	src/mantle/client/SmallFontRenderer.java
	src/mantle/items/Manual.java
	src/mantle/items/abstracts/CraftingItem.java
	src/mantle/lib/CoreConfig.java
	src/mantle/utils/ItemMetaWrapper.java
	src/mantle/utils/ItemStackNBTWrapper.java
This commit is contained in:
Bernhard Bonigl committed 2016-01-11 22:06:01 +01:00
commit a6df441c8c
170 files changed
+5054 -7549

No files matched your search

+3 -1
View File
@@ -26,4 +26,6 @@ version.properties
#eclipse stuffs
/*.classpath
/*.project
/.settings/
/.settings/
/*.launch
/out
+49 -31
View File
@@ -4,25 +4,27 @@
* Based on TConstruct's master build file
* Authors: Sunstrike, ProgWML6
* Help from AbrarSyed
*/
*/
buildscript {
repositories {
mavenCentral()
mavenLocal()
mavenLocal()
jcenter()
maven {
name = 'ForgeFS'
url = 'http://files.minecraftforge.net/maven'
name = "forge"
url = "http://files.minecraftforge.net/maven"
}
maven {
maven {
name = "sonatype"
url = "https://oss.sonatype.org/content/repositories/snapshots/"
}
}
dependencies {
classpath 'net.minecraftforge.gradle:ForgeGradle:1.2-SNAPSHOT'
classpath 'net.minecraftforge.gradle:ForgeGradle:2.1-SNAPSHOT'
}
}
apply plugin: 'net.minecraftforge.gradle.forge'
repositories {
mavenLocal()
@@ -30,11 +32,19 @@ repositories {
name 'ForgeFS'
url 'http://files.minecraftforge.net/maven'
}
maven {
name 'CB Maven FS'
url "http://chickenbones.net/maven/"
}
maven {
name 'forge'
url 'http://files.minecraftforge.net/maven'
}
}
apply plugin: 'forge'
group = 'mantle'
group = 'slimeknights.mantle'
sourceCompatibility = 1.7
targetCompatibility = 1.7
// Define properties file
ext.configFile = file "build.properties"
@@ -46,8 +56,7 @@ configFile.withReader {
project.ext.config = new ConfigSlurper().parse prop
}
// sets version to the slimeKnights default version format
// Finds and sets version data
// sets version to the slimeKnights version format
task buildInfo {
def cmd = "git rev-parse --short HEAD"
def proc = cmd.execute()
@@ -75,41 +84,52 @@ if (System.getenv().ARTIFACT_VERSION != null) {
version = "${config.minecraft_version}-${artifact_version}"
minecraft {
version = config.forge_version + "-" + config.minecraft_version
version = config.minecraft_version + "-" + config.forge_version
mappings = config.mappings
runDir = 'run'
replace '${version}', project.version
mappings = "snapshot_${config.snapshot}"
}
sourceSets {
main {
resources {
srcDir 'resources'
}
java {
srcDir 'src'
}
}
configurations {
shade
compile.extendsFrom shade
}
dependencies {
//compile "codechicken:CodeChickenLib:${config.minecraft_version}-${config.CCLIB_version}:dev"
//compile "codechicken:CodeChickenCore:${config.minecraft_version}-${config.ccc_version}:dev"
//compile "codechicken:NotEnoughItems:${config.minecraft_version}-${config.NEI_version}:dev"
// Configuration
shade "ninja.leaping.configurate:configurate-hocon:${config.configurate_version}"
shade "ninja.leaping.configurate:configurate-gson:${config.configurate_version}"
}
processResources
{
inputs.property "version", artifact_version
inputs.property "MCversion", config.minecraft_version
// replace stuff in text files, not binary ones.
// replace stuff in text files, not binary ones.
from(sourceSets.main.resources.srcDirs) {
include '**/*.info'
// replace version and MCVersion
// replace version and MCVersion
expand 'version':artifact_version,'MCversion':config.minecraft_version
}
// copy everything else, thats not text
// copy everything else, thats not text
from(sourceSets.main.resources.srcDirs) {
exclude '**/*.info'
}
}
jar {
// Shading
configurations.shade.each { dep ->
from(project.zipTree(dep)){
exclude 'META-INF', 'META-INF/**'
}
}
}
// because the normal output has been made to be obfuscated
task deobfJar(type: Jar) {
from sourceSets.main.output
@@ -127,9 +147,7 @@ artifacts {
}
task("uploadJars", dependsOn:"build") {
description = "uploads JARs"
if (project.hasProperty("local_maven")) {
apply plugin: 'maven'
uploadArchives {
@@ -140,4 +158,4 @@ task("uploadJars", dependsOn:"build") {
}
}
}
}
}
+9 -4
View File
@@ -1,4 +1,9 @@
mod_version=0.3.2
minecraft_version=1.7.10
forge_version=10.13.4.1448
snapshot=20140925
mod_version=0.6
minecraft_version=1.8.9
forge_version=11.15.0.1663
mappings=snapshot_20151212
CCLIB_version=1.1.2.133
ccc_version=1.0.5.36
NEI_version=1.0.5.104
configurate_version=2.0
Binary file not shown.
+2 -2
View File
@@ -1,6 +1,6 @@
#Wed Jul 02 15:54:47 CDT 2014
#Mon Sep 14 12:28:28 PDT 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.0-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-2.7-bin.zip
Vendored
+90 -90
View File
@@ -1,90 +1,90 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
@@ -0,0 +1,34 @@
package slimeknights.mantle;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.SidedProxy;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import slimeknights.mantle.common.CommonProxy;
/**
* Mantle
*
* Central mod object for Mantle
*
* @author Sunstrike <[email protected]>
*/
@Mod(modid = Mantle.modId, name = Mantle.modName, version = Mantle.modVersion, dependencies = "required-after:Forge@[11.15,)", acceptedMinecraftVersions="[1.8.8,1.8.9]")
public class Mantle {
public static final String modId = "mantle";
public static final String modName = "Mantle";
public static final String modVersion = "${version}";
public static final Logger logger = LogManager.getLogger("Mantle");
/* Instance of this mod, used for grabbing prototype fields */
@Instance("mantle")
public static Mantle instance;
/* Proxies for sides, used for graphics processing */
@SidedProxy(clientSide = "slimeknights.mantle.client.ClientProxy", serverSide = "slimeknights.mantle.common.CommonProxy")
public static CommonProxy proxy;
}
@@ -0,0 +1,91 @@
package slimeknights.mantle.block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.InventoryHelper;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.World;
import slimeknights.mantle.tileentity.TileInventory;
// Updated Version of InventoryBlock in Mantle
public abstract class BlockInventory extends BlockContainer {
protected BlockInventory(Material material) {
super(material);
}
// inventories usually need a tileEntity
@Override
public boolean hasTileEntity(IBlockState state) {
return true;
}
@Override
public abstract TileEntity createNewTileEntity(World worldIn, int meta);
/**
* Called when the block is activated. Return true if a GUI is opened, false if the block has no GUI.
*/
protected abstract boolean openGui(EntityPlayer player, World world, BlockPos pos);
@Override
public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumFacing side,
float clickX, float clickY, float clickZ) {
if(player.isSneaking()) {
return false;
}
if(!world.isRemote) {
return this.openGui(player, world, pos);
}
return true;
}
@Override
public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer,
ItemStack stack) {
super.onBlockPlacedBy(worldIn, pos, state, placer, stack);
// set custom name from named stack
if(stack.hasDisplayName()) {
TileEntity tileentity = worldIn.getTileEntity(pos);
if(tileentity instanceof TileInventory) {
((TileInventory) tileentity).setCustomName(stack.getDisplayName());
}
}
}
public void breakBlock(World worldIn, BlockPos pos, IBlockState state) {
TileEntity tileentity = worldIn.getTileEntity(pos);
if(tileentity instanceof TileInventory) {
InventoryHelper.dropInventoryItems(worldIn, pos, (IInventory) tileentity);
worldIn.updateComparatorOutputLevel(pos, this);
}
super.breakBlock(worldIn, pos, state);
}
@Override
public int damageDropped(IBlockState state) {
return getMetaFromState(state);
}
// BlockContainer sets this to -1, which equals invisible
// we need 3 for standard forge rendering
@Override
public int getRenderType() {
return 3;
}
}
@@ -0,0 +1,78 @@
package slimeknights.mantle.block;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IStringSerializable;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.List;
public class EnumBlock<E extends Enum<E> & EnumBlock.IEnumMeta & IStringSerializable> extends Block {
public final PropertyEnum<E> prop;
private final E[] values;
private static PropertyEnum<?> tmp;
public EnumBlock(Material material, PropertyEnum<E> prop, Class<E> clazz) {
super(preInit(material, prop));
this.prop = prop;
values = clazz.getEnumConstants();
}
@SuppressWarnings("unchecked")
private static Material preInit(Material material, PropertyEnum<?> property) {
tmp=property;
return material;
}
@SideOnly(Side.CLIENT)
@Override
public void getSubBlocks(Item itemIn, CreativeTabs tab, List<ItemStack> list) {
for(E type : values) {
list.add(new ItemStack(this, 1, type.getMeta()));
}
}
@Override
protected BlockState createBlockState() {
if(prop == null) {
return new BlockState(this, tmp);
}
return new BlockState(this, prop);
}
@Override
public IBlockState getStateFromMeta(int meta) {
return this.getDefaultState().withProperty(prop, fromMeta(meta));
}
@Override
public int getMetaFromState(IBlockState state) {
return ((E) state.getValue(prop)).getMeta();
}
@Override
public int damageDropped(IBlockState state) {
return getMetaFromState(state);
}
protected E fromMeta(int meta) {
if(meta < 0 || meta >= values.length) {
meta = 0;
}
return values[meta];
}
public interface IEnumMeta {
int getMeta();
}
}
@@ -0,0 +1,6 @@
package slimeknights.mantle.client;
import slimeknights.mantle.common.CommonProxy;
public class ClientProxy extends CommonProxy {
}
@@ -0,0 +1,43 @@
package slimeknights.mantle.client;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class CreativeTab extends CreativeTabs {
private ItemStack icon;
// a vanilla icon in case the other one isn't present
public CreativeTab(String label, ItemStack backupIcon) {
super(label);
this.icon = backupIcon;
}
public void setDisplayIcon(ItemStack displayIcon) {
if(displayIcon != null && displayIcon.getItem() != null) {
this.icon = displayIcon;
}
}
@SideOnly(Side.CLIENT)
@Override
public ItemStack getIconItemStack() {
return icon;
}
@SideOnly(Side.CLIENT)
@Override
public int getIconItemDamage() {
return icon.getItemDamage();
}
@SideOnly(Side.CLIENT)
@Override
public Item getTabIconItem() {
return icon.getItem();
}
}
@@ -0,0 +1,159 @@
package slimeknights.mantle.client;
import com.google.common.base.Charsets;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.resources.IResource;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.model.IColoredBakedQuad;
import net.minecraftforge.client.model.IModelPart;
import net.minecraftforge.client.model.IModelState;
import net.minecraftforge.client.model.SimpleModelState;
import net.minecraftforge.client.model.TRSRTransformation;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Type;
import java.util.Map;
import javax.vecmath.Vector3f;
public class ModelHelper {
static final Type maptype = new TypeToken<Map<String, String>>() {}.getType();
private static final Gson
GSON =
new GsonBuilder().registerTypeAdapter(maptype, ModelTextureDeserializer.INSTANCE).create();
public static final Optional<IModelState> DEFAULT_ITEM_STATE;
public static final Optional<IModelState> DEFAULT_TOOL_STATE;
public static TextureAtlasSprite getTextureFromBlock(Block block, int meta) {
IBlockState state = block.getStateFromMeta(meta);
return Minecraft.getMinecraft().getBlockRendererDispatcher().getBlockModelShapes().getTexture(state);
}
public static TextureAtlasSprite getTextureFromBlockstate(IBlockState state) {
return Minecraft.getMinecraft().getBlockRendererDispatcher().getBlockModelShapes().getTexture(state);
}
public static BakedQuad colorQuad(int color, BakedQuad quad) {
int[] data = quad.getVertexData();
int a = (color >> 24);
if(a == 0) {
a = 255;
}
int c = 0;
c |= ((color >> 16) & 0xFF) << 0; // red
c |= ((color >> 8) & 0xFF) << 8; // green
c |= ((color >> 0) & 0xFF) << 16; // blue
c |= (a & 0xFF) << 24; // alpha
// update color in the data. all 4 Vertices.
for(int i = 0; i < 4; i++) {
data[i * 7 + 3] = c;
}
return new IColoredBakedQuad.ColoredBakedQuad(data, -1, quad.getFace());
}
public static Map<String, String> loadTexturesFromJson(ResourceLocation location) throws IOException {
// get the json
IResource
iresource =
Minecraft.getMinecraft().getResourceManager()
.getResource(new ResourceLocation(location.getResourceDomain(), location.getResourcePath() + ".json"));
Reader reader = new InputStreamReader(iresource.getInputStream(), Charsets.UTF_8);
return GSON.fromJson(reader, maptype);
}
public static ImmutableList<ResourceLocation> loadTextureListFromJson(ResourceLocation location) throws IOException {
ImmutableList.Builder<ResourceLocation> builder = ImmutableList.builder();
for(String s : loadTexturesFromJson(location).values()) {
builder.add(new ResourceLocation(s));
}
return builder.build();
}
public static ResourceLocation getModelLocation(ResourceLocation location) {
return new ResourceLocation(location.getResourceDomain(), "models/" + location.getResourcePath() + ".json");
}
static {
{
// equals forge:default-item
TRSRTransformation thirdperson = TRSRTransformation.blockCenterToCorner(new TRSRTransformation(
new Vector3f(0, 1f / 16, -3f / 16),
TRSRTransformation.quatFromYXZDegrees(new Vector3f(-90, 0, 0)),
new Vector3f(0.55f, 0.55f, 0.55f),
null));
TRSRTransformation firstperson = TRSRTransformation.blockCenterToCorner(new TRSRTransformation(
new Vector3f(0, 4f / 16, 2f / 16),
TRSRTransformation.quatFromYXZDegrees(new Vector3f(0, -135, 25)),
new Vector3f(1.7f, 1.7f, 1.7f),
null));
DEFAULT_ITEM_STATE = Optional.<IModelState>of(new SimpleModelState(ImmutableMap.of(ItemCameraTransforms.TransformType.THIRD_PERSON, thirdperson, ItemCameraTransforms.TransformType.FIRST_PERSON, firstperson)));
}
{
TRSRTransformation thirdperson = TRSRTransformation.blockCenterToCorner(new TRSRTransformation(
new Vector3f(0, 1.25f / 16, -3.5f / 16),
TRSRTransformation.quatFromYXZDegrees(new Vector3f(0, 90, -35)),
new Vector3f(0.85f, 0.85f, 0.85f),
null));
TRSRTransformation firstperson = TRSRTransformation.blockCenterToCorner(new TRSRTransformation(
new Vector3f(0, 4f / 16, 2f / 16),
TRSRTransformation.quatFromYXZDegrees(new Vector3f(0, -135, 25)),
new Vector3f(1.7f, 1.7f, 1.7f),
null));
DEFAULT_TOOL_STATE = Optional.<IModelState>of(new SimpleModelState(ImmutableMap
.of(ItemCameraTransforms.TransformType.THIRD_PERSON, thirdperson, ItemCameraTransforms.TransformType.FIRST_PERSON, firstperson)));
}
}
/**
* Deseralizes a json in the format of { "textures": { "foo": "texture",... }}
* Ignores all invalid json
*/
public static class ModelTextureDeserializer implements JsonDeserializer<Map<String, String>> {
public static final ModelTextureDeserializer INSTANCE = new ModelTextureDeserializer();
private static final Gson GSON = new Gson();
@Override
public Map<String, String> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonObject obj = json.getAsJsonObject();
JsonElement texElem = obj.get("textures");
if(texElem == null) {
throw new JsonParseException("Missing textures entry in json");
}
return GSON.fromJson(texElem, maptype);
}
}
}
@@ -0,0 +1,78 @@
package slimeknights.mantle.client.gui;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* Represents a GUI element INSIDE the graphics file.
* The coordinates all refer to the coordinates inside the graphics!
*/
@SideOnly(Side.CLIENT)
public class GuiElement {
// this is totally completely ugly but it's a simple solution that doesn't clutter everything too much >_>
public static int defaultTexW = 256;
public static int defaultTexH = 256;
public final int x;
public final int y;
public final int w;
public final int h;
public int texW;
public int texH;
public GuiElement(int x, int y, int w, int h, int texW, int texH) {
this(x, y, w, h);
setTextureSize(texW, texH);
defaultTexW = texW;
defaultTexH = texH;
}
public GuiElement(int x, int y, int w, int h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
setTextureSize(defaultTexW, defaultTexH);
}
public GuiElement setTextureSize(int w, int h) {
texW = w;
texH = h;
return this;
}
public GuiElement shift(int xd, int yd) {
return new GuiElement(this.x + xd, this.y + yd, this.w, this.h, this.texW, this.texH);
}
/**
* Draws the element at the given x/y coordinates
*
* @param xPos X-Coordinate on the screen
* @param yPos Y-Coordinate on the screen
*/
public int draw(int xPos, int yPos) {
GuiScreen.drawModalRectWithCustomSizedTexture(xPos, yPos, x, y, w, h, texW, texH);
return w;
}
public static class Builder {
public int w;
public int h;
public Builder(int w, int h) {
this.w = w;
this.h = h;
}
public GuiElement get(int x, int y, int w, int h) {
return new GuiElement(x, y, w, h, this.w, this.h);
}
}
}
@@ -0,0 +1,73 @@
package slimeknights.mantle.client.gui;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class GuiElementScalable extends GuiElement {
public GuiElementScalable(int x, int y, int w, int h, int texW, int texH) {
super(x, y, w, h, texW, texH);
}
public GuiElementScalable(int x, int y, int w, int h) {
super(x, y, w, h);
}
public int drawScaledX(int xPos, int yPos, int width) {
for(int i = 0; i < width / w; i++) {
draw(xPos + i * w, yPos);
}
// remainder that doesn't fit total width
int remainder = width % w;
if(remainder > 0) {
GuiScreen.drawModalRectWithCustomSizedTexture(xPos + width - remainder, yPos, x, y, remainder, h, texW, texH);
}
return width;
}
public int drawScaledY(int xPos, int yPos, int height) {
for(int i = 0; i < height / h; i++) {
draw(xPos, yPos + i * h);
}
// remainder that doesn't fit total width
int remainder = height % h;
if(remainder > 0) {
GuiScreen.drawModalRectWithCustomSizedTexture(xPos, yPos + height - remainder, x, y, w, remainder, texW, texH);
}
return w;
}
public int drawScaled(int xPos, int yPos, int width, int height) {
// we draw full height row-wise
int full = height / this.h;
for(int i = 0; i < full; i++) {
drawScaledX(xPos, yPos + i * this.h, width);
}
yPos += full * this.h;
// and the remainder is drawn manually
int yRest = height % this.h;
// the same as drawScaledX but with the remaining height
for(int i = 0; i < width / w; i++) {
drawScaledY(xPos + i * w, yPos, yRest);
}
// remainder that doesn't fit total width
int remainder = width % w;
if(remainder > 0) {
GuiScreen.drawModalRectWithCustomSizedTexture(xPos + width - remainder, yPos, x, y, remainder, yRest, texW, texH);
}
return width;
}
public GuiElementScalable shift(int xd, int yd) {
GuiElementScalable element = new GuiElementScalable(this.x + xd, this.y + yd, this.w, this.h);
element.setTextureSize(this.texW, texH);
return element;
}
}
@@ -0,0 +1,133 @@
package slimeknights.mantle.client.gui;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.io.IOException;
import java.util.List;
// a sub-gui. Mostly the same as a separate GuiContainer, but doesn't do the calls that affect the game as if this were the only gui
@SideOnly(Side.CLIENT)
public abstract class GuiModule extends GuiContainer {
protected final GuiMultiModule parent;
// left or right of the parent
protected final boolean right;
// top or bottom of the parent
protected final boolean bottom;
public int yOffset = 0;
public int xOffset = 0;
public GuiModule(GuiMultiModule parent, Container container, boolean right, boolean bottom) {
super(container);
this.parent = parent;
this.right = right;
this.bottom = bottom;
}
public int guiRight() {
return guiLeft + xSize;
}
public int guiBottom() {
return guiTop + ySize;
}
@Override
public void initGui() {
this.guiLeft = (this.width - this.xSize) / 2;
this.guiTop = (this.height - this.ySize) / 2;
}
public void updatePosition(int parentX, int parentY, int parentSizeX, int parentSizeY) {
if(right) {
this.guiLeft = parentX + parentSizeX;
}
else {
this.guiLeft = parentX - this.xSize;
}
if(bottom) {
this.guiTop = parentY + parentSizeY - this.ySize;
}
else {
this.guiTop = parentY;
}
this.guiLeft += xOffset;
this.guiTop += yOffset;
}
public boolean shouldDrawSlot(Slot slot) {
return true;
}
public boolean isMouseInModule(int mouseX, int mouseY) {
return mouseX >= this.guiLeft && mouseX < this.guiRight() &&
mouseY >= this.guiTop && mouseY < this.guiBottom();
}
public boolean isMouseOverFullSlot(int mouseX, int mouseY) {
for(Slot slot : (List<Slot>)inventorySlots.inventorySlots) {
if(parent.isMouseOverSlot(slot, mouseX, mouseY) && slot.getHasStack()) {
return true;
}
}
return false;
}
/*
public void updateDragged(boolean dragSplitting, Set draggedSlots) {
this.dragSplitting = dragSplitting;
this.dragSplittingSlots.clear();
for(Object o : draggedSlots) {
if(o instanceof SlotWrapper)
this.dragSplittingSlots.add(((SlotWrapper) o).parent);
else
this.dragSplittingSlots.add(o);
}
}
*/
public void handleDrawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) {
this.drawGuiContainerBackgroundLayer(partialTicks, mouseX, mouseY);
}
public void handleDrawGuiContainerForegroundLayer(int mouseX, int mouseY) {
this.drawGuiContainerForegroundLayer(mouseX, mouseY);
}
/**
* Custom mouse click handling.
*
* @return True to prevent the main container handling the mouseclick
*/
public boolean handleMouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException {
return false;
}
/**
* Custom mouse click handling.
*
* @return True to prevent the main container handling the mouseclick
*/
public boolean handleMouseClickMove(int mouseX, int mouseY, int clickedMouseButton, long timeSinceLastClick) {
return false;
}
/**
* Custom mouse click handling.
*
* @return True to prevent the main container handling the mouseclick
*/
public boolean handleMouseReleased(int mouseX, int mouseY, int state) {
return false;
}
}
@@ -0,0 +1,362 @@
package slimeknights.mantle.client.gui;
import com.google.common.collect.Lists;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IChatComponent;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.Optional;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.List;
import slimeknights.mantle.Mantle;
import slimeknights.mantle.inventory.ContainerMultiModule;
import slimeknights.mantle.inventory.SlotWrapper;
@SideOnly(Side.CLIENT)
@Optional.Interface(iface = "codechicken.nei.api.INEIGuiHandler", modid = "NotEnoughItems")
// todo: NEI
public class GuiMultiModule extends GuiContainer { //implements INEIGuiHandler {
// NEI-stuff >:(
private static Field NEI_Manager;
static {
try {
NEI_Manager = GuiContainer.class.getDeclaredField("manager");
} catch(NoSuchFieldException e) {
NEI_Manager = null;
}
}
protected List<GuiModule> modules = Lists.newArrayList();
public int cornerX;
public int cornerY;
public int realWidth;
public int realHeight;
public GuiMultiModule(ContainerMultiModule container) {
super(container);
realWidth = -1;
realHeight = -1;
}
protected void addModule(GuiModule module) {
modules.add(module);
}
@Override
public void initGui() {
if(realWidth > -1) {
// has to be reset before calling initGui so the position is getting retained
xSize = realWidth;
ySize = realHeight;
}
super.initGui();
this.cornerX = this.guiLeft;
this.cornerY = this.guiTop;
this.realWidth = xSize;
this.realHeight = ySize;
for(GuiModule module : modules) {
updateSubmodule(module);
}
//this.guiLeft = this.guiTop = 0;
//this.xSize = width;
//this.ySize = height;
}
@Override
protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) {
for(GuiModule module : modules) {
module.handleDrawGuiContainerBackgroundLayer(partialTicks, mouseX, mouseY);
}
}
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
for(GuiModule module : modules) {
// set correct state for the module
GlStateManager.pushMatrix();
GlStateManager.translate(-this.guiLeft, -this.guiTop, 0.0F);
GlStateManager.translate(module.guiLeft, module.guiTop, 0.0F);
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
module.handleDrawGuiContainerForegroundLayer(mouseX, mouseY);
GlStateManager.popMatrix();
}
drawContainerName();
drawPlayerInventoryName();
}
protected void drawBackground(ResourceLocation background) {
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
this.mc.getTextureManager().bindTexture(background);
this.drawTexturedModalRect(cornerX, cornerY, 0, 0, realWidth, realHeight);
}
protected void drawContainerName() {
ContainerMultiModule multiContainer = (ContainerMultiModule) this.inventorySlots;
IChatComponent localizedName = multiContainer.getInventoryDisplayName();
if(localizedName != null) {
this.fontRendererObj.drawString(localizedName.getUnformattedText(), 8, 6, 0x404040);
}
}
protected void drawPlayerInventoryName() {
String localizedName = Minecraft.getMinecraft().thePlayer.inventory.getDisplayName().getUnformattedText();
this.fontRendererObj.drawString(localizedName, 8, this.ySize - 96 + 2, 0x404040);
}
@Override
public void setWorldAndResolution(Minecraft mc, int width, int height) {
super.setWorldAndResolution(mc, width, height);
// workaround for NEIs ASM hax. sigh.
try {
for(GuiModule module : modules) {
module.setWorldAndResolution(mc, width, height);
if(NEI_Manager != null) {
NEI_Manager.set(module, NEI_Manager.get(this));
}
updateSubmodule(module);
}
} catch(IllegalAccessException e) {
Mantle.logger.error(e);
}
}
@Override
public void onResize(Minecraft mc, int width, int height) {
super.onResize(mc, width, height);
for(GuiModule module : modules) {
module.onResize(mc, width, height);
updateSubmodule(module);
}
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
int oldX = guiLeft;
int oldY = guiTop;
int oldW = xSize;
int oldH = ySize;
guiLeft = cornerX;
guiTop = cornerY;
xSize = realWidth;
ySize = realHeight;
super.drawScreen(mouseX, mouseY, partialTicks);
guiLeft = oldX;
guiTop = oldY;
xSize = oldW;
ySize = oldH;
}
// needed to get the correct slot on clicking
@Override
protected boolean isPointInRegion(int left, int top, int right, int bottom, int pointX, int pointY) {
pointX -= this.cornerX;
pointY -= this.cornerY;
return pointX >= left - 1 && pointX < left + right + 1 && pointY >= top - 1 && pointY < top + bottom + 1;
}
protected void updateSubmodule(GuiModule module) {
module.updatePosition(this.cornerX, this.cornerY, this.realWidth, this.realHeight);
if(module.guiLeft < this.guiLeft) {
this.xSize += this.guiLeft - module.guiLeft;
this.guiLeft = module.guiLeft;
}
if(module.guiTop < this.guiTop) {
this.ySize += this.guiTop - module.guiTop;
this.guiTop = module.guiTop;
}
if(module.guiRight() > this.guiLeft + this.xSize) {
xSize = module.guiRight() - this.guiLeft;
}
if(module.guiBottom() > this.guiTop + this.ySize) {
ySize = module.guiBottom() - this.guiTop;
}
}
@Override
public void drawSlot(Slot slotIn) {
GuiModule module = getModuleForSlot(slotIn.slotNumber);
if(module != null) {
Slot slot = slotIn;
// unwrap for the call to the module
if(slotIn instanceof SlotWrapper) {
slot = ((SlotWrapper) slotIn).parent;
}
if(!module.shouldDrawSlot(slot)) {
return;
}
}
// update slot positions
if(slotIn instanceof SlotWrapper) {
slotIn.xDisplayPosition = ((SlotWrapper) slotIn).parent.xDisplayPosition;
slotIn.yDisplayPosition = ((SlotWrapper) slotIn).parent.yDisplayPosition;
}
super.drawSlot(slotIn);
}
@Override
public boolean isMouseOverSlot(Slot slotIn, int mouseX, int mouseY) {
GuiModule module = getModuleForSlot(slotIn.slotNumber);
// mouse inside the module of the slot?
if(module != null) {
Slot slot = slotIn;
// unwrap for the call to the module
if(slotIn instanceof SlotWrapper) {
slot = ((SlotWrapper) slotIn).parent;
}
if(!module.shouldDrawSlot(slot)) {
return false;
}
}
return super.isMouseOverSlot(slotIn, mouseX, mouseY);
}
@Override
protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException {
GuiModule module = getModuleForPoint(mouseX, mouseY);
if(module != null) {
if(module.handleMouseClicked(mouseX, mouseY, mouseButton)) {
return;
}
}
super.mouseClicked(mouseX, mouseY, mouseButton);
}
@Override
protected void mouseClickMove(int mouseX, int mouseY, int clickedMouseButton, long timeSinceLastClick) {
GuiModule module = getModuleForPoint(mouseX, mouseY);
if(module != null) {
if(module.handleMouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick)) {
return;
}
}
super.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick);
}
@Override
protected void mouseReleased(int mouseX, int mouseY, int state) {
GuiModule module = getModuleForPoint(mouseX, mouseY);
if(module != null) {
if(module.handleMouseReleased(mouseX, mouseY, state)) {
return;
}
}
super.mouseReleased(mouseX, mouseY, state);
}
protected GuiModule getModuleForPoint(int x, int y) {
for(GuiModule module : modules) {
if(this.isPointInRegion(module.guiLeft, module.guiTop, module.guiRight(), module.guiBottom(),
x + this.cornerX, y + this.cornerY)) {
return module;
}
}
return null;
}
protected GuiModule getModuleForSlot(int slotNumber) {
return getModuleForContainer(getContainer().getSlotContainer(slotNumber));
}
protected GuiModule getModuleForContainer(Container container) {
for(GuiModule module : modules) {
if(module.inventorySlots == container) {
return module;
}
}
return null;
}
protected ContainerMultiModule getContainer() {
return (ContainerMultiModule) inventorySlots;
}
/* NEI INTEGRATION */
// todo: NEI
/*
@Override
@Optional.Method(modid = "NotEnoughItems")
public VisiblityData modifyVisiblity(GuiContainer guiContainer, VisiblityData visiblityData) {
int x = LayoutManager.stateButtons[0].x + LayoutManager.stateButtons[0].w;
int x2 = LayoutManager.timeButtons[3].x + LayoutManager.timeButtons[3].w;
int y2 = LayoutManager.heal.y + LayoutManager.heal.h;
for(GuiModule module : modules) {
if(x > module.guiLeft) {
visiblityData.showStateButtons = false;
}
if(x2 > module.guiLeft && y2 > module.guiTop) {
visiblityData.showUtilityButtons = false;
}
}
return visiblityData;
}
@Override
@Optional.Method(modid = "NotEnoughItems")
public Iterable<Integer> getItemSpawnSlots(GuiContainer guiContainer, ItemStack itemStack) {
return null;
}
@Override
@Optional.Method(modid = "NotEnoughItems")
public List<TaggedInventoryArea> getInventoryAreas(GuiContainer guiContainer) {
return Collections.EMPTY_LIST;
}
@Override
@Optional.Method(modid = "NotEnoughItems")
public boolean handleDragNDrop(GuiContainer guiContainer, int x, int y, ItemStack itemStack, int k) {
return false;
}
@Override
@Optional.Method(modid = "NotEnoughItems")
public boolean hideItemPanelSlot(GuiContainer guiContainer, int x, int y, int w, int h) {
for(GuiModule module : modules) {
// check if the panel overlaps the module (check totally not stolen from stackoverflow)
if(module.guiLeft < x + w && module.guiRight() > x &&
module.guiTop < y + h && module.guiBottom() > y) {
return true;
}
}
return false;
}
*/
}
@@ -0,0 +1,26 @@
package slimeknights.mantle.client.gui;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public abstract class GuiWidget {
public int xPos;
public int yPos;
public int height;
public int width;
public abstract void draw();
/** Where the part will be drawn. Upper left corner. */
public void setPosition(int x, int y) {
this.xPos = x;
this.yPos = y;
}
public void setSize(int width, int height) {
this.width = width;
this.height = height;
}
}
@@ -0,0 +1,255 @@
package slimeknights.mantle.client.gui;
import net.minecraft.util.MathHelper;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.input.Mouse;
// a vertical slider!
@SideOnly(Side.CLIENT)
public class GuiWidgetSlider extends GuiWidget {
// gui info
public final GuiElement slider;
public final GuiElement sliderHighlighted;
public final GuiElement sliderDisabled;
public final GuiElement slideBarTop;
public final GuiElement slideBarBottom;
public final GuiElementScalable slideBar;
// slider info
protected int minValue;
protected int maxValue;
protected int increment;
// positioning info
protected int currentValue;
public int sliderOffset; // x-offset of the slider to the left edge of the slideBar
protected boolean enabled;
protected boolean hidden;
protected boolean isScrolling;
protected boolean isHighlighted;
// where the slider was clicked on the slider itself (not on the bar, on the thing that slides)
private int clickX;
private int clickY;
private boolean clickedBar; // if the bar has already been clicked and not released
public GuiWidgetSlider(GuiElement slider, GuiElement sliderHighlighted, GuiElement sliderDisabled, GuiElement slideBarTop, GuiElement slideBarBottom, GuiElementScalable slideBar) {
this.slider = slider;
this.sliderHighlighted = sliderHighlighted;
this.sliderDisabled = sliderDisabled;
this.slideBar = slideBar;
this.slideBarTop = slideBarTop;
this.slideBarBottom = slideBarBottom;
height = slideBar.h;
width = slideBar.w;
currentValue = minValue = 0;
maxValue = slideBar.h;
increment = 1;
sliderOffset = MathHelper.abs_int(slideBar.w - slider.w) / 2;
isScrolling = false;
isHighlighted = false;
enabled = true;
hidden = false;
}
/** Sets the height of the whole slider and slidebar */
public void setSize(int height) {
this.height = height;
}
/** specifies the values that the slider represents */
public void setSliderParameters(int min, int max, int stepsize) {
this.minValue = min;
this.maxValue = max;
this.increment = stepsize;
// just in case
setSliderValue(currentValue);
}
public int getValue() {
return currentValue;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public void enable() {
this.enabled = true;
}
public void disable() {
this.enabled = false;
}
public boolean isEnabled() {
return this.enabled;
}
public void setHidden(boolean hidden) {
this.hidden = hidden;
}
public void hide() {
this.hidden = true;
}
public void show() {
this.hidden = false;
}
public boolean isHidden() {
return this.hidden;
}
public void draw() {
if(hidden) {
return;
}
// slidebar background
slideBarTop.draw(xPos, yPos);
slideBar.drawScaledY(xPos, yPos + slideBarTop.h, getUsableSlidebarHeight());
slideBarBottom.draw(xPos, yPos + height - slideBarBottom.h);
int x = xPos + sliderOffset;
int y = yPos + getSliderTop();
// the slider depending on state
if(enabled) {
if(isScrolling) {
sliderDisabled.draw(x, y);
}
else if(isHighlighted) {
sliderHighlighted.draw(x, y);
}
else {
slider.draw(x, y);
}
}
else {
sliderDisabled.draw(x, y);
}
}
public void update(int mouseX, int mouseY, boolean useMouseWheel) {
if(!enabled || hidden) {
return;
}
boolean mouseDown = Mouse.isButtonDown(0); // left mouse button
int wheel = Mouse.getDWheel();
if(useMouseWheel) {
if(wheel > 0) {
decrement();
return;
}
else if(wheel < 0) {
increment();
return;
}
}
// relative position inside the widget
int x = mouseX - xPos;
int y = mouseY - yPos;
// reset click data
if(!mouseDown && clickedBar) {
clickedBar = false;
}
// button not pressed and scrolling -> stop scrolling
if(!mouseDown && isScrolling) {
isScrolling = false;
}
// button pressed and scrolling -> update position of slider
else if(isScrolling) {
float d = maxValue - minValue;
float val = (float) (y - clickY) / (float) (getUsableSlidebarHeight() - slider.h);
val *= d;
if(val < (float) increment / 2f) {
// < 1/2 increment
setSliderValue(minValue);
}
else if(val > maxValue - ((float) increment / 2f)) {
// > max-1/2 increment
setSliderValue(maxValue);
}
else {
// in between
setSliderValue((int) (minValue + (float) increment * Math.round(val)));
}
}
// not scrolling yet but possibly inside the slider
else if(x >= 0 && y >= getSliderTop() &&
x - sliderOffset <= slider.w && y <= getSliderTop() + slider.h) {
isHighlighted = true;
if(mouseDown) {
isScrolling = true;
clickX = x - sliderOffset;
clickY = y - getSliderTop();
}
}
// not on the slider but clicked on the bar
else if(mouseDown && !clickedBar &&
x >= 0 && y >= 0 &&
x <= slideBar.w && y <= height) {
if(y < getSliderTop()) {
decrement();
}
else {
increment();
}
clickedBar = true;
}
else {
isHighlighted = false;
}
}
public int increment() {
setSliderValue(currentValue + increment);
return currentValue;
}
public int decrement() {
setSliderValue(currentValue - increment);
return currentValue;
}
public int setSliderValue(int val) {
if(val > maxValue) {
val = maxValue;
}
else if(val < minValue) {
val = minValue;
}
currentValue = val;
return currentValue;
}
private int getSliderTop() {
float d = maxValue - minValue;
d = (float) (currentValue - minValue) / d;
d *= getUsableSlidebarHeight() - slider.h;
return (int) d + slideBarTop.h;
}
private int getUsableSlidebarHeight() {
return height - slideBarTop.h - slideBarBottom.h;
}
}
@@ -0,0 +1,171 @@
package slimeknights.mantle.client.gui;
import com.google.common.collect.Lists;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.input.Mouse;
import java.util.List;
@SideOnly(Side.CLIENT)
public class GuiWidgetTabs extends GuiWidget {
private static final ResourceLocation
creativeInventoryTabs = new ResourceLocation("textures/gui/container/creative_inventory/tabs.png");
private final GuiElement[] tabActive = new GuiElement[3];
private final GuiElement[] tab = new GuiElement[3];
// change this if you need different tabs
public ResourceLocation tabsResource = creativeInventoryTabs;
// changes the y-offset of the tab row
public int yOffset = 4;
// space between 2 tabs
public int spacing = 2;
public int selected;
public int highlighted;
protected List<ItemStack> icons = Lists.newArrayList();
private final GuiMultiModule parent;
private boolean clicked = false;
public GuiWidgetTabs(GuiMultiModule parent, GuiElement tabLeft, GuiElement tabCenter, GuiElement tabRight, GuiElement activeLeft, GuiElement activeCenter, GuiElement activeRight) {
this.parent = parent;
this.tab[0] = tabLeft;
this.tab[1] = tabCenter;
this.tab[2] = tabRight;
this.tabActive[0] = activeLeft;
this.tabActive[1] = activeCenter;
this.tabActive[2] = activeRight;
selected = 0;
}
public void addTab(ItemStack icon) {
icons.add(icon);
}
public void clear() {
selected = 0;
icons.clear();
}
public void update(int mouseX, int mouseY) {
boolean mouseDown = Mouse.isButtonDown(0); // left mouse button
// did we click on a tab?
mouseX -= this.xPos;
mouseY -= this.yPos;
// update highlighted
highlighted = -1;
if(mouseY >= 0 && mouseY <= tab[1].h) {
// which one did we click?
int x = 0;
for(int i = 0; i < icons.size(); i++) {
// clicking on spacing has no effect
if(mouseX >= x && mouseX < x + tab[1].w) {
highlighted = i;
break;
}
x += tab[1].w;
x += spacing;
}
}
// already clicked
if(clicked) {
// still clicking
if(mouseDown) {
return;
}
// release click
else {
clicked = false;
return;
}
}
// new click
else if(mouseDown) {
clicked = true;
}
// no click - do nothing
else {
return;
}
// was new click, select highlighted
if(highlighted > -1) {
selected = highlighted;
}
}
@Override
public void draw() {
int y = yPos + yOffset;
for(int i = 0; i < icons.size(); i++) {
int x = xPos + i * tab[0].w;
if(i > 0) {
x += i * spacing;
}
GuiElement[] toDraw;
if(i == selected) {
toDraw = tabActive;
}
else {
toDraw = tab;
}
GuiElement actualTab;
if(i == 0 && x == parent.cornerX) {
actualTab = toDraw[0];
}
else if(x == parent.cornerX + parent.width) {
actualTab = toDraw[2];
}
else {
actualTab = toDraw[1];
}
// todo: draw all the tabs first and then all the itemstacks so it doesn't have to switch texture in between all the time
// rebind texture from drawing an itemstack
Minecraft.getMinecraft().getTextureManager().bindTexture(tabsResource);
actualTab.draw(x, y);
ItemStack icon = icons.get(i);
if(icon != null) {
RenderHelper.enableGUIStandardItemLighting();
drawItemStack(icon, x + (actualTab.w - 16) / 2, y + (actualTab.h - 16) / 2);
RenderHelper.disableStandardItemLighting();
//RenderHelper.enableStandardItemLighting();
}
}
}
// guiContainer.drawItemStack
private void drawItemStack(ItemStack stack, int x, int y) {
RenderItem itemRender = Minecraft.getMinecraft().getRenderItem();
GlStateManager.translate(0.0F, 0.0F, 32.0F);
itemRender.zLevel = 200;
//FontRenderer font = stack.getItem().getFontRenderer(stack);
itemRender.renderItemAndEffectIntoGUI(stack, x, y);
//this.itemRender.renderItemOverlayIntoGUI(font, stack, x, y - (this.draggedStack == null ? 0 : 8), altText);
//this.zLevel = 0.0F;
itemRender.zLevel = 0.0F;
}
}
@@ -0,0 +1,88 @@
package slimeknights.mantle.client.model;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.client.resources.model.IBakedModel;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.client.model.IFlexibleBakedModel;
import net.minecraftforge.client.model.IPerspectiveAwareModel;
import net.minecraftforge.client.model.TRSRTransformation;
import org.apache.commons.lang3.tuple.Pair;
import java.util.List;
import javax.vecmath.Matrix4f;
import javax.vecmath.Vector3f;
/**
* Takes a blockmodel and applies the standard-block-perspective for third_person to it
*/
public class BlockItemModelWrapper implements IPerspectiveAwareModel, IFlexibleBakedModel {
// copied from the forge variants V1 default-block transform
public static final Matrix4f THIRD_PERSON_BLOCK_TRANSFORM = new TRSRTransformation(
new Vector3f(0, 1.5f / 16, -2.75f / 16), // translation
TRSRTransformation.quatFromYXZDegrees(new Vector3f(10, -45, 170)), // rotation
new Vector3f(0.375f, 0.375f, 0.375f), // scale
null).getMatrix();
private final IFlexibleBakedModel parent;
public BlockItemModelWrapper(IFlexibleBakedModel parent) {
this.parent = parent;
}
@Override
public Pair<? extends IFlexibleBakedModel, Matrix4f> handlePerspective(ItemCameraTransforms.TransformType cameraTransformType) {
Matrix4f matrix = null;
// fix transformation in hand
if(cameraTransformType == ItemCameraTransforms.TransformType.THIRD_PERSON) {
matrix = THIRD_PERSON_BLOCK_TRANSFORM;
}
return Pair.of(this, matrix);
}
@Override
public List<BakedQuad> getFaceQuads(EnumFacing p_177551_1_) {
return parent.getFaceQuads(p_177551_1_);
}
@Override
public List<BakedQuad> getGeneralQuads() {
return parent.getGeneralQuads();
}
@Override
public VertexFormat getFormat() {
return parent.getFormat();
}
@Override
public boolean isAmbientOcclusion() {
return false;
}
@Override
public boolean isGui3d() {
return parent.isGui3d();
}
@Override
public boolean isBuiltInRenderer() {
return parent.isBuiltInRenderer();
}
@Override
public TextureAtlasSprite getParticleTexture() {
return parent.getParticleTexture();
}
@Override
public ItemCameraTransforms getItemCameraTransforms() {
return parent.getItemCameraTransforms();
}
}
@@ -0,0 +1,166 @@
package slimeknights.mantle.client.model;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.client.renderer.vertex.VertexFormatElement;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.client.model.IFlexibleBakedModel;
import net.minecraftforge.client.model.TRSRTransformation;
import net.minecraftforge.client.model.pipeline.UnpackedBakedQuad;
import net.minecraftforge.client.model.pipeline.VertexTransformer;
import java.util.EnumMap;
import java.util.List;
import javax.vecmath.Matrix3f;
import javax.vecmath.Matrix4f;
import javax.vecmath.Vector3f;
import javax.vecmath.Vector4f;
// for those wondering TRSR stands for Translation Rotation Scale Rotation
public class TRSRBakedModel implements IFlexibleBakedModel {
protected final ImmutableList<BakedQuad> general;
protected final ImmutableMap<EnumFacing, ImmutableList<BakedQuad>> faces;
protected final IFlexibleBakedModel original;
public TRSRBakedModel(IFlexibleBakedModel original, float x, float y, float z, float scale) {
this(original, x, y, z, 0, 0, 0, scale, scale, scale);
}
public TRSRBakedModel(IFlexibleBakedModel original, float x, float y, float z, float rotX, float rotY, float rotZ, float scale) {
this(original, x, y, z, rotX, rotY, rotZ, scale, scale, scale);
}
public TRSRBakedModel(IFlexibleBakedModel original, float x, float y, float z, float rotX, float rotY, float rotZ, float scaleX, float scaleY, float scaleZ) {
this(original, new TRSRTransformation(new Vector3f(x, y, z),
null,
new Vector3f(scaleX, scaleY, scaleZ),
TRSRTransformation.quatFromYXZ(rotY, rotX, rotZ)));
}
public TRSRBakedModel(IFlexibleBakedModel original, TRSRTransformation transform) {
this.original = original;
ImmutableList.Builder<BakedQuad> builder;
builder = ImmutableList.builder();
transform = TRSRTransformation.blockCenterToCorner(transform);
// face quads
EnumMap<EnumFacing, ImmutableList<BakedQuad>> faces = Maps.newEnumMap(EnumFacing.class);
for(EnumFacing face : EnumFacing.values()) {
if(!original.isBuiltInRenderer()) {
for(BakedQuad quad : original.getFaceQuads(face)) {
Transformer transformer = new Transformer(transform, original.getFormat());
quad.pipe(transformer);
builder.add(transformer.build());
}
}
//faces.put(face, builder.build());
faces.put(face, ImmutableList.<BakedQuad>of());
}
// general quads
//builder = ImmutableList.builder();
if(!original.isBuiltInRenderer()) {
for(BakedQuad quad : original.getGeneralQuads()) {
Transformer transformer = new Transformer(transform, original.getFormat());
quad.pipe(transformer);
builder.add(transformer.build());
}
}
this.general = builder.build();
this.faces = Maps.immutableEnumMap(faces);
}
@Override
public List<BakedQuad> getFaceQuads(EnumFacing side) {
return faces.get(side);
}
@Override
public List<BakedQuad> getGeneralQuads() {
return general;
}
@Override
public boolean isAmbientOcclusion() {
return false;
}
@Override
public boolean isGui3d() {
return original.isGui3d();
}
@Override
public boolean isBuiltInRenderer() {
return original.isBuiltInRenderer();
}
@Override
public TextureAtlasSprite getParticleTexture() {
return original.getParticleTexture();
}
@Override
public ItemCameraTransforms getItemCameraTransforms() {
return original.getItemCameraTransforms();
}
@Override
public VertexFormat getFormat() {
return original.getFormat();
}
public static class Transformer extends VertexTransformer {
protected Matrix4f transformation;
protected Matrix3f normalTransformation;
public Transformer(TRSRTransformation transformation, VertexFormat format) {
super(new UnpackedBakedQuad.Builder(format));
// position transform
this.transformation = transformation.getMatrix();
// normal transform
this.normalTransformation = new Matrix3f();
this.transformation.getRotationScale(this.normalTransformation);
this.normalTransformation.invert();
this.normalTransformation.transpose();
}
@Override
public void put(int element, float... data) {
VertexFormatElement.EnumUsage usage = parent.getVertexFormat().getElement(element).getUsage();
// transform normals and position
if(usage == VertexFormatElement.EnumUsage.POSITION && data.length >= 3) {
Vector4f vec = new Vector4f(data);
vec.setW(1.0f);
transformation.transform(vec);
data = new float[4];
vec.get(data);
}
else if(usage == VertexFormatElement.EnumUsage.NORMAL && data.length >= 3) {
Vector3f vec = new Vector3f(data);
normalTransformation.transform(vec);
vec.normalize();
data = new float[4];
vec.get(data);
}
super.put(element, data);
}
public UnpackedBakedQuad build() {
return ((UnpackedBakedQuad.Builder)parent).build();
}
}
}
@@ -0,0 +1,4 @@
package slimeknights.mantle.common;
public class CommonProxy {
}
@@ -0,0 +1,31 @@
package slimeknights.mantle.common;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.IGuiHandler;
/**
* A GuiHandler implementation that forwards the container/gui creation to the TEs, eliminating the need for GUI IDs.
*/
public class GuiHandler implements IGuiHandler {
@Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
TileEntity te = world.getTileEntity(new BlockPos(x, y, z));
if(te instanceof IInventoryGui) {
return ((IInventoryGui) te).createContainer(player.inventory, world, new BlockPos(x, y, z));
}
return null;
}
@Override
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
TileEntity te = world.getTileEntity(new BlockPos(x, y, z));
if(te instanceof IInventoryGui) {
return ((IInventoryGui) te).createGui(player.inventory, world, new BlockPos(x, y, z));
}
return null;
}
}
@@ -0,0 +1,20 @@
package slimeknights.mantle.common;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* Used in conjunction with GuiHandler. Implement in a TE to have it open its GUI/Container.
*/
public interface IInventoryGui {
Container createContainer(InventoryPlayer inventoryplayer, World world, BlockPos pos);
@SideOnly(Side.CLIENT)
GuiContainer createGui(InventoryPlayer inventoryplayer, World world, BlockPos pos);
}
@@ -0,0 +1,301 @@
package slimeknights.mantle.inventory;
import com.google.common.collect.Lists;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import net.minecraft.util.IChatComponent;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import java.util.List;
import slimeknights.mantle.util.SlimeknightException;
/** Same as Container but provides some extra functionality to simplify things */
public abstract class BaseContainer<T extends TileEntity & IInventory> extends Container {
protected double maxDist = 8 * 8; // 8 blocks
protected T tile;
protected final Block originalBlock; // used to check if the block we interacted with got broken
protected final BlockPos pos;
protected final World world;
public List<Container> subContainers = Lists.newArrayList();
public BaseContainer(T tile) {
this.tile = tile;
this.world = tile.getWorld();
this.pos = tile.getPos();
this.originalBlock = world.getBlockState(pos).getBlock();
}
public void syncOnOpen(EntityPlayerMP playerOpened) {
// find another player that already has the gui for this tile open
WorldServer server = playerOpened.getServerForPlayer();
for(EntityPlayer player : (List<EntityPlayer>) server.playerEntities) {
if(player == playerOpened) {
continue;
}
if(player.openContainer instanceof BaseContainer) {
if(this.sameGui((BaseContainer<T>) player.openContainer)) {
syncWithOtherContainer((BaseContainer<T>) player.openContainer, playerOpened);
return;
}
}
}
// no player has a container open for the tile
syncNewContainer(playerOpened);
}
public T getTile() {
return tile;
}
/**
* Called when the container is opened and another player already has a container for this tile open
* Sync to the same state here.
*/
protected void syncWithOtherContainer(BaseContainer<T> otherContainer, EntityPlayerMP player) {
}
/**
* Called when the container is opened and no other player has it open.
* Set the default state here.
*/
protected void syncNewContainer(EntityPlayerMP player) {
}
public boolean sameGui(BaseContainer otherContainer) {
return this.tile == otherContainer.tile;
}
@Override
public boolean canInteractWith(EntityPlayer playerIn) {
Block block = world.getBlockState(pos).getBlock();
// does the block we interacted with still exist?
if(block == Blocks.air || block != originalBlock) {
return false;
}
// too far away from block?
return playerIn.getDistanceSq((double) pos.getX() + 0.5d,
(double) pos.getY() + 0.5d,
(double) pos.getZ() + 0.5d) <= maxDist;
}
@SuppressWarnings("unchecked")
public List<ItemStack> getInventory() {
return (List<ItemStack>) super.getInventory();
}
public IChatComponent getInventoryDisplayName() {
if(tile instanceof IInventory) {
return ((IInventory) tile).getDisplayName();
}
return null;
}
// standard yOffset calculation for chestlike inventories:
// yOffset = (numRows - 4) * 18; (the -4 because of the 3 rows of inventory + 1 row of hotbar)
protected int playerInventoryStart = -1;
/**
* Draws the player inventory starting at the given position
*
* @param playerInventory The players inventory
* @param xCorner Default Value: 8
* @param yCorner Default Value: (rows - 4) * 18 + 103
*/
protected void addPlayerInventory(InventoryPlayer playerInventory, int xCorner, int yCorner) {
int index = 9;
int start = this.inventorySlots.size();
for(int row = 0; row < 3; row++) {
for(int col = 0; col < 9; col++) {
this.addSlotToContainer(new Slot(playerInventory, index, xCorner + col * 18, yCorner + row * 18));
index++;
}
}
index = 0;
for(int col = 0; col < 9; col++) {
this.addSlotToContainer(new Slot(playerInventory, index, xCorner + col * 18, yCorner + 58));
index++;
}
playerInventoryStart = start;
}
@Override
protected Slot addSlotToContainer(Slot slotIn) {
if(playerInventoryStart >= 0) {
throw new SlimeknightException("BaseContainer: Player inventory has to be last slots. Add all slots before adding the player inventory.");
}
return super.addSlotToContainer(slotIn);
}
@Override
public ItemStack transferStackInSlot(EntityPlayer playerIn, int index) {
// we can only support inventory <-> playerInventory
if(playerInventoryStart < 0) {
// so we don't do anything if no player inventory is present because we don't know what to do
return null;
}
ItemStack itemstack = null;
Slot slot = (Slot) this.inventorySlots.get(index);
// slot that was clicked on not empty?
if(slot != null && slot.getHasStack()) {
ItemStack itemstack1 = slot.getStack();
itemstack = itemstack1.copy();
int end = this.inventorySlots.size();
// Is it a slot in the main inventory? (aka not player inventory)
if(index < playerInventoryStart) {
// try to put it into the player inventory (if we have a player inventory)
if(!this.mergeItemStack(itemstack1, playerInventoryStart, end, true)) {
return null;
}
}
// Slot is in the player inventory (if it exists), transfer to main inventory
else if(!this.mergeItemStack(itemstack1, 0, playerInventoryStart, false)) {
return null;
}
if(itemstack1.stackSize == 0) {
slot.putStack(null);
}
else {
slot.onSlotChanged();
}
}
return itemstack;
}
// Fix for a vanilla bug: doesn't take Slot.getMaxStackSize into account
protected boolean mergeItemStack(ItemStack stack, int startIndex, int endIndex, boolean useEndIndex) {
return mergeItemStackRefill(stack, startIndex, endIndex, useEndIndex)
|| mergeItemStackMove(stack, startIndex, endIndex, useEndIndex);
}
// only refills items that are already present
protected boolean mergeItemStackRefill(ItemStack stack, int startIndex, int endIndex, boolean useEndIndex) {
if(stack.stackSize <= 0) {
return false;
}
boolean flag1 = false;
int k = startIndex;
if(useEndIndex) {
k = endIndex - 1;
}
Slot slot;
ItemStack itemstack1;
if(stack.isStackable()) {
while(stack.stackSize > 0 && (!useEndIndex && k < endIndex || useEndIndex && k >= startIndex)) {
slot = (Slot) this.inventorySlots.get(k);
itemstack1 = slot.getStack();
if(itemstack1 != null && itemstack1.getItem() == stack.getItem() && (!stack.getHasSubtypes()
|| stack.getMetadata() == itemstack1
.getMetadata()) && ItemStack.areItemStackTagsEqual(stack, itemstack1)) {
int l = itemstack1.stackSize + stack.stackSize;
int limit = Math.min(stack.getMaxStackSize(), slot.getItemStackLimit(stack));
if(l <= limit) {
stack.stackSize = 0;
itemstack1.stackSize = l;
slot.onSlotChanged();
flag1 = true;
}
else if(itemstack1.stackSize < limit) {
stack.stackSize -= limit - itemstack1.stackSize;
itemstack1.stackSize = limit;
slot.onSlotChanged();
flag1 = true;
}
}
if(useEndIndex) {
--k;
}
else {
++k;
}
}
}
return flag1;
}
// only moves items into empty slots
protected boolean mergeItemStackMove(ItemStack stack, int startIndex, int endIndex, boolean useEndIndex) {
if(stack.stackSize <= 0) {
return false;
}
boolean flag1 = false;
int k;
if(useEndIndex) {
k = endIndex - 1;
}
else {
k = startIndex;
}
while(!useEndIndex && k < endIndex || useEndIndex && k >= startIndex) {
Slot slot = (Slot) this.inventorySlots.get(k);
ItemStack itemstack1 = slot.getStack();
if(itemstack1 == null && slot.isItemValid(stack)) // Forge: Make sure to respect isItemValid in the slot.
{
int limit = slot.getItemStackLimit(stack);
ItemStack stack2 = stack.copy();
if(stack2.stackSize > limit) {
stack2.stackSize = limit;
stack.stackSize -= limit;
}
else {
stack.stackSize = 0;
}
slot.putStack(stack2);
slot.onSlotChanged();
flag1 = true;
if(stack.stackSize == 0) {
break;
}
}
if(useEndIndex) {
--k;
}
else {
++k;
}
}
return flag1;
}
}
@@ -0,0 +1,284 @@
package slimeknights.mantle.inventory;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.tuple.Pair;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class ContainerMultiModule<T extends TileEntity & IInventory> extends BaseContainer<T> {
public List<Container> subContainers = Lists.newArrayList();
// lookup used to redirect slot specific things to the appropriate container
protected Map<Integer, Container> slotContainerMap = Maps.newHashMap();
protected Map<Container, Pair<Integer, Integer>> subContainerSlotRanges = Maps.newHashMap();
protected int subContainerSlotStart = -1;
protected Set<Container> shiftClickContainers = Sets.newHashSet();
public ContainerMultiModule(T tile) {
super(tile);
}
/**
* @param subcontainer The container to add
* @param preferForShiftClick If true shift clicking on slots of the main-container will try to move to this module before the player inventory
*/
public void addSubContainer(Container subcontainer, boolean preferForShiftClick) {
if(subContainers.isEmpty()) {
subContainerSlotStart = inventorySlots.size();
}
subContainers.add(subcontainer);
if(preferForShiftClick) {
shiftClickContainers.add(subcontainer);
}
int begin = inventorySlots.size();
for(Object slot : subcontainer.inventorySlots) {
SlotWrapper wrapper = new SlotWrapper((Slot) slot);
addSlotToContainer(wrapper);
slotContainerMap.put(wrapper.slotNumber, subcontainer);
}
int end = inventorySlots.size();
subContainerSlotRanges.put(subcontainer, Pair.of(begin, end));
}
public <TC extends Container> TC getSubContainer(Class<TC> clazz) {
return getSubContainer(clazz, 0);
}
public <TC extends Container> TC getSubContainer(Class<TC> clazz, int index) {
for(Container sub : subContainers) {
if(clazz.isAssignableFrom(sub.getClass())) {
index--;
}
if(index < 0) {
return (TC) sub;
}
}
return null;
}
public Container getSlotContainer(int slotNumber) {
if(slotContainerMap.containsKey(slotNumber)) {
return slotContainerMap.get(slotNumber);
}
return this;
}
@Override
public boolean canInteractWith(EntityPlayer playerIn) {
// check if subcontainers are valid
for(Container sub : subContainers) {
if(!sub.canInteractWith(playerIn)) {
return false;
}
}
return super.canInteractWith(playerIn);
}
@Override
public void onContainerClosed(EntityPlayer playerIn) {
for(Container sub : subContainers) {
sub.onContainerClosed(playerIn);
}
super.onContainerClosed(playerIn);
}
@Override
public ItemStack slotClick(int slotId, int clickedButton, int mode, EntityPlayer playerIn) {
if(slotId == -999 && mode == 5) {
for(Container container : subContainers) {
container.slotClick(slotId, clickedButton, mode, playerIn);
}
}
/*
if(slotContainerMap.containsKey(slotId)) {
int actualId = slotId;
if(this.inventorySlots.get(slotId) instanceof SlotWrapper) {
actualId = ((SlotWrapper) this.inventorySlots.get(slotId)).parent.slotNumber;
}
return slotContainerMap.get(slotId).slotClick(actualId, clickedButton, mode, playerIn);
}*/
return super.slotClick(slotId, clickedButton, mode, playerIn);
}
// More sophisticated version of the one in BaseContainer
// Takes submodules into account when shiftclicking!
@Override
public ItemStack transferStackInSlot(EntityPlayer playerIn, int index) {
Slot slot = (Slot) this.inventorySlots.get(index);
if(slot == null || !slot.getHasStack()) {
return null;
}
ItemStack ret = slot.getStack().copy();
ItemStack itemstack = slot.getStack().copy();
Container container = getSlotContainer(index);
boolean nothingDone = true;
// Is the slot from a module?
if(container != this) {
// Try moving module -> tile inventory
nothingDone &= moveToTileInventory(itemstack);
// Try moving module -> player inventory
nothingDone &= moveToPlayerInventory(itemstack);
}
// Is the slot from the tile?
else if(index < subContainerSlotStart || (index < playerInventoryStart && subContainerSlotStart < 0)) {
// Try moving tile -> preferred modules
nothingDone &= refillAnyContainer(itemstack, subContainers);
// Try moving module -> player inventory
nothingDone &= moveToPlayerInventory(itemstack);
// Try moving module -> all submodules
nothingDone &= moveToAnyContainer(itemstack, subContainers);
}
// Slot is from the player inventory (if present)
else if(index >= playerInventoryStart && playerInventoryStart >= 0) {
// Try moving player -> tile inventory
nothingDone &= moveToTileInventory(itemstack);
// try moving player -> modules
nothingDone &= moveToAnyContainer(itemstack, subContainers);
}
// you violated some assumption or something. Shame on you.
else {
return null;
}
if(nothingDone) {
return null;
}
return notifySlotAfterTransfer(playerIn, itemstack, ret, slot);
}
protected ItemStack notifySlotAfterTransfer(EntityPlayer player, ItemStack stack, ItemStack original, Slot slot) {
// notify slot
slot.onSlotChange(stack, original);
if(stack.stackSize == original.stackSize) {
return null;
}
// update slot we pulled from
slot.putStack(stack);
slot.onPickupFromSlot(player, stack);
if(slot.getHasStack() && slot.getStack().stackSize == 0) {
slot.putStack(null);
}
return original;
}
protected boolean moveToTileInventory(ItemStack itemstack) {
if(itemstack == null || itemstack.stackSize == 0) {
return false;
}
int end = subContainerSlotStart;
if(end < 0) {
end = playerInventoryStart;
}
return !this.mergeItemStack(itemstack, 0, end, false);
}
protected boolean moveToPlayerInventory(ItemStack itemstack) {
if(itemstack == null || itemstack.stackSize == 0) {
return false;
}
return playerInventoryStart > 0 && !this
.mergeItemStack(itemstack, playerInventoryStart, this.inventorySlots.size(), true);
}
protected boolean moveToAnyContainer(ItemStack itemstack, Collection<Container> containers) {
if(itemstack == null || itemstack.stackSize == 0) {
return false;
}
for(Container submodule : containers) {
if(moveToContainer(itemstack, submodule)) {
return true;
}
}
return false;
}
protected boolean moveToContainer(ItemStack itemstack, Container container) {
Pair<Integer, Integer> range = subContainerSlotRanges.get(container);
if(!this.mergeItemStack(itemstack, range.getLeft(), range.getRight(), false)) {
return true;
}
return false;
}
protected boolean refillAnyContainer(ItemStack itemstack, Collection<Container> containers) {
if(itemstack == null || itemstack.stackSize == 0) {
return false;
}
for(Container submodule : containers) {
if(refillContainer(itemstack, submodule)) {
return true;
}
}
return false;
}
protected boolean refillContainer(ItemStack itemstack, Container container) {
Pair<Integer, Integer> range = subContainerSlotRanges.get(container);
if(!this.mergeItemStackRefill(itemstack, range.getLeft(), range.getRight(), false)) {
return true;
}
return false;
}
/** Searches for a sidechest to display in the UI */
public <TE extends TileEntity> TE detectTE(Class<TE> clazz) {
return ObjectUtils.firstNonNull(detectChest(this.pos.north(), clazz),
detectChest(this.pos.east(), clazz),
detectChest(this.pos.south(), clazz),
detectChest(this.pos.west(), clazz));
}
private <TE extends TileEntity> TE detectChest(BlockPos pos, Class<TE> clazz) {
TileEntity te = this.world.getTileEntity(pos);
if(te != null && clazz.isAssignableFrom(te.getClass())) {
return (TE) te;
}
return null;
}
}
@@ -0,0 +1,36 @@
package slimeknights.mantle.inventory;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import slimeknights.mantle.tileentity.TileInventory;
public class ContainerSimpleChest extends BaseContainer<TileInventory> {
public ContainerSimpleChest(TileInventory tile, int rows, int columns, InventoryPlayer playerInventory) {
super(tile);
int index = 0;
// chest inventory
for(int i = 0; i < rows; ++i) {
for(int j = 0; j < columns; ++j) {
// safety
if(index > tile.getSizeInventory()) {
break;
}
this.addSlotToContainer(createSlot(tile, index, 8 + j * 18, 18 + i * 18));
index++;
}
}
// player inventory
addPlayerInventory(playerInventory, 17, 86);
}
protected Slot createSlot(IInventory inventory, int index, int x, int y) {
return new Slot(inventory, index, x, y);
}
}
@@ -0,0 +1,10 @@
package slimeknights.mantle.inventory;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
public interface IContainerCraftingCustom {
void onCrafting(EntityPlayer player, ItemStack output, IInventory craftMatrix);
}
@@ -0,0 +1,34 @@
package slimeknights.mantle.inventory;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.inventory.SlotCrafting;
import net.minecraft.item.ItemStack;
public class SlotCraftingCustom extends SlotCrafting {
private final InventoryCrafting craftMatrix;
private final IContainerCraftingCustom callback;
/**
* @param callback Container that gets the crafting call on crafting
* @param player Player that does the crafting
* @param craftingInventory Inventory where the ingredients are taken from
* @param craftResult Inventory where the result is put
*/
public SlotCraftingCustom(IContainerCraftingCustom callback, EntityPlayer player, InventoryCrafting craftingInventory, IInventory craftResult, int slotIndex, int xPosition, int yPosition) {
super(player, craftingInventory, craftResult, slotIndex, xPosition, yPosition);
this.craftMatrix = craftingInventory;
this.callback = callback;
}
@Override
public void onPickupFromSlot(EntityPlayer playerIn, ItemStack stack) {
net.minecraftforge.fml.common.FMLCommonHandler.instance().firePlayerCraftingEvent(playerIn, stack, craftMatrix);
this.onCrafting(stack);
callback.onCrafting(playerIn, stack, craftMatrix);
}
}
@@ -0,0 +1,18 @@
package slimeknights.mantle.inventory;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
/** Slot that can only be taken out of */
public class SlotOut extends Slot {
public SlotOut(IInventory inventoryIn, int index, int xPosition, int yPosition) {
super(inventoryIn, index, xPosition, yPosition);
}
@Override
public boolean isItemValid(ItemStack stack) {
return false;
}
}
@@ -0,0 +1,21 @@
package slimeknights.mantle.inventory;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
public class SlotRestrictedItem extends Slot {
private final Item allowedItem;
public SlotRestrictedItem(Item item, IInventory inventoryIn, int index, int xPosition, int yPosition) {
super(inventoryIn, index, xPosition, yPosition);
allowedItem = item;
}
@Override
public boolean isItemValid(ItemStack stack) {
return stack != null && stack.getItem() == allowedItem;
}
}
@@ -0,0 +1,46 @@
package slimeknights.mantle.inventory;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* Used to wrap the slots inside Modules/Subcontainers
*/
public class SlotWrapper extends Slot {
public final Slot parent;
public SlotWrapper(Slot slot) {
super(slot.inventory, slot.getSlotIndex(), slot.xDisplayPosition, slot.yDisplayPosition);
this.parent = slot;
}
@Override
public void onSlotChange(ItemStack p_75220_1_, ItemStack p_75220_2_) {
parent.onSlotChange(p_75220_1_, p_75220_2_);
}
@Override
public void onSlotChanged() {
parent.onSlotChanged();
}
@Override
public boolean isItemValid(ItemStack stack) {
return parent.isItemValid(stack);
}
@Override
public boolean canTakeStack(EntityPlayer playerIn) {
return parent.canTakeStack(playerIn);
}
@SideOnly(Side.CLIENT)
@Override
public boolean canBeHovered() {
return parent.canBeHovered();
}
}
@@ -0,0 +1,72 @@
package slimeknights.mantle.item;
import net.minecraft.block.Block;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.resources.model.ModelResourceLocation;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemColored;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.registry.GameData;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import slimeknights.mantle.util.LocUtils;
public class ItemBlockMeta extends ItemColored {
protected IProperty mappingProperty;
public ItemBlockMeta(Block block) {
super(block, true);
}
@Override
public String getUnlocalizedName(ItemStack stack) {
if(mappingProperty == null) return super.getUnlocalizedName(stack);
IBlockState state = block.getStateFromMeta(stack.getMetadata());
String name = state.getValue(mappingProperty).toString().toLowerCase(Locale.US);
return super.getUnlocalizedName(stack) + "." + name;
}
public static void setMappingProperty(Block block, IProperty<?> property) {
((ItemBlockMeta)Item.getItemFromBlock(block)).mappingProperty = property;
}
@Override
public void addInformation(ItemStack stack, EntityPlayer playerIn, List<String> tooltip, boolean advanced) {
if(StatCollector.canTranslate(this.getUnlocalizedName(stack) + ".tooltip")) {
tooltip.add(EnumChatFormatting.GRAY.toString() +
LocUtils.translateRecursive(this.getUnlocalizedName(stack) + ".tooltip"));
}
else if(StatCollector.canTranslate(super.getUnlocalizedName(stack) + ".tooltip")) {
tooltip.add(EnumChatFormatting.GRAY.toString() + LocUtils.translateRecursive(super.getUnlocalizedName(stack) + ".tooltip"));
}
super.addInformation(stack, playerIn, tooltip, advanced);
}
@SideOnly(Side.CLIENT)
public void registerItemModels() {
final Item item = this;
final ResourceLocation loc = (ResourceLocation) GameData.getBlockRegistry().getNameForObject(block);
for(Comparable o : (Collection<Comparable>)mappingProperty.getAllowedValues()) {
int meta = block.getMetaFromState(block.getDefaultState().withProperty(mappingProperty, o));
String name = mappingProperty.getName(o);
ModelLoader.setCustomModelResourceLocation(item, meta, new ModelResourceLocation(loc, mappingProperty.getName() + "=" + name));
}
}
}
@@ -0,0 +1,110 @@
package slimeknights.mantle.item;
import gnu.trove.map.hash.TIntFloatHashMap;
import gnu.trove.map.hash.TIntIntHashMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemFood;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.PotionEffect;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.List;
public class ItemEdible extends ItemFood {
// we use this so we don't have to copy all the logic
private ItemMetaDynamic dynamic;
protected TIntIntHashMap foodLevels;
protected TIntFloatHashMap saturations;
protected TIntObjectHashMap<PotionEffect[]> potionEffects;
public ItemEdible() {
super(0, 0, false);
this.setHasSubtypes(true);
dynamic = new ItemMetaDynamic();
foodLevels = new TIntIntHashMap();
saturations = new TIntFloatHashMap();
potionEffects = new TIntObjectHashMap<PotionEffect[]>();
}
/**
* Add a new food type!
* @param meta Metadata to use, has to be free
* @param food How much food it restores on eating
* @param saturation Saturation multiplier on the food
* @param name Unlocalized postfix
* @param effects PotionEffects that will be applied on eating. The PotionEffect passed will be directly applied
* @return Itemstack containing the registered item
*/
public ItemStack addFood(int meta, int food, float saturation, String name, PotionEffect... effects) {
dynamic.addMeta(meta, name);
foodLevels.put(meta, food);
saturations.put(meta, saturation);
potionEffects.put(meta, effects);
return new ItemStack(this, 1, meta);
}
@Override
public float getSaturationModifier(ItemStack stack) {
return saturations.get(stack.getMetadata()); // should call getMetadata below
// default value if meta not present is 0
}
@Override
public int getHealAmount(ItemStack stack) {
return foodLevels.get(stack.getMetadata()); // should call getMetadata below
// default value if meta not present is 0
}
@Override
protected void onFoodEaten(ItemStack stack, World worldIn, EntityPlayer player) {
if (!worldIn.isRemote)
{
for(PotionEffect potion : potionEffects.get(stack.getMetadata())) {
player.addPotionEffect(new PotionEffect(potion.getPotionID(), potion.getDuration(), potion.getAmplifier(), potion.getIsAmbient(), potion.getIsShowParticles()));
}
}
}
/* ItemMetaDynamic Functionality */
@Override
public Item setUnlocalizedName(String unlocalizedName) {
dynamic.setUnlocalizedName(unlocalizedName);
return super.setUnlocalizedName(unlocalizedName);
}
@Override
public String getUnlocalizedName(ItemStack stack) {
return dynamic.getUnlocalizedName(stack);
}
@Override
public int getMetadata(ItemStack stack) {
return dynamic.getMetadata(stack);
}
@Override
public void addInformation(ItemStack stack, EntityPlayer playerIn, List<String> tooltip, boolean advanced) {
dynamic.addInformation(stack, playerIn, tooltip, advanced);
}
@SideOnly(Side.CLIENT)
@Override
public void getSubItems(Item itemIn, CreativeTabs tab, List<ItemStack> subItems) {
dynamic.getSubItems(itemIn, tab, subItems);
}
@SideOnly(Side.CLIENT)
public void registerItemModels(final String prefix) {
dynamic.registerItemModels(prefix, this);
}
}
@@ -0,0 +1,132 @@
package slimeknights.mantle.item;
import gnu.trove.map.hash.TIntObjectHashMap;
import gnu.trove.procedure.TIntObjectProcedure;
import net.minecraft.client.resources.model.ModelBakery;
import net.minecraft.client.resources.model.ModelResourceLocation;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.StatCollector;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import slimeknights.mantle.util.LocUtils;
/**
* Item representing a dynamic amount of different items represented by meta.
* Only returns valid metadatas. The validity is determined by a bitmask.
* Current maximum is 64 metas - that should suffice for most applications.
*/
public class ItemMetaDynamic extends Item {
private static int MAX = (2 << 16) - 1;
protected boolean[] availabilityMask; // boolean[] actually is much more performant for our case than BitSet
protected TIntObjectHashMap<String> names;
public ItemMetaDynamic() {
availabilityMask = new boolean[1];
names = new TIntObjectHashMap<String>();
this.setHasSubtypes(true);
}
/**
* Add a valid metadata.
* @param meta The metadata value
* @param name The name used for registering the itemmodel as well as the unlocalized name of the meta. The unlocalized name will be lowercased and stripped of whitespaces.
* @return An itemstack representing the Item-Meta combination.
*/
public ItemStack addMeta(int meta, String name) {
if(meta > MAX) {
throw new IllegalArgumentException(String.format("Metadata for %s too high, highest supported value is %d. Meta was %d", name, MAX, meta));
}
else if(isValid(meta)) {
throw new IllegalArgumentException(String.format("Metadata for %s is already taken. Meta %d is %s", name, meta, names.get(meta)));
}
while(meta >= availabilityMask.length) {
availabilityMask = Arrays.copyOf(availabilityMask, availabilityMask.length*2);
}
setValid(meta);
names.put(meta, name);
return new ItemStack(this, 1, meta);
}
@Override
public String getUnlocalizedName(ItemStack stack) {
int meta = stack.getMetadata(); // should call getMetadata below
if(isValid(meta))
return super.getUnlocalizedName(stack) + "." + LocUtils.makeLocString(names.get(meta));
else
return super.getUnlocalizedName(stack);
}
@Override
public void getSubItems(Item itemIn, CreativeTabs tab, List<ItemStack> subItems) {
for(int i = 0; i <= availabilityMask.length; i++) {
if(isValid(i)) {
subItems.add(new ItemStack(itemIn, 1, i));
}
}
}
@Override
public int getMetadata(int damage) {
int meta = super.getMetadata(damage);
return isValid(meta) ? meta : 0;
}
protected void setValid(int meta) {
availabilityMask[meta] = true;
}
protected boolean isValid(int meta) {
if(meta > MAX || meta >= availabilityMask.length) {
return false;
}
return availabilityMask[meta];
}
@SideOnly(Side.CLIENT)
public void registerItemModels(final String prefix) {
registerItemModels(prefix, this);
}
@SideOnly(Side.CLIENT)
protected void registerItemModels(final String prefix, final Item item) {
final String resourceId = Loader.instance().activeModContainer().getModId().toLowerCase();
names.forEachEntry(new TIntObjectProcedure<String>() {
@Override
public boolean execute(int meta, String name) {
name = String.format("%s:%s%s", resourceId, prefix, name);
ModelBakery.addVariantName(item, name);
// tell the game which model to use for this item-meta combination
ModelLoader.setCustomModelResourceLocation(item, meta, new ModelResourceLocation(name, "inventory"));
return true;
}
});
}
@Override
public void addInformation(ItemStack stack, EntityPlayer playerIn, List<String> tooltip, boolean advanced) {
if(StatCollector.canTranslate(this.getUnlocalizedName(stack) + ".tooltip")) {
tooltip.add(EnumChatFormatting.GRAY.toString() +
LocUtils.translateRecursive(this.getUnlocalizedName(stack) + ".tooltip"));
}
else if(StatCollector.canTranslate(super.getUnlocalizedName(stack) + ".tooltip")) {
tooltip.add(EnumChatFormatting.GRAY.toString() + LocUtils.translateRecursive(super.getUnlocalizedName(stack) + ".tooltip"));
}
super.addInformation(stack, playerIn, tooltip, advanced);
}
}
@@ -0,0 +1,12 @@
package slimeknights.mantle.multiblock;
import net.minecraft.util.BlockPos;
public interface IMasterLogic
{
/** Called when servants change their state
*
* @param pos servant position
*/
public void notifyChange(IServantLogic servant, BlockPos pos);
}
@@ -0,0 +1,8 @@
package slimeknights.mantle.multiblock;
public interface IMasterNode extends IMasterLogic, IServantLogic
{
public boolean isCurrentlyMaster();
public boolean isEquivalentMaster(IMasterLogic master);
}
@@ -0,0 +1,41 @@
package slimeknights.mantle.multiblock;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
public interface IServantLogic
{
public BlockPos getMasterPosition();
/** The block should already have a valid master */
public void notifyMasterOfChange();
/** Checks if this block can be tied to this master
*
* @param master
* @param world the world of master
* @param pos position of master
* @return whether the servant can be tied to this master
*/
public boolean setPotentialMaster(IMasterLogic master, World world, BlockPos pos);
/** Used to set and verify that this is the block's master
*
* @param master
* @param world
* @param pos position of master
* @return Is this block tied to this master?
*/
public boolean verifyMaster(IMasterLogic master, World world, BlockPos pos);
/** Exactly what it says on the tin
*
* @param master
* @param world
* @param pos position of master
*/
public void invalidateMaster(IMasterLogic master, World world, BlockPos pos);
}
@@ -0,0 +1,197 @@
package slimeknights.mantle.multiblock;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.registry.GameData;
public class MultiServantLogic extends TileEntity implements IServantLogic
{
boolean hasMaster;
BlockPos master;
Block masterBlock;
IBlockState state;
public boolean canUpdate()
{
return false;
}
public boolean getHasMaster()
{
return this.hasMaster;
}
public boolean hasValidMaster()
{
if (!this.hasMaster)
{
return false;
}
if (this.worldObj.getBlockState(this.master).getBlock() == this.masterBlock && this.worldObj.getBlockState(this.master) == this.state)
{
return true;
}
else
{
this.hasMaster = false;
this.master = null;
return false;
}
}
@Override
public BlockPos getMasterPosition()
{
return this.master;
}
public void overrideMaster(BlockPos pos)
{
this.hasMaster = true;
this.master = pos;
this.state = this.worldObj.getBlockState(this.master);
this.masterBlock = this.state.getBlock();
}
public void removeMaster()
{
this.hasMaster = false;
this.master = null;
this.masterBlock = null;
this.state = null;
}
@Override
public boolean setPotentialMaster(IMasterLogic master, World w, BlockPos pos)
{
return !this.hasMaster;
}
@Deprecated
public boolean verifyMaster(IMasterLogic logic, BlockPos pos)
{
return this.master.equals(pos) && this.worldObj.getBlockState(pos) == this.state && this.worldObj.getBlockState(pos).getBlock() == this.masterBlock;
}
@Override
public boolean verifyMaster(IMasterLogic logic, World world, BlockPos pos)
{
if (this.hasMaster)
{
return this.hasValidMaster();
}
else
{
this.overrideMaster(pos);
return true;
}
}
@Override
public void invalidateMaster(IMasterLogic master, World w, BlockPos pos)
{
this.hasMaster = false;
master = null;
}
@Override
public void notifyMasterOfChange()
{
if (this.hasValidMaster())
{
IMasterLogic logic = (IMasterLogic) this.worldObj.getTileEntity(this.master);
logic.notifyChange(this, this.pos);
}
}
public void readCustomNBT(NBTTagCompound tags)
{
this.hasMaster = tags.getBoolean("hasMaster");
if (this.hasMaster)
{
int xCenter = tags.getInteger("xCenter");
int yCenter = tags.getInteger("yCenter");
int zCenter = tags.getInteger("zCenter");
this.master = new BlockPos(xCenter, yCenter, zCenter);
this.masterBlock = GameData.getBlockRegistry().getObject(new ResourceLocation(tags.getString("MasterBlockName")));
this.state = Block.getStateById(tags.getInteger("masterState"));
}
}
public void writeCustomNBT(NBTTagCompound tags)
{
tags.setBoolean("hasMaster", this.hasMaster);
if (this.hasMaster)
{
tags.setInteger("xCenter", this.master.getX());
tags.setInteger("yCenter", this.master.getY());
tags.setInteger("zCenter", this.master.getZ());
tags.setString("MasterBlockName", GameData.getBlockRegistry().getNameForObject(this.masterBlock).toString());
tags.setInteger("masterState", Block.getStateId(this.state));
}
}
@Override
public void readFromNBT(NBTTagCompound tags)
{
super.readFromNBT(tags);
this.readCustomNBT(tags);
}
@Override
public void writeToNBT(NBTTagCompound tags)
{
super.writeToNBT(tags);
this.writeCustomNBT(tags);
}
/* Packets */
@Override
public Packet getDescriptionPacket()
{
NBTTagCompound tag = new NBTTagCompound();
this.writeCustomNBT(tag);
return new S35PacketUpdateTileEntity(this.pos, 1, tag);
}
@Override
public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity packet)
{
this.readCustomNBT(packet.getNbtCompound());
this.worldObj.notifyLightSet(this.pos);
this.worldObj.markBlockForUpdate(this.pos);
}
@Override
public World getWorld()
{
return this.worldObj;
}
@Deprecated
public boolean setMaster(BlockPos pos)
{
if (!this.hasMaster || this.worldObj.getBlockState(this.master) != this.state || (this.worldObj.getBlockState(this.master).getBlock() != this.masterBlock))
{
this.overrideMaster(pos);
return true;
}
else
{
return false;
}
}
}
@@ -0,0 +1,31 @@
package slimeknights.mantle.network;
import net.minecraft.client.network.NetHandlerPlayClient;
import net.minecraft.network.NetHandlerPlayServer;
import net.minecraft.util.BlockPos;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import net.minecraftforge.fml.relauncher.Side;
import io.netty.buffer.ByteBuf;
public abstract class AbstractPacket implements IMessage {
public abstract IMessage handleClient(NetHandlerPlayClient netHandler);
public abstract IMessage handleServer(NetHandlerPlayServer netHandler);
protected void writePos(BlockPos pos, ByteBuf buf) {
buf.writeInt(pos.getX());
buf.writeInt(pos.getY());
buf.writeInt(pos.getZ());
}
protected BlockPos readPos(ByteBuf buf) {
int x = buf.readInt();
int y = buf.readInt();
int z = buf.readInt();
return new BlockPos(x, y, z);
}
}
@@ -0,0 +1,42 @@
package slimeknights.mantle.network;
import net.minecraft.client.Minecraft;
import net.minecraft.client.network.NetHandlerPlayClient;
import net.minecraft.network.NetHandlerPlayServer;
import net.minecraft.server.MinecraftServer;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
/**
* Threadsafe integration of the abstract packet.
* Basically if you're doing something that has any influence on the world you should use this.
* (That's ~everything)
*/
public abstract class AbstractPacketThreadsafe extends AbstractPacket {
@Override
public final IMessage handleClient(final NetHandlerPlayClient netHandler) {
Minecraft.getMinecraft().addScheduledTask(new Runnable() {
@Override
public void run() {
handleClientSafe(netHandler);
}
});
return null;
}
@Override
public final IMessage handleServer(final NetHandlerPlayServer netHandler) {
MinecraftServer.getServer().addScheduledTask(new Runnable() {
@Override
public void run() {
handleServerSafe(netHandler);
}
});
return null;
}
public abstract void handleClientSafe(NetHandlerPlayClient netHandler);
public abstract void handleServerSafe(NetHandlerPlayServer netHandler);
}
@@ -0,0 +1,62 @@
package slimeknights.mantle.network;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import net.minecraftforge.fml.relauncher.Side;
/**
* A small network implementation/wrapper using AbstractPackets instead of IMessages.
* Instantiate in your mod class and register your packets accordingly.
*/
public class NetworkWrapper {
public final SimpleNetworkWrapper network;
protected final AbstactPacketHandler handler;
private int id = 0;
public NetworkWrapper(String channelName) {
network = NetworkRegistry.INSTANCE.newSimpleChannel(channelName);
handler = new AbstactPacketHandler();
}
/**
* Packet will be received on both cliend and server side.
*/
public void registerPacket(Class<? extends AbstractPacket> packetClazz) {
registerPacketClient(packetClazz);
registerPacketServer(packetClazz);
}
/**
* Packet will only be received on the client side
*/
public void registerPacketClient(Class<? extends AbstractPacket> packetClazz) {
registerPacketImpl(packetClazz, Side.CLIENT);
}
/**
* Packet will only be received on the server side
*/
public void registerPacketServer(Class<? extends AbstractPacket> packetClazz) {
registerPacketImpl(packetClazz, Side.SERVER);
}
private void registerPacketImpl(Class<? extends AbstractPacket> packetClazz, Side side) {
network.registerMessage(handler, packetClazz, id++, side);
}
public static class AbstactPacketHandler implements IMessageHandler<AbstractPacket, IMessage> {
@Override
public IMessage onMessage(AbstractPacket packet, MessageContext ctx) {
if(ctx.side == Side.SERVER) {
return packet.handleServer(ctx.getServerHandler());
}
else {
return packet.handleClient(ctx.getClientHandler());
}
}
}
}
@@ -0,0 +1,32 @@
package slimeknights.mantle.property;
import net.minecraftforge.common.property.IUnlistedProperty;
public class PropertyString implements IUnlistedProperty<String> {
private final String name;
public PropertyString(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public boolean isValid(String value) {
return !value.isEmpty();
}
@Override
public Class<String> getType() {
return String.class;
}
@Override
public String valueToString(String value) {
return value;
}
}
@@ -0,0 +1,38 @@
package slimeknights.mantle.property;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import net.minecraft.block.properties.PropertyDirection;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.common.property.IUnlistedProperty;
import java.util.Collection;
public class PropertyUnlistedDirection extends PropertyDirection implements IUnlistedProperty<EnumFacing> {
public PropertyUnlistedDirection(String name, Collection<EnumFacing> values) {
super(name, values);
}
public PropertyUnlistedDirection(String name, Predicate<EnumFacing> filter) {
this(name, Collections2.filter(Lists.newArrayList(EnumFacing.values()), filter));
}
@Override
public boolean isValid(EnumFacing value) {
return true;
}
@Override
public Class<EnumFacing> getType() {
return this.getValueClass();
}
@Override
public String valueToString(EnumFacing value) {
return getName(value);
}
}
@@ -0,0 +1,71 @@
package slimeknights.mantle.pulsar.config;
import java.io.File;
import java.util.Locale;
import slimeknights.mantle.pulsar.pulse.PulseMeta;
import net.minecraftforge.common.config.ConfigCategory;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.config.Property;
import net.minecraftforge.fml.common.Loader;
/**
* Mantle specific pulsar addon class to support using the forge CFG format for configurations
* @author progwml6
*/
public class ForgeCFG implements IConfiguration
{
private Configuration config;
private final String confPath;
private final String description;
/**
* Creates a new Configuration object.
*
* Do NOT make this the same as the overall mod configuration; it will clobber it!
*
* @param confName The config file name (without path or .cfg suffix)
* @param description The description for the group that the config entries will be placed in.
*/
public ForgeCFG(String confName, String description)
{
this.confPath = Loader.instance().getConfigDir().toString() + File.separator + confName + ".cfg";
this.description = description.toLowerCase(Locale.US);
}
@Override
public void load()
{
config = new Configuration(new File(this.confPath), "1");
config.load();
}
@Override
public boolean isModuleEnabled(PulseMeta meta)
{
Property prop = config.get(this.description, meta.getId(), meta.isEnabled(), meta.getDescription());
prop.setRequiresMcRestart(true);
return prop.getBoolean(meta.isEnabled());
}
@Override
public void flush()
{
if (config.hasChanged())
{
config.save();
}
}
public Configuration getConfig() {
return config;
}
public ConfigCategory getCategory() {
return config.getCategory(this.description);
}
}
@@ -1,12 +1,15 @@
package mantle.pulsar.config;
package slimeknights.mantle.pulsar.config;
import mantle.pulsar.pulse.PulseMeta;
import slimeknights.mantle.pulsar.pulse.PulseMeta;
import javax.annotation.ParametersAreNonnullByDefault;
/**
* Interface for config handlers.
*
* @author Arkan <[email protected]>
*/
@ParametersAreNonnullByDefault
public interface IConfiguration {
/**
@@ -0,0 +1,253 @@
package slimeknights.mantle.pulsar.control;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.FMLModContainer;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.annotation.ParametersAreNonnullByDefault;
import slimeknights.mantle.pulsar.config.IConfiguration;
import slimeknights.mantle.pulsar.flightpath.Flightpath;
import slimeknights.mantle.pulsar.flightpath.IExceptionHandler;
import slimeknights.mantle.pulsar.flightpath.lib.AnnotationLocator;
import slimeknights.mantle.pulsar.internal.BusExceptionHandler;
import slimeknights.mantle.pulsar.internal.Configuration;
import slimeknights.mantle.pulsar.internal.CrashHandler;
import slimeknights.mantle.pulsar.pulse.Pulse;
import slimeknights.mantle.pulsar.pulse.PulseMeta;
/**
* Manager class for a given mods Pulses.
*
* This MUST be constructed by a mod BEFORE preinit as it registers on to the mod event bus - a static block would serve
* for this. No more Pulses can be registered after preinit has been caught, so assume preinit is too late to register
* new Pulses.
*
* Each Pulsar-enabled mod should create one and only one of these to manage its Pulses.
*
* @author Arkan <[email protected]>
*/
@SuppressWarnings("unused")
@ParametersAreNonnullByDefault
public class PulseManager {
private Logger log;
private final boolean useConfig;
private final LinkedHashMap<Object, PulseMeta> pulses = new LinkedHashMap<Object, PulseMeta>();
// Use the Google @Subscribe to avoid confusion/breaking changes.
private final Flightpath flightpath = new Flightpath(new AnnotationLocator(Subscribe.class));
private boolean blockNewRegistrations = false;
private boolean configLoaded = false;
private IConfiguration conf;
private String id;
/**
* Configuration-using constructor.
*
* This form creates a PulseManager that supports configuration of Pulses by file.
*
* @param configName The config file name.
*/
public PulseManager(String configName) {
init();
useConfig = true;
conf = new Configuration(configName, log);
}
/**
* Custom configuration-using constructor.
*
* Don't like JSON? Heathen. Lets you handle configuration, to whatever media you like - File, database, death star.
* Whatever really. See {@link slimeknights.mantle.pulsar.config.IConfiguration}.
*
* @param config Configuration handler.
*/
public PulseManager(IConfiguration config) {
init();
useConfig = true;
conf = config;
}
/**
* Shared initialiser code between all the constructors.
*/
private void init() {
String modId = Loader.instance().activeModContainer().getModId();
this.id = modId;
log = LogManager.getLogger("Pulsar-" + modId);
flightpath.setExceptionHandler(new BusExceptionHandler(modId));
FMLCommonHandler.instance().registerCrashCallable(new CrashHandler(modId, this));
// Attach us to the mods FML bus
attachToContainerEventBus(this);
}
/**
* Overrides Pulsars default behaviour when a pulse emits an exception. See Flightpath's documentation.
*
* @param handler The Flightpath-compatible exception handler to use.
*/
public void setPulseExceptionHandler(IExceptionHandler handler) {
flightpath.setExceptionHandler(handler);
}
/**
* Register a new Pulse with the manager.
*
* This CANNOT be done after preinit has been invoked.
*
* @param pulse The Pulse to register.
*/
public void registerPulse(Object pulse) {
if (blockNewRegistrations) throw new RuntimeException("A mod tried to register a plugin after preinit! Pulse: "
+ pulse);
if (!configLoaded) {
conf.load();
configLoaded = true;
}
String id, description, deps;
boolean forced, enabled, defaultEnabled, missingDeps = false;
try {
Pulse p = pulse.getClass().getAnnotation(Pulse.class);
id = p.id();
description = p.description();
deps = p.modsRequired();
forced = p.forced();
enabled = p.defaultEnable();
defaultEnabled = p.defaultEnable();
} catch (NullPointerException ex) {
throw new RuntimeException("Could not parse @Pulse annotation for Pulse: " + pulse);
}
// Work around Java not allowing default-null fields.
if (description.equals("")) description = null;
if (!deps.equals("")) {
String[] parsedDeps = deps.split(";");
for (String s : parsedDeps) {
if (!Loader.isModLoaded(s)) {
log.info("Skipping Pulse " + id + "; missing dependency: " + s);
missingDeps = true;
enabled = false;
break;
}
}
}
PulseMeta meta = new PulseMeta(id, description, forced, enabled, defaultEnabled);
meta.setMissingDeps(missingDeps);
meta.setEnabled(getEnabledFromConfig(meta));
if (meta.isEnabled()) {
pulses.put(pulse, meta);
flightpath.register(pulse);
}
}
/**
* Helper to attach a given object to the mod container event bus.
*
* @param obj Object to register.
*/
private void attachToContainerEventBus(Object obj) {
ModContainer cnt = Loader.instance().activeModContainer();
log.debug("Attaching [" + obj + "] to event bus for container [" + cnt + "]");
try {
FMLModContainer mc = (FMLModContainer)cnt;
Field ebf = mc.getClass().getDeclaredField("eventBus");
boolean access = ebf.isAccessible();
ebf.setAccessible(true);
EventBus eb = (EventBus)ebf.get(mc);
ebf.setAccessible(access);
eb.register(obj);
} catch (NoSuchFieldException nsfe) {
throw new RuntimeException("Pulsar >> Incompatible FML mod container (missing eventBus field) - wrong Forge version?");
} catch (IllegalAccessException iae) {
throw new RuntimeException("Pulsar >> Security Manager blocked access to eventBus on mod container. Cannot continue.");
} catch (ClassCastException cce) {
throw new RuntimeException("Pulsar >> Something in the mod container had the wrong type? " + cce.getMessage());
}
}
/**
* Internal (but public for EventBus use) handler for events.
*
* DO NOT CALL THIS DIRECTLY! Let EventBus handle it.
*
* @param evt An event object.
*/
@Subscribe
public void propagateEvent(Object evt) {
if (evt instanceof FMLPreInitializationEvent) preInit((FMLPreInitializationEvent) evt);
// We use individual buses due to the EventBus class using a Set rather than a List, thus losing the ordering.
// This trick is shamelessly borrowed from FML.
flightpath.post(evt);
}
private boolean getEnabledFromConfig(PulseMeta meta) {
if (meta.isForced() || !useConfig) return true; // Forced or no config set.
return conf.isModuleEnabled(meta);
}
private void preInit(FMLPreInitializationEvent evt) {
if (!blockNewRegistrations) conf.flush(); // First preInit call, so flush config
blockNewRegistrations = true;
}
private boolean hasRequiredPulses(Map.Entry<Object, PulseMeta> entry) {
String deps = entry.getKey().getClass().getAnnotation(Pulse.class).pulsesRequired();
if (!deps.equals("")) {
String[] parsedDeps = deps.split(";");
for (String s : parsedDeps) {
if (!isPulseLoaded(s)) {
log.info("Skipping Pulse " + entry.getValue().getId() + "; missing pulse: " + s);
return false;
}
}
}
return true;
}
/**
* Check if a given Pulse ID is loaded in this manager.
*
* @param pulseId The ID to check.
* @return Whether the ID was present.
*/
public boolean isPulseLoaded(String pulseId) {
for(Map.Entry<Object, PulseMeta> entry : pulses.entrySet()) {
if (entry.getValue().getId().equals(pulseId)) {
return true;
}
}
return false;
}
public Collection<PulseMeta> getAllPulseMetadata() {
return pulses.values();
}
@Override
public String toString() {
return "PulseManager[" + id + "]";
}
}
@@ -0,0 +1,28 @@
package slimeknights.mantle.pulsar.debug;
import com.google.common.eventbus.Subscribe;
import net.minecraftforge.fml.common.Loader;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import slimeknights.mantle.pulsar.pulse.Pulse;
/**
* Debug Pulse to 'eavesdrop' on the PulseManager event bus traffic.
*
* @author Arkan <[email protected]>
*/
@SuppressWarnings("unused")
@Pulse(id="EventSpy", description="we iz in ur buses, monitorin ur eventz", forced=true)
public class EventSpy {
private final Logger log = LogManager.getLogger("EventSpy/" + Loader.instance().activeModContainer().getModId());
@Subscribe
public void receive(Object evt) {
log.info("Received event: " + evt);
}
}
@@ -0,0 +1,15 @@
package slimeknights.mantle.pulsar.flightpath;
import java.lang.annotation.*;
/**
* Default annotation for Flightpath subscriptions.
*
* We don't use @Subscriber, as too many frameworks use it (which may lead to import hell)
*
* @author Arkan <[email protected]>
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Airdrop {}
@@ -0,0 +1,101 @@
package slimeknights.mantle.pulsar.flightpath;
import slimeknights.mantle.pulsar.flightpath.lib.AnnotationLocator;
import slimeknights.mantle.pulsar.flightpath.lib.BlackholeExceptionHandler;
import javax.annotation.ParametersAreNonnullByDefault;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
/**
* Flightpath - an ordered event bus implementation.
*
* @author Arkan <[email protected]>
*/
@ParametersAreNonnullByDefault
@SuppressWarnings({"unused","unchecked"})
public class Flightpath {
private final ISubscriberLocator locator;
// Note we *MUST* use a linked map, otherwise order is lost.
private final LinkedHashMap<Object, Map<Class, Set<Method>>> subscribers = new LinkedHashMap<Object,
Map<Class, Set<Method>>>();
// Anything that manipulates state *MUST* acquire this lock. It prevents awkward issues when iterating.
private final Object lock = new Object();
private IExceptionHandler exceptionHandler = new BlackholeExceptionHandler();
/**
* Generates a plain old Flightpath, using the default @Airdrop annotation.
*/
public Flightpath() {
this.locator = new AnnotationLocator(Airdrop.class);
}
/**
* Generates a Flightpath using a different locator implementation.
*
* Pass a custom constructed instance of AnnotationLocator to use alternative annotations.
*
* @param locator The locator to be applied to new objects.
*/
public Flightpath(ISubscriberLocator locator) {
this.locator = locator;
}
/**
* Used to change exception handling behaviour.
*
* @param handler The handler to use.
*/
public void setExceptionHandler(IExceptionHandler handler) {
synchronized (lock) {
this.exceptionHandler = handler;
}
}
/**
* Registers a given object onto the bus.
*
* @param obj Object to attach to the bus.
*/
public void register(Object obj) {
synchronized (lock) {
if (subscribers.containsKey(obj)) return; // Nothing to do.
subscribers.put(obj, locator.findSubscribers(obj));
}
}
/**
* Posts the given event on the bus.
*
* By default this blackholes exceptions. If you need different behaviour, see setExceptionHandler.
*
* @param evt The event to post.
*/
public void post(Object evt) {
synchronized (lock) {
for (Map.Entry<Object, Map<Class, Set<Method>>> ent : subscribers.entrySet()) {
for (Map.Entry<Class, Set<Method>> objEnt: ent.getValue().entrySet()) {
if (!objEnt.getKey().isAssignableFrom(evt.getClass())) continue;
Set<Method> ms = objEnt.getValue();
for (Method m : ms) {
try {
boolean access = m.isAccessible();
m.setAccessible(true);
m.invoke(ent.getKey(), evt);
m.setAccessible(access);
} catch (Exception ex) {
exceptionHandler.handle(ex);
}
}
}
}
exceptionHandler.flush();
}
}
}
@@ -0,0 +1,25 @@
package slimeknights.mantle.pulsar.flightpath;
import javax.annotation.ParametersAreNonnullByDefault;
/**
* General interface for an exception handler.
*
* @author Arkan <[email protected]>
*/
@ParametersAreNonnullByDefault
public interface IExceptionHandler {
/**
* Handle a given exception.
*
* @param ex The exception (duh)
*/
void handle(Exception ex);
/**
* Called after all methods have been invoked for cleanup or coalescing.
*/
void flush();
}
@@ -0,0 +1,18 @@
package slimeknights.mantle.pulsar.flightpath;
import javax.annotation.Nonnull;
import javax.annotation.ParametersAreNonnullByDefault;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;
/**
* Interface for defining custom subscriber scanners.
*/
@ParametersAreNonnullByDefault
public interface ISubscriberLocator {
@Nonnull
Map<Class, Set<Method>> findSubscribers(Object obj);
}
@@ -0,0 +1,38 @@
package slimeknights.mantle.pulsar.flightpath.lib;
import slimeknights.mantle.pulsar.flightpath.ISubscriberLocator;
import javax.annotation.Nonnull;
import javax.annotation.ParametersAreNonnullByDefault;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.*;
/**
* Default implementation of ISubscriberLocator
*
* @author Arkan <[email protected]>
*/
@ParametersAreNonnullByDefault
public class AnnotationLocator implements ISubscriberLocator {
private final Class<? extends Annotation> annotation;
public AnnotationLocator(Class<? extends Annotation> annotation) {
this.annotation = annotation;
}
@Override
public @Nonnull Map<Class, Set<Method>> findSubscribers(Object obj) {
Map<Class, Set<Method>> methods = new HashMap<Class, Set<Method>>();
for (Method m : obj.getClass().getMethods()) {
if (m.isAnnotationPresent(annotation) && m.getParameterTypes().length == 1) {
Class param = m.getParameterTypes()[0];
if (!methods.containsKey(param)) methods.put(param, new HashSet<Method>());
methods.get(param).add(m);
}
}
return methods;
}
}
@@ -0,0 +1,25 @@
package slimeknights.mantle.pulsar.flightpath.lib;
import slimeknights.mantle.pulsar.flightpath.IExceptionHandler;
import javax.annotation.ParametersAreNonnullByDefault;
/**
* Default exception handler when Flightpath has been asked to ignore errors.
*
* @author Arkan <[email protected]>
*/
@ParametersAreNonnullByDefault
public class BlackholeExceptionHandler implements IExceptionHandler {
@Override
public void handle(Exception ex) {
// NO-OP
}
@Override
public void flush() {
// NO-OP
}
}
@@ -0,0 +1,40 @@
package slimeknights.mantle.pulsar.internal;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import slimeknights.mantle.pulsar.flightpath.IExceptionHandler;
import javax.annotation.ParametersAreNonnullByDefault;
/**
* Custom exception catcher that logs events.
*/
@ParametersAreNonnullByDefault
public final class BusExceptionHandler implements IExceptionHandler {
private final String id;
private final Logger logger;
/**
* @param id Mod ID to include in exception raises.
*/
public BusExceptionHandler(String id) {
this.id = id;
this.logger = LogManager.getLogger(id + "-Pulsar-Flightpath");
}
@Override
public void handle(Exception ex) {
this.logger.error("Exception caught from a pulse on flightpath for mod ID " + id + ": ", ex);
if(ex instanceof RuntimeException) {
throw (RuntimeException)ex;
}
}
@Override
public void flush() {
// NO-OP
}
}
@@ -1,4 +1,4 @@
package mantle.pulsar.internal;
package slimeknights.mantle.pulsar.internal;
import java.io.*;
import java.util.*;
@@ -8,23 +8,28 @@ import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import cpw.mods.fml.common.Loader;
import mantle.pulsar.config.IConfiguration;
import mantle.pulsar.internal.logging.ILogger;
import mantle.pulsar.pulse.PulseMeta;
import net.minecraftforge.fml.common.Loader;
import org.apache.logging.log4j.Logger;
import slimeknights.mantle.pulsar.config.IConfiguration;
import slimeknights.mantle.pulsar.pulse.PulseMeta;
import javax.annotation.ParametersAreNonnullByDefault;
/**
* Default Gson Configuration helper.
*
* @author Arkan <[email protected]>
*/
@ParametersAreNonnullByDefault
public class Configuration implements IConfiguration {
private static final int CONFIG_LEVEL = 1;
private static final Gson gson = new GsonBuilder().setPrettyPrinting().create();
private final String confPath;
private final ILogger logger;
private final Logger logger;
private Map<String, ConfigEntry> modules;
@@ -36,7 +41,7 @@ public class Configuration implements IConfiguration {
* @param confName The config file name (without path or .json suffix)
* @param logger The logger to send debug info to.
*/
public Configuration(String confName, ILogger logger) {
public Configuration(String confName, Logger logger) {
this.confPath = Loader.instance().getConfigDir().toString() + File.separator + confName + ".json";
this.logger = logger;
}
@@ -50,7 +55,7 @@ public class Configuration implements IConfiguration {
public boolean isModuleEnabled(PulseMeta meta) {
ConfigEntry entry = modules.get(meta.getId());
if (entry == null) {
modules.put(meta.getId(), new ConfigEntry(meta.isEnabled(), meta.getDescription()));
modules.put(meta.getId(), new ConfigEntry(meta.isDefaultEnabled(), meta.getDescription()));
return meta.isEnabled();
} else {
return entry.getEnabled();
@@ -0,0 +1,49 @@
package slimeknights.mantle.pulsar.internal;
import net.minecraftforge.fml.common.ICrashCallable;
import slimeknights.mantle.pulsar.control.PulseManager;
import slimeknights.mantle.pulsar.pulse.PulseMeta;
/**
* FML crash callable for Pulse Managers; dumps a list of loaded pulses to the error log.
*
* @author Arkan <[email protected]>
*/
public class CrashHandler implements ICrashCallable {
private String id;
private PulseManager manager;
public CrashHandler(String modId, PulseManager manager) {
this.id = "Pulsar/" + modId + " loaded Pulses";
this.manager = manager;
}
@Override
public String getLabel() {
return id;
}
@Override
public String call() throws Exception {
String out = "\n";
for (PulseMeta meta : manager.getAllPulseMetadata()) {
String state = getStateFromMeta(meta);
out += "\t\t- " + meta.getId() + " (" + state + ")\n"; // Yes, yes, manual indenting, I know...
}
return out;
}
private static String getStateFromMeta(PulseMeta meta) {
if (meta.isForced()) {
return "Enabled/Forced";
} else {
if (meta.isEnabled()) {
return "Enabled/Not Forced";
} else {
return "Disabled/Not Forced";
}
}
}
}
@@ -33,4 +33,4 @@
*
* @author Arkan <[email protected]>
*/
package mantle.pulsar;
package slimeknights.mantle.pulsar;
@@ -1,10 +1,13 @@
package mantle.pulsar.pulse;
package slimeknights.mantle.pulsar.pulse;
import java.lang.annotation.*;
/**
* Metadata annotation for IPulse implementations.
*
* Pulses should use the standard Google Event Bus @Subscribe annotation to catch FML events, which are forwarded from
* the current mod container (including Pre/Init/Post events).
*
* @author Arkan <[email protected]>
*/
@Retention(RetentionPolicy.RUNTIME)
@@ -0,0 +1,53 @@
package slimeknights.mantle.pulsar.pulse;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
/**
* Metadata wrapper for parsed @Pulse metadata.
*
* @author Arkan <[email protected]>
*/
@ParametersAreNonnullByDefault
public class PulseMeta {
private String id, description;
private boolean forced, enabled, defaultEnabled;
private boolean missingDeps = false;
public PulseMeta(String id, @Nullable String description, boolean forced, boolean enabled, boolean defaultEnabled) {
this.id = id;
this.description = description;
this.forced = forced;
this.enabled = enabled;
this.defaultEnabled = defaultEnabled;
}
public String getId() {
return id;
}
public String getDescription() {
return description;
}
public boolean isForced() {
return !missingDeps && forced;
}
public boolean isEnabled() {
return !missingDeps && enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public void setMissingDeps(boolean missing) {
missingDeps = missing;
}
public boolean isDefaultEnabled() {
return defaultEnabled;
}
}
@@ -0,0 +1,261 @@
package slimeknights.mantle.tileentity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.IChatComponent;
import java.util.Arrays;
// Updated version of InventoryLogic in Mantle. Also contains a few bugfixes
public class TileInventory extends TileEntity implements IInventory {
private ItemStack[] inventory;
protected String inventoryTitle;
protected boolean hasCustomName;
protected int stackSizeLimit;
/**
* @param name Localization String for the inventory title. Can be overridden through setCustomName
*/
public TileInventory(String name, int inventorySize) {
this(name, inventorySize, 64);
}
/**
* @param name Localization String for the inventory title. Can be overridden through setCustomName
*/
public TileInventory(String name, int inventorySize, int maxStackSize) {
this.inventory = new ItemStack[inventorySize];
this.stackSizeLimit = maxStackSize;
this.inventoryTitle = name;
}
/* Inventory management */
@Override
public ItemStack getStackInSlot(int slot) {
if(slot < 0 || slot >= inventory.length) {
return null;
}
return inventory[slot];
}
public boolean isStackInSlot(int slot) {
return getStackInSlot(slot) != null;
}
public void resize(int size) {
inventory = Arrays.copyOf(inventory, size);
}
@Override
public int getSizeInventory() {
return inventory.length;
}
@Override
public int getInventoryStackLimit() {
return stackSizeLimit;
}
@Override
public void setInventorySlotContents(int slot, ItemStack itemstack) {
if(slot < 0 || slot >= inventory.length) {
return;
}
inventory[slot] = itemstack;
if(itemstack != null && itemstack.stackSize > getInventoryStackLimit()) {
itemstack.stackSize = getInventoryStackLimit();
}
}
@Override
public ItemStack decrStackSize(int slot, int quantity) {
ItemStack itemStack = getStackInSlot(slot);
if(itemStack == null) {
return null;
}
// whole itemstack taken out
if(itemStack.stackSize <= quantity) {
setInventorySlotContents(slot, null);
this.markDirty();
return itemStack;
}
// split itemstack
itemStack = itemStack.splitStack(quantity);
// slot is empty, set to null
if(getStackInSlot(slot).stackSize == 0) {
setInventorySlotContents(slot, null);
}
this.markDirty();
// return remainder
return itemStack;
}
@Override
public ItemStack removeStackFromSlot(int slot) {
ItemStack itemStack = getStackInSlot(slot);
setInventorySlotContents(slot, null);
return itemStack;
}
@Override
public boolean isItemValidForSlot(int slot, ItemStack itemstack) {
if(slot < getSizeInventory()) {
if(inventory[slot] == null || itemstack.stackSize + inventory[slot].stackSize <= getInventoryStackLimit()) {
return true;
}
}
return false;
}
@Override
public void clear() {
for(int i = 0; i < inventory.length; i++) {
inventory[i] = null;
}
}
@Override
public String getName() {
return this.inventoryTitle;
}
@Override
public boolean hasCustomName() {
return this.hasCustomName;
}
public void setCustomName(String customName) {
this.hasCustomName = true;
this.inventoryTitle = customName;
}
@Override
public IChatComponent getDisplayName() {
if(hasCustomName()) {
return new ChatComponentText(getName());
}
return new ChatComponentTranslation(getName());
}
/* Supporting methods */
@Override
public boolean isUseableByPlayer(EntityPlayer entityplayer) {
// block changed/got broken?
if(worldObj.getTileEntity(pos) != this || worldObj.getBlockState(pos).getBlock() == Blocks.air) {
return false;
}
return
entityplayer.getDistanceSq((double) pos.getX() + 0.5D, (double) pos.getY() + 0.5D, (double) pos.getZ() + 0.5D)
<= 64D;
}
@Override
public void openInventory(EntityPlayer player) {
}
@Override
public void closeInventory(EntityPlayer player) {
}
/* NBT */
@Override
public void readFromNBT(NBTTagCompound tags) {
super.readFromNBT(tags);
readInventoryFromNBT(tags);
}
public void readInventoryFromNBT(NBTTagCompound tags) {
super.readFromNBT(tags);
this.resize(tags.getInteger("InventorySize"));
readInventoryFromNBT(this, tags);
if(tags.hasKey("CustomName", 8)) {
this.inventoryTitle = tags.getString("CustomName");
}
}
@Override
public void writeToNBT(NBTTagCompound tags) {
super.writeToNBT(tags);
tags.setInteger("InventorySize", inventory.length);
writeInventoryToNBT(this, tags);
if(this.hasCustomName()) {
tags.setString("CustomName", this.inventoryTitle);
}
}
/** Writes the contents of the inventory to the tag */
public static void writeInventoryToNBT(IInventory inventory, NBTTagCompound tag) {
NBTTagList nbttaglist = new NBTTagList();
for(int i = 0; i < inventory.getSizeInventory(); i++) {
if(inventory.getStackInSlot(i) != null) {
NBTTagCompound itemTag = new NBTTagCompound();
itemTag.setByte("Slot", (byte) i);
inventory.getStackInSlot(i).writeToNBT(itemTag);
nbttaglist.appendTag(itemTag);
}
}
tag.setTag("Items", nbttaglist);
}
/** Reads a an inventory from the tag. Overwrites current content */
public static void readInventoryFromNBT(IInventory inventory, NBTTagCompound tag) {
NBTTagList nbttaglist = tag.getTagList("Items", 10);
for(int i = 0; i < nbttaglist.tagCount(); ++i) {
NBTTagCompound itemTag = nbttaglist.getCompoundTagAt(i);
int slot = itemTag.getByte("Slot") & 255;
if(slot >= 0 && slot < inventory.getSizeInventory()) {
inventory.setInventorySlotContents(slot, ItemStack.loadItemStackFromNBT(itemTag));
}
}
}
/* Default implementations of hardly used methods */
public ItemStack getStackInSlotOnClosing(int slot) {
return null;
}
@Override
public int getField(int id) {
return 0;
}
@Override
public void setField(int id, int value) {
}
@Override
public int getFieldCount() {
return 0;
}
}
@@ -0,0 +1,21 @@
package slimeknights.mantle.util;
import net.minecraft.util.StatCollector;
import java.util.Locale;
// localization utils
public abstract class LocUtils {
private LocUtils() {}
/**
* Removes all whitespaces from the string and makes it lowercase.
*/
public static String makeLocString(String unclean) {
return unclean.toLowerCase(Locale.US).replaceAll(" ", "");
}
public static String translateRecursive(String key, Object... params) {
return StatCollector.translateToLocal(StatCollector.translateToLocalFormatted(key, params));
}
}
@@ -0,0 +1,294 @@
package slimeknights.mantle.util;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import slimeknights.mantle.Mantle;
/**
* Utility class that allows to find a specific subset of items in a list of itemstacks.
* Matches can be found through oredictionary, simple nbt-independant item-meta combinations etc.
*
* The match returned by this class can then be used to remove the found recipe match from the items.
*/
public abstract class RecipeMatch {
public final int amountNeeded;
public final int amountMatched;
/**
* @param amountNeeded How many of the itemstack are needed for the match
* @param amountMatched If amount needed itemstacks are present, as how many matches does this count?
*/
public RecipeMatch(int amountMatched, int amountNeeded) {
this.amountMatched = amountMatched;
this.amountNeeded = amountNeeded;
}
/**
* Return all possible inputs that are a single item, if applicable.
*/
public abstract List<ItemStack> getInputs();
public abstract Match matches(ItemStack[] stacks);
public static RecipeMatch of(String oredict) {
return of(oredict, 1);
}
public static RecipeMatch of(String oredict, int matched) {
return of(oredict, 1, matched);
}
public static RecipeMatch of(String oredict, int amount, int matched) {
return new RecipeMatch.Oredict(oredict, amount, matched);
}
public static RecipeMatch of(List<ItemStack> oredict) {
return of(oredict, 1);
}
public static RecipeMatch of(List<ItemStack> oredict, int matched) {
return of(oredict, 1, matched);
}
public static RecipeMatch of(List<ItemStack> oredict, int amount, int matched) {
return new RecipeMatch.Oredict(oredict, amount, matched);
}
public static RecipeMatch of(net.minecraft.item.Item item) {
return of(item, 1);
}
public static RecipeMatch of(net.minecraft.item.Item item, int matched) {
return of(item, 1, matched);
}
public static RecipeMatch of(net.minecraft.item.Item item, int amount, int matched) {
return new RecipeMatch.Item(new ItemStack(item), amount, matched);
}
public static RecipeMatch of(Block block) {
return of(block, 1);
}
public static RecipeMatch of(Block block, int matched) {
return of(block, 1, matched);
}
public static RecipeMatch of(Block block, int amount, int matched) {
return new RecipeMatch.Item(new ItemStack(block), amount, matched);
}
public static RecipeMatch ofNBT(ItemStack stack) {
return ofNBT(stack, 1);
}
public static RecipeMatch ofNBT(ItemStack stack, int matched) {
return new RecipeMatch.ItemCombination(matched, stack);
}
/** Removes the match from the stacks */
public static void removeMatch(ItemStack[] stacks, Match match) {
for(ItemStack stack : match.stacks) {
for(int i = 0; i < stacks.length; i++) {
// nbt sensitive since toolparts etc. use nbt
if(ItemStack.areItemsEqual(stack, stacks[i]) && ItemStack.areItemStackTagsEqual(stack, stacks[i])) {
if(stacks[i].stackSize < stack.stackSize) {
Mantle.logger.error("RecipeMatch has incorrect stacksize! {}", stacks[i].toString());
}
else {
stacks[i].stackSize -= stack.stackSize;
if(stacks[i].stackSize == 0) {
stacks[i] = null;
}
}
break;
}
}
}
}
/** A specific amount of a certain item is needed. Supports wildcard-metadata. Not NBT sensitive. */
public static class Item extends RecipeMatch {
private final ItemStack template;
public Item(ItemStack template, int amountNeeded) {
this(template, amountNeeded, 1);
}
/**
* @param template The itemstack to match
* @param amountNeeded How many of the itemstack are needed for the match
* @param amountMatched If amountneeded itemstacks are present, as how many matches does this count?
*/
public Item(ItemStack template, int amountNeeded, int amountMatched) {
super(amountMatched, amountNeeded);
this.template = template;
}
@Override
public List<ItemStack> getInputs() {
return ImmutableList.of(template);
}
@Override
public Match matches(ItemStack[] stacks) {
List<ItemStack> found = Lists.newLinkedList();
int stillNeeded = amountNeeded;
for(ItemStack stack : stacks) {
if(OreDictionary.itemMatches(template, stack, false)) {
// add the amount found to the list
ItemStack copy = stack.copy();
copy.stackSize = Math.min(copy.stackSize, stillNeeded);
found.add(copy);
stillNeeded -= copy.stackSize;
// we found enough
if(stillNeeded <= 0) {
return new Match(found, amountMatched);
}
}
}
return null;
}
}
/** A combination of multiple items. NBT SENSITIVE! */
public static class ItemCombination extends RecipeMatch {
protected final ItemStack[] itemStacks;
/**
* @param amountMatched If amount needed itemstacks are present, as how many matches does this count?
*/
public ItemCombination(int amountMatched, ItemStack... stacks) {
super(amountMatched, 0);
this.itemStacks = stacks;
}
@Override
public List<ItemStack> getInputs() {
if(itemStacks.length == 0 || itemStacks.length > 1) {
return ImmutableList.of();
}
return ImmutableList.of(itemStacks[0]);
}
@Override
public Match matches(ItemStack[] stacks) {
List<ItemStack> found = Lists.newLinkedList();
Set<Integer> needed = Sets.newHashSet();
for(int i = 0; i < itemStacks.length; i++) {
if(itemStacks[i] != null) {
needed.add(i);
}
}
for(ItemStack stack : stacks) {
Iterator<Integer> iter = needed.iterator();
while(iter.hasNext()) {
int index = iter.next();
ItemStack template = itemStacks[index];
if(ItemStack.areItemsEqual(template, stack) && ItemStack.areItemStackTagsEqual(template, stack)) {
// add the amount found to the list
ItemStack copy = stack.copy();
copy.stackSize = 1;
found.add(copy);
iter.remove();
break;
}
}
}
if(needed.isEmpty()) {
return new Match(found, amountMatched);
}
return null;
}
}
/** A specific amount of an oredicted material is needed to match. */
public static class Oredict extends RecipeMatch {
private final List<ItemStack> oredictEntry; // todo: change this to the actual list in the oredict
public Oredict(List<ItemStack> oredictEntry, int amountNeeded) {
this(oredictEntry, amountNeeded, 1);
}
public Oredict(List<ItemStack> oredictEntry, int amountNeeded, int amountMatched) {
super(amountMatched, amountNeeded);
this.oredictEntry = oredictEntry;
}
public Oredict(String oredictEntry, int amountNeeded) {
this(oredictEntry, amountNeeded, 1);
}
public Oredict(String oredictEntry, int amountNeeded, int amountMatched) {
super(amountMatched, amountNeeded);
this.oredictEntry = OreDictionary.getOres(oredictEntry);
}
@Override
public List<ItemStack> getInputs() {
return oredictEntry;
}
@Override
public Match matches(ItemStack[] stacks) {
List<ItemStack> found = Lists.newLinkedList();
int stillNeeded = amountNeeded;
for(ItemStack ore : oredictEntry) {
for(ItemStack stack : stacks) {
if(OreDictionary.itemMatches(ore, stack, false)) {
// add the amount found to the list
ItemStack copy = stack.copy();
copy.stackSize = Math.min(copy.stackSize, stillNeeded);
found.add(copy);
stillNeeded -= copy.stackSize;
// we found enough
if(stillNeeded <= 0) {
return new Match(found, amountMatched);
}
}
}
}
return null;
}
}
/** Represents a collection of items that match the recipies */
public static class Match {
/** The stacks that have to be removed to apply this match */
public List<ItemStack> stacks;
/** How often the recipe is found within this match */
public int amount;
public Match(List<ItemStack> stacks, int amount) {
this.stacks = stacks;
this.amount = amount;
}
}
}
@@ -0,0 +1,133 @@
package slimeknights.mantle.util;
import com.google.common.collect.Lists;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import java.util.Collection;
import java.util.List;
/**
* Contains a set of matches. Allows you to easily find if a set of itemstacks matches one of them.
*/
// MANTLE
public class RecipeMatchRegistry {
protected final List<RecipeMatch> items = Lists.newArrayList();
public RecipeMatch.Match matches(Collection<ItemStack> stacks) {
return matches(stacks.toArray(new ItemStack[stacks.size()]));
}
// looks for a match in the given itemstacks
public RecipeMatch.Match matches(ItemStack... stacks) {
for(RecipeMatch recipe : items) {
RecipeMatch.Match match = recipe.matches(stacks);
if(match != null) {
return match;
}
}
return null;
}
// looks for a match with at least the given amount in the given itemstacks
public RecipeMatch.Match matches(ItemStack[] stacks, int minAmount) {
stacks = copyItemStackArray(stacks); // copy so we don't modify original
List<RecipeMatch.Match> matches = Lists.newLinkedList();
RecipeMatch.Match match;
int sum = 0;
while(sum < minAmount && (match = matches(stacks)) != null) {
matches.add(match);
RecipeMatch.removeMatch(stacks, match);
sum += match.amount;
}
// not enough found
if(sum < minAmount) {
return null;
}
// merge all found matches into one match
List<ItemStack> foundStacks = Lists.newLinkedList();
for(RecipeMatch.Match m : matches) {
foundStacks.addAll(m.stacks);
}
return new RecipeMatch.Match(foundStacks, sum);
}
/**
* Associates an oredict entry with this material. Used for repairing and other.
*
* @param oredictItem Oredict-String
* @param amountNeeded How many of this item are needed to count as one full material item.
* @param amountMatched If both item and amount are present, how often did they match?
*/
public void addItem(String oredictItem, int amountNeeded, int amountMatched) {
items.add(new RecipeMatch.Oredict(oredictItem, amountNeeded, amountMatched));
}
public void addItem(String oredictItem) {
addItem(oredictItem, 1, 1);
}
/**
* Associates a block with this material. Used for repairing and other.
*
* @param amountMatched For how many matches the block counts (e.g. redstone dust = 1 match, Redstone block = 9)
*/
public void addItem(Block block, int amountMatched) {
items.add(new RecipeMatch.Item(new ItemStack(block), 1, amountMatched));
}
/**
* Associates an item entry with this material. Used for repairing and other.
*
* @param item The item
* @param amountNeeded How many of this item are needed to count as one full material item.
* @param amountMatched If both item and amount are present, how often did they match?
*/
public void addItem(Item item, int amountNeeded, int amountMatched) {
items.add(new RecipeMatch.Item(new ItemStack(item), amountNeeded, amountMatched));
}
/**
* Associates an item entry with this material. Used for repairing and other.
*
* @param item The item
* @param amountNeeded How many of this item are needed to count as one full material item.
* @param amountMatched If both item and amount are present, how often did they match?
*/
public void addItem(ItemStack item, int amountNeeded, int amountMatched) {
items.add(new RecipeMatch.Item(item, amountNeeded, amountMatched));
}
/**
* Associates an item with this material. Used for repairing and other.
*/
public void addItem(Item item) {
addItem(item, 1, 1);
}
public void addRecipeMatch(RecipeMatch match) {
items.add(match);
}
public static ItemStack[] copyItemStackArray(ItemStack[] in) {
ItemStack[] stacksCopy = new ItemStack[in.length];
for(int i = 0; i < in.length; i++) {
if(in[i] != null) {
stacksCopy[i] = in[i].copy();
}
}
return stacksCopy;
}
}
@@ -1,4 +1,4 @@
package mantle.utils;
package slimeknights.mantle.util;
import java.util.List;
import java.util.Map;
@@ -15,13 +15,15 @@ import net.minecraftforge.common.ChestGenHooks;
@SuppressWarnings("unchecked")
public class RecipeRemover
{
public static void removeShapedRecipes (List<ItemStack> removelist)
public static void removeShapedRecipes(List<ItemStack> removelist)
{
for (ItemStack stack : removelist)
{
removeShapedRecipe(stack);
}
}
public static void removeAnyRecipe (ItemStack resultItem)
public static void removeAnyRecipe(ItemStack resultItem)
{
List<IRecipe> recipes = CraftingManager.getInstance().getRecipeList();
for (int i = 0; i < recipes.size(); i++)
@@ -35,7 +37,7 @@ public class RecipeRemover
}
}
public static void removeShapedRecipe (ItemStack resultItem)
public static void removeShapedRecipe(ItemStack resultItem)
{
List<IRecipe> recipes = CraftingManager.getInstance().getRecipeList();
for (int i = 0; i < recipes.size(); i++)
@@ -54,7 +56,7 @@ public class RecipeRemover
}
}
public static void removeShapelessRecipe (ItemStack resultItem)
public static void removeShapelessRecipe(ItemStack resultItem)
{
List<IRecipe> recipes = CraftingManager.getInstance().getRecipeList();
for (int i = 0; i < recipes.size(); i++)
@@ -73,24 +75,24 @@ public class RecipeRemover
}
}
public static void removeFurnaceRecipe (ItemStack resultItem)
public static void removeFurnaceRecipe(ItemStack resultItem)
{
Map<ItemStack, ItemStack> recipes = FurnaceRecipes.instance().getSmeltingList();
recipes.remove(resultItem);
}
public static void removeFurnaceRecipe (Item i, int metadata)
public static void removeFurnaceRecipe(Item i, int metadata)
{
removeFurnaceRecipe(new ItemStack(i, 1, metadata));
}
public static void removeFurnaceRecipe (Item i)
public static void removeFurnaceRecipe(Item i)
{
removeFurnaceRecipe(new ItemStack(i, 1, 32767));
}
//removes from all vanilla worldgen chests :D
public static void removeFromChests (ItemStack resultItem)
public static void removeFromChests(ItemStack resultItem)
{
ChestGenHooks.getInfo(ChestGenHooks.BONUS_CHEST).removeItem(resultItem);
ChestGenHooks.getInfo(ChestGenHooks.VILLAGE_BLACKSMITH).removeItem(resultItem);
@@ -0,0 +1,27 @@
package slimeknights.mantle.util;
public class SlimeknightException extends RuntimeException {
public SlimeknightException() {
}
public SlimeknightException(String message) {
super(message);
}
public SlimeknightException(String message, Object... params) {
super(String.format(message, params));
}
public SlimeknightException(String message, Throwable cause) {
super(message, cause);
}
public SlimeknightException(Throwable cause) {
super(cause);
}
public SlimeknightException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
@@ -0,0 +1,40 @@
package slimeknights.mantle.util;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTTagString;
public class TagHelper {
public static int TAG_TYPE_STRING = (new NBTTagString()).getId();
public static int TAG_TYPE_COMPOUND = (new NBTTagCompound()).getId();
private TagHelper() {
}
/* Generic Tag Operations */
public static NBTTagCompound getTagSafe(ItemStack stack) {
if(stack == null || stack.getItem() == null || !stack.hasTagCompound()) {
return new NBTTagCompound();
}
return stack.getTagCompound();
}
public static NBTTagCompound getTagSafe(NBTTagCompound tag, String key) {
if(tag == null || !tag.hasKey(key)) {
return new NBTTagCompound();
}
return tag.getCompoundTag(key);
}
public static NBTTagList getTagListSafe(NBTTagCompound tag, String key, int type) {
if(tag == null || !tag.hasKey(key)) {
return new NBTTagList();
}
return tag.getTagList(key, type);
}
}
+11
View File
@@ -0,0 +1,11 @@
# Mantle -- Access Transformer
# GuiContainer
public net.minecraft.client.gui.inventory.GuiContainer field_146999_f #xSize
public net.minecraft.client.gui.inventory.GuiContainer field_147000_g #ySize
public net.minecraft.client.gui.inventory.GuiContainer field_147009_r #guiTop
public net.minecraft.client.gui.inventory.GuiContainer field_147003_i #guiLeft
public net.minecraft.client.gui.inventory.GuiContainer func_146977_a(Lnet/minecraft/inventory/Slot;)V #renderSlot
public net.minecraft.client.gui.inventory.GuiContainer func_146981_a(Lnet/minecraft/inventory/Slot;II)Z #isMouseOverSlot
# GuiScreen
public net.minecraft.client.gui.GuiScreen field_146292_n #buttonList
File renamed without changes.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 18 KiB

@@ -0,0 +1,18 @@
{
"parent": "builtin/generated",
"textures": {
"layer0": "mantle:items/mantlebook_blue"
},
"display": {
"thirdperson": {
"rotation": [ -90, 0, 0 ],
"translation": [ 0, 1, -3 ],
"scale": [ 0.55, 0.55, 0.55 ]
},
"firstperson": {
"rotation": [ 0, -135, 25 ],
"translation": [ 0, 4, 2 ],
"scale": [ 1.7, 1.7, 1.7 ]
}
}
}
File renamed without changes.

Before

Width:  |  Height:  |  Size: 7.7 KiB

After

Width:  |  Height:  |  Size: 7.7 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 3.7 KiB

After

Width:  |  Height:  |  Size: 3.7 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.6 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 12 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 8.3 KiB

After

Width:  |  Height:  |  Size: 8.3 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 3.0 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 468 B

After

Width:  |  Height:  |  Size: 468 B

File renamed without changes.

Before

Width:  |  Height:  |  Size: 465 B

After

Width:  |  Height:  |  Size: 465 B

File renamed without changes.

Before

Width:  |  Height:  |  Size: 468 B

After

Width:  |  Height:  |  Size: 468 B

File renamed without changes.

Before

Width:  |  Height:  |  Size: 468 B

After

Width:  |  Height:  |  Size: 468 B

File renamed without changes.

Before

Width:  |  Height:  |  Size: 464 B

After

Width:  |  Height:  |  Size: 464 B

File renamed without changes.

Before

Width:  |  Height:  |  Size: 465 B

After

Width:  |  Height:  |  Size: 465 B

File renamed without changes.

Before

Width:  |  Height:  |  Size: 436 B

After

Width:  |  Height:  |  Size: 436 B

File renamed without changes.

Before

Width:  |  Height:  |  Size: 455 B

After

Width:  |  Height:  |  Size: 455 B

@@ -1,5 +1,5 @@
[{
"modid": "Mantle",
"modid": "mantle",
"name": "Mantle",
"description": "Shared code for Slime Knights mods and others.",
"version": "${version}",
-120
View File
@@ -1,120 +0,0 @@
package mantle;
import static mantle.lib.CoreRepo.logger;
import static mantle.lib.CoreRepo.modId;
import static mantle.lib.CoreRepo.modName;
import static mantle.lib.CoreRepo.modVersion;
import cpw.mods.fml.common.event.FMLServerStartedEvent;
import mantle.books.BookData;
import mantle.books.BookDataStore;
import mantle.common.IDDumps;
import mantle.common.MProxyCommon;
import mantle.items.Manual;
import mantle.lib.CoreConfig;
import mantle.lib.CoreRepo;
import mantle.lib.environment.EnvironmentChecks;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.registry.GameRegistry;
import mantle.utils.CraftingHandler;
import java.io.File;
/**
* Mantle
*
* Central mod object for Mantle
*
* @author Sunstrike <[email protected]>
*/
@Mod(modid = modId, name = modName, version = modVersion, dependencies = "required-after:Forge@[10.13,)")
public class Mantle
{
/* Instance of this mod, used for grabbing prototype fields */
@Instance("Mantle")
public static Mantle instance;
/* Proxies for sides, used for graphics processing */
@SidedProxy(clientSide = "mantle.client.MProxyClient", serverSide = "mantle.common.MProxyCommon")
public static MProxyCommon proxy;
public static Manual mantleBook;
/**
* Constructor
*
* EnvChecks invoked here so they run as soon as possible to enhance crash reports that may happen in preinit.
*/
public Mantle()
{
EnvironmentChecks.verifyEnvironmentSanity();
}
/**
* FML preinitialisation handler
*
* This is where we load our configs and related data, preparing for main load.
*
* @param evt The FMLPreInitializationEvent from FML
*/
@EventHandler
public void preInit (FMLPreInitializationEvent evt)
{
logger.info("Mantle (" + modVersion + ") -- Preparing for launch.");
logger.info("Entering preinitialization phase.");
CoreConfig.loadConfiguration(evt.getModConfigurationDirectory());
NetworkRegistry.INSTANCE.registerGuiHandler(instance, proxy);
mantleBook = (Manual) new Manual().setUnlocalizedName("mantle.manual");
GameRegistry.registerItem(mantleBook, "mantleBook");
}
/**
* FML initialisation handler
*
* This is where we handle basic loading and populating any missing data in the Repo
*
* @param evt The FMLInitializationEvent from FML
*/
@EventHandler
public void Init (FMLInitializationEvent evt)
{
logger.info("Entering initialization phase.");
proxy.registerRenderer();
}
/**
* FML postinitialisation handler
*
* Final chance for cleanup before main game launch
*
* @param evt The FMLPostInitializationEvent from FML
*/
@EventHandler
public void postInit (FMLPostInitializationEvent evt)
{
logger.info("Entering postinitialization phase.");
proxy.readManuals();
BookData data = new BookData();
data.unlocalizedName = "item.mantle.manual.test";
data.toolTip = "Test Book";
data.modID = CoreRepo.modId;
BookDataStore.addBook(data);
mantleBook.updateManual();
CoreConfig.loadBookLocations();
IDDumps.dump();
}
@EventHandler
public void serverStart(FMLServerStartedEvent evt)
{
CraftingHandler.logConflicts();
}
}
-31
View File
@@ -1,31 +0,0 @@
package mantle.blocks;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.registry.GameData;
public class BlockUtils
{
public static Block getBlockFromItem (Item item)
{
return Block.getBlockFromItem(item);
}
@SuppressWarnings("unused")
public static Block getBlockFromItemStack (ItemStack itemStack)
{
return getBlockFromItem(itemStack.getItem());
}
public static String getUniqueName (Block block)
{
return GameData.getBlockRegistry().getNameForObject(block);
}
public static Block getBlockFromUniqueName (String uniqueName)
{
return GameData.getBlockRegistry().getObject(uniqueName);
}
}
-43
View File
@@ -1,43 +0,0 @@
package mantle.blocks;
import mantle.debug.DebugHelper;
import mantle.debug.IDebuggable;
import mantle.items.iface.IDebugItem;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
/**
* Root class for inheriting the Minecraft Block.
*
* @author Sunstrike <[email protected]>
*/
public abstract class MantleBlock extends Block
{
public MantleBlock(Material material)
{
super(material);
}
// IDebuggable support - Uses a stick for debug purposes.
@Override
public void onBlockClicked (World world, int x, int y, int z, EntityPlayer player)
{
if (FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER && player.getHeldItem() != null
&& (player.getHeldItem().getItem() == Items.stick || player.getHeldItem().getItem() instanceof IDebugItem))
{
TileEntity te = world.getTileEntity(x, y, z);
if (te instanceof IDebuggable)
DebugHelper.handleDebugData(((IDebuggable) te).getDebugInfo(player));
}
super.onBlockClicked(world, x, y, z, player);
}
}
@@ -1,102 +0,0 @@
package mantle.blocks.abstracts;
import java.util.Random;
import mantle.blocks.iface.IFacingLogic;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import cpw.mods.fml.common.FMLCommonHandler;
public abstract class AdaptiveInventoryLogic extends InventoryLogic implements IFacingLogic
{
Random random = new Random();
protected int inventorySize;
public AdaptiveInventoryLogic()
{
super(0);
}
protected void adjustInventory (int size, boolean forceAdjust)
{
if (size != inventorySize || forceAdjust)
{
inventorySize = size;
ItemStack[] tempInv = inventory;
inventory = new ItemStack[size];
int invLength = tempInv.length > inventory.length ? inventory.length : tempInv.length;
System.arraycopy(tempInv, 0, inventory, 0, invLength);
if (tempInv.length > inventory.length)
{
for (int i = inventory.length; i < tempInv.length; i++)
{
ItemStack stack = tempInv[i];
if (stack != null)
{
float jumpX = random.nextFloat() * 0.8F + 0.1F;
float jumpY = random.nextFloat() * 0.8F + 0.1F;
float jumpZ = random.nextFloat() * 0.8F + 0.1F;
int offsetX = 0;
int offsetY = 0;
int offsetZ = 0;
switch (getTossDirection())
{
case 0: // -y
offsetY--;
break;
case 1: // +y
offsetY++;
break;
case 2: // +z
offsetZ--;
break;
case 3: // -z
offsetZ++;
break;
case 4: // +x
offsetX--;
break;
case 5: // -x
offsetX++;
break;
}
while (stack.stackSize > 0)
{
int itemSize = random.nextInt(21) + 10;
if (itemSize > stack.stackSize)
{
itemSize = stack.stackSize;
}
stack.stackSize -= itemSize;
EntityItem entityitem = new EntityItem(worldObj, (double) ((float) xCoord + jumpX + offsetX), (double) ((float) yCoord + jumpY),
(double) ((float) zCoord + jumpZ + offsetZ), new ItemStack(stack.getItem(), itemSize, stack.getMetadata()));
if (stack.hasTagCompound())
{
entityitem.getEntityItem().setTagCompound((NBTTagCompound) stack.getTagCompound().copy());
}
float offset = 0.05F;
entityitem.motionX = (double) ((float) random.nextGaussian() * offset);
entityitem.motionY = (double) ((float) random.nextGaussian() * offset + 0.2F);
entityitem.motionZ = (double) ((float) random.nextGaussian() * offset);
worldObj.spawnEntityInWorld(entityitem);
}
}
}
}
}
}
public int getTossDirection ()
{
return getRenderDirection();
}
}
@@ -1,217 +0,0 @@
package mantle.blocks.abstracts;
import java.util.*;
import net.minecraft.entity.player.*;
import net.minecraft.inventory.*;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.*;
import net.minecraft.world.World;
public abstract class ExpandableInventoryLogic extends InventoryLogic implements IInventory
{
public ExpandableInventoryLogic()
{
super(0);
}
protected ArrayList<ItemStack> inventory = new ArrayList<ItemStack>();
protected String invName;
@Override
public ItemStack getStackInSlot (int slot)
{
return slot < inventory.size() ? inventory.get(slot) : null;
}
public boolean isStackInSlot (int slot)
{
return slot < inventory.size() && inventory.get(slot) != null;
}
@Override
public int getSizeInventory ()
{
return inventory.size();
}
public int getMaxSize ()
{
return 64;
}
@Override
public int getInventoryStackLimit ()
{
return 64;
}
public boolean canDropInventorySlot (int slot)
{
return true;
}
@Override
public void setInventorySlotContents (int slot, ItemStack itemstack)
{
if (slot < inventory.size())
{
inventory.set(slot, itemstack);
}
else if (slot == inventory.size())
{
inventory.add(itemstack);
}
else if (slot < getMaxSize())
{
inventory.ensureCapacity(slot);
inventory.set(slot, itemstack);
}
else
{
return;
}
if (itemstack != null && itemstack.stackSize > getInventoryStackLimit())
{
itemstack.stackSize = getInventoryStackLimit();
}
}
@Override
public ItemStack decrStackSize (int slot, int quantity)
{
if (slot < inventory.size() && inventory.get(slot) != null)
{
if (inventory.get(slot).stackSize <= quantity)
{
ItemStack stack = inventory.get(slot);
inventory.set(slot, null);
return stack;
}
ItemStack split = inventory.get(slot).splitStack(quantity);
if (inventory.get(slot).stackSize == 0)
{
inventory.set(slot, null);
}
return split;
}
else
{
return null;
}
}
/* Supporting methods */
@Override
public boolean isUseableByPlayer (EntityPlayer entityplayer)
{
if (worldObj.getTileEntity(xCoord, yCoord, zCoord) != this)
return false;
else
return entityplayer.getDistance((double) xCoord + 0.5D, (double) yCoord + 0.5D, (double) zCoord + 0.5D) <= 64D;
}
public abstract Container getGuiContainer (InventoryPlayer inventoryplayer, World world, int x, int y, int z);
/* NBT */
@Override
public void readFromNBT (NBTTagCompound tags)
{
super.readFromNBT(tags);
this.invName = tags.getString("InvName");
NBTTagList nbttaglist = tags.getTagList("Items", 9);
inventory = new ArrayList<ItemStack>();
inventory.ensureCapacity(nbttaglist.tagCount() > getMaxSize() ? getMaxSize() : nbttaglist.tagCount());
for (int iter = 0; iter < nbttaglist.tagCount(); iter++)
{
NBTTagCompound tagList = nbttaglist.getCompoundTagAt(iter);
byte slotID = tagList.getByte("Slot");
if (slotID >= 0 && slotID < inventory.size())
{
inventory.set(slotID, ItemStack.loadItemStackFromNBT(tagList));
}
}
}
@Override
public void writeToNBT (NBTTagCompound tags)
{
super.writeToNBT(tags);
if (invName != null)
tags.setString("InvName", invName);
NBTTagList nbttaglist = new NBTTagList();
for (int iter = 0; iter < inventory.size(); iter++)
{
if (inventory.get(iter) != null)
{
NBTTagCompound tagList = new NBTTagCompound();
tagList.setByte("Slot", (byte) iter);
inventory.get(iter).writeToNBT(tagList);
nbttaglist.appendTag(tagList);
}
}
tags.setTag("Items", nbttaglist);
}
/* Default implementations of hardly used methods */
public ItemStack getStackInSlotOnClosing (int slot)
{
return null;
}
public void openChest ()
{
}
public void closeChest ()
{
}
protected abstract String getDefaultName ();
public void setInvName (String name)
{
this.invName = name;
}
public String getInvName ()
{
return this.isInvNameLocalized() ? this.invName : getDefaultName();
}
public boolean isInvNameLocalized ()
{
return this.invName != null && this.invName.length() > 0;
}
public void cleanInventory ()
{
Iterator<ItemStack> i1 = inventory.iterator();
while (i1.hasNext())
{
if (i1.next() == null)
{
i1.remove();
}
}
}
@Override
public boolean isItemValidForSlot (int slot, ItemStack itemstack)
{
if (slot < getSizeInventory())
{
if (inventory.get(slot) == null || itemstack.stackSize + inventory.get(slot).stackSize <= getInventoryStackLimit())
return true;
}
else
{
return slot < getMaxSize();
}
return false;
}
}
@@ -1,217 +0,0 @@
package mantle.blocks.abstracts;
import java.util.Random;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
import mantle.blocks.iface.IActiveLogic;
import mantle.blocks.iface.IFacingLogic;
import mantle.debug.DebugHelper;
import mantle.debug.IDebuggable;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityChest;
import net.minecraft.util.IIcon;
import net.minecraft.util.MathHelper;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
public abstract class InventoryBlock extends BlockContainer
{
protected Random rand = new Random();
protected InventoryBlock(Material material)
{
super(material);
}
/* Logic backend */
public TileEntity createNewTileEntity (World var1)
{
return null;
}
public abstract TileEntity createNewTileEntity (World world, int metadata);
public abstract Integer getGui (World world, int x, int y, int z, EntityPlayer entityplayer);
public abstract Object getModInstance ();
@Override
public boolean onBlockActivated (World world, int x, int y, int z, EntityPlayer player, int side, float clickX, float clickY, float clickZ)
{
if (player.isSneaking())
return false;
Integer integer = getGui(world, x, y, z, player);
if (integer == null || integer == -1)
{
return false;
}
else
{
if (!world.isRemote)
player.openGui(getModInstance(), integer, world, x, y, z);
return true;
}
}
/* Inventory */
@Override
public void breakBlock (World par1World, int x, int y, int z, Block blockID, int meta)
{
TileEntity te = par1World.getTileEntity(x, y, z);
if (te != null && te instanceof InventoryLogic)
{
InventoryLogic logic = (InventoryLogic) te;
logic.removeBlock();
for (int iter = 0; iter < logic.getSizeInventory(); ++iter)
{
ItemStack stack = logic.getStackInSlot(iter);
if (stack != null && logic.canDropInventorySlot(iter))
{
float jumpX = rand.nextFloat() * 0.8F + 0.1F;
float jumpY = rand.nextFloat() * 0.8F + 0.1F;
float jumpZ = rand.nextFloat() * 0.8F + 0.1F;
while (stack.stackSize > 0)
{
int itemSize = rand.nextInt(21) + 10;
if (itemSize > stack.stackSize)
{
itemSize = stack.stackSize;
}
stack.stackSize -= itemSize;
EntityItem entityitem = new EntityItem(par1World, (double) ((float) x + jumpX), (double) ((float) y + jumpY), (double) ((float) z + jumpZ), new ItemStack(stack.getItem(),
itemSize, stack.getMetadata()));
if (stack.hasTagCompound())
{
entityitem.getEntityItem().setTagCompound((NBTTagCompound) stack.getTagCompound().copy());
}
float offset = 0.05F;
entityitem.motionX = (double) ((float) rand.nextGaussian() * offset);
entityitem.motionY = (double) ((float) rand.nextGaussian() * offset + 0.2F);
entityitem.motionZ = (double) ((float) rand.nextGaussian() * offset);
par1World.spawnEntityInWorld(entityitem);
}
}
}
}
super.breakBlock(par1World, x, y, z, blockID, meta);
}
/* Placement */
int side = -1;
//This class does not have an actual block placed in the world
@Override
public int onBlockPlaced (World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ, int meta)
{
this.side = side;
return meta;
}
@Override
@SuppressWarnings("deprecation") // TODO: Remove this when setDirection calls updated.
public void onBlockPlacedBy (World world, int x, int y, int z, EntityLivingBase entityliving, ItemStack stack)
{
TileEntity logic = world.getTileEntity(x, y, z);
if (logic instanceof IFacingLogic)
{
IFacingLogic direction = (IFacingLogic) logic;
// TODO: Convert all setDirection calls to modern invokation, when that's ready.
if (side != -1)
{
direction.setDirection(side);
side = -1;
}
if (entityliving == null)
{
direction.setDirection(0F, 0F, null);
}
else
{
direction.setDirection(entityliving.rotationYaw * 4F, entityliving.rotationPitch, entityliving);
}
}
if (logic instanceof InventoryLogic)
{
InventoryLogic inv = (InventoryLogic) logic;
inv.placeBlock(entityliving, stack);
if (stack.hasDisplayName())
{
inv.setInvName(stack.getDisplayName());
}
}
}
@SuppressWarnings("unused")
public static boolean isActive (IBlockAccess world, int x, int y, int z)
{
TileEntity logic = world.getTileEntity(x, y, z);
if (logic instanceof IActiveLogic)
{
return ((IActiveLogic) logic).getActive();
}
return false;
}
public int damageDropped (int meta)
{
return meta;
}
/* Textures */
public IIcon[] icons;
public abstract String[] getTextureNames ();
public abstract String getTextureDomain (int textureNameIndex);
@Override
public void registerIcons (IIconRegister iconRegister)
{
String[] textureNames = getTextureNames();
this.icons = new IIcon[textureNames.length];
for (int i = 0; i < this.icons.length; ++i)
{
this.icons[i] = iconRegister.registerIcon(getTextureDomain(i) + ":" + textureNames[i]);
}
}
/* IDebuggable */
@Override
public void onBlockClicked (World world, int x, int y, int z, EntityPlayer player)
{
if (FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER && player.getHeldItem() != null && player.getHeldItem().getItem() != null && player.getHeldItem().getItem() == Items.stick)
{
TileEntity te = world.getTileEntity(x, y, z);
if (te instanceof IDebuggable)
{
DebugHelper.handleDebugData(((IDebuggable) te).getDebugInfo(player));
}
}
super.onBlockClicked(world, x, y, z, player);
}
}
@@ -1,286 +0,0 @@
package mantle.blocks.abstracts;
import mantle.debug.DebugData;
import mantle.debug.IDebuggable;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
/*
* A simple logic class for storing items
* Abstract to avoid instantiation
*/
public abstract class InventoryLogic extends TileEntity implements IInventory, IDebuggable
{
protected ItemStack[] inventory;
protected String invName;
protected int stackSizeLimit;
public InventoryLogic(int invSize)
{
this(invSize, 64);
}
public InventoryLogic(int invSize, int maxStackSize)
{
inventory = new ItemStack[invSize];
stackSizeLimit = maxStackSize;
}
/* Inventory management */
@Override
public ItemStack getStackInSlot (int slot)
{
return slot < inventory.length ? inventory[slot] : null;
}
public boolean isStackInSlot (int slot)
{
return slot < inventory.length && inventory[slot] != null;
}
@Override
public int getSizeInventory ()
{
return inventory.length;
}
@Override
public int getInventoryStackLimit ()
{
return stackSizeLimit;
}
public boolean canDropInventorySlot (int slot)
{
return true;
}
@Override
public void setInventorySlotContents (int slot, ItemStack itemstack)
{
inventory[slot] = itemstack;
if (itemstack != null && itemstack.stackSize > getInventoryStackLimit())
{
itemstack.stackSize = getInventoryStackLimit();
}
}
@Override
public ItemStack decrStackSize (int slot, int quantity)
{
if (inventory[slot] != null)
{
if (inventory[slot].stackSize <= quantity)
{
ItemStack stack = inventory[slot];
inventory[slot] = null;
return stack;
}
ItemStack split = inventory[slot].splitStack(quantity);
if (inventory[slot].stackSize == 0)
{
inventory[slot] = null;
}
return split;
}
else
{
return null;
}
}
/* Supporting methods */
@Override
public boolean isUseableByPlayer (EntityPlayer entityplayer)
{
if (worldObj.getTileEntity(xCoord, yCoord, zCoord) != this)
return false;
else
return entityplayer.getDistance((double) xCoord + 0.5D, (double) yCoord + 0.5D, (double) zCoord + 0.5D) <= 64D;
}
public abstract Container getGuiContainer (InventoryPlayer inventoryplayer, World world, int x, int y, int z);
/* NBT */
@Override
public void readFromNBT (NBTTagCompound tags)
{
super.readFromNBT(tags);
readInventoryFromNBT(tags);
}
public void readInventoryFromNBT (NBTTagCompound tags)
{
super.readFromNBT(tags);
NBTTagList nbttaglist = tags.getTagList("Items", 10);
this.inventory = new ItemStack[this.getSizeInventory()];
if (tags.hasKey("CustomName", 8))
{
this.invName = tags.getString("CustomName");
}
for (int i = 0; i < nbttaglist.tagCount(); ++i)
{
NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
int j = nbttagcompound1.getByte("Slot") & 255;
if (j >= 0 && j < this.inventory.length)
{
this.inventory[j] = ItemStack.loadItemStackFromNBT(nbttagcompound1);
}
}
//Not removed in case of things going terribly wrong
// super.readFromNBT(tags);
// this.invName = tags.getString("InvName");
// NBTTagList nbttaglist = tags.getTagList("Items", 9);
// inventory = new ItemStack[getSizeInventory()];
// for (int iter = 0; iter < nbttaglist.tagCount(); iter++)
// {
// NBTTagCompound tagList = (NBTTagCompound) nbttaglist.getCompoundTagAt(iter);
// byte slotID = tagList.getByte("Slot");
// if (slotID >= 0 && slotID < inventory.length)
// {
// inventory[slotID] = ItemStack.loadItemStackFromNBT(tagList);
// }
// }
}
@Override
public void writeToNBT (NBTTagCompound tags)
{
super.writeToNBT(tags);
writeInventoryToNBT(tags);
}
public void writeInventoryToNBT (NBTTagCompound tags)
{
super.writeToNBT(tags);
NBTTagList nbttaglist = new NBTTagList();
for (int i = 0; i < this.inventory.length; ++i)
{
if (this.inventory[i] != null)
{
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
nbttagcompound1.setByte("Slot", (byte)i);
this.inventory[i].writeToNBT(nbttagcompound1);
nbttaglist.appendTag(nbttagcompound1);
}
}
tags.setTag("Items", nbttaglist);
if (this.isInvNameLocalized())
{
tags.setString("CustomName", this.invName);
}
//Not removed in case of things going terribly wrong
// if (invName != null)
// tags.setString("InvName", invName);
// NBTTagList nbttaglist = new NBTTagList();
// for (int iter = 0; iter < inventory.length; iter++)
// {
// if (inventory[iter] != null)
// {
// NBTTagCompound tagList = new NBTTagCompound();
// tagList.setByte("Slot", (byte) iter);
// inventory[iter].writeToNBT(tagList);
// nbttaglist.appendTag(tagList);
// }
// }
//
// tags.setTag("Items", nbttaglist);
}
/* Cause of the heisenbug. Do not uncomment! */
/*public void superReadFromNBT (NBTTagCompound tags)
{
super.readFromNBT(tags);
}
public void superWriteToNBT (NBTTagCompound tags)
{
super.writeToNBT(tags);
}*/
/* Default implementations of hardly used methods */
public ItemStack getStackInSlotOnClosing (int slot)
{
return null;
}
public void openChest ()
{
}
public void closeChest ()
{
}
protected abstract String getDefaultName ();
public void setInvName (String name)
{
this.invName = name;
}
public String getInvName ()
{
return this.isInvNameLocalized() ? this.invName : getDefaultName();
}
public boolean hasCustomInventoryName()
{
return isInvNameLocalized();
}
public boolean isInvNameLocalized ()
{
return this.invName != null && this.invName.length() > 0;
}
@Override
public boolean isItemValidForSlot (int slot, ItemStack itemstack)
{
if (slot < getSizeInventory())
{
if (inventory[slot] == null || itemstack.stackSize + inventory[slot].stackSize <= getInventoryStackLimit())
return true;
}
return false;
}
public void placeBlock (EntityLivingBase entity, ItemStack stack)
{
}
public void removeBlock ()
{
}
/* IDebuggable */
@Override
public DebugData getDebugInfo (EntityPlayer player)
{
String[] strs = new String[1];
strs[0] = "invName: " + invName + ", inventory.length: " + inventory.length + ", stackSizeLimit: " + stackSizeLimit;
return new DebugData(player, getClass(), strs);
}
}
@@ -1,90 +0,0 @@
package mantle.blocks.abstracts;
import java.util.List;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
/**
* Slab version of InventoryBlock.
*
* @author mDiyo
*/
public abstract class InventorySlab extends InventoryBlock
{
public InventorySlab(Material material)
{
super(material);
}
/* Rendering */
@Override
//TODO: renderAsNormalBlock()
public boolean renderAsNormalBlock ()
{
return false;
}
//TODO: isOpaqueCube()
@Override
public boolean isOpaqueCube ()
{
return false;
}
//TODO shouldSideBeRendered
@Override
public boolean shouldSideBeRendered (IBlockAccess world, int x, int y, int z, int side)
{
if (side > 1)
return super.shouldSideBeRendered(world, x, y, z, side);
int meta = world.getBlockMetadata(x, y, z);
boolean top = (meta | 8) == 1;
if ((top && side == 0) || (!top && side == 1))
return true;
return super.shouldSideBeRendered(world, x, y, z, side);
}
//TODO: addCollisionBoxesToList()
@Override
@SuppressWarnings("rawtypes")
public void addCollisionBoxesToList (World world, int x, int y, int z, AxisAlignedBB axisalignedbb, List arraylist, Entity entity)
{
setBlockBoundsBasedOnState(world, x, y, z);
super.addCollisionBoxesToList(world, x, y, z, axisalignedbb, arraylist, entity);
}
public void setBlockBoundsForItemRender ()
{
//TODO: setBlockBounds
setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.5F, 1.0F);
}
public void setBlockBoundsBasedOnState (IBlockAccess world, int x, int y, int z)
{
int meta = world.getBlockMetadata(x, y, z) / 8;
float minY = meta == 1 ? 0.5F : 0.0F;
float maxY = meta == 1 ? 1.0F : 0.5F;
setBlockBounds(0.0F, minY, 0F, 1.0F, maxY, 1.0F);
}
public int onBlockPlaced (World par1World, int blockX, int blockY, int blockZ, int side, float clickX, float clickY, float clickZ, int metadata)
{
if (side == 1)
return metadata;
if (side == 0 || clickY >= 0.5F)
return metadata | 8;
return metadata;
}
public int damageDropped (int meta)
{
return meta % 8;
}
}
@@ -1,71 +0,0 @@
package mantle.blocks.abstracts;
import static mantle.lib.CoreRepo.logger;
import net.minecraft.block.Block;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MathHelper;
/**
*
* @author progwml6
* base class for itemBlocks with different unlocalized names based on metadata
*/
public class MultiItemBlock extends ItemBlock
{
private String blockType[];
private String unlocalizedName;
private String append;
private int specialIndex[] = { -1, -1 };
public MultiItemBlock(Block b, String itemBlockUnlocalizedName, String[] blockTypes)
{
super(b);
if (itemBlockUnlocalizedName.isEmpty())
this.unlocalizedName = super.getUnlocalizedName();
else
this.unlocalizedName = itemBlockUnlocalizedName;
this.blockType = blockTypes;
this.append = "";
}
public MultiItemBlock(Block b, String itemBlockUnlocalizedName, String appendToEnd, String[] blockTypes)
{
super(b);
this.unlocalizedName = itemBlockUnlocalizedName;
this.blockType = blockTypes;
this.append = "." + appendToEnd;
}
public void setSpecialIndex (int clampIndex, int stringBuilderIndex)
{
specialIndex[0] = clampIndex;
specialIndex[1] = stringBuilderIndex;
}
public int getMetadata (int meta)
{
return meta;
}
public String getUnlocalizedName (ItemStack itemstack)
{
int pos = MathHelper.clamp_int(itemstack.getMetadata(), 0, (specialIndex[0] > -1) ? specialIndex[0] : (blockType.length - 1));
int sbIndex = (specialIndex[1] > -1) ? pos : (specialIndex[1] - pos);
if (sbIndex < 0)
sbIndex = -1 * sbIndex;
try
{
return (new StringBuilder()).append(unlocalizedName).append(".").append(blockType[sbIndex - 1]).append(append).toString();
}
catch (ArrayIndexOutOfBoundsException ex)
{
logger.warn("[MultiItemBlock] Caught array index error in getUnlocalizedName: " + ex.getMessage());
logger.warn("[MultiItemBlock] Returning unlocalized name: " + getUnlocalizedName());
return getUnlocalizedName();
}
}
}
@@ -1,212 +0,0 @@
package mantle.blocks.abstracts;
import mantle.blocks.BlockUtils;
import mantle.blocks.iface.IMasterLogic;
import mantle.blocks.iface.IServantLogic;
import mantle.debug.DebugData;
import mantle.debug.IDebuggable;
import mantle.world.CoordTuple;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import cpw.mods.fml.common.registry.GameRegistry;
public class MultiServantLogic extends TileEntity implements IServantLogic, IDebuggable
{
boolean hasMaster;
CoordTuple master;
Block masterBlock;
byte masterMeat; //Typo, it stays!
public boolean canUpdate ()
{
return false;
}
public boolean getHasMaster ()
{
return hasMaster;
}
public boolean hasValidMaster ()
{
if (!hasMaster)
return false;
if (worldObj.getBlock(master.x, master.y, master.z) == masterBlock && worldObj.getBlockMetadata(master.x, master.y, master.z) == masterMeat)
return true;
else
{
hasMaster = false;
master = null;
return false;
}
}
public CoordTuple getMasterPosition ()
{
return master;
}
public void overrideMaster (int x, int y, int z)
{
hasMaster = true;
master = new CoordTuple(x, y, z);
masterBlock = worldObj.getBlock(x, y, z);
masterMeat = (byte) worldObj.getBlockMetadata(x, y, z);
}
public void removeMaster ()
{
hasMaster = false;
master = null;
masterBlock = null;
masterMeat = 0;
}
@Override
public boolean setPotentialMaster (IMasterLogic master, World w, int x, int y, int z)
{
return !hasMaster;
}
@Deprecated
public boolean verifyMaster (IMasterLogic logic, int x, int y, int z)
{
if (master.equalCoords(x, y, z) && worldObj.getBlock(x, y, z) == masterBlock && worldObj.getBlockMetadata(x, y, z) == masterMeat)
return true;
else
return false;
}
@Override
public boolean verifyMaster (IMasterLogic logic, World world, int x, int y, int z)
{
if (hasMaster)
{
return hasValidMaster();
}
else
{
overrideMaster(x, y, z);
return true;
}
}
@Override
public void invalidateMaster (IMasterLogic master, World w, int x, int y, int z)
{
hasMaster = false;
master = null;
}
public void notifyMasterOfChange ()
{
if (hasValidMaster())
{
IMasterLogic logic = (IMasterLogic) worldObj.getTileEntity(master.x, master.y, master.z);
logic.notifyChange(this, xCoord, yCoord, zCoord);
}
}
public void readCustomNBT (NBTTagCompound tags)
{
hasMaster = tags.getBoolean("TiedToMaster");
if (hasMaster)
{
int xCenter = tags.getInteger("xCenter");
int yCenter = tags.getInteger("yCenter");
int zCenter = tags.getInteger("zCenter");
master = new CoordTuple(xCenter, yCenter, zCenter);
masterBlock = BlockUtils.getBlockFromUniqueName(tags.getString("MasterBlockName"));
masterMeat = tags.getByte("masterMeat");
}
}
public void writeCustomNBT (NBTTagCompound tags)
{
tags.setBoolean("TiedToMaster", hasMaster);
if (hasMaster)
{
tags.setInteger("xCenter", master.x);
tags.setInteger("yCenter", master.y);
tags.setInteger("zCenter", master.z);
tags.setString("MasterBlockName", BlockUtils.getUniqueName(masterBlock));
tags.setByte("masterMeat", masterMeat);
}
}
@Override
public void readFromNBT (NBTTagCompound tags)
{
super.readFromNBT(tags);
readCustomNBT(tags);
}
@Override
public void writeToNBT (NBTTagCompound tags)
{
super.writeToNBT(tags);
writeCustomNBT(tags);
}
/* Packets */
@Override
public Packet getDescriptionPacket ()
{
NBTTagCompound tag = new NBTTagCompound();
writeCustomNBT(tag);
return new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 1, tag);
}
@Override
public void onDataPacket (NetworkManager net, S35PacketUpdateTileEntity packet)
{
readCustomNBT(packet.getNbtCompound());
worldObj.markBlockForRenderUpdate(xCoord, yCoord, zCoord);
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
/* IDebuggable */
@Override
public DebugData getDebugInfo (EntityPlayer player)
{
String[] strs = new String[2];
strs[0] = "Location: x" + xCoord + ", y" + yCoord + ", z" + zCoord;
if (hasMaster)
{
strs[1] = "masterBlock: " + masterBlock.toString() + ", masterMeat: " + masterMeat;
}
else
{
strs[1] = "No active master.";
}
return new DebugData(player, getClass(), strs);
}
public World getWorld ()
{
return super.getWorld();
}
@Deprecated
public boolean setMaster (int x, int y, int z)
{
if (!hasMaster || worldObj.getBlock(master.x, master.y, master.z) != masterBlock || (worldObj.getBlockMetadata(master.x, master.y, master.z) != masterMeat))
{
overrideMaster(x, y, z);
return true;
}
else
{
return false;
}
}
}
-13
View File
@@ -1,13 +0,0 @@
package mantle.blocks.iface;
/**
* Marks blocks that can be active and inactive.
*
* @author mDiyo
*/
public interface IActiveLogic
{
public boolean getActive ();
public void setActive (boolean flag);
}
-27
View File
@@ -1,27 +0,0 @@
package mantle.blocks.iface;
import net.minecraft.entity.EntityLivingBase;
import net.minecraftforge.common.util.ForgeDirection;
/**
* Logic for blocks which have a specific direction facing.
*
* @author mDiyo
*/
public interface IFacingLogic
{
public byte getRenderDirection ();
public ForgeDirection getForgeDirection ();
@Deprecated
public void setDirection (int side);
@Deprecated
public void setDirection (float yaw, float pitch, EntityLivingBase player);
/** This will be added next version
* public void setDirection(int side, float yaw, float pitch, EntityLivingBase player); */
}
-12
View File
@@ -1,12 +0,0 @@
package mantle.blocks.iface;
public interface IMasterLogic
{
/** Called when servants change their state
*
* @param x Servant X
* @param y Servant Y
* @param z Servant Z
*/
public void notifyChange (IServantLogic servant, int x, int y, int z);
}
-8
View File
@@ -1,8 +0,0 @@
package mantle.blocks.iface;
public interface IMasterNode extends IMasterLogic, IServantLogic
{
public boolean isCurrentlyMaster ();
public boolean isEquivalentMaster (IMasterLogic master);
}
Loaded 100 of 170 files, more files were not shown because too many files have changed in this diff. Show more