Move in ttCore code, add gradle stuff

This commit is contained in:
tterrag1098 committed 2015-04-29 01:20:33 -04:00
1 parent bc78a4e745
commit 1805db39ad
87 files changed
+8402

No files matched your search

@@ -0,0 +1,149 @@
package com.enderio.core;
import java.io.File;
import java.util.List;
import lombok.SneakyThrows;
import net.minecraft.command.CommandHandler;
import net.minecraft.server.MinecraftServer;
import net.minecraftforge.client.ClientCommandHandler;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.enderio.core.api.common.config.IConfigHandler;
import com.enderio.core.common.CommonProxy;
import com.enderio.core.common.Handlers;
import com.enderio.core.common.Lang;
import com.enderio.core.common.OreDict;
import com.enderio.core.common.command.CommandReloadConfigs;
import com.enderio.core.common.command.CommandScoreboardInfo;
import com.enderio.core.common.compat.CompatabilityRegistry;
import com.enderio.core.common.config.ConfigHandler;
import com.enderio.core.common.enchant.EnchantAutoSmelt;
import com.enderio.core.common.enchant.EnchantXPBoost;
import com.enderio.core.common.imc.IMCRegistry;
import com.enderio.core.common.util.EnderFileUtils;
import com.enderio.core.common.util.TextureErrorRemover;
import com.google.common.collect.Lists;
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.FMLInterModComms.IMCEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerStartingEvent;
@Mod(modid = EnderCore.MODID, name = EnderCore.NAME, version = EnderCore.VERSION, guiFactory = "com.enderio.core.common.config.BaseConfigFactory")
public class EnderCore implements IEnderMod
{
public static final String MODID = "endercore";
public static final String NAME = "EnderCore";
public static final String BASE_PACKAGE = "com.enderio";
public static final String VERSION = "@VERSION@";
public static final Logger logger = LogManager.getLogger(NAME);
public static final Lang lang = new Lang(MODID);
@Instance
public static EnderCore instance;
@SidedProxy(serverSide = "com.enderio.core.common.CommonProxy", clientSide = "com.enderio.core.client.ClientProxy")
public static CommonProxy proxy;
public List<IConfigHandler> configs = Lists.newArrayList();
@EventHandler
@SneakyThrows
public void preInit(FMLPreInitializationEvent event)
{
if (event.getSide().isClient())
{
TextureErrorRemover.beginIntercepting();
}
ConfigHandler.configFolder = event.getModConfigurationDirectory();
ConfigHandler.enderConfigFolder = new File(ConfigHandler.configFolder.getPath() + "/" + MODID);
ConfigHandler.configFile = new File(ConfigHandler.enderConfigFolder.getPath() + "/" + event.getSuggestedConfigurationFile().getName());
if (!ConfigHandler.configFile.exists() && event.getSuggestedConfigurationFile().exists())
{
FileUtils.copyFile(event.getSuggestedConfigurationFile(), ConfigHandler.configFile);
EnderFileUtils.safeDelete(event.getSuggestedConfigurationFile());
}
ConfigHandler.instance().initialize(ConfigHandler.configFile);
Handlers.findPackages();
CompatabilityRegistry.INSTANCE.handle(event);
OreDict.registerVanilla();
EnchantXPBoost.INSTANCE.register();
EnchantAutoSmelt.INSTANCE.register();
}
@EventHandler
public void init(FMLInitializationEvent event)
{
for (IConfigHandler c : configs)
{
c.initHook();
}
Handlers.register();
CompatabilityRegistry.INSTANCE.handle(event);
ClientCommandHandler.instance.registerCommand(CommandReloadConfigs.CLIENT);
if (event.getSide().isServer())
{
((CommandHandler) MinecraftServer.getServer().getCommandManager()).registerCommand(CommandReloadConfigs.SERVER);
}
IMCRegistry.INSTANCE.init();
}
@EventHandler
public void postInit(FMLPostInitializationEvent event)
{
for (IConfigHandler c : configs)
{
c.postInitHook();
}
CompatabilityRegistry.INSTANCE.handle(event);
ConfigHandler.instance().loadRightClickCrops();
}
@EventHandler
public void onServerStarting(FMLServerStartingEvent event)
{
event.registerServerCommand(new CommandScoreboardInfo());
}
@EventHandler
public void onIMCEvent(IMCEvent event)
{
IMCRegistry.INSTANCE.handleEvent(event);
}
@Override
public String modid()
{
return MODID;
}
@Override
public String name()
{
return NAME;
}
@Override
public String version()
{
return VERSION;
}
}
@@ -0,0 +1,15 @@
package com.enderio.core;
/**
* By implementing this interface, your mod package will automatically be added to the handler search and other package based functionality.
*
* It also provides convenience functions for later use.
*/
public interface IEnderMod
{
String modid();
String name();
String version();
}
@@ -0,0 +1,26 @@
package com.enderio.core.api.client.model;
import net.minecraft.client.model.ModelRenderer;
/**
* To be used on techne-style box models
*/
public interface IEnderModel
{
/**
* Renders all parts of the model
*
* @param size - Size of the model (usually 0.0625f)
*/
public void render(float size);
/**
* Rotates the model part in the given directions
*
* @param model - part of the model to rotate
* @param x
* @param y
* @param z
*/
public void setRotation(ModelRenderer model, float x, float y, float z);
}
@@ -0,0 +1,33 @@
package com.enderio.core.api.common.config;
import java.io.File;
import java.util.List;
import com.enderio.core.common.config.AbstractConfigHandler.Section;
import net.minecraftforge.common.config.ConfigCategory;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
public interface IConfigHandler
{
void initialize(File cfg);
List<Section> getSections();
ConfigCategory getCategory(String name);
String getModID();
/**
* A hook for the {@link FMLInitializationEvent}, also called during config reloads depending on
* {@link #shouldHookOnReload()}
*/
void initHook();
/**
* A hook for the {@link FMLPostInitializationEvent}, also called during config reloads
* depending on {@link #shouldHookOnReload()}
*/
void postInitHook();
}
@@ -0,0 +1,17 @@
package com.enderio.core.api.common.enchant;
import net.minecraft.item.ItemStack;
/**
* Allows your enchants to have some flavor or descrtiption text underneath them
*/
public interface IAdvancedEnchant
{
/**
* Get the detail for this itemstack
*
* @param stack
* @return a list of <code>String</code>s to be bulleted under the enchantment
*/
public String[] getTooltipDetails(ItemStack stack);
}
@@ -0,0 +1,16 @@
package com.enderio.core.api.common.imc;
public class IMC
{
/**
* Use an IMC event with this string to add a right click crop as compatible. Syntax is a single
* string, with '|' separating the values, in the order seed, block, meta, resetMeta. A valid
* entry would look like this:
* <p>
* {@literal "minecraft:wheat_seeds|minecraft:wheat|7|0"}
* <p>
* The "reset meta" is the metadata that the plant will be reset to when it is harvested.
* Regular meta is the meta that must match the plant in world for the harvest to occur.
*/
public static final String ADD_RIGHT_CLICK_CROP = "addRightClickCrop";
}
@@ -0,0 +1,15 @@
package com.enderio.core.client;
import com.enderio.core.common.CommonProxy;
import com.enderio.core.common.util.Scheduler;
public class ClientProxy extends CommonProxy
{
private static final Scheduler scheduler = new Scheduler();
@Override
public Scheduler getScheduler()
{
return scheduler;
}
}
@@ -0,0 +1,167 @@
package com.enderio.core.client.config;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import com.enderio.core.EnderCore;
import com.enderio.core.api.common.config.IConfigHandler;
import com.enderio.core.common.config.ConfigHandler;
import com.enderio.core.common.config.AbstractConfigHandler.Section;
import lombok.SneakyThrows;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.common.config.ConfigCategory;
import net.minecraftforge.common.config.ConfigElement;
import net.minecraftforge.common.config.Property;
import cpw.mods.fml.client.config.GuiConfig;
import cpw.mods.fml.client.config.IConfigElement;
public class BaseConfigGui extends GuiConfig
{
@SuppressWarnings("rawtypes")
public BaseConfigGui(GuiScreen parentScreen)
{
// dummy super so we can call instance methods
super(parentScreen, new ArrayList<IConfigElement>(), null, false, false, null);
try
{
// pffft final, what a wimpy modifier
Field modID = GuiConfig.class.getDeclaredField("modID");
Field configElements = GuiConfig.class.getDeclaredField("configElements");
modID.setAccessible(true);
configElements.setAccessible(true);
modID.set(this, getConfigHandler().getModID());
configElements.set(this, getConfigElements());
}
catch (Exception e)
{
throw new RuntimeException(e);
}
this.title = getTitle();
}
/**
* The <b>localized</b> title of this config screen
*/
protected String getTitle()
{
return EnderCore.lang.localize("config.title");
}
/**
* The {@link IConfigHandler} to refer to when generating this config screen
*/
protected IConfigHandler getConfigHandler()
{
return ConfigHandler.instance();
}
/**
* The lang prefix to use before your section lang keys. Default is "config.".
*/
protected String getLangPrefix()
{
return "config.";
}
@SuppressWarnings("rawtypes")
private List<IConfigElement> getConfigElements()
{
List<IConfigElement> list = new ArrayList<IConfigElement>();
String prefix = getLangPrefix();
IConfigHandler config = getConfigHandler();
prefix = prefix.endsWith(".") ? prefix : prefix + ".";
for (Section s : config.getSections())
{
list.add(new ConfigSection(s, prefix));
}
return list;
}
@SuppressWarnings("rawtypes")
private class ConfigSection extends ConfigElement<ConfigCategory>
{
private Section section;
private String prefix;
private ConfigSection(Section s, String prefix)
{
super(BaseConfigGui.this.getConfigHandler().getCategory(s.lc()).setLanguageKey(prefix + s.lang));
this.section = s;
this.prefix = prefix;
}
@Override
public List<IConfigElement> getChildElements()
{
List<IConfigElement> temp = super.getChildElements();
List<IConfigElement> ret = new ArrayList<IConfigElement>(temp.size());
for (IConfigElement e : temp)
{
if (e.isProperty())
{
ret.add(new ConfigElementExtended(e));
}
else
{
ret.add(new ConfigSection(section, prefix));
}
}
return ret;
}
}
@SuppressWarnings("rawtypes")
private static class ConfigElementExtended<T> extends ConfigElement<T>
{
private static final Field _prop;
static
{
try
{
_prop = ConfigElement.class.getDeclaredField("prop");
_prop.setAccessible(true);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
private ConfigElementExtended(IConfigElement other)
{
super(getProp(other));
}
@SneakyThrows
private static Property getProp(IConfigElement other)
{
return (Property) _prop.get(other);
}
@Override
public String getComment()
{
String comment = super.getComment();
String range = "[range:";
String def = "[default:";
if (comment.contains(range))
{
comment = comment.substring(0, comment.indexOf(range) - 1);
}
else if (comment.contains(def))
{
comment = comment.substring(0, comment.indexOf(def) - 1);
}
return comment;
}
}
}
@@ -0,0 +1,391 @@
package com.enderio.core.client.gui;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import com.enderio.core.EnderCore;
import com.enderio.core.common.config.ConfigHandler;
import lombok.SneakyThrows;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiTextField;
import net.minecraft.util.StringUtils;
import cpw.mods.fml.client.GuiModList;
import cpw.mods.fml.client.GuiScrollingList;
import cpw.mods.fml.client.GuiSlotModList;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
public class GuiEnhancedModList extends GuiModList
{
private enum SortType
{
NORMAL(24), A_TO_Z(25), Z_TO_A(26);
private final int buttonID;
private final ModComparator comparator;
private SortType(int buttonID)
{
this.buttonID = buttonID;
this.comparator = new ModComparator(this);
}
public static SortType getTypeForButton(GuiButton button)
{
for (SortType t : values())
{
if (t.buttonID == button.id)
{
return t;
}
}
return null;
}
}
private static class ModComparator implements Comparator<ModContainer>
{
private SortType type;
private ModComparator(SortType type)
{
this.type = type;
}
@Override
public int compare(ModContainer o1, ModContainer o2)
{
String name1 = StringUtils.stripControlCodes(o1.getName()).toLowerCase();
String name2 = StringUtils.stripControlCodes(o2.getName()).toLowerCase();
switch(type)
{
case A_TO_Z:
return name1.compareTo(name2);
case Z_TO_A:
return name2.compareTo(name1);
default:
return 0;
}
}
}
private class InfoButton extends GuiButton
{
public InfoButton()
{
super(30, GuiEnhancedModList.this.width - 22, 2, 20, 20, "?");
}
@Override
public void drawButton(Minecraft p_146112_1_, int p_146112_2_, int p_146112_3_)
{
if (this.field_146123_n)
{
ModContainer sel = GuiEnhancedModList.this.getSelectedMod();
if (sel != null && sel.getName().equals(EnderCore.NAME))
{
this.displayString = EnderCore.lang.localize("gui.modlistinfo2");
}
else
{
this.displayString = EnderCore.lang.localize("gui.modlistinfo1");
}
this.width = p_146112_1_.fontRenderer.getStringWidth(this.displayString) + 10;
if (this.width % 2 != 0) // Fixes the button shifting to the left
{
this.width++;
}
this.xPosition = GuiEnhancedModList.this.width - this.width - 2;
}
else
{
this.displayString = "?";
this.width = 20;
this.xPosition = GuiEnhancedModList.this.width - this.width - 2;
}
super.drawButton(p_146112_1_, p_146112_2_, p_146112_3_);
}
}
private static Field _mods, _selected, _selectedMod;
private static Field _modList, _modListRight, _modListBottom, _modListMods, _listWidth;
static
{
try
{
_mods = GuiModList.class.getDeclaredField("mods");
_mods.setAccessible(true);
_selected = GuiModList.class.getDeclaredField("selected");
_selected.setAccessible(true);
_selectedMod = GuiModList.class.getDeclaredField("selectedMod");
_selectedMod.setAccessible(true);
_modList = GuiModList.class.getDeclaredField("modList");
_modList.setAccessible(true);
_modListRight = GuiScrollingList.class.getDeclaredField("right");
_modListRight.setAccessible(true);
_modListBottom = GuiScrollingList.class.getDeclaredField("bottom");
_modListBottom.setAccessible(true);
_modListMods = GuiSlotModList.class.getDeclaredField("mods");
_modListMods.setAccessible(true);
_listWidth = GuiModList.class.getDeclaredField("listWidth");
_listWidth.setAccessible(true);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
private int buttonMargin = 1;
private int numButtons = SortType.values().length;
private String lastFilterText = "";
private GuiTextField search;
private boolean sorted = false;
private SortType sortType = SortType.values()[ConfigHandler.defaultModSort];
public GuiEnhancedModList(GuiScreen mainMenu)
{
super(mainMenu);
}
@SuppressWarnings("unchecked")
@Override
public void initGui()
{
super.initGui();
// Let's move some buttons
for (GuiButton button : (List<GuiButton>) buttonList)
{
if (button.id == 6) // Done button
{
int min = getGuiModListRight();
int max = width;
button.xPosition = ((min + max) / 2) - (button.width / 2);
button.yPosition += 10;
}
else if (button.id == 20 || button.id == 21) // Config/Disable
{
button.yPosition += 10;
}
}
setGuiModListBottom(getGuiModListBottom() - 25);
search = new GuiTextField(mc.fontRenderer, 12, getGuiModListBottom() + 17, getListWidth() - 4, 14);
search.setFocused(true);
search.setCanLoseFocus(true);
int width = (getListWidth() / numButtons);
int x = 10, y = 10;
GuiButton normalSort = new GuiButton(SortType.NORMAL.buttonID, x, y, width - buttonMargin, 20, EnderCore.lang.localize("gui.normal"));
normalSort.enabled = false;
buttonList.add(normalSort);
x += width + buttonMargin;
buttonList.add(new GuiButton(SortType.A_TO_Z.buttonID, x, y, width - buttonMargin, 20, "A-Z"));
x += width + buttonMargin;
buttonList.add(new GuiButton(SortType.Z_TO_A.buttonID, x, y, width - buttonMargin, 20, "Z-A"));
buttonList.add(new InfoButton());
reloadMods();
disableButton();
}
@Override
protected void mouseClicked(int x, int y, int button)
{
super.mouseClicked(x, y, button);
search.mouseClicked(x, y, button);
if (button == 1 && x >= search.xPosition && x < search.xPosition + search.width && y >= search.yPosition && y < search.yPosition + search.height)
{
search.setText("");
}
}
@Override
protected void keyTyped(char p_73869_1_, int p_73869_2_)
{
super.keyTyped(p_73869_1_, p_73869_2_);
search.textboxKeyTyped(p_73869_1_, p_73869_2_);
}
@Override
public void updateScreen()
{
super.updateScreen();
search.updateCursorCounter();
if (!search.getText().equals(lastFilterText))
{
reloadMods();
sorted = false;
}
if (!sorted)
{
reloadMods();
Collections.sort(getMods(), sortType.comparator);
setMods();
sorted = true;
}
}
private void reloadMods()
{
List<ModContainer> mods = getMods();
mods.clear();
for (ModContainer m : Loader.instance().getActiveModList())
{
if (m.getName().toLowerCase().contains(search.getText().toLowerCase()) && m.getMetadata().parentMod == null)
{
mods.add(m);
}
}
setMods();
lastFilterText = search.getText();
}
@Override
public void drawScreen(int p_571_1_, int p_571_2_, float p_571_3_)
{
super.drawScreen(p_571_1_, p_571_2_, p_571_3_);
String text = EnderCore.lang.localize("gui.search");
int x = ((10 + getGuiModListRight()) / 2) - (mc.fontRenderer.getStringWidth(text) / 2);
mc.fontRenderer.drawString(text, x, getGuiModListBottom() + 5, 0xFFFFFF);
search.drawTextBox();
}
@Override
protected void actionPerformed(GuiButton button)
{
super.actionPerformed(button);
if (button.id == 30)
{
search.setText("");
reloadMods();
for (ModContainer m : getMods())
{
if (m.getName().equals(EnderCore.NAME))
{
setSelectedMod(m);
setMods();
}
}
}
SortType type = SortType.getTypeForButton(button);
if (type == null)
{
return;
}
else
{
sorted = false;
sortType = type;
disableButton();
}
setMods();
}
@SuppressWarnings("unchecked")
private void disableButton()
{
for (GuiButton b : (List<GuiButton>) buttonList)
{
if (SortType.getTypeForButton(b) != null)
{
b.enabled = true;
}
if (b.id == sortType.buttonID)
{
b.enabled = false;
}
}
}
@SneakyThrows
private void setMods()
{
List<ModContainer> mods = getMods();
ModContainer sel = getSelectedMod();
boolean found = false;
for (int i = 0; !found && i < mods.size(); i++)
{
if (sel == mods.get(i))
{
_selected.setInt(this, i);
found = true;
}
}
if (!found)
{
_selected.setInt(this, -1);
_selectedMod.set(this, null);
}
_mods.set(this, getMods());
}
@SneakyThrows
private GuiSlotModList getGuiModList()
{
return (GuiSlotModList) _modList.get(this);
}
@SneakyThrows
private int getGuiModListRight()
{
return _modListRight.getInt(getGuiModList());
}
@SneakyThrows
private void setGuiModListBottom(int bottom)
{
_modListBottom.set(getGuiModList(), bottom);
}
@SneakyThrows
private int getGuiModListBottom()
{
return _modListBottom.getInt(getGuiModList());
}
@SuppressWarnings("unchecked")
@SneakyThrows
private List<ModContainer> getMods()
{
return (List<ModContainer>) _modListMods.get(_modList.get(this));
}
@SneakyThrows
private int getListWidth()
{
return _listWidth.getInt(this);
}
@SneakyThrows
private ModContainer getSelectedMod()
{
return (ModContainer) _selectedMod.get(this);
}
@SneakyThrows
private void setSelectedMod(ModContainer mod)
{
_selectedMod.set(this, mod);
}
}
@@ -0,0 +1,55 @@
package com.enderio.core.client.gui;
import java.lang.reflect.Field;
import com.enderio.core.common.Handlers.Handler;
import com.enderio.core.common.Handlers.Handler.HandlerType;
import lombok.SneakyThrows;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.client.event.GuiOpenEvent;
import cpw.mods.fml.client.GuiIngameModOptions;
import cpw.mods.fml.client.GuiModList;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
@Handler(HandlerType.FORGE)
public class GuiEventHandler
{
private static Field _mainMenu, _parentScreen;
static
{
try
{
_mainMenu = GuiModList.class.getDeclaredField("mainMenu");
_mainMenu.setAccessible(true);
_parentScreen = GuiIngameModOptions.class.getDeclaredField("parentScreen");
_parentScreen.setAccessible(true);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
@SubscribeEvent
@SneakyThrows
public void onGuiOpen(GuiOpenEvent event)
{
if (event.gui == null)
{
return;
}
if (event.gui.getClass() == GuiModList.class)
{
event.setCanceled(true);
Minecraft.getMinecraft().displayGuiScreen(new GuiEnhancedModList((GuiScreen) _mainMenu.get(event.gui)));
}
if (event.gui.getClass() == GuiIngameModOptions.class)
{
event.setCanceled(true);
Minecraft.getMinecraft().displayGuiScreen(new GuiEnhancedModList((GuiScreen) _parentScreen.get(event.gui)));
}
}
}
@@ -0,0 +1,25 @@
package com.enderio.core.client.handlers;
import com.enderio.core.common.Handlers.Handler;
import com.enderio.core.common.Handlers.Handler.HandlerType;
import lombok.Getter;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent.ClientTickEvent;
import cpw.mods.fml.common.gameevent.TickEvent.Phase;
@Handler(HandlerType.FML)
public class ClientHandler
{
@Getter
private static int ticksElapsed;
@SubscribeEvent
public void onClientTick(ClientTickEvent event)
{
if (event.phase == Phase.END)
{
ticksElapsed++;
}
}
}
@@ -0,0 +1,48 @@
package com.enderio.core.client.handlers;
import java.util.Map;
import com.enderio.core.api.common.enchant.IAdvancedEnchant;
import com.enderio.core.common.Handlers.Handler;
import com.enderio.core.common.Handlers.Handler.HandlerType;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.StatCollector;
import net.minecraftforge.event.entity.player.ItemTooltipEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
@Handler(HandlerType.FORGE)
public class EnchantTooltipHandler
{
@SuppressWarnings("unchecked")
@SubscribeEvent
public void handleTooltip(ItemTooltipEvent event)
{
if (event.itemStack.hasTagCompound())
{
Map<Integer, Integer> enchantments = EnchantmentHelper.getEnchantments(event.itemStack);
for (Integer integer : enchantments.keySet())
{
Enchantment enchant = Enchantment.enchantmentsList[integer];
if (enchant instanceof IAdvancedEnchant)
{
for (int i = 0; i < event.toolTip.size(); i++)
{
if (event.toolTip.get(i).contains(StatCollector.translateToLocal(enchant.getName())))
{
for (String s : ((IAdvancedEnchant) enchant).getTooltipDetails(event.itemStack))
{
event.toolTip.add(i + 1, EnumChatFormatting.DARK_GRAY.toString() + EnumChatFormatting.ITALIC + " - " + s);
i++;
}
}
}
}
}
}
}
}
@@ -0,0 +1,48 @@
package com.enderio.core.client.handlers;
import net.minecraft.client.Minecraft;
import net.minecraft.item.Item;
import net.minecraftforge.event.entity.player.ItemTooltipEvent;
import net.minecraftforge.oredict.OreDictionary;
import org.lwjgl.input.Keyboard;
import com.enderio.core.EnderCore;
import com.enderio.core.common.Handlers.Handler;
import com.enderio.core.common.Handlers.Handler.HandlerType;
import static com.enderio.core.common.config.ConfigHandler.*;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
@Handler(HandlerType.FORGE)
public class OreDictTooltipHandler
{
@SubscribeEvent
public void onItemTooltip(ItemTooltipEvent event)
{
boolean shiftDown = Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT);
boolean debugMode = Minecraft.getMinecraft().gameSettings.advancedItemTooltips;
boolean doRegistry = showRegistryNameTooltips == 3 ? debugMode : showRegistryNameTooltips == 2 ? shiftDown : showRegistryNameTooltips == 1;
boolean doOredict = showOredictTooltips == 3 ? debugMode : showOredictTooltips == 2 ? shiftDown : showOredictTooltips == 1;
if (doRegistry)
{
event.toolTip.add(Item.itemRegistry.getNameForObject(event.itemStack.getItem()));
}
if (doOredict)
{
int[] ids = OreDictionary.getOreIDs(event.itemStack);
if (ids.length > 0)
{
event.toolTip.add(EnderCore.lang.localize("tooltip.oreDictNames"));
for (int i : ids)
{
event.toolTip.add(" - " + OreDictionary.getOreName(i));
}
}
}
}
}
@@ -0,0 +1,158 @@
package com.enderio.core.client.render;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.IItemRenderer;
import net.minecraftforge.client.model.AdvancedModelLoader;
import net.minecraftforge.client.model.IModelCustom;
import org.lwjgl.opengl.GL11;
import com.enderio.core.api.client.model.IEnderModel;
import com.enderio.core.common.util.EnderItemUtils;
/**
* Renders a model with directional placement
*
* @author Garrett Spicer-Davis
*/
public class DirectionalModelRenderer<T extends TileEntity> extends TileEntitySpecialRenderer implements IItemRenderer
{
private IModelCustom model;
private ResourceLocation texture;
private IEnderModel modelSMT;
public DirectionalModelRenderer(ResourceLocation model, ResourceLocation texture)
{
this.model = AdvancedModelLoader.loadModel(model);
this.texture = texture;
}
public DirectionalModelRenderer(IEnderModel model, ResourceLocation texture)
{
this.modelSMT = model;
this.texture = texture;
}
private void renderDirectionalTileEntityAt(T tile, double x, double y, double z, int metaOverride)
{
int meta = getMetadata(tile, metaOverride);
setup(x, y, z, metaOverride);
rotate(getRotation(tile, metaOverride));
renderModel(tile, meta);
}
protected final int getMetadata(T tile, int metaOverride)
{
return metaOverride >= 0 ? metaOverride : tile.getBlockMetadata();
}
protected void setup(double x, double y, double z, int metaOverride)
{
GL11.glPushMatrix();
GL11.glTranslatef((float) x + 0.5f, (float) y - (metaOverride >= 0 ? 0.1f : 0), (float) z + 0.5f);
Minecraft.getMinecraft().getTextureManager().bindTexture(texture);
}
protected int getRotation(T tile, int metaOverride)
{
return getMetadata(tile, metaOverride);
}
protected void rotate(int rotation)
{
switch (rotation)
{
case 1:
GL11.glRotatef(180f, 0, 0, 1);
GL11.glTranslatef(0, -1f, 0);
break;
case 2:
GL11.glRotatef(90f, 1f, 0, 0);
GL11.glTranslatef(0, -0.5f, -0.5f);
break;
case 3:
GL11.glRotatef(90f, -1f, 0, 0);
GL11.glTranslatef(0, -0.5f, 0.5f);
break;
case 4:
GL11.glRotatef(90f, 0, 0, -1f);
GL11.glTranslatef(-0.5f, -0.5f, 0);
break;
case 5:
GL11.glRotatef(90f, 0, 0, 1f);
GL11.glTranslatef(0.5f, -0.5f, 0);
break;
}
}
protected void renderModel(T tile, int meta)
{
if (model != null)
{
GL11.glScalef(0.5f, 0.5f, 0.5f);
model.renderAll();
}
else
{
GL11.glTranslated(0, -0.5, 0);
modelSMT.render(0.0625f);
}
GL11.glPopMatrix();
}
@SuppressWarnings("unchecked")
@Override
public void renderTileEntityAt(TileEntity tile, double x, double y, double z, float yaw)
{
renderDirectionalTileEntityAt((T) tile, x, y, z, -1);
}
@Override
public boolean handleRenderType(ItemStack item, ItemRenderType type)
{
return true;
}
@Override
public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper)
{
return helper == ItemRendererHelper.INVENTORY_BLOCK || helper == ItemRendererHelper.ENTITY_BOBBING || helper == ItemRendererHelper.ENTITY_ROTATION;
}
@Override
public void renderItem(ItemRenderType type, ItemStack item, Object... data)
{
GL11.glPushMatrix();
switch (type)
{
case ENTITY:
GL11.glTranslatef(-0.4f, 0.1f, -0.4f);
GL11.glScalef(0.75f, 0.75f, 0.75f);
break;
case EQUIPPED:
GL11.glScalef(0.75f, 0.75f, 0.75f);
GL11.glTranslatef(-0.1f, 0.2f, 0.5f);
GL11.glRotatef(-40, 1, 0, 0);
GL11.glRotatef(45, 0, 1, 0);
GL11.glRotatef(20, 0, 0, 1);
break;
case EQUIPPED_FIRST_PERSON:
GL11.glScalef(0.75f, 0.75f, 0.75f);
break;
case FIRST_PERSON_MAP:
break;
case INVENTORY:
break;
}
renderDirectionalTileEntityAt(null, 0, 0, 0, EnderItemUtils.getNBTTag(item).getInteger("storedMetaData"));
GL11.glPopMatrix();
}
}
@@ -0,0 +1,52 @@
package com.enderio.core.client.render;
import com.enderio.core.client.util.RenderingUtils;
import lombok.AllArgsConstructor;
import lombok.Getter;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.client.model.obj.WavefrontObject;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
@AllArgsConstructor
public class SimpleModelRenderer implements ISimpleBlockRenderingHandler
{
private final Tessellator tes = Tessellator.instance;
private final WavefrontObject model;
@Getter
private final int renderId;
@Override
public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer)
{
RenderHelper.disableStandardItemLighting();
tes.startDrawingQuads();
tes.setColorOpaque_F(1, 1, 1);
RenderingUtils.renderWithIcon(model, block.getIcon(0, metadata), tes);
tes.draw();
RenderHelper.enableStandardItemLighting();
}
@Override
public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer)
{
tes.setBrightness(block.getMixedBrightnessForBlock(world, x, y, z));
tes.setColorOpaque_F(1, 1, 1);
tes.addTranslation(x + .5F, y + .5F, z + .5F);
RenderingUtils.renderWithIcon(model, block.getIcon(0, world.getBlockMetadata(x, y, z)), tes);
tes.addTranslation(-x - .5F, -y - .5F, -z - .5F);
return true;
}
@Override
public boolean shouldRender3DInInventory(int modelId)
{
return true;
}
}
@@ -0,0 +1,53 @@
package com.enderio.core.client.sound;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import net.minecraft.client.audio.ITickableSound;
import net.minecraft.client.audio.PositionedSound;
import net.minecraft.util.ResourceLocation;
@Accessors(chain = true)
public class BlockSound extends PositionedSound implements ITickableSound
{
@Getter
@Setter
private boolean donePlaying = false;
public BlockSound(ResourceLocation p_i45103_1_)
{
super(p_i45103_1_);
}
public BlockSound setVolume(float vol)
{
this.volume = vol;
return this;
}
public BlockSound setPitch(float pitch)
{
this.field_147663_c = pitch;
return this;
}
public BlockSound setLocation(float x, float y, float z)
{
this.xPosF = x;
this.yPosF = y;
this.zPosF = z;
return this;
}
public BlockSound setDoRepeat(boolean bool)
{
this.repeat = bool;
return this;
}
@Override
public void update()
{
;
}
}
@@ -0,0 +1,100 @@
package com.enderio.core.client.util;
import com.enderio.core.client.handlers.ClientHandler;
import lombok.experimental.UtilityClass;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.util.IIcon;
import net.minecraftforge.client.model.obj.Face;
import net.minecraftforge.client.model.obj.GroupObject;
import net.minecraftforge.client.model.obj.TextureCoordinate;
import net.minecraftforge.client.model.obj.Vertex;
import net.minecraftforge.client.model.obj.WavefrontObject;
import static org.lwjgl.opengl.GL11.*;
@UtilityClass
public class RenderingUtils
{
public void renderWithIcon(WavefrontObject model, IIcon icon, Tessellator tes)
{
for (GroupObject go : model.groupObjects)
{
for (Face f : go.faces)
{
Vertex n = f.faceNormal;
tes.setNormal(n.x, n.y, n.z);
for (int i = 0; i < f.vertices.length; i++)
{
Vertex v = f.vertices[i];
TextureCoordinate t = f.textureCoordinates[i];
tes.addVertexWithUV(v.x, v.y, v.z, icon.getInterpolatedU(t.u * 16), icon.getInterpolatedV(t.v * 16));
}
}
}
}
/**
* Renders an item entity in 3D
*
* @param item
* The item to render
* @param rotate
* Whether to "spin" the item like it would if it were a real dropped entity
*/
public void render3DItem(EntityItem item, boolean rotate)
{
float rot = getRotation(1.0f);
glPushMatrix();
glDepthMask(true);
rotate &= Minecraft.getMinecraft().gameSettings.fancyGraphics;
if (rotate)
{
glRotatef(rot, 0, 1, 0);
}
item.hoverStart = 0.0F;
RenderManager.instance.renderEntityWithPosYaw(item, 0.0D, 0.0D, 0.0D, 0.0F, 0.0F);
glPopMatrix();
}
public float getRotation(float mult)
{
return ClientHandler.getTicksElapsed() * mult;
}
public void renderBillboardQuad(float rot, double scale)
{
glPushMatrix();
glRotatef(-RenderManager.instance.playerViewY, 0.0F, 1.0F, 0.0F);
glRotatef(RenderManager.instance.playerViewX, 1.0F, 0.0F, 0.0F);
glPushMatrix();
glRotatef(rot, 0, 0, 1);
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
glColor3f(1, 1, 1);
tessellator.setColorRGBA(255, 255, 255, 255);
tessellator.addVertexWithUV(-scale, -scale, 0, 0, 0);
tessellator.addVertexWithUV(-scale, scale, 0, 0, 1);
tessellator.addVertexWithUV(scale, scale, 0, 1, 1);
tessellator.addVertexWithUV(scale, -scale, 0, 1, 0);
tessellator.draw();
glPopMatrix();
glPopMatrix();
}
public void rotateToPlayer()
{
glRotatef(-RenderManager.instance.playerViewY, 0.0F, 1.0F, 0.0F);
glRotatef(RenderManager.instance.playerViewX, 1.0F, 0.0F, 0.0F);
}
}
@@ -0,0 +1,19 @@
package com.enderio.core.common;
import com.enderio.core.common.util.Scheduler;
public class CommonProxy
{
private static final Scheduler scheduler = new Scheduler();
/**
* Returns a scheduler for the current side
* <p>
* For internal use only, please call {@link Scheduler#instance()} to obtain an
* {@link Scheduler} instance.
*/
public Scheduler getScheduler()
{
return scheduler;
}
}
@@ -0,0 +1,266 @@
package com.enderio.core.common;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import lombok.NoArgsConstructor;
import lombok.experimental.UtilityClass;
import net.minecraftforge.common.MinecraftForge;
import org.apache.commons.lang3.ArrayUtils;
import com.enderio.core.IEnderMod;
import com.enderio.core.EnderCore;
import com.enderio.core.common.Handlers.Handler.HandlerType;
import com.enderio.core.common.Handlers.Handler.Inst;
import com.google.common.reflect.ClassPath;
import com.google.common.reflect.ClassPath.ClassInfo;
import static com.enderio.core.common.Handlers.Handler.Inst.*;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.LoaderState;
import cpw.mods.fml.common.ModContainer;
@UtilityClass
public class Handlers
{
/**
* To be put on classes that are Forge/FML event handlers. If you are using this from another mod, be sure to implement {@link IEnderMod} on your
* {@code @Mod} class, or call {@code Handlers.addPackage("your.base.package")} so that this class can search your classes
* <p>
* Class must have either:<br>
* A public no args constructor (or lombok {@link NoArgsConstructor}) <b>OR</b><br>
* A static singleton object with field name {@code INSTANCE} (public or private). <b>OR</b><br>
* A static method with name <code>instance()</code> (public or private)
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Handler
{
public enum HandlerType
{
/**
* Represents the {@link MinecraftForge#EVENT_BUS}
*/
FORGE,
/**
* Represents the {@link FMLCommonHandler#instance()#bus()}
*/
FML
}
public enum Inst
{
/**
* The default, will try all three methods, in the order {@link Inst#CONSTRUCTOR}, {@link Inst#FIELD}, {@link Inst#METHOD}
*/
AUTO,
/**
* The handler should be constructed from the default constructor of the class
*/
CONSTRUCTOR,
/**
* The handler should be grabbed from the static {@code INSTANCE} field of the class
*/
FIELD,
/**
* The handler should be grabbed from the static {@code instance()} method of the class
*/
METHOD;
boolean matches(Inst other)
{
return this == AUTO || other == AUTO || other == this;
}
}
/**
* Array of buses to register this handler to. Leave blank for all.
*/
HandlerType[] value() default { HandlerType.FORGE, HandlerType.FML };
/**
* The method of getting your handler's instance. Defaults to {@link Inst#AUTO}
*/
Inst getInstFrom() default AUTO;
}
private static final Set<String> packageSet = new HashSet<String>();
public void findPackages()
{
for (ModContainer mod : Loader.instance().getActiveModList())
{
if (mod.getMod() instanceof IEnderMod)
{
addPackage(getEnclosingPackage(mod.getMod()));
}
}
}
private String getEnclosingPackage(Object obj)
{
Class<?> modClass = obj.getClass();
while (modClass.getComponentType() != null)
{
modClass = modClass.getComponentType();
}
while (modClass.getEnclosingClass() != null)
{
modClass = modClass.getEnclosingClass();
}
String name = modClass.getName();
int lastDot = name.lastIndexOf('.');
return lastDot == -1 ? name : name.substring(0, lastDot);
}
/**
* Registers a top level package to be searched for {@link Handler} classes. Not needed if your {@code @Mod} class implements {@link IEnderMod}
*
* @param packageName
*/
public void addPackage(String packageName)
{
if (Loader.instance().hasReachedState(LoaderState.INITIALIZATION))
{
throw new RuntimeException("This method must only be called in preinit");
}
EnderCore.logger.info("Adding package " + packageName + " to handler search.");
packageSet.add(packageName);
}
private boolean registered = false;
/**
* For internal use only. Do not call. Callers will be sacked.
*/
public void register()
{
if (registered)
{
throw new IllegalStateException("I warned you!");
}
ClassPath classpath;
try
{
classpath = ClassPath.from(EnderCore.class.getClassLoader());
}
catch (IOException e)
{
throw new RuntimeException(e);
}
for (String packageName : packageSet)
{
Set<ClassInfo> classes = classpath.getTopLevelClassesRecursive(packageName);
for (ClassInfo info : classes)
{
// if not client handler, or we are on client, continue
if (!info.getPackageName().contains("client") || FMLCommonHandler.instance().getEffectiveSide().isClient())
{
try
{
Class<?> c = info.load();
Annotation a = c.getAnnotation(Handler.class);
if (a != null)
{
registerHandler(c, (Handler) a);
}
}
catch (Throwable t)
{
EnderCore.logger.error(String.format("[Handlers] %s threw an error on load, skipping...", info.getName()));
t.printStackTrace();
}
}
else
{
EnderCore.logger.info(String.format("[Handlers] Skipping client class %s, we are on a dedicated server", info.getSimpleName()));
}
}
}
registered = true;
}
private void registerHandler(Class<?> c, Handler handler) throws InstantiationException, IllegalAccessException
{
EnderCore.logger.info(String.format("[Handlers] Registering handler %s to busses: %s", c.getSimpleName(), Arrays.deepToString(handler.value())));
HandlerType[] types = handler.value();
Object inst = tryInit(handler, c);
if (ArrayUtils.contains(types, HandlerType.FORGE))
MinecraftForge.EVENT_BUS.register(inst);
if (ArrayUtils.contains(types, HandlerType.FML))
FMLCommonHandler.instance().bus().register(inst);
}
private Object tryInit(Handler annot, Class<?> c)
{
Inst pref = annot.getInstFrom();
// Silence all exceptions to trickle down to next if statement.
// If all three fail, RuntimeException is thrown.
if (pref.matches(CONSTRUCTOR))
{
try
{
return c.newInstance();
}
catch (Exception e)
{}
}
if (pref.matches(FIELD))
{
try
{
Field inst = c.getDeclaredField("INSTANCE");
inst.setAccessible(true);
return inst.get(null);
}
catch (Exception e)
{}
}
if (pref.matches(METHOD))
{
try
{
Method inst = c.getDeclaredMethod("instance");
inst.setAccessible(true);
return inst.invoke(null);
}
catch (Exception e)
{}
}
throw new RuntimeException("Could not instantiate @Handler class " + c.getName() + " or access INSTANCE field or instance() method.");
}
}
@@ -0,0 +1,108 @@
package com.enderio.core.common;
import lombok.AllArgsConstructor;
import lombok.Getter;
import net.minecraft.util.StatCollector;
@AllArgsConstructor
@Getter
public class Lang
{
private static final String REGEX = "\\" + '|';
public static final char CHAR = '|';
private String locKey;
/**
* Adds the stored prefix to this string, separating with a period. Using this method returns the string that is used for localizing if you passed
* this arg into {@link #localize(String, Object...)}.
*
* @param suffix
* The suffix string
* @return The full string
*/
public String addPrefix(String suffix)
{
return locKey + "." + suffix;
}
/**
* Localizes the string passed, first appending the prefix stored in this instance of the class.
*
* @param unloc
* The unlocalized string.
* @param args
* The args to format the localized text withi.
*
* @return A localized string.
*/
public String localize(String unloc, Object... args)
{
return localizeExact(addPrefix(unloc), args);
}
/**
* Ignores the prefix stored in this instance of the class and localizes the raw string passed.
*
* @param unloc
* The unlocalized string.
* @param args
* The args to format the localized text withi.
*
* @return A localized string.
*/
public String localizeExact(String unloc, Object... args)
{
return StatCollector.translateToLocalFormatted(unloc, args);
}
/**
* Splits the localized text on "|" into a String[].
*
* @param unloc
* The unlocalized string.
* @param args
* The args to format the localized text withi.
* @return A localized list of strings.
*/
public String[] localizeList(String unloc, String... args)
{
return splitList(localize(unloc, true, args));
}
/**
* Splits a list of strings based on {@value #CHAR}
*
* @param list
* The list of strings to split
* @return An array of strings split on {@value #CHAR}
*/
public String[] splitList(String list)
{
return list.split(REGEX);
}
/**
* Checks if the passed string (plus the prefix) has a localization mapped.
*
* @param unloc
* The unlocalized suffix
* @return True if there is a localization mapped, false otherwise.
*/
public boolean canLocalize(String unloc)
{
return canLocalizeExact(addPrefix(unloc));
}
/**
* Checks if the passed string has a localization mapped. Does not use the prefix.
*
* @param unloc
* The unlocalized string
* @return True if there is a localization mapped, false otherwise.
*/
public boolean canLocalizeExact(String unloc)
{
return StatCollector.canTranslate(unloc);
}
}
@@ -0,0 +1,79 @@
package com.enderio.core.common;
import java.util.ArrayList;
import lombok.experimental.UtilityClass;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
@UtilityClass
public class OreDict
{
public void registerVanilla()
{
safeRegister("barsIron", Blocks.iron_bars);
safeRegister("blockHopper", Blocks.hopper);
safeRegister("blockObsidian", Blocks.obsidian);
safeRegister("itemNetherStar", Items.nether_star);
safeRegister("itemCoal", Items.coal);
safeRegister("itemCharcoal", new ItemStack(Items.coal, 1, 1));
safeRegister("pearlEnder", Items.ender_pearl);
safeRegister("pearlEnderEye", Items.ender_eye);
safeRegister("itemBlazeRod", Items.blaze_rod);
safeRegister("itemBlazePowder", Items.blaze_powder);
safeRegister("itemClay", Items.clay_ball);
safeRegister("itemFlint", Items.flint);
safeRegister("itemGhastTear", Items.ghast_tear);
safeRegister("dustGunpowder", Items.gunpowder);
safeRegister("itemLeather", Items.leather);
safeRegister("slabWoodOak", new ItemStack(Blocks.wooden_slab, 1, 0));
safeRegister("slabWoodSpruce", new ItemStack(Blocks.wooden_slab, 1, 1));
safeRegister("slabWoodBirch", new ItemStack(Blocks.wooden_slab, 1, 2));
safeRegister("slabWoodJungle", new ItemStack(Blocks.wooden_slab, 1, 3));
safeRegister("slabWoodAcacia", new ItemStack(Blocks.wooden_slab, 1, 4));
safeRegister("slabWoodDarkOak", new ItemStack(Blocks.wooden_slab, 1, 5));
safeRegister("slabStone", new ItemStack(Blocks.stone_slab, 1, 0));
safeRegister("slabSandstone", new ItemStack(Blocks.stone_slab, 1, 1));
safeRegister("slabCobblestone", new ItemStack(Blocks.stone_slab, 1, 3));
safeRegister("slabBricks", new ItemStack(Blocks.stone_slab, 1, 4));
safeRegister("slabStoneBricks", new ItemStack(Blocks.stone_slab, 1, 5));
safeRegister("slabNetherBrick", new ItemStack(Blocks.stone_slab, 1, 6));
safeRegister("slabQuartz", new ItemStack(Blocks.stone_slab, 1, 7));
}
public void safeRegister(String name, Block block)
{
safeRegister(name, Item.getItemFromBlock(block));
}
public void safeRegister(String name, Item item)
{
safeRegister(name, new ItemStack(item));
}
public void safeRegister(String name, ItemStack stack)
{
if (!isRegistered(stack, OreDictionary.getOres(name)))
OreDictionary.registerOre(name, stack);
}
private boolean isRegistered(ItemStack stack, ArrayList<ItemStack> toCheck)
{
for (ItemStack check : toCheck)
{
if (stack != null && stack.getItem() == check.getItem()
&& (stack.getItemDamage() == check.getItemDamage() || stack.getItemDamage() == OreDictionary.WILDCARD_VALUE))
{
return true;
}
}
return false;
}
}
@@ -0,0 +1,131 @@
package com.enderio.core.common.command;
import java.util.ArrayList;
import java.util.List;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommandSender;
import net.minecraft.util.ChatComponentText;
import org.apache.commons.lang3.ArrayUtils;
import com.enderio.core.EnderCore;
import com.enderio.core.common.event.ConfigFileChangedEvent;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.relauncher.Side;
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class CommandReloadConfigs extends CommandBase
{
public static final CommandReloadConfigs SERVER = new CommandReloadConfigs(Side.SERVER);
public static final CommandReloadConfigs CLIENT = new CommandReloadConfigs(Side.CLIENT);
private static List<String> validModIDs = new ArrayList<String>();
private final Side side;
static
{
EnderCore.logger.info("Sending dummy event to all mods");
for (ModContainer mod : Loader.instance().getActiveModList())
{
ConfigFileChangedEvent event = new ConfigFileChangedEvent(mod.getModId());
FMLCommonHandler.instance().bus().post(event);
if (event.isSuccessful())
{
validModIDs.add(mod.getModId());
}
}
}
@Override
public String getCommandName()
{
return side == Side.SERVER ? "reloadServerConfigs" : "reloadConfigs";
}
@Override
public String getCommandUsage(ICommandSender p_71518_1_)
{
return "/" + getCommandName() + " <modid> (<modid2> <modid3> ...)";
}
@Override
public int getRequiredPermissionLevel()
{
return 2;
}
@Override
public boolean canCommandSenderUseCommand(ICommandSender player)
{
return player.getEntityWorld().isRemote || super.canCommandSenderUseCommand(player);
}
@SuppressWarnings("rawtypes")
@Override
public List addTabCompletionOptions(ICommandSender player, String[] args)
{
if (args.length >= 1)
{
String[] avail = validModIDs.toArray(new String[validModIDs.size()]);
for (int i = 0; i < args.length - 1; i++)
{
avail = ArrayUtils.removeElement(avail, args[i]);
}
return getListOfStringsMatchingLastWord(args, avail);
}
return null;
}
@Override
public void processCommand(ICommandSender player, String[] args)
{
if (side == Side.CLIENT == player.getEntityWorld().isRemote)
for (String s : args)
{
boolean validModid = false;
for (ModContainer mod : Loader.instance().getModObjectList().keySet())
{
if (mod.getModId().equals(s))
{
validModid = true;
}
}
if (validModid)
{
ConfigFileChangedEvent event = new ConfigFileChangedEvent(s);
FMLCommonHandler.instance().bus().post(event);
if (event.isSuccessful())
{
sendResult(player, s, "success");
}
else
{
sendResult(player, s, "fail");
}
}
else
{
sendResult(player, s, "invalid");
}
}
}
private void sendResult(ICommandSender player, String modid, String result)
{
player.addChatMessage(new ChatComponentText(EnderCore.lang.localize("command.config.result." + result, modid)));
}
}
@@ -0,0 +1,102 @@
package com.enderio.core.common.command;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommandSender;
import net.minecraft.command.WrongUsageException;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.scoreboard.Score;
import net.minecraft.scoreboard.ScoreObjective;
import net.minecraft.scoreboard.Scoreboard;
import net.minecraft.util.ChatComponentText;
public class CommandScoreboardInfo extends CommandBase
{
@Override
public String getCommandName()
{
return "scoreboardinfo";
}
@Override
public String getCommandUsage(ICommandSender p_71518_1_)
{
return "/scoreboardinfo <board> <name>";
}
@Override
public int getRequiredPermissionLevel()
{
return 0;
}
@Override
public boolean canCommandSenderUseCommand(ICommandSender p_71519_1_)
{
return true;
}
@SuppressWarnings("unchecked")
@Override
public void processCommand(ICommandSender player, String[] args)
{
if (args.length < 2)
{
throw new WrongUsageException("This command requires 2 args: <board> <name>");
}
Scoreboard board = player.getEntityWorld().getScoreboard();
ScoreObjective obj = board.getObjective(args[0]);
if (obj == null)
{
player.addChatMessage(new ChatComponentText("No such board " + args[0]));
}
Collection<Score> collection = board.func_96534_i(obj);
for (Score score : collection)
{
if (score.getPlayerName().equals(args[1]))
{
player.addChatMessage(new ChatComponentText(args[1] + "'s score on board \"" + args[0] + "\": " + score.getScorePoints()));
return;
}
}
player.addChatMessage(new ChatComponentText("No score for " + args[1] + " on board \"" + args[0] + "\""));
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public List addTabCompletionOptions(ICommandSender player, String[] args)
{
if (args.length == 1)
{
List<String> boards = new ArrayList<String>();
for (ScoreObjective obj : (Collection<ScoreObjective>) player.getEntityWorld().getScoreboard().getScoreObjectives())
{
boards.add(obj.getName());
}
return getListOfStringsFromIterableMatchingLastWord(args, boards);
}
if (args.length == 2)
{
List<String> players = new ArrayList<String>();
for (EntityPlayer p : (List<EntityPlayer>) player.getEntityWorld().playerEntities)
{
players.add(p.getCommandSenderName());
}
return getListOfStringsFromIterableMatchingLastWord(args, players);
}
return null;
}
}
@@ -0,0 +1,122 @@
package com.enderio.core.common.compat;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Value;
import org.apache.commons.lang3.ArrayUtils;
import com.enderio.core.EnderCore;
import com.enderio.core.common.util.RegisterTime;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.event.FMLStateEvent;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class CompatabilityRegistry
{
@Value
private static class Registration
{
String[] modids;
RegisterTime[] times;
private Registration(RegisterTime time, String... modids)
{
this.modids = modids;
this.times = new RegisterTime[] { time };
}
private Registration(RegisterTime[] times, String... modids)
{
this.modids = modids;
this.times = times;
}
}
public static final CompatabilityRegistry INSTANCE = new CompatabilityRegistry();
private Map<Registration, String> compatMap = new HashMap<Registration, String>();
@Getter
private RegisterTime state = null;
public void registerCompat(RegisterTime time, String clazz, String... modids)
{
compatMap.put(new Registration(time, modids), clazz);
}
public void registerCompat(RegisterTime[] times, String clazz, String... modids)
{
compatMap.put(new Registration(times, modids), clazz);
}
public void handle(FMLStateEvent event)
{
RegisterTime time = RegisterTime.timeFor(event);
state = time;
for (Registration r : compatMap.keySet())
{
if (ArrayUtils.contains(r.times, time) && allModsLoaded(r.modids))
{
doLoad(compatMap.get(r));
}
}
}
private boolean allModsLoaded(String[] modids)
{
for (String s : modids)
{
if (!Loader.isModLoaded(s))
{
return false;
}
}
return true;
}
public void forceLoad(String clazz)
{
Iterator<Registration> iter = compatMap.keySet().iterator();
while (iter.hasNext())
{
Registration r = iter.next();
String s = compatMap.get(r);
if (s.equals(clazz))
{
doLoad(s);
}
}
}
private void doLoad(String clazz)
{
try
{
EnderCore.logger.info("[Compat] Loading compatability class " + clazz);
Class<?> compat = Class.forName(clazz);
compat.getDeclaredMethod(ICompatability.METHOD_NAME).invoke(null);
}
catch (NoSuchMethodException e)
{
EnderCore.logger.error("[Compat] ICompatability class {} did not contain static method {}!", clazz, ICompatability.METHOD_NAME);
e.printStackTrace();
}
catch (InvocationTargetException e)
{
throw new RuntimeException("Error in compatability class " + clazz, e.getTargetException());
}
catch (Exception e)
{
EnderCore.logger.error("[Compat] An unknown error was thrown loading class {}.", clazz);
e.printStackTrace();
}
}
}
@@ -0,0 +1,10 @@
package com.enderio.core.common.compat;
/**
* By implementing this marker interface the class must have a static method by the name of the
* constant contained within this interface
*/
public interface ICompatability
{
public static final String METHOD_NAME = "load";
}
@@ -0,0 +1,748 @@
package com.enderio.core.common.config;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import lombok.NonNull;
import net.minecraftforge.common.config.ConfigCategory;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.config.Property;
import net.minecraftforge.common.config.Property.Type;
import com.enderio.core.EnderCore;
import com.enderio.core.api.common.config.IConfigHandler;
import com.enderio.core.common.Lang;
import com.enderio.core.common.event.ConfigFileChangedEvent;
import com.enderio.core.common.util.Bound;
import com.google.common.collect.ImmutableList;
import cpw.mods.fml.client.event.ConfigChangedEvent;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
public abstract class AbstractConfigHandler implements IConfigHandler
{
/**
* Represents a section in a config handler.
*/
public class Section
{
public final String name;
public final String lang;
public Section(String name, String lang)
{
this.name = name;
this.lang = "section." + lang;
}
private Section register()
{
sections.add(this);
return this;
}
public String lc()
{
return name.toLowerCase();
}
}
public enum RestartReqs
{
/**
* No restart needed for this config to be applied. Default value.
*/
NONE,
/**
* This config requires the world to be restarted to take effect.
*/
REQUIRES_WORLD_RESTART,
/**
* This config requires the game to be restarted to take effect. {@code REQUIRES_WORLD_RESTART} is implied when using this.
*/
REQUIRES_MC_RESTART;
public Property apply(Property prop)
{
if (this == REQUIRES_MC_RESTART)
{
prop.setRequiresMcRestart(true);
}
else if (this == REQUIRES_WORLD_RESTART)
{
prop.setRequiresWorldRestart(true);
}
return prop;
}
}
String modid;
Configuration config;
private List<Section> sections = new ArrayList<Section>();
private Section activeSection = null;
protected AbstractConfigHandler(String modid)
{
this.modid = modid;
FMLCommonHandler.instance().bus().register(this);
EnderCore.instance.configs.add(this);
}
@Override
public final void initialize(File cfg)
{
config = new Configuration(cfg);
init();
reloadAllConfigs();
saveConfigFile();
}
protected void loadConfigFile()
{
config.load();
}
protected void saveConfigFile()
{
config.save();
}
@SubscribeEvent
public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event)
{
if (event.modID.equals(modid))
{
EnderCore.logger.info("Reloading all configs for modid: " + modid);
reloadAllConfigs();
saveConfigFile();
}
}
@SubscribeEvent
public void onConfigFileChanged(ConfigFileChangedEvent event)
{
if (event.modID.equals(modid))
{
EnderCore.logger.info("Reloading ingame configs for modid: " + modid);
loadConfigFile();
reloadIngameConfigs();
event.setSuccessful();
saveConfigFile();
}
}
// convenience for reloading all configs
private void reloadAllConfigs()
{
reloadNonIngameConfigs();
reloadIngameConfigs();
}
/**
* Called after config is loaded, but before properties are processed.
* <p>
* Use this method to add your sections and do other setup.
*/
protected abstract void init();
/**
* Refresh all config values that can only be loaded when NOT in-game.
* <p>
* {@code reloadIngameConfigs()} will be called after this, do not duplicate calls in this method and that one.
*/
protected abstract void reloadNonIngameConfigs();
/**
* Refresh all config values that can only be loaded when in-game.
* <p>
* This is separated from {@code reloadNonIngameConfigs()} because some values may not be able to be modified at runtime.
*/
protected abstract void reloadIngameConfigs();
/**
* Adds a section to your config to be used later
*
* @param sectionName
* The name of the section. Will also be used as language key.
* @return A {@link Section} representing your section in the config
*/
protected Section addSection(String sectionName)
{
return addSection(sectionName, sectionName, null);
}
/**
* Adds a section to your config to be used later
*
* @param sectionName
* The name of the section
* @param langKey
* The language key to use to display your section name in the Config GUI
* @return A {@link Section} representing your section in the config
*/
protected Section addSection(String sectionName, String langKey)
{
return addSection(sectionName, langKey, null);
}
/**
* Adds a section to your config to be used later
*
* @param sectionName
* The name of the section
* @param langKey
* The language key to use to display your section name in the Config GUI
* @param comment
* The section comment
* @return A {@link Section} representing your section in the config
*/
protected Section addSection(String sectionName, String langKey, String comment)
{
Section section = new Section(sectionName, langKey);
if (activeSection == null && sections.isEmpty())
{
activeSection = section;
}
if (comment != null)
{
config.addCustomCategoryComment(sectionName, comment);
}
return section.register();
}
private void checkInitialized()
{
if (activeSection == null)
{
throw new IllegalStateException("No section is active!");
}
}
/**
* Activates a section
*
* @param sectionName
* The name of the section
*
* @throws NullPointerException
* if {@code sectionName} is null
* @throws IllegalArgumentException
* if {@code sectionName} is not valid
*/
protected void activateSection(@NonNull String sectionName)
{
Section section = getSectionByName(sectionName);
if (section == null)
{
throw new IllegalArgumentException("Section " + sectionName + " does not exist!");
}
activateSection(section);
}
/**
* Activates a section
*
* @param section
* The section to activate
*
* @throws NullPointerException
* if {@code section} is null
*/
protected void activateSection(@NonNull Section section)
{
activeSection = section;
}
/**
* Gets a {@link Section} for a name
*
* @param sectionName
* The name of the section
* @return A section object representing the section in your config with this name
*
* @throws NullPointerException
* if {@code sectionName} is null
*/
protected Section getSectionByName(@NonNull String sectionName)
{
for (Section s : sections)
{
if (s.name.equalsIgnoreCase(sectionName))
{
return s;
}
}
return null;
}
/**
* Gets a value from this config handler
*
* @param key
* Name of the key for this property
* @param defaultVal
* Default value so a new property can be created
* @return The value of the property
*
* @throws IllegalArgumentException
* If defaultVal is not a valid property type
* @throws IllegalStateException
* If there is no active section
*/
protected <T> T getValue(String key, T defaultVal)
{
return getValue(key, defaultVal, RestartReqs.NONE);
}
/**
* Gets a value from this config handler
*
* @param key
* Name of the key for this property
* @param defaultVal
* Default value so a new property can be created
* @param req
* Restart requirement of the property to be created
* @return The value of the property
*
* @throws IllegalArgumentException
* If defaultVal is not a valid property type
* @throws IllegalStateException
* If there is no active section
*/
protected <T> T getValue(String key, T defaultVal, RestartReqs req)
{
return getValue(key, null, defaultVal, req);
}
/**
* Gets a value from this config handler
*
* @param key
* Name of the key for this property
* @param defaultVal
* Default value so a new property can be created
* @param bound
* The bounds to set on this property
* @return The value of the property
*
* @throws IllegalArgumentException
* If defaultVal is not a valid property type
* @throws IllegalStateException
* If there is no active section
*/
protected <T> T getValue(String key, T defaultVal, Bound<? extends Number> bound)
{
return getValue(key, null, defaultVal, bound);
}
/**
* Gets a value from this config handler
*
* @param key
* Name of the key for this property
* @param comment
* The comment to put on this property
* @param defaultVal
* Default value so a new property can be created
* @return The value of the property
*
* @throws IllegalArgumentException
* if defaultVal is not a valid property type
* @throws IllegalStateException
* if there is no active section
*/
protected <T> T getValue(String key, String comment, T defaultVal)
{
return getValue(key, comment, defaultVal, RestartReqs.NONE);
}
/**
* Gets a value from this config handler
*
* @param key
* Name of the key for this property
* @param comment
* The comment to put on this property
* @param defaultVal
* Default value so a new property can be created
* @param req
* Restart requirement of the property to be created
* @return The value of the property
*
* @throws IllegalArgumentException
* if defaultVal is not a valid property type
* @throws IllegalStateException
* if there is no active section
*/
protected <T> T getValue(String key, String comment, T defaultVal, RestartReqs req)
{
return getValue(key, comment, defaultVal, req, null);
}
/**
* Gets a value from this config handler
*
* @param key
* Name of the key for this property
* @param comment
* The comment to put on this property
* @param defaultVal
* Default value so a new property can be created
* @param bound
* The bounds to set on this property
* @return The value of the property
*
* @throws IllegalArgumentException
* if defaultVal is not a valid property type
* @throws IllegalStateException
* if there is no active section
*/
protected <T> T getValue(String key, String comment, T defaultVal, Bound<? extends Number> bound)
{
return getValue(key, comment, defaultVal, RestartReqs.NONE, bound);
}
/**
* Gets a value from this config handler
*
* @param key
* Name of the key for this property
* @param comment
* The comment to put on this property
* @param defaultVal
* Default value so a new property can be created
* @param req
* Restart requirement of the property to be created
* @param bound
* The bounds to set on this property
* @return The value of the property
*
* @throws IllegalArgumentException
* if defaultVal is not a valid property type
* @throws IllegalStateException
* if there is no active section
*/
protected <T> T getValue(String key, String comment, T defaultVal, RestartReqs req, Bound<? extends Number> bound)
{
Property prop = getProperty(key, defaultVal, req);
prop.comment = comment;
return getValue(prop, defaultVal, bound);
}
/**
* Gets a value from a property
*
* @param prop
* Property to get value from
* @param defaultVal
* Default value so a new property can be created
*
* @throws IllegalArgumentException
* if defaultVal is not a valid property type
* @throws IllegalStateException
* if there is no active section
*/
protected <T> T getValue(Property prop, T defaultVal)
{
return getValue(prop, defaultVal, null);
}
/**
* Gets a value from a property
*
* @param prop
* Property to get value from
* @param defaultVal
* Default value so a new property can be created
* @param bound
* The bounds to set on this property
*
* @throws IllegalArgumentException
* if defaultVal is not a valid property type
* @throws IllegalStateException
* if there is no active section
*/
@SuppressWarnings("unchecked")
// we check type of defaultVal but compiler still complains about a cast to T
protected <T> T getValue(Property prop, T defaultVal, Bound<? extends Number> bound)
{
checkInitialized();
if (bound != null)
{
setBounds(prop, bound);
}
else
{
bound = Bound.MAX_BOUND;
}
addCommentDetails(prop, bound);
if (defaultVal instanceof Integer)
{
Bound<Integer> b = Bound.of(bound.min.intValue(), bound.max.intValue());
return (T) boundValue(prop, b, (Integer) defaultVal);
}
if (defaultVal instanceof Float)
{
Bound<Float> b = Bound.of(bound.min.floatValue(), bound.max.floatValue());
return (T) boundValue(prop, b, (Float) defaultVal);
}
if (defaultVal instanceof Double)
{
Bound<Double> b = Bound.of(bound.min.doubleValue(), bound.max.doubleValue());
return (T) boundValue(prop, b, (Double) defaultVal);
}
if (defaultVal instanceof Boolean)
{
return (T) Boolean.valueOf(prop.getBoolean());
}
if (defaultVal instanceof int[])
{
return (T) prop.getIntList();
}
if (defaultVal instanceof String)
{
return (T) prop.getString();
}
if (defaultVal instanceof String[])
{
return (T) prop.getStringList();
}
throw new IllegalArgumentException("default value is not a config value type.");
}
static void setBounds(Property prop, Bound<?> bound) throws IllegalArgumentException
{
if (bound.equals(Bound.MAX_BOUND))
{
return;
}
if (prop.getType() == Type.INTEGER)
{
Bound<Integer> b = Bound.of(bound.min.intValue(), bound.max.intValue());
prop.setMinValue(b.min);
prop.setMaxValue(b.max);
}
else if (prop.getType() == Type.DOUBLE)
{
Bound<Double> b = Bound.of(bound.min.doubleValue(), bound.max.doubleValue());
prop.setMinValue(b.min);
prop.setMaxValue(b.max);
}
else
{
throw new IllegalArgumentException(String.format("A mod tried to set bounds %s on a property that was not either of Integer of Double type.", bound));
}
}
static int[] boundIntArr(Property prop, Bound<Integer> bound)
{
int[] prev = prop.getIntList();
int[] res = new int[prev.length];
for (int i = 0; i < prev.length; i++)
{
res[i] = bound.clamp(prev[i]);
}
prop.set(res);
return res;
}
static double[] boundDoubleArr(Property prop, Bound<Double> bound)
{
double[] prev = prop.getDoubleList();
double[] res = new double[prev.length];
for (int i = 0; i < prev.length; i++)
{
res[i] = bound.clamp(prev[i]);
}
prop.set(res);
return res;
}
@SuppressWarnings("unchecked")
static <T extends Number & Comparable<T>> T boundValue(Property prop, Bound<T> bound, T defVal) throws IllegalArgumentException
{
Object b = (Object) bound;
if (defVal instanceof Integer)
{
return (T) boundInt(prop, (Bound<Integer>) b);
}
if (defVal instanceof Double)
{
return (T) boundDouble(prop, (Bound<Double>) b);
}
if (defVal instanceof Float)
{
return (T) boundFloat(prop, (Bound<Float>) b);
}
throw new IllegalArgumentException(bound.min.getClass().getName() + " is not a valid config type.");
}
private static Integer boundInt(Property prop, Bound<Integer> bound)
{
prop.set(bound.clamp(prop.getInt()));
return Integer.valueOf(prop.getInt());
}
private static Double boundDouble(Property prop, Bound<Double> bound)
{
prop.set(bound.clamp(prop.getDouble()));
return Double.valueOf(prop.getDouble());
}
private static Float boundFloat(Property prop, Bound<Float> bound)
{
return boundDouble(prop, Bound.of(bound.min.doubleValue(), bound.max.doubleValue())).floatValue();
}
private static Lang fmlLang = new Lang("fml.configgui.tooltip");
static void addCommentDetails(Property prop, Bound<?> bound)
{
prop.comment += (prop.comment.isEmpty() ? "" : "\n");
if (bound.equals(Bound.MAX_BOUND))
{
prop.comment += fmlLang.localize("default", prop.isList() ? Arrays.toString(prop.getDefaults()) : prop.getDefault());
}
else
{
boolean minIsInt = bound.min.doubleValue() == bound.min.intValue();
boolean maxIsInt = bound.max.doubleValue() == bound.max.intValue();
prop.comment += fmlLang.localize("defaultNumeric", minIsInt ? bound.min.intValue() : bound.min, maxIsInt ? bound.max.intValue()
: bound.max, prop.isList() ? Arrays.toString(prop.getDefaults()) : prop.getDefault());
}
}
/**
* Gets a property from this config handler
*
* @param key
* name of the key for this property
* @param defaultVal
* default value so a new property can be created
* @return The property in the config
*
* @throws IllegalArgumentException
* if defaultVal is not a valid property type
* @throws IllegalStateException
* if there is no active section
*/
protected <T> Property getProperty(String key, T defaultVal)
{
return getProperty(key, defaultVal, RestartReqs.NONE);
}
/**
* Gets a property from this config handler
*
* @param key
* name of the key for this property
* @param defaultVal
* default value so a new property can be created
* @return The property in the config
*
* @throws IllegalArgumentException
* if defaultVal is not a valid property type
* @throws IllegalStateException
* if there is no active section
*/
protected <T> Property getProperty(String key, T defaultVal, RestartReqs req)
{
checkInitialized();
Section section = activeSection;
Property prop = null;
// @formatter:off
// same logic as above method, mostly
if (defaultVal instanceof Integer)
{
prop = config.get(section.name, key, (Integer) defaultVal);
}
if (defaultVal instanceof Boolean)
{
prop = config.get(section.name, key, (Boolean) defaultVal);
}
if (defaultVal instanceof int[])
{
prop = config.get(section.name, key, (int[]) defaultVal);
}
if (defaultVal instanceof String)
{
prop = config.get(section.name, key, (String) defaultVal);
}
if (defaultVal instanceof String[])
{
prop = config.get(section.name, key, (String[]) defaultVal);
}
// @formatter:on
if (defaultVal instanceof Float || defaultVal instanceof Double)
{
double val = defaultVal instanceof Float ? ((Float) defaultVal).doubleValue() : ((Double) defaultVal).doubleValue();
prop = config.get(section.name, key, val);
}
if (prop != null)
{
return req.apply(prop);
}
throw new IllegalArgumentException("default value is not a config value type.");
}
/**
* @return If this config handler should recieve {@link #initHook()} and {@link #postInitHook()} during config reload events. If this returns
* false, these methods will only be called on load.
* <p>
* Defaults to false.
*/
protected boolean shouldHookOnReload()
{
return true;
}
/* IConfigHandler impl */
@Override
public void initHook()
{
}
@Override
public void postInitHook()
{
}
// no need to override these, they are merely utilities, and reference private fields anyways
@Override
public final List<Section> getSections()
{
return ImmutableList.copyOf(sections);
}
@Override
public final ConfigCategory getCategory(String name)
{
return config.getCategory(name);
}
@Override
public final String getModID()
{
return modid;
}
}
@@ -0,0 +1,37 @@
package com.enderio.core.common.config;
import java.util.Set;
import com.enderio.core.client.config.BaseConfigGui;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import cpw.mods.fml.client.IModGuiFactory;
public class BaseConfigFactory implements IModGuiFactory
{
@Override
public void initialize(Minecraft minecraftInstance)
{
;
}
@Override
public Class<? extends GuiScreen> mainConfigGuiClass()
{
return BaseConfigGui.class;
}
@Override
public Set<RuntimeOptionCategoryElement> runtimeGuiCategories()
{
return null;
}
@Override
public RuntimeOptionGuiHandler getHandlerFor(RuntimeOptionCategoryElement element)
{
return null;
}
}
@@ -0,0 +1,171 @@
package com.enderio.core.common.config;
import java.io.File;
import com.enderio.core.EnderCore;
import com.enderio.core.common.Handlers.Handler;
import com.enderio.core.common.Handlers.Handler.HandlerType;
import com.enderio.core.common.Handlers.Handler.Inst;
import com.enderio.core.common.config.ConfigProcessor.IReloadCallback;
import com.enderio.core.common.config.JsonConfigReader.ModToken;
import com.enderio.core.common.config.annot.Comment;
import com.enderio.core.common.config.annot.Config;
import com.enderio.core.common.config.annot.NoSync;
import com.enderio.core.common.config.annot.Range;
import com.enderio.core.common.config.annot.RestartReq;
import com.enderio.core.common.handlers.RightClickCropHandler;
import com.enderio.core.common.handlers.RightClickCropHandler.PlantInfo;
import com.enderio.core.common.tweaks.Tweak;
import com.enderio.core.common.tweaks.Tweaks;
import net.minecraftforge.common.config.Configuration;
@Handler(value = HandlerType.FML, getInstFrom = Inst.METHOD)
public class ConfigHandler extends AbstractConfigHandler implements ITweakConfigHandler, IReloadCallback
{
private static final String sectionGeneral = Configuration.CATEGORY_GENERAL;
private static final String sectionEnchants = "enchants";
@Config
@Comment({"Show oredictionary names of every item in its tooltip.", "0 - Off", "1 - Always on", "2 - Only with shift", "3 - Only in debug mode"})
@Range(min = 0, max = 3)
@NoSync
public static int showOredictTooltips = 1;
@Config
@Comment({ "Show item registry names in tooltips.", "0 - Off", "1 - Always on", "2 - Only with shift", "3 - Only in debug mode" })
@Range(min = 0, max = 3)
@NoSync
public static int showRegistryNameTooltips = 3;
@Config
@Comment({ "Removes all void fog.", "0 = off", "1 = DEFAULT worldtype only", "2 = all world types" })
@NoSync
@Range(min = 0, max = 2)
public static int disableVoidFog = 1;
@Config
@Comment("The max amount of XP levels an anvil recipe can use.")
public static int anvilMaxLevel = 40;
@Config
@Comment("The way the game should have been made (Yes this is the fireworks thing).")
public static boolean betterAchievements = true;
@Config
@Comment("Disabling this option will prevent any crops added to the config json from being right clickable.")
public static boolean allowCropRC = true;
@Config
@Comment({ "0 - Do nothing", "1 - Remove stacktraces, leave 1-line missing texture errors", "2 - Remove all missing texture errors completely." })
@NoSync
@Range(min = 0, max = 2)
public static int textureErrorRemover = 1;
@Config
@Comment({ "Controls the default sorting on the mod list GUI.", "0 - Default sort (load order)", "1 - A to Z sort", "2 - Z to A sort" })
@NoSync
@Range(min = 0, max = 2)
public static int defaultModSort = 1;
@Config(sectionEnchants)
@Comment("Enchant ID for the XP boost enchant.")
@RestartReq(RestartReqs.REQUIRES_MC_RESTART)
@Range(min = 0, max = 255)
public static int enchantIDXPBoost = 45;
@Config(sectionEnchants)
@Comment("Allow the XP Boost enchant to be registered.")
@RestartReq(RestartReqs.REQUIRES_MC_RESTART)
public static boolean allowXPBoost = true;
@Config(sectionEnchants)
@Comment("Enchant ID for the Auto Smelt enchant.")
@RestartReq(RestartReqs.REQUIRES_MC_RESTART)
@Range(min = 0, max = 255)
public static int enchantIDAutoSmelt = 46;
@Config(sectionEnchants)
@Comment("Allow the Auto Smelt enchant to be registered.")
@RestartReq(RestartReqs.REQUIRES_MC_RESTART)
public static boolean allowAutoSmelt = true;
@Config(sectionEnchants)
@Comment("Allow the Auto Smelt enchant to work with Fortune.")
public static boolean allowAutoSmeltWithFortune = true;
// @Config("test")
// public static List<Integer> test1 = Lists.newArrayList(1, 2, 3);
// @Config("test")
// public static List<Double> test2 = Lists.newArrayList(0.1, 0.2, 0.3);
// @Config("test")
// public static List<Boolean> test3 = Lists.newArrayList(true, false, true);
// @Config("test")
// public static List<String> test4 = Lists.newArrayList("test1", "test2", "test3");
private static ConfigHandler INSTANCE;
public static File configFolder, enderConfigFolder;
public static File configFile;
public static ConfigProcessor processor;
public static ConfigHandler instance()
{
if (INSTANCE == null)
{
INSTANCE = new ConfigHandler();
}
return INSTANCE;
}
protected ConfigHandler()
{
super(EnderCore.MODID);
}
@Override
public void init()
{
addSection(sectionGeneral);
addSection(sectionEnchants);
addSection("tweaks");
processor = new ConfigProcessor(getClass(), this, this);
processor.process(true);
}
@Override
protected void reloadIngameConfigs()
{
Tweaks.loadIngameTweaks();
}
@Override
protected void reloadNonIngameConfigs()
{
Tweaks.loadNonIngameTweaks();
}
@Override
public void callback(ConfigProcessor inst)
{
Tweaks.loadIngameTweaks();
}
@Override
public boolean addBooleanFor(Tweak tweak)
{
activateSection("tweaks");
return getValue(tweak.getName(), tweak.getComment(), true);
}
public void loadRightClickCrops()
{
JsonConfigReader<PlantInfo> reader = new JsonConfigReader<PlantInfo>(new ModToken(EnderCore.class, EnderCore.MODID.toLowerCase() + "/config"),
enderConfigFolder.getAbsolutePath() + "/cropConfig.json", PlantInfo.class);
for (PlantInfo i : reader)
{
i.init();
RightClickCropHandler.INSTANCE.addCrop(i);
}
}
}
@@ -0,0 +1,425 @@
package com.enderio.core.common.config;
import java.io.File;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraftforge.common.config.ConfigCategory;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.config.Property;
import com.enderio.core.common.config.AbstractConfigHandler.RestartReqs;
import com.enderio.core.common.config.annot.Comment;
import com.enderio.core.common.config.annot.Config;
import com.enderio.core.common.config.annot.NoSync;
import com.enderio.core.common.config.annot.Range;
import com.enderio.core.common.config.annot.RestartReq;
import com.enderio.core.common.event.ConfigFileChangedEvent;
import com.enderio.core.common.network.EnderPacketHandler;
import com.enderio.core.common.util.Bound;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.reflect.TypeToken;
import cpw.mods.fml.client.event.ConfigChangedEvent;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.PlayerEvent;
/**
* This class can be used to automatically process {@link Config} annotations on fields, and sync the data in those fields to clients. It will also
* automatically respond to all config changed events and handle them appropriately.
*
* @see #process(boolean)
*/
public class ConfigProcessor
{
public interface IReloadCallback
{
void callback(ConfigProcessor inst);
}
/**
* A simple adapter for reading custom config types.
*
* @param <BASE>
* Must be a possible class that can be used in configs. This consists of:
* <ul>
* <code>
* <li>Boolean</li>
* <li>Integer</li>
* <li>Double</li>
* <li>String</li>
* <li>boolean[]</li>
* <li>int[]</li>
* <li>double[]</li>
* <li>String[]</li>
* </code>
* </ul>
* @param <ACTUAL>
* The actual type of this adapter. This is what the field type must be for this adapter to be applied.
*/
public interface ITypeAdapter<ACTUAL, BASE>
{
TypeToken<ACTUAL> getActualType();
Property.Type getType();
/**
* If this binds to a primitive type, return it here (e.g. int.class). Otherwise, return null.
*
* @return The class for this ITypeAdapter's primitive type.
*/
@Nullable
Class<?> getPrimitiveType();
ACTUAL createActualType(BASE base);
BASE createBaseType(ACTUAL actual);
}
static final Map<String, ConfigProcessor> processorMap = Maps.newHashMap();
private final List<ITypeAdapter<?, ?>> adapters = Lists.newArrayList();
final String modid;
private final Class<?> configs;
private final Configuration configFile;
private final IReloadCallback callback;
Map<String, Object> configValues = Maps.newHashMap();
Map<String, Object> defaultValues = Maps.newHashMap();
private Set<String> sections = Sets.newHashSet();
/**
* This constructor omits the callback arg.
*
* @see #ConfigProcessor(Class, File, String, IReloadCallback)
*/
public ConfigProcessor(Class<?> configs, File configFile, String modid)
{
this(configs, configFile, modid, null);
}
/**
* Constructs a new ConfigProcessor to read and set {@link Config} values.
*
* @param configs
* The class which contains your {@link Config} annotations
* @param configFile
* The file to use as the configuration file
* @param modid
* The modid of the owner mod
* @param callback
* an {@link IReloadCallback} object which will be called whenever config values are edited.
*/
public ConfigProcessor(Class<?> configs, File configFile, String modid, IReloadCallback callback)
{
this(configs, new Configuration(configFile), modid, callback);
}
/**
* Use this constructor if you are using a {@code ConfigProcessor} alongside an {@link AbstractConfigHandler}. Do not pass a handler that has not
* been {@link AbstractConfigHandler#initialize(File) initialized}!
*
* @param configs
* The class which contains your {@link Config} annotations (typically same class as your {@link AbstractConfigHandler handler})
* @param handler
* Your {@link AbstractConfigHandler}
*/
public ConfigProcessor(Class<?> configs, AbstractConfigHandler handler)
{
this(configs, handler, null);
}
/**
* Use this constructor if you are using a {@code ConfigProcessor} alongside an {@link AbstractConfigHandler}. Do not pass a handler that has not
* been {@link AbstractConfigHandler#initialize(File) initialized}!
*
* @param configs
* The class which contains your {@link Config} annotations (typically same class as your {@link AbstractConfigHandler handler})
* @param handler
* Your {@link AbstractConfigHandler}
* @param callback
* an {@link IReloadCallback} object which will be called whenever config values are edited.
*/
public ConfigProcessor(Class<?> configs, AbstractConfigHandler handler, IReloadCallback callback)
{
this(configs, handler.config, handler.modid, callback);
}
private ConfigProcessor(Class<?> configs, Configuration configFile, String modid, IReloadCallback callback)
{
this.configs = configs;
this.configFile = configFile;
this.modid = modid;
this.callback = callback;
processorMap.put(modid, this);
FMLCommonHandler.instance().bus().register(this);
adapters.addAll(TypeAdapterBase.all);
}
public <ACTUAL, BASE> ConfigProcessor addAdapter(ITypeAdapter<ACTUAL, BASE> adapter)
{
adapters.add(adapter);
return this;
}
public <ACTUAL, BASE> ConfigProcessor addAdapters(ITypeAdapter<ACTUAL, BASE>... adapters)
{
for (ITypeAdapter<ACTUAL, BASE> adapter : adapters)
{
addAdapter(adapter);
}
return this;
}
/**
* Processes all the configs in this processors class, optionally loading them from file first.
*
* @param load
* If true, the values from the file will be loaded. Otherwise, the values existing in memory will be used.
*/
public void process(boolean load)
{
if (load)
{
configFile.load();
}
try
{
for (Field f : configs.getDeclaredFields())
{
processField(f);
}
if (callback != null)
{
callback.callback(this);
}
}
catch (Exception e)
{
throw new RuntimeException(e);
}
configFile.save();
}
// returns true if the config value changed
private boolean processField(Field f) throws Exception
{
Config cfg = f.getAnnotation(Config.class);
if (cfg == null)
{
return false;
}
String name = f.getName();
Object value = defaultValues.get(name);
if (value == null)
{
value = f.get(null);
defaultValues.put(name, value);
}
Object newValue = getConfigValue(cfg.value(), getComment(f), f, value);
configValues.put(f.getName(), newValue);
f.set(null, newValue);
sections.add(cfg.value());
return !value.equals(newValue);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private Object getConfigValue(String section, String[] commentLines, Field f, Object defVal)
{
Property prop = null;
Object res = null;
Bound<Double> bound = getBound(f);
ITypeAdapter adapter = getAdapterFor(f);
String comment = StringUtils.join(commentLines, "\n");
if (adapter != null)
{
defVal = adapter.createBaseType(defVal);
switch (adapter.getType())
{
case BOOLEAN:
if (defVal.getClass().isArray())
{
prop = configFile.get(section, f.getName(), (boolean[]) defVal, comment);
res = prop.getBooleanList();
}
else
{
prop = configFile.get(section, f.getName(), (Boolean) defVal, comment);
res = prop.getBoolean();
}
break;
case DOUBLE:
if (defVal.getClass().isArray())
{
prop = configFile.get(section, f.getName(), (double[]) defVal, comment);
res = AbstractConfigHandler.boundDoubleArr(prop, Bound.of(bound.min.doubleValue(), bound.max.doubleValue()));
}
else
{
prop = configFile.get(section, f.getName(), (Double) defVal, comment);
res = AbstractConfigHandler.boundValue(prop, Bound.of(bound.min.doubleValue(), bound.max.doubleValue()), (Double) defVal);
}
break;
case INTEGER:
if (defVal.getClass().isArray())
{
prop = configFile.get(section, f.getName(), (int[]) defVal, comment);
res = AbstractConfigHandler.boundIntArr(prop, Bound.of(bound.min.intValue(), bound.max.intValue()));
}
else
{
prop = configFile.get(section, f.getName(), (Integer) defVal, comment);
res = AbstractConfigHandler.boundValue(prop, Bound.of(bound.min.intValue(), bound.max.intValue()), (Integer) defVal);
}
break;
case STRING:
if (defVal.getClass().isArray())
{
prop = configFile.get(section, f.getName(), (String[]) defVal, comment);
res = prop.getStringList();
}
else
{
prop = configFile.get(section, f.getName(), (String) defVal, comment);
res = prop.getString();
}
break;
default:
break;
}
if (res != null)
{
AbstractConfigHandler.setBounds(prop, bound);
AbstractConfigHandler.addCommentDetails(prop, bound);
getRestartReq(f).apply(prop);
return adapter.createActualType(res);
}
}
throw new IllegalArgumentException(String.format("No adapter for type %s in class %s, field %s", f.getGenericType(), configs, f));
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private ITypeAdapter getAdapterFor(Field f)
{
TypeToken<?> t = TypeToken.of(f.getGenericType());
Class<?> c = f.getType();
for (ITypeAdapter adapter : adapters)
{
if ((c.isPrimitive() && c == adapter.getPrimitiveType()) || adapter.getActualType().isAssignableFrom(t))
{
return adapter;
}
}
return null;
}
public ImmutableSet<String> sections()
{
return ImmutableSet.copyOf(sections);
}
public ConfigCategory getCategory(String category)
{
return configFile.getCategory(category);
}
public void syncTo(Map<String, Object> values)
{
this.configValues = values;
for (String s : configValues.keySet())
{
try
{
Field f = configs.getDeclaredField(s);
Config annot = f.getAnnotation(Config.class);
if (annot != null && !getNoSync(f))
{
Object newVal = configValues.get(s);
boolean changed = false;
if (!f.get(null).equals(newVal))
{
f.set(null, newVal);
changed = true;
}
if (changed && callback != null)
{
callback.callback(this);
}
}
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
}
private String[] getComment(Field f)
{
Comment c = f.getAnnotation(Comment.class);
return c == null ? new String[0] : c.value();
}
private Bound<Double> getBound(Field f)
{
Range r = f.getAnnotation(Range.class);
return r == null ? Bound.MAX_BOUND : Bound.of(r.min(), r.max());
}
private boolean getNoSync(Field f)
{
return f.getAnnotation(NoSync.class) != null;
}
private RestartReqs getRestartReq(Field f)
{
RestartReq r = f.getAnnotation(RestartReq.class);
return r == null ? RestartReqs.NONE : r.value();
}
/* Event Handling */
@SubscribeEvent
public void onPlayerLogin(PlayerEvent.PlayerLoggedInEvent event)
{
EnderPacketHandler.INSTANCE.sendTo(new PacketConfigSync(this), (EntityPlayerMP) event.player);
}
@SubscribeEvent
public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event)
{
if (event.modID.equals(modid))
{
process(false);
}
}
@SubscribeEvent
public void onConfigFileChanged(ConfigFileChangedEvent event)
{
if (event.modID.equals(modid))
{
process(true);
}
}
}
@@ -0,0 +1,8 @@
package com.enderio.core.common.config;
import com.enderio.core.common.tweaks.Tweak;
public interface ITweakConfigHandler
{
public boolean addBooleanFor(Tweak tweak);
}
@@ -0,0 +1,221 @@
package com.enderio.core.common.config;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import lombok.Value;
import com.enderio.core.common.util.EnderFileUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
/**
* A utility to easily read in JSON config files.
*
* The format of the JSON file is as follows:
* <p>
* {@code "data":[<br>
* <br>
* ]}
* <p>
* Where the objects go inbetween the brackets ( [] )
*
* @param <T>
* The type of the object to be read in. If this type is generic in itself (ex. {@code HashMap}) you should use one of the TypeToken
* constructors.
*/
public class JsonConfigReader<T> implements Iterable<T>
{
/**
* A class representing some info about your mod.
* <p>
* <b>mainClass</b> is a class in your mod so that files can be copied out of your jar.<br>
* <b>assetPath</b> is the path to your default json file. This includes the /modid part and whatever subfolders follow.
*/
@Value
public static class ModToken
{
private Class<?> mainClass;
private String assetPath;
}
private static final Gson gson = new GsonBuilder().setPrettyPrinting().create();
private static final JsonParser parser = new JsonParser();
private static final String DEFAULT_KEY = "data";
private File file;
private JsonObject root;
private Class<T> type = null;
private TypeToken<T> typeToken = null;
/**
* An easy way to read in config files in JSON format
*
* @param mod
* A {@link ModToken} object to hold data about your mod. This is used to automatically copy the file from your jar if it does not
* exist in the config folder
* @param fullFileName
* The full file path and name of your JSON config. Can be relative to the working directory or absolute.
* @param objClass
* The type of the object being deserialized. Must be of the same type as the generic type of this class.
*/
public JsonConfigReader(ModToken mod, String fullFileName, Class<T> objClass)
{
this(mod, new File(fullFileName), objClass);
}
/**
* An easy way to read in config files in JSON format
*
* @param mod
* A {@link ModToken} object to hold data about your mod. This is used to automatically copy the file from your jar if it does not
* exist in the config folder
* @param file
* The {@link File} representing your JSON config.
* @param objClass
* The type of the object being deserialized. Must be of the same type as the generic type of this class.
*/
public JsonConfigReader(ModToken mod, File file, Class<T> objClass)
{
this.type = objClass;
initialize(mod, file);
}
/**
* An easy way to read in config files in JSON format. Use this constructor if the type of this class is generic in itself. (ex.
* {@code HashMap<K, V>})
*
* @param mod
* A {@link ModToken} object to hold data about your mod. This is used to automatically copy the file from your jar if it does not
* exist in the config folder
* @param fullFileName
* The full file path and name of your JSON config. Can be relative to the working directory or absolute.
* @param objType
* A {@link TypeToken} representing the type of the object to be deserialized. Must be of the same type as the generic type of this
* class.
*/
public JsonConfigReader(ModToken mod, String fullFileName, TypeToken<T> objType)
{
this(mod, new File(fullFileName), objType);
}
/**
* An easy way to read in config files in JSON format. Use this constructor if the type of this class is generic in itself. (ex.
* {@code HashMap<K, V>})
*
* @param mod
* A {@link ModToken} object to hold data about your mod. This is used to automatically copy the file from your jar if it does not
* exist in the config folder
* @param file
* The {@link File} representing your JSON config.
* @param objType
* A {@link TypeToken} representing the type of the object to be deserialized. Must be of the same type as the generic type of this
* class.
*/
public JsonConfigReader(ModToken mod, File file, TypeToken<T> objType)
{
this.typeToken = objType;
initialize(mod, file);
}
private void initialize(ModToken mod, File file)
{
this.file = file;
if (!file.exists())
{
file.getParentFile().mkdirs();
String assetPath = mod.getAssetPath();
if (!assetPath.endsWith("/"))
{
assetPath = assetPath + "/";
}
EnderFileUtils.copyFromJar(mod.getMainClass(), assetPath + file.getName(), file);
}
refresh();
}
/**
* Reparses the config file.
*
* @return The {@link JsonObject} read.
*
* @throws RuntimeException
* If there is an exception while reading the file.
*/
public JsonObject parseFile()
{
try
{
return parser.parse(new FileReader(file)).getAsJsonObject();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
/**
* Reparses the config file and stores the result in this class. Use this if your JSON config was edited and you want to reload from disk.
*
* @throws RuntimeException
* If there is an exception while reading the file.
*/
public void refresh()
{
this.root = parseFile();
}
/**
* Reads from the {@link JsonObject} linked to the {@link String key} and returns a List of all the elements contained in its array.
*
* @return A list of the generic type of this class containing the deserialized elements from the passed key.
*/
@SuppressWarnings("unchecked")
public List<T> getElements(String key)
{
JsonArray elements = root.get(key).getAsJsonArray();
List<T> list = new ArrayList<T>();
for (int i = 0; i < elements.size(); i++)
{
if (type == null)
{
list.add((T) gson.fromJson(elements.get(i), typeToken.getType()));
}
else
{
list.add(gson.fromJson(elements.get(i), type));
}
}
return list;
}
/**
* Reads the default (defined by {@value #DEFAULT_KEY}) cached JsonObject in this class and returns a List of all the elements contained in its
* array.
* <p>
* {@link #getElements(String)} should be used if your config has multiple keys.
*
* @return A list of the generic type of this class containing the deserialized elements from your JSON config's default key.
*/
public List<T> getElements()
{
return getElements(DEFAULT_KEY);
}
@Override
public Iterator<T> iterator()
{
return getElements().iterator();
}
}
@@ -0,0 +1,79 @@
package com.enderio.core.common.config;
import io.netty.buffer.ByteBuf;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import lombok.SneakyThrows;
import cpw.mods.fml.common.network.ByteBufUtils;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
public class PacketConfigSync implements IMessage, IMessageHandler<PacketConfigSync, PacketConfigSync>
{
public PacketConfigSync()
{
}
private Map<String, Object> configValues;
private String modid;
public PacketConfigSync(ConfigProcessor toSync)
{
this.configValues = toSync.configValues;
this.modid = toSync.modid;
}
@Override
@SneakyThrows
public void toBytes(ByteBuf buf)
{
ByteArrayOutputStream obj = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(obj);
ObjectOutputStream objStream = new ObjectOutputStream(gzip);
objStream.writeObject(configValues);
objStream.close();
buf.writeShort(obj.size());
buf.writeBytes(obj.toByteArray());
ByteBufUtils.writeUTF8String(buf, modid);
}
@SuppressWarnings("unchecked")
@Override
@SneakyThrows
public void fromBytes(ByteBuf buf)
{
short len = buf.readShort();
byte[] compressedBody = new byte[len];
for (short i = 0; i < len; i++)
compressedBody[i] = buf.readByte();
ObjectInputStream obj = new ObjectInputStream(new GZIPInputStream(new ByteArrayInputStream(compressedBody)));
configValues = (Map<String, Object>) obj.readObject();
obj.close();
modid = ByteBufUtils.readUTF8String(buf);
}
@Override
public PacketConfigSync onMessage(PacketConfigSync message, MessageContext ctx)
{
ConfigProcessor processor = ConfigProcessor.processorMap.get(message.modid);
if (processor != null)
{
processor.syncTo(message.configValues);
}
return null;
}
}
@@ -0,0 +1,213 @@
package com.enderio.core.common.config;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
import lombok.AllArgsConstructor;
import lombok.Getter;
import net.minecraftforge.common.config.Property;
import net.minecraftforge.common.config.Property.Type;
import com.enderio.core.common.config.ConfigProcessor.ITypeAdapter;
import com.google.common.collect.Lists;
import com.google.common.reflect.TypeToken;
@AllArgsConstructor
@Getter
@SuppressWarnings({ "serial", "unchecked" })
public abstract class TypeAdapterBase<ACTUAL, BASE> implements ITypeAdapter<ACTUAL, BASE>
{
private final TypeToken<ACTUAL> actualType;
private final Property.Type type;
private final Class<?> primitiveType;
public TypeAdapterBase(TypeToken<ACTUAL> actualType, Property.Type baseType)
{
this(actualType, baseType, null);
}
public static final class TypeAdapterSame<TYPE> extends TypeAdapterBase<TYPE, TYPE>
{
public TypeAdapterSame(TypeToken<TYPE> actual, Property.Type base)
{
super(actual, base);
}
public TypeAdapterSame(TypeToken<TYPE> actual, Property.Type base, Class<?> primitiveType)
{
super(actual, base, primitiveType);
}
@Override
public TYPE createActualType(TYPE base)
{
return base;
}
@Override
public TYPE createBaseType(TYPE actual)
{
return actual;
}
}
// @formatter:off
public static final TypeAdapterSame<Integer> INTEGER = new TypeAdapterSame<Integer>(TypeToken.of(Integer.class), Type.INTEGER, int.class);
public static final TypeAdapterSame<int[]> INTEGER_ARR = new TypeAdapterSame<int[]>(TypeToken.of(int[].class), Type.INTEGER);
public static final TypeAdapterSame<Double> DOUBLE = new TypeAdapterSame<Double>(TypeToken.of(Double.class), Type.DOUBLE, double.class);
public static final TypeAdapterSame<double[]> DOUBLE_ARR = new TypeAdapterSame<double[]>(TypeToken.of(double[].class), Type.DOUBLE);
public static final TypeAdapterSame<Boolean> BOOLEAN = new TypeAdapterSame<Boolean>(TypeToken.of(Boolean.class), Type.BOOLEAN, boolean.class);
public static final TypeAdapterSame<boolean[]> BOOLEAN_ARR = new TypeAdapterSame<boolean[]>(TypeToken.of(boolean[].class), Type.BOOLEAN);
public static final TypeAdapterSame<String> STRING = new TypeAdapterSame<String>(TypeToken.of(String.class), Type.STRING);
public static final TypeAdapterSame<String[]> STRING_ARR = new TypeAdapterSame<String[]>(TypeToken.of(String[].class), Type.STRING);
private static DecimalFormat Floatfmt = new DecimalFormat();
static
{
Floatfmt.setMaximumFractionDigits(5);
}
public static final TypeAdapterBase<Float, Double> FLOAT =
new TypeAdapterBase<Float, Double>(TypeToken.of(Float.class), Type.DOUBLE, float.class)
{
@Override
public Float createActualType(Double data)
{
return data.floatValue();
}
public Double createBaseType(Float actual)
{
return Double.parseDouble(Floatfmt.format(actual));
}
};
public static final TypeAdapterBase<float[], double[]> FLOAT_ARR =
new TypeAdapterBase<float[], double[]>(TypeToken.of(float[].class), Type.DOUBLE)
{
@Override
public float[] createActualType(double[] base)
{
float[] ret = new float[base.length];
for (int i = 0; i < ret.length; i++)
{
ret[i] = (float) base[i];
}
return ret;
}
@Override
public double[] createBaseType(float[] actual)
{
double[] ret = new double[actual.length];
for (int i = 0; i < ret.length; i++)
{
ret[i] = Double.parseDouble(Floatfmt.format(actual[i]));
}
return ret;
}
};
public static final TypeAdapterBase<List<Integer>, int[]> INTEGER_LIST =
new TypeAdapterBase<List<Integer>, int[]>(new TypeToken<List<Integer>>(){}, Type.INTEGER)
{
@Override
public List<Integer> createActualType(int[] data)
{
return Lists.newArrayList(ArrayUtils.toObject(data));
}
@Override
public int[] createBaseType(List<Integer> actual)
{
return ArrayUtils.toPrimitive(actual.toArray(new Integer[actual.size()]));
}
};
public static final TypeAdapterBase<List<Double>, double[]> DOUBLE_LIST =
new TypeAdapterBase<List<Double>, double[]>(new TypeToken<List<Double>>(){}, Type.DOUBLE)
{
@Override
public List<Double> createActualType(double[] data)
{
return Lists.newArrayList(ArrayUtils.toObject(data));
}
@Override
public double[] createBaseType(List<Double> actual)
{
return ArrayUtils.toPrimitive(actual.toArray(new Double[actual.size()]));
}
};
public static final TypeAdapterBase<List<Float>, double[]> FLOAT_LIST =
new TypeAdapterBase<List<Float>, double[]>(new TypeToken<List<Float>>(){}, Type.DOUBLE)
{
@Override
public List<Float> createActualType(double[] data)
{
return Lists.newArrayList(ArrayUtils.toObject(FLOAT_ARR.createActualType(data)));
}
@Override
public double[] createBaseType(List<Float> actual)
{
float[] temp = ArrayUtils.toPrimitive(actual.toArray(new Float[actual.size()]));
return FLOAT_ARR.createBaseType(temp);
}
};
public static final TypeAdapterBase<List<Boolean>, boolean[]> BOOLEAN_LIST =
new TypeAdapterBase<List<Boolean>, boolean[]>(new TypeToken<List<Boolean>>(){}, Type.BOOLEAN)
{
@Override
public List<Boolean> createActualType(boolean[] data)
{
return Lists.newArrayList(ArrayUtils.toObject(data));
}
@Override
public boolean[] createBaseType(List<Boolean> actual)
{
return ArrayUtils.toPrimitive(actual.toArray(new Boolean[actual.size()]));
}
};
public static final TypeAdapterBase<List<String>, String[]> STRING_LIST =
new TypeAdapterBase<List<String>, String[]>(new TypeToken<List<String>>(){}, Type.STRING)
{
@Override
public List<String> createActualType(String[] data)
{
return Lists.newArrayList(data);
}
@Override
public String[] createBaseType(List<String> actual)
{
return actual.toArray(new String[actual.size()]);
}
};
public static final List<TypeAdapterBase<?, ? extends Serializable>> all = Lists.newArrayList(
INTEGER,
INTEGER_ARR,
DOUBLE,
DOUBLE_ARR,
BOOLEAN,
BOOLEAN_ARR,
STRING,
STRING_ARR,
FLOAT,
FLOAT_ARR,
INTEGER_LIST,
DOUBLE_LIST,
FLOAT_LIST,
BOOLEAN_LIST,
STRING_LIST
);
}
@@ -0,0 +1,21 @@
package com.enderio.core.common.config.annot;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Contains the comment for a config option. Has no effect is this field is not also annotated with {@link Config}.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface Comment
{
/**
* The comment for the config option. Multiple strings will be split into lines.
*/
String[] value() default "";
}
@@ -0,0 +1,29 @@
package com.enderio.core.common.config.annot;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.enderio.core.common.config.ConfigProcessor;
import net.minecraftforge.common.config.Configuration;
/**
* Used to mark a {@code static} field as a config option. Has no effect if the class is not processed with a {@link ConfigProcessor}
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface Config
{
/**
* The section of the config option.
*
* (AKA Category)
*
* @return A string section name.
*/
String value() default Configuration.CATEGORY_GENERAL;
}
@@ -0,0 +1,21 @@
package com.enderio.core.common.config.annot;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* If annotation exists, this config will not be synced to the client upon connection to a server. Has no effect is this field is not also annotated
* with {@link Config}.
* <p>
* This is useful for configs that have no need to be the same between client and server (or are purely client-sided).
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface NoSync
{
}
@@ -0,0 +1,36 @@
package com.enderio.core.common.config.annot;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Represents the range a config value can be, i.e. a minimum and maximum value. This is applied forcefully, any value past one of the extremes will
* be clamped inside this range. Has no effect is this field is not also annotated with {@link Config}.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface Range
{
/**
* The min value of the config.
* <p>
* For non-numeric values, or if there is no min value, this should remain unset.
*
* @return A double minimum value for the config.
*/
double min() default Double.MIN_VALUE;
/**
* The max value of the config.
* <p>
* For non-numeric values, or if there is no max value, this should remain unset.
*
* @return A double maximum value for the config.
*/
double max() default Double.MAX_VALUE;
}
@@ -0,0 +1,28 @@
package com.enderio.core.common.config.annot;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.enderio.core.common.config.AbstractConfigHandler.RestartReqs;
/**
* Represents the restart requirements of a config value. Use this if your config will have no effect if changed while the game is running. Has no
* effect is this field is not also annotated with {@link Config}.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface RestartReq
{
/**
* What requirements this config has for restarting the game.
*
* @see RestartReqs#NONE
* @see RestartReqs#REQUIRES_WORLD_RESTART
* @see RestartReqs#REQUIRES_MC_RESTART
*/
RestartReqs value() default RestartReqs.NONE;
}
@@ -0,0 +1,83 @@
package com.enderio.core.common.enchant;
import com.enderio.core.EnderCore;
import com.enderio.core.api.common.enchant.IAdvancedEnchant;
import com.enderio.core.common.config.ConfigHandler;
import cpw.mods.fml.common.event.FMLInterModComms;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnumEnchantmentType;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
public class EnchantAutoSmelt extends Enchantment implements IAdvancedEnchant
{
public static final EnchantAutoSmelt INSTANCE = new EnchantAutoSmelt(ConfigHandler.enchantIDAutoSmelt);
private EnchantAutoSmelt(int id)
{
super(id, 2, EnumEnchantmentType.breakable);
}
@Override
public int getMaxEnchantability(int level)
{
return super.getMaxEnchantability(level) + 30;
}
@Override
public int getMinEnchantability(int level)
{
return super.getMinEnchantability(level);
}
@Override
public int getMaxLevel()
{
return 1;
}
@Override
public boolean canApply(ItemStack stack)
{
return type.canEnchantItem(stack.getItem()) && !(stack.getItem() instanceof ItemArmor);
}
@Override
public String getName()
{
return "enchantment.autosmelt";
}
@Override
public boolean isAllowedOnBooks()
{
return ConfigHandler.allowAutoSmelt;
}
@Override
public String[] getTooltipDetails(ItemStack stack)
{
return new String[] { EnderCore.lang.localize("enchantment.autosmelt.tooltip", false) };
}
public void register()
{
if (ConfigHandler.allowAutoSmelt)
{
FMLInterModComms.sendMessage("EnderIO", "recipe:enchanter",
"<enchantment name=\"enchantment.autosmelt\" costPerLevel=\"30\">\n<itemStack oreDictionary=\"blockCoal\" number=\"32\"/>\n</enchantment>");
}
else
{
Enchantment.enchantmentsList[this.effectId] = null;
}
}
public boolean canApplyTogether(Enchantment ench)
{
return super.canApplyTogether(ench) && ench.effectId != silkTouch.effectId
&& ((ench.effectId != fortune.effectId) || ConfigHandler.allowAutoSmeltWithFortune);
}
}
@@ -0,0 +1,76 @@
package com.enderio.core.common.enchant;
import com.enderio.core.EnderCore;
import com.enderio.core.api.common.enchant.IAdvancedEnchant;
import com.enderio.core.common.config.ConfigHandler;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnumEnchantmentType;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.event.FMLInterModComms;
public class EnchantXPBoost extends Enchantment implements IAdvancedEnchant
{
public static final EnchantXPBoost INSTANCE = new EnchantXPBoost(ConfigHandler.enchantIDXPBoost);
private EnchantXPBoost(int id)
{
super(id, 2, EnumEnchantmentType.breakable);
}
@Override
public int getMaxEnchantability(int level)
{
return super.getMaxEnchantability(level) + 30;
}
@Override
public int getMinEnchantability(int level)
{
return super.getMinEnchantability(level);
}
@Override
public int getMaxLevel()
{
return 3;
}
@Override
public boolean canApply(ItemStack stack)
{
return type.canEnchantItem(stack.getItem()) && !(stack.getItem() instanceof ItemArmor);
}
@Override
public String getName()
{
return "enchantment.xpboost";
}
@Override
public boolean isAllowedOnBooks()
{
return ConfigHandler.allowXPBoost;
}
@Override
public String[] getTooltipDetails(ItemStack stack)
{
return new String[] { EnderCore.lang.localize("enchantment.xpboost.tooltip", false) };
}
public void register()
{
if (ConfigHandler.allowXPBoost)
{
FMLInterModComms.sendMessage("EnderIO", "recipe:enchanter",
"<enchantment name=\"enchantment.xpboost\" costPerLevel=\"4\">\n<itemStack oreDictionary=\"ingotGold\" number=\"16\"/>\n</enchantment>");
}
else
{
Enchantment.enchantmentsList[this.effectId] = null;
}
}
}
@@ -0,0 +1,24 @@
package com.enderio.core.common.event;
import net.minecraft.entity.Entity;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.EntityEvent;
import cpw.mods.fml.common.eventhandler.Cancelable;
/**
* Fires each tick that a Projectile or Arrow is updated. <br>
* This event is in EntityArrow.onUpdate().<br>
* <br>
* This event is not {@link Cancelable}.<br>
* <br>
* This event does not have a result. {@link HasResult}<br>
* <br>
* This event is fired on the {@link MinecraftForge#EVENT_BUS}.<br>
**/
public class ArrowUpdateEvent extends EntityEvent
{
public ArrowUpdateEvent(Entity entity)
{
super(entity);
}
}
@@ -0,0 +1,36 @@
package com.enderio.core.common.event;
import lombok.Getter;
import cpw.mods.fml.client.event.ConfigChangedEvent;
/**
* This event is posted to the FML bus when the /reloadConfigs command is run,
* and should be used to reload your config file and parse its contents.
* <p>
* This differs from the existing events because you should call config.load()
* before re-parsing the contents, to reload the file from disk.
* <p>
* This event will be sent once to all mods on load to determine if they are
* valid candidates for receiving the event.
* <p>
* Note that requiresMcRestart is always false, so this might not work 100% of
* the time
* <p>
* <b>If <code>setSuccessful()</code> is not called, the event post will be
* considered a failure!</b>
*/
public class ConfigFileChangedEvent extends ConfigChangedEvent
{
@Getter
private boolean successful;
public ConfigFileChangedEvent(String modID)
{
super(modID, "null", true, false);
}
public void setSuccessful()
{
this.successful = true;
}
}
@@ -0,0 +1,68 @@
package com.enderio.core.common.event;
import lombok.RequiredArgsConstructor;
import net.minecraft.item.EnumRarity;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import cpw.mods.fml.common.eventhandler.Cancelable;
import cpw.mods.fml.common.eventhandler.Event;
/**
* ItemEvent is fired when an event involving any ItemStack occurs.<br>
* If a method utilizes this {@link Event} as its parameter, the method will
* receive every child event of this class.<br>
* <br>
* {@link #item} contains the ItemStack that caused this event to occur.<br>
* <br>
* All children of this event are fired on the {@link MinecraftForge#EVENT_BUS}.<br>
**/
@RequiredArgsConstructor
public class ItemStackEvent extends Event
{
public final ItemStack item;
/**
* ItemEnchantabilityEvent is fired when calculating an Item's
* enchantability. <br>
* <br>
* This event is not {@link Cancelable}.<br>
* <br>
* {@link #enchantability} will be the final value returned for these
* calculations, and is provided with the base enchantability when the event
* is first fired. <br>
* This event is fired on the {@link MinecraftForge#EVENT_BUS}.<br>
**/
public static class ItemEnchantabilityEvent extends ItemStackEvent
{
public int enchantability;
public ItemEnchantabilityEvent(ItemStack itemStack, int baseEnchantability)
{
super(itemStack);
enchantability = baseEnchantability;
}
}
/**
* ItemRarityEvent is fired when calculating an Item's Rarity. (Text color
* for the item name in tooltips) <br>
* This event is fired whenever vanilla Minecraft determines that an entity <br>
* <br>
* This event is not {@link Cancelable}.<br>
* <br>
* {@link #rarity} will be the final value returned for these calculations,
* and is provided with the normal rarity from Item.getRarity() when the
* event is first fired. <br>
* This event is fired on the {@link MinecraftForge#EVENT_BUS}.<br>
**/
public static class ItemRarityEvent extends ItemStackEvent
{
public EnumRarity rarity;
public ItemRarityEvent(ItemStack itemStack, EnumRarity baseRarity)
{
super(itemStack);
rarity = baseRarity;
}
}
}
@@ -0,0 +1,104 @@
package com.enderio.core.common.handlers;
import java.util.Map;
import com.enderio.core.common.Handlers.Handler;
import com.enderio.core.common.Handlers.Handler.HandlerType;
import com.enderio.core.common.config.ConfigHandler;
import com.enderio.core.common.enchant.EnchantAutoSmelt;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.item.EntityXPOrb;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.FurnaceRecipes;
import net.minecraft.util.MathHelper;
import net.minecraftforge.event.world.BlockEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
@Handler(HandlerType.FORGE)
public class AutoSmeltHandler {
@SubscribeEvent
public void handleBlockBreak(BlockEvent.HarvestDropsEvent event)
{
if (!event.world.isRemote && event.harvester != null)
{
ItemStack held = event.harvester.getCurrentEquippedItem();
if (held != null)
{
int level = getAutoSmeltLevel(held);
int fortune = EnchantmentHelper.getEnchantmentLevel(Enchantment.fortune.effectId, held);
if (level >= 0)
{
for (ItemStack stack : event.drops)
{
if (stack != null && !event.isSilkTouching)
{
if (FurnaceRecipes.smelting().getSmeltingResult(stack) != null)
{
ItemStack furnaceStack = FurnaceRecipes.smelting().getSmeltingResult(stack).copy();
//Fortune stuffs
if (fortune > 0 && ConfigHandler.allowAutoSmeltWithFortune)
furnaceStack.stackSize *= (event.world.rand.nextInt(fortune + 1) + 1);
event.drops.remove(stack);
event.drops.add(furnaceStack);
//XP (adapted vanilla code)
int i = furnaceStack.stackSize;
float f = FurnaceRecipes.smelting().func_151398_b(furnaceStack);
int j;
if (f == 0.0F)
{
i = 0;
}
else if (f < 1.0F)
{
j = MathHelper.floor_float((float) i * f);
if (j < MathHelper.ceiling_float_int((float) i * f) && (float) Math.random() < (float) i * f - (float) j)
{
++j;
}
i = j;
}
while (i > 0)
{
j = EntityXPOrb.getXPSplit(i);
i -= j;
event.world.spawnEntityInWorld(new EntityXPOrb(event.world, event.x, event.y + 0.5, event.z, j));
}
}
}
}
}
}
}
}
@SuppressWarnings("unchecked")
private int getAutoSmeltLevel(ItemStack tool)
{
if (tool == null)
{
return -1;
}
Map<Integer, Integer> enchants = EnchantmentHelper.getEnchantments(tool);
for (int i : enchants.keySet())
{
Enchantment enchant = Enchantment.enchantmentsList[i];
if (enchant == EnchantAutoSmelt.INSTANCE)
{
return enchants.get(i);
}
}
return -1;
}
}
@@ -0,0 +1,83 @@
package com.enderio.core.common.handlers;
import java.util.Calendar;
import com.enderio.core.EnderCore;
import com.enderio.core.common.Handlers.Handler;
import com.enderio.core.common.config.ConfigHandler;
import com.enderio.core.common.util.BlockCoord;
import com.enderio.core.common.util.EnderEntityUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.stats.StatisticsFile;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.EnumChatFormatting;
import net.minecraftforge.event.entity.player.AchievementEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent.Phase;
import cpw.mods.fml.common.gameevent.TickEvent.PlayerTickEvent;
import static java.util.Calendar.*;
@Handler
public class FireworkHandler
{
@SubscribeEvent
public void onAchievement(AchievementEvent event)
{
StatisticsFile file = ((EntityPlayerMP) event.entityPlayer).func_147099_x();
if (!event.entity.worldObj.isRemote && file.canUnlockAchievement(event.achievement) && !file.hasAchievementUnlocked(event.achievement)
&& ConfigHandler.betterAchievements)
{
event.entityPlayer.getEntityData().setInteger("fireworksLeft", 9);
event.entityPlayer.getEntityData().setBoolean("fireworkDelay", false);
}
}
@SubscribeEvent
public void onPlayerTick(PlayerTickEvent event)
{
EntityPlayer player = event.player;
if (!player.worldObj.isRemote && event.phase == Phase.END)
{
if (player.worldObj.getTotalWorldTime() % 100 == 0)
{
Calendar cal = Calendar.getInstance();
if (cal.get(DAY_OF_MONTH) == 1 && cal.get(MONTH) == JANUARY && !player.getEntityData().getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG).getBoolean("celebrated"))
{
player.getEntityData().setInteger("fireworksLeft", 15);
player.getEntityData().setBoolean("fireworkDelay", false);
NBTTagCompound tag = player.getEntityData().getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG);
tag.setBoolean("celebrated", true);
player.getEntityData().setTag(EntityPlayer.PERSISTED_NBT_TAG, tag);
player.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + EnderCore.lang.localize("celebrate")));
}
}
int fireworksLeft = player.getEntityData().getInteger("fireworksLeft");
if (fireworksLeft > 0 && (!player.getEntityData().getBoolean("fireworkDelay") || player.worldObj.getTotalWorldTime() % 20 == 0))
{
BlockCoord pos = getBlockCoord(player);
pos.y += 2;
EnderEntityUtils.spawnFirework(pos, player.worldObj.provider.dimensionId, 12);
player.getEntityData().setInteger("fireworksLeft", fireworksLeft - 1);
if (fireworksLeft > 5)
{
player.getEntityData().setBoolean("fireworkDelay", true);
}
else
{
player.getEntityData().setBoolean("fireworkDelay", false);
}
}
}
}
private BlockCoord getBlockCoord(EntityPlayer player)
{
return new BlockCoord((int) Math.floor(player.posX), (int) Math.floor(player.posY), (int) Math.floor(player.posZ));
}
}
@@ -0,0 +1,116 @@
package com.enderio.core.common.handlers;
import java.util.List;
import lombok.NoArgsConstructor;
import net.minecraft.block.Block;
import net.minecraft.item.ItemStack;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent.Action;
import net.minecraftforge.event.world.BlockEvent.HarvestDropsEvent;
import net.minecraftforge.oredict.OreDictionary;
import com.enderio.core.common.Handlers.Handler;
import com.enderio.core.common.Handlers.Handler.HandlerType;
import com.enderio.core.common.config.ConfigHandler;
import com.enderio.core.common.util.EnderItemUtils;
import com.google.common.collect.Lists;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.registry.GameRegistry;
@Handler(HandlerType.FORGE)
public class RightClickCropHandler
{
@NoArgsConstructor
public static class PlantInfo
{
public String seed;
public String block;
public int meta = 7;
public int resetMeta = 0;
private transient ItemStack seedStack;
private transient Block blockInst;
public PlantInfo(String seed, String block, int meta, int resetMeta)
{
this.seed = seed;
this.block = block;
this.meta = meta;
this.resetMeta = resetMeta;
}
public void init()
{
seedStack = EnderItemUtils.parseStringIntoItemStack(seed);
String[] blockinfo = block.split(":");
blockInst = GameRegistry.findBlock(blockinfo[0], blockinfo[1]);
}
}
private List<PlantInfo> plants = Lists.newArrayList();
private PlantInfo currentPlant = null;
public static final RightClickCropHandler INSTANCE = new RightClickCropHandler();
private RightClickCropHandler()
{
}
public void addCrop(PlantInfo info)
{
plants.add(info);
}
@SubscribeEvent
public void handleCropRightClick(PlayerInteractEvent event)
{
int x = event.x, y = event.y, z = event.z;
Block block = event.world.getBlock(x, y, z);
int meta = event.world.getBlockMetadata(x, y, z);
if (ConfigHandler.allowCropRC && event.action == Action.RIGHT_CLICK_BLOCK
&& (event.entityPlayer.getHeldItem() == null || !event.entityPlayer.isSneaking()))
{
for (PlantInfo info : plants)
{
if (info.blockInst == block && meta == info.meta)
{
if (event.world.isRemote)
{
event.entityPlayer.swingItem();
}
else
{
currentPlant = info;
block.dropBlockAsItem(event.world, x, y, z, meta, 0);
currentPlant = null;
event.world.setBlockMetadataWithNotify(x, y, z, info.resetMeta, 3);
event.setCanceled(true);
}
break;
}
}
}
}
@SubscribeEvent
public void onHarvestDrop(HarvestDropsEvent event)
{
if (currentPlant != null)
{
for (int i = 0; i < event.drops.size(); i++)
{
ItemStack stack = event.drops.get(i);
if (stack.getItem() == currentPlant.seedStack.getItem()
&& (currentPlant.seedStack.getItemDamage() == OreDictionary.WILDCARD_VALUE || stack.getItemDamage() == currentPlant.seedStack
.getItemDamage()))
{
event.drops.remove(i);
break;
}
}
}
}
}
@@ -0,0 +1,157 @@
package com.enderio.core.common.handlers;
import java.lang.reflect.Method;
import java.util.Map;
import com.enderio.core.common.Handlers.Handler;
import com.enderio.core.common.Handlers.Handler.HandlerType;
import com.enderio.core.common.enchant.EnchantXPBoost;
import com.enderio.core.common.util.Scheduler;
import lombok.SneakyThrows;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityXPOrb;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import net.minecraftforge.event.entity.living.LivingDeathEvent;
import net.minecraftforge.event.world.BlockEvent.BreakEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.relauncher.ReflectionHelper;
@Handler(HandlerType.FORGE)
public class XPBoostHandler
{
private static final Method getExperiencePoints = ReflectionHelper.findMethod(EntityLivingBase.class, null,
new String[] { "e", "func_70693_a", "getExperiencePoints" }, EntityPlayer.class);
private static final String NBT_KEY = "ttCore:xpboost";
@SubscribeEvent
public void handleEntityKill(LivingDeathEvent event)
{
EntityLivingBase entity = event.entityLiving;
Entity killer = event.source.getSourceOfDamage();
if (!entity.worldObj.isRemote && killer != null)
{
if (killer instanceof EntityPlayer)
{
scheduleXP(entity, getXPBoost(entity, (EntityPlayer) killer));
}
else if (killer instanceof EntityArrow)
{
NBTTagCompound tag = killer.getEntityData();
if (tag.hasKey(NBT_KEY) && tag.getInteger(NBT_KEY) >= 0)
{
int level = tag.getInteger(NBT_KEY);
EntityArrow arrow = (EntityArrow) killer;
scheduleXP(entity, getXPBoost(entity, (EntityPlayer) arrow.shootingEntity, level));
}
}
}
}
@SubscribeEvent
public void handleArrowFire(EntityJoinWorldEvent event)
{
if (event.entity instanceof EntityArrow)
{
EntityArrow arrow = (EntityArrow) event.entity;
if (arrow.shootingEntity != null && arrow.shootingEntity instanceof EntityPlayer)
{
arrow.getEntityData().setInteger(NBT_KEY, getXPBoostLevel(((EntityPlayer)arrow.shootingEntity).getCurrentEquippedItem()));
}
}
}
@SubscribeEvent
public void handleBlockBreak(BreakEvent event)
{
ItemStack held = event.getPlayer().getCurrentEquippedItem();
if (held != null)
{
int level = getXPBoostLevel(held);
int fortune = EnchantmentHelper.getEnchantmentLevel(Enchantment.fortune.effectId, held);
if (level >= 0)
{
int xp = event.block.getExpDrop(event.world, event.blockMetadata, fortune);
if (xp > 0)
{
event.world.spawnEntityInWorld(new EntityXPOrb(event.world, event.x + 0.5, event.y + 0.5, event.z + 0.5, getXPBoost(xp, level)));
}
}
}
}
private int getXPBoost(EntityLivingBase killed, EntityPlayer player)
{
return getXPBoost(killed, player, getXPBoostLevel(player.getCurrentEquippedItem()));
}
@SneakyThrows
private int getXPBoost(EntityLivingBase killed, EntityPlayer player, int level)
{
if (level >= 0)
{
int xp = (Integer) getExperiencePoints.invoke(killed, player);
return getXPBoost(xp, level);
}
return 0;
}
private int getXPBoost(int xp, int level)
{
return Math.round(xp * ((float) Math.log10(level + 1) * 2));
}
@SuppressWarnings("unchecked")
private int getXPBoostLevel(ItemStack weapon)
{
if (weapon == null)
{
return -1;
}
Map<Integer, Integer> enchants = EnchantmentHelper.getEnchantments(weapon);
for (int i : enchants.keySet())
{
Enchantment enchant = Enchantment.enchantmentsList[i];
if (enchant == EnchantXPBoost.INSTANCE)
{
return enchants.get(i);
}
}
return -1;
}
private void scheduleXP(Entity entity, int boost)
{
scheduleXP(entity.worldObj, entity.posX, entity.posY, entity.posZ, boost);
}
private void scheduleXP(final World world, final double x, final double y, final double z, final int boost)
{
if (boost <= 0)
{
return;
}
Scheduler.instance().schedule(20, new Runnable()
{
@Override
public void run()
{
world.spawnEntityInWorld(new EntityXPOrb(world, x, y, z, boost));
}
});
}
}
@@ -0,0 +1,66 @@
package com.enderio.core.common.imc;
import java.util.List;
import com.enderio.core.common.imc.handlers.IMCRightClickCrop;
import com.google.common.collect.Lists;
import cpw.mods.fml.common.event.FMLInterModComms.IMCEvent;
import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage;
public class IMCRegistry
{
public interface IIMC
{
String getKey();
void act(IMCMessage msg);
}
public static abstract class IMCBase implements IIMC
{
private String key;
public IMCBase(String key)
{
this.key = key;
}
@Override
public String getKey()
{
return key;
}
}
public static final IMCRegistry INSTANCE = new IMCRegistry();
private List<IIMC> handlers = Lists.newArrayList();
private IMCRegistry()
{}
public void addIMCHandler(IIMC handler)
{
handlers.add(handler);
}
public void handleEvent(IMCEvent event)
{
for (IIMC handler : handlers)
{
for (IMCMessage msg : event.getMessages())
{
if (msg.key.equals(handler.getKey()))
{
handler.act(msg);
}
}
}
}
public void init()
{
addIMCHandler(new IMCRightClickCrop());
}
}
@@ -0,0 +1,36 @@
package com.enderio.core.common.imc.handlers;
import com.enderio.core.api.common.imc.IMC;
import com.enderio.core.common.handlers.RightClickCropHandler;
import com.enderio.core.common.handlers.RightClickCropHandler.PlantInfo;
import com.enderio.core.common.imc.IMCRegistry.IMCBase;
import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage;
public class IMCRightClickCrop extends IMCBase
{
public IMCRightClickCrop()
{
super(IMC.ADD_RIGHT_CLICK_CROP);
}
@Override
public void act(IMCMessage msg)
{
if (!msg.isStringMessage())
{
return;
}
String[] data = msg.getStringValue().split("\\|");
if (data.length != 3)
{
return;
}
PlantInfo plantinfo = new PlantInfo(data[0], data[1], Integer.parseInt(data[2]), Integer.parseInt(data[3]));
plantinfo.init();
RightClickCropHandler.INSTANCE.addCrop(plantinfo);
}
}
@@ -0,0 +1,17 @@
package com.enderio.core.common.network;
import com.enderio.core.EnderCore;
import com.enderio.core.common.config.PacketConfigSync;
import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import cpw.mods.fml.relauncher.Side;
public class EnderPacketHandler
{
public static final SimpleNetworkWrapper INSTANCE = new SimpleNetworkWrapper(EnderCore.NAME);
static
{
INSTANCE.registerMessage(PacketConfigSync.class, PacketConfigSync.class, 0, Side.CLIENT);
}
}
@@ -0,0 +1,238 @@
package com.enderio.core.common.transform;
import lombok.experimental.UtilityClass;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.ContainerFurnace;
import net.minecraft.inventory.Slot;
import net.minecraft.item.EnumRarity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.FurnaceRecipes;
import net.minecraft.tileentity.TileEntityFurnace;
import net.minecraft.world.WorldType;
import net.minecraftforge.common.MinecraftForge;
import com.enderio.core.common.config.ConfigHandler;
import com.enderio.core.common.event.ArrowUpdateEvent;
import com.enderio.core.common.event.ItemStackEvent.ItemEnchantabilityEvent;
import com.enderio.core.common.event.ItemStackEvent.ItemRarityEvent;
@UtilityClass
public class EnderCoreMethods
{
public boolean hasVoidParticles(WorldType type, boolean hasSky)
{
if (ConfigHandler.disableVoidFog == 0)
{
return type != WorldType.FLAT && !hasSky;
}
else if (ConfigHandler.disableVoidFog == 1)
{
return type != WorldType.FLAT && type != WorldType.DEFAULT && !hasSky;
}
else
{
return false;
}
}
public int getMaxAnvilCost()
{
return ConfigHandler.anvilMaxLevel;
}
public int getItemEnchantability(ItemStack stack, int base)
{
ItemEnchantabilityEvent event = new ItemEnchantabilityEvent(stack, base);
MinecraftForge.EVENT_BUS.post(event);
return event.enchantability;
}
public EnumRarity getItemRarity(ItemStack stack)
{
ItemRarityEvent event = new ItemRarityEvent(stack, stack.getItem().getRarity(stack));
MinecraftForge.EVENT_BUS.post(event);
return event.rarity;
}
public void onArrowUpdate(EntityArrow entity)
{
MinecraftForge.EVENT_BUS.post(new ArrowUpdateEvent(entity));
}
// mostly copied from ContainerFurnace
public ItemStack transferStackInSlot(ContainerFurnace inv, EntityPlayer p_82846_1_, int p_82846_2_)
{
ItemStack itemstack = null;
Slot slot = (Slot) inv.inventorySlots.get(p_82846_2_);
if (slot != null && slot.getHasStack())
{
ItemStack itemstack1 = slot.getStack();
itemstack = itemstack1.copy();
if (p_82846_2_ == 2)
{
if (!mergeItemStack(inv, itemstack1, 3, 39, true))
{
return null;
}
slot.onSlotChange(itemstack1, itemstack);
}
else if (p_82846_2_ != 1 && p_82846_2_ != 0)
{
// I have moved this check to the beginning
if (TileEntityFurnace.isItemFuel(itemstack1))
{
if (!mergeItemStack(inv, itemstack1, 1, 2, false))
{
// Nest this inside so that if the above fails it will
// attempt to do the input slot
if (FurnaceRecipes.smelting().getSmeltingResult(itemstack1) != null)
{
if (!mergeItemStack(inv, itemstack1, 0, 1, false))
{
return null;
}
}
}
}
else if (FurnaceRecipes.smelting().getSmeltingResult(itemstack1) != null)
{
if (!mergeItemStack(inv, itemstack1, 0, 1, false))
{
return null;
}
}
else if (p_82846_2_ >= 3 && p_82846_2_ < 30)
{
if (!mergeItemStack(inv, itemstack1, 30, 39, false))
{
return null;
}
}
else if (p_82846_2_ >= 30 && p_82846_2_ < 39 && !mergeItemStack(inv, itemstack1, 3, 30, false))
{
return null;
}
}
else if (!mergeItemStack(inv, itemstack1, 3, 39, false))
{
return null;
}
if (itemstack1.stackSize == 0)
{
slot.putStack((ItemStack) null);
}
else
{
slot.onSlotChanged();
}
if (itemstack1.stackSize == itemstack.stackSize)
{
return null;
}
slot.onPickupFromSlot(p_82846_1_, itemstack1);
}
return itemstack;
}
// copied from Container
private boolean mergeItemStack(Container inv, ItemStack p_75135_1_, int p_75135_2_, int p_75135_3_, boolean p_75135_4_)
{
boolean flag1 = false;
int k = p_75135_2_;
if (p_75135_4_)
{
k = p_75135_3_ - 1;
}
Slot slot;
ItemStack itemstack1;
if (p_75135_1_.isStackable())
{
while (p_75135_1_.stackSize > 0 && (!p_75135_4_ && k < p_75135_3_ || p_75135_4_ && k >= p_75135_2_))
{
slot = (Slot) inv.inventorySlots.get(k);
itemstack1 = slot.getStack();
if (itemstack1 != null && itemstack1.getItem() == p_75135_1_.getItem()
&& (!p_75135_1_.getHasSubtypes() || p_75135_1_.getItemDamage() == itemstack1.getItemDamage())
&& ItemStack.areItemStackTagsEqual(p_75135_1_, itemstack1))
{
int l = itemstack1.stackSize + p_75135_1_.stackSize;
if (l <= p_75135_1_.getMaxStackSize())
{
p_75135_1_.stackSize = 0;
itemstack1.stackSize = l;
slot.onSlotChanged();
flag1 = true;
}
else if (itemstack1.stackSize < p_75135_1_.getMaxStackSize())
{
p_75135_1_.stackSize -= p_75135_1_.getMaxStackSize() - itemstack1.stackSize;
itemstack1.stackSize = p_75135_1_.getMaxStackSize();
slot.onSlotChanged();
flag1 = true;
}
}
if (p_75135_4_)
{
--k;
}
else
{
++k;
}
}
}
if (p_75135_1_.stackSize > 0)
{
if (p_75135_4_)
{
k = p_75135_3_ - 1;
}
else
{
k = p_75135_2_;
}
while (!p_75135_4_ && k < p_75135_3_ || p_75135_4_ && k >= p_75135_2_)
{
slot = (Slot) inv.inventorySlots.get(k);
itemstack1 = slot.getStack();
if (itemstack1 == null)
{
slot.putStack(p_75135_1_.copy());
slot.onSlotChanged();
p_75135_1_.stackSize = 0;
flag1 = true;
break;
}
if (p_75135_4_)
{
--k;
}
else
{
++k;
}
}
}
return flag1;
}
}
@@ -0,0 +1,47 @@
package com.enderio.core.common.transform;
import java.util.Map;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.MCVersion;
@SuppressWarnings("unused")
@MCVersion("1.7.10")
@IFMLLoadingPlugin.SortingIndex(Integer.MAX_VALUE) // we want deobf no matter what
public class EnderCorePlugin implements IFMLLoadingPlugin
{
public static boolean runtimeDeobfEnabled = false;
@Override
public String[] getASMTransformerClass()
{
return new String[] {
"com.enderio.core.common.transform.TTCoreTransformer",
"com.enderio.core.common.transform.TTCoreTransformerClient"
};
}
@Override
public String getModContainerClass()
{
return null;
}
@Override
public String getSetupClass()
{
return null;
}
@Override
public void injectData(Map<String, Object> data)
{
runtimeDeobfEnabled = (Boolean) data.get("runtimeDeobfuscationEnabled");
}
@Override
public String getAccessTransformerClass()
{
return null;
}
}
@@ -0,0 +1,299 @@
package com.enderio.core.common.transform;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import lombok.AllArgsConstructor;
import net.minecraft.launchwrapper.IClassTransformer;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.IntInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.VarInsnNode;
import com.enderio.core.EnderCore;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.MCVersion;
import static org.objectweb.asm.Opcodes.*;
@MCVersion(value = "1.7.10")
public class EnderCoreTransformer implements IClassTransformer
{
@AllArgsConstructor
protected static class ObfSafeName
{
private String deobf, srg;
public String getName()
{
return EnderCorePlugin.runtimeDeobfEnabled ? srg : deobf;
}
@Override
public boolean equals(Object obj)
{
if (obj instanceof String)
{
return obj.equals(deobf) || obj.equals(srg);
}
else if (obj instanceof ObfSafeName)
{
return ((ObfSafeName) obj).deobf.equals(deobf) && ((ObfSafeName) obj).srg.equals(srg);
}
return false;
}
// no hashcode because I'm naughty
}
protected static abstract class Transform
{
abstract void transform(Iterator<MethodNode> methods);
}
private static final String worldTypeClass = "net.minecraft.world.WorldType";
private static final ObfSafeName voidFogMethod = new ObfSafeName("hasVoidParticles", "func_76564_j");
private static final String voidFogMethodSig = "(Lnet/minecraft/world/WorldType;Z)Z";
private static final String anvilContainerClass = "net.minecraft.inventory.ContainerRepair";
private static final ObfSafeName anvilContainerMethod = new ObfSafeName("updateRepairOutput", "func_82848_d");
private static final String anvilGuiClass = "net.minecraft.client.gui.GuiRepair";
private static final ObfSafeName anvilGuiMethod = new ObfSafeName("drawGuiContainerForegroundLayer", "func_146979_b");
private static final String enchantHelperClass = "net.minecraft.enchantment.EnchantmentHelper";
private static final String enchantHelperMethodSig = "(Lnet/minecraft/item/ItemStack;I)I";
private static final ObfSafeName buildEnchantListMethod = new ObfSafeName("buildEnchantmentList", "func_77513_b");
private static final ObfSafeName calcEnchantabilityMethod = new ObfSafeName("calcItemStackEnchantability", "func_77514_a");
private static final String itemStackClass = "net.minecraft.item.ItemStack";
private static final ObfSafeName itemStackMethod = new ObfSafeName("getRarity", "func_77953_t");
private static final String itemStackMethodSig = "(Lnet/minecraft/item/ItemStack;)Lnet/minecraft/item/EnumRarity;";
private static final String entityArrowClass = "net.minecraft.entity.projectile.EntityArrow";
private static final ObfSafeName entityArrowMethod = new ObfSafeName("onUpdate", "func_70071_h_");
private static final String entityArrowMethodSig = "(Lnet/minecraft/entity/projectile/EntityArrow;)V";
private static final String containerFurnaceClass = "net.minecraft.inventory.ContainerFurnace";
private static final ObfSafeName containerFurnaceMethod = new ObfSafeName("transferStackInSlot", "func_82846_b");
private static final String containerFurnaceMethodSig = "(Lnet/minecraft/inventory/ContainerFurnace;Lnet/minecraft/entity/player/EntityPlayer;I)Lnet/minecraft/item/ItemStack;";
@Override
public byte[] transform(String name, String transformedName, byte[] basicClass)
{
// Void fog removal
if (transformedName.equals(worldTypeClass))
{
basicClass = transform(basicClass, worldTypeClass, voidFogMethod, new Transform()
{
@Override
void transform(Iterator<MethodNode> methods)
{
while (methods.hasNext())
{
MethodNode m = methods.next();
if (voidFogMethod.equals(m.name))
{
m.instructions.clear();
m.instructions.add(new VarInsnNode(ALOAD, 0));
m.instructions.add(new VarInsnNode(ILOAD, 1));
m.instructions.add(new MethodInsnNode(INVOKESTATIC, "com/enderio/core/common/transform/TTCoreMethods", "hasVoidParticles",
voidFogMethodSig, false));
m.instructions.add(new InsnNode(IRETURN));
break;
}
}
}
});
}
// Anvil max level
else if (transformedName.equals(anvilContainerClass) || transformedName.equals(anvilGuiClass))
{
basicClass = transform(basicClass, anvilContainerClass, anvilContainerMethod, new Transform()
{
@Override
void transform(Iterator<MethodNode> methods)
{
while (methods.hasNext())
{
MethodNode m = methods.next();
if (anvilContainerMethod.equals(m.name) || anvilGuiMethod.equals(m.name))
{
for (int i = 0; i < m.instructions.size(); i++)
{
AbstractInsnNode next = m.instructions.get(i);
next = m.instructions.get(i);
if (next instanceof IntInsnNode && ((IntInsnNode) next).operand == 40)
{
m.instructions.set(next, new MethodInsnNode(INVOKESTATIC, "com/enderio/core/common/transform/TTCoreMethods",
"getMaxAnvilCost", "()I", false));
}
}
}
}
}
});
}
// Item Enchantability Event
else if (transformedName.equals(enchantHelperClass))
{
final Map<String, int[]> data = new HashMap<String, int[]>();
data.put(buildEnchantListMethod.getName(), new int[] { 1, 4 });
data.put(calcEnchantabilityMethod.getName(), new int[] { 3, 5 });
Transform transformer = new Transform()
{
@Override
void transform(Iterator<MethodNode> methods)
{
while (methods.hasNext())
{
MethodNode m = methods.next();
if (data.keySet().contains(m.name))
{
int[] indeces = data.get(m.name);
for (int i = 0; i < m.instructions.size(); i++)
{
AbstractInsnNode next = m.instructions.get(i);
if (next instanceof VarInsnNode)
{
VarInsnNode varNode = (VarInsnNode) next;
if (varNode.getOpcode() == ISTORE && varNode.var == indeces[1])
{
InsnList toAdd = new InsnList();
toAdd.add(new VarInsnNode(ALOAD, indeces[0]));
toAdd.add(new VarInsnNode(ILOAD, indeces[1]));
toAdd.add(new MethodInsnNode(INVOKESTATIC, "com/enderio/core/common/transform/TTCoreMethods",
"getItemEnchantability", enchantHelperMethodSig, false));
toAdd.add(new VarInsnNode(ISTORE, indeces[1]));
m.instructions.insert(next, toAdd);
break;
}
}
}
break;
}
}
}
};
basicClass = transform(basicClass, enchantHelperClass, buildEnchantListMethod, transformer);
}
// ItemRarity Event
else if (transformedName.equals(itemStackClass))
{
basicClass = transform(basicClass, itemStackClass, itemStackMethod, new Transform()
{
@Override
void transform(Iterator<MethodNode> methods)
{
while (methods.hasNext())
{
MethodNode m = methods.next();
if (itemStackMethod.equals(m.name))
{
m.instructions.clear();
m.instructions.add(new VarInsnNode(ALOAD, 0));
m.instructions.add(new MethodInsnNode(INVOKESTATIC, "com/enderio/core/common/transform/TTCoreMethods", "getItemRarity",
itemStackMethodSig, false));
m.instructions.add(new InsnNode(ARETURN));
break;
}
}
}
});
}
// ArrowUpdate Event
else if (transformedName.equals(entityArrowClass))
{
basicClass = transform(basicClass, entityArrowClass, entityArrowMethod, new Transform()
{
@Override
void transform(Iterator<MethodNode> methods)
{
while (methods.hasNext())
{
MethodNode m = methods.next();
if (entityArrowMethod.equals(m.name))
{
for (int i = 0; i < m.instructions.size(); i++)
{
AbstractInsnNode next = m.instructions.get(i);
if (next instanceof MethodInsnNode)
{
InsnList toAdd = new InsnList();
toAdd.add(new VarInsnNode(ALOAD, 0));
toAdd.add(new MethodInsnNode(INVOKESTATIC, "com/enderio/core/common/transform/TTCoreMethods", "onArrowUpdate",
entityArrowMethodSig, false));
m.instructions.insert(next, toAdd);
break;
}
}
break;
}
}
}
});
}
// Furnace Shift Click Fix
else if (transformedName.equals(containerFurnaceClass))
{
basicClass = transform(basicClass, containerFurnaceClass, containerFurnaceMethod, new Transform()
{
@Override
void transform(Iterator<MethodNode> methods)
{
while (methods.hasNext())
{
MethodNode m = methods.next();
if (containerFurnaceMethod.equals(m.name))
{
m.instructions.clear();
m.instructions.add(new VarInsnNode(ALOAD, 0));
m.instructions.add(new VarInsnNode(ALOAD, 1));
m.instructions.add(new VarInsnNode(ILOAD, 2));
m.instructions.add(new MethodInsnNode(INVOKESTATIC, "com/enderio/core/common/transform/TTCoreMethods", "transferStackInSlot",
containerFurnaceMethodSig, false));
m.instructions.add(new InsnNode(ARETURN));
break;
}
}
}
});
}
return basicClass;
}
protected final byte[] transform(byte[] classBytes, String className, ObfSafeName methodName, Transform transformer)
{
EnderCore.logger.info("Transforming Class [" + className + "], Method [" + methodName.getName() + "]");
ClassNode classNode = new ClassNode();
ClassReader classReader = new ClassReader(classBytes);
classReader.accept(classNode, 0);
Iterator<MethodNode> methods = classNode.methods.iterator();
transformer.transform(methods);
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
classNode.accept(cw);
EnderCore.logger.info("Transforming " + className + " Finished.");
return cw.toByteArray();
}
}
@@ -0,0 +1,97 @@
package com.enderio.core.common.transform;
import java.util.Iterator;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.VarInsnNode;
import static org.objectweb.asm.Opcodes.*;
public class EnderCoreTransformerClient extends EnderCoreTransformer
{
private static final String scrollingListClass = "cpw.mods.fml.client.GuiScrollingList";
private static final ObfSafeName drawScreen = new ObfSafeName("func_73863_a", "drawScreen");
private static final String slotModListClass = "cpw.mods.fml.client.GuiSlotModList";
private static final ObfSafeName drawBackground = new ObfSafeName("drawBackground", "drawBackground");
@Override
public byte[] transform(String name, String transformedName, byte[] basicClass)
{
if (transformedName.equals(scrollingListClass))
{
basicClass = transform(basicClass, scrollingListClass, drawScreen, new Transform()
{
@Override
void transform(Iterator<MethodNode> methods)
{
while (methods.hasNext())
{
MethodNode m = methods.next();
if (drawScreen.equals(m.name))
{
for (int i = 0; i < m.instructions.size(); i++)
{
AbstractInsnNode n = m.instructions.get(i);
if (n instanceof InsnNode && n.getOpcode() == ICONST_4)
{
AbstractInsnNode next = m.instructions.get(++i);
if (next instanceof VarInsnNode && next.getOpcode() == ISTORE && ((VarInsnNode) next).var == 15)
{
i += 2;
AbstractInsnNode insertPoint = m.instructions.get(i++);
m.instructions.remove(m.instructions.get(i));
m.instructions.remove(m.instructions.get(i));
m.instructions.remove(m.instructions.get(i));
m.instructions.remove(m.instructions.get(i));
m.instructions.insert(insertPoint, new InsnNode(ICONST_1));
}
}
}
break;
}
}
}
});
}
else if (transformedName.equals(slotModListClass))
{
basicClass = transform(basicClass, slotModListClass, drawBackground, new Transform()
{
@SuppressWarnings("deprecation")
@Override
void transform(Iterator<MethodNode> methods)
{
while (methods.hasNext())
{
MethodNode m = methods.next();
if (drawBackground.equals(m.name))
{
m.instructions.clear();
ObfSafeName drawBackground = new ObfSafeName("drawBackground", "func_146278_c");
String fieldOwner = "cpw/mods/fml/client/GuiSlotModList";
String fieldName = "parent";
String fieldType = "Lcpw/mods/fml/client/GuiModList;";
InsnList list = new InsnList();
list.add(new VarInsnNode(ALOAD, 0));
list.add(new FieldInsnNode(GETFIELD, fieldOwner, fieldName, fieldType));
list.add(new InsnNode(ICONST_0));
list.add(new MethodInsnNode(INVOKEVIRTUAL, "cpw/mods/fml/client/GuiModList", drawBackground.getName(), "(I)V"));
list.add(new InsnNode(RETURN));
m.instructions.insert(list);
break;
}
}
}
});
}
return basicClass;
}
}
@@ -0,0 +1,41 @@
package com.enderio.core.common.tweaks;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.ShapelessOreRecipe;
import cpw.mods.fml.common.registry.GameRegistry;
public class SlabRecipes extends Tweak
{
private static final String[] slabEndingsWood = { "WoodOak", "WoodSpruce", "WoodBirch", "WoodJungle", "WoodAcacia", "WoodDarkOak" };
private static final String[] slabEndingsStone = { "Stone", "Sandstone", "Cobblestone", "Bricks", "StoneBricks", "NetherBrick", "Quartz" };
private static final Block[] slabResults = { Blocks.stone, Blocks.sandstone, Blocks.cobblestone, Blocks.brick_block, Blocks.stonebrick, Blocks.nether_brick,
Blocks.quartz_block };
public static final SlabRecipes INSTANCE = new SlabRecipes();
SlabRecipes()
{
super("slabToBlockRecipes", "Adds recipes to turn any two slabs back into a full block");
}
@Override
public void load()
{
registerSlabToBlock();
}
private void registerSlabToBlock()
{
for (int i = 0; i <= 1; i++)
{
String[] arr = i == 0 ? slabEndingsWood : slabEndingsStone;
Block[] results = i == 1 ? slabResults : null;
for (int j = 0; j < arr.length; j++)
{
GameRegistry.addRecipe(new ShapelessOreRecipe(i == 0 ? new ItemStack(Blocks.planks, 1, j) : new ItemStack(results[j]), "slab" + arr[j], "slab" + arr[j]));
}
}
}
}
@@ -0,0 +1,23 @@
package com.enderio.core.common.tweaks;
import com.enderio.core.common.config.ConfigHandler;
import lombok.Getter;
@Getter
public abstract class Tweak
{
private String name, comment;
public Tweak(String key, String comment)
{
this.name = key;
this.comment = comment;
if (ConfigHandler.instance().addBooleanFor(this))
{
load();
}
}
public abstract void load();
}
@@ -0,0 +1,52 @@
package com.enderio.core.common.tweaks;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.registry.GameRegistry;
public class Tweaks
{
/**
* As of yet unused, but might be nice in the future to have a list
*/
private static final List<Tweak> tweaks = new ArrayList<Tweak>();
public static void loadIngameTweaks()
{
// @formatter:off
tweaks.add(new Tweak("fixBedSound", "Makes the bed stepSound wool instead of stone") {
@Override
public void load() { Blocks.bed.setStepSound(Block.soundTypeCloth); }
});
tweaks.add(new Tweak("changeBoatStackSize", "Makes boats stack to 16") {
@Override
public void load() { Items.boat.setMaxStackSize(16); }
});
tweaks.add(new Tweak("fixPackedIceTool", "Allows packed ice to be mined with a pickaxe") {
@Override
public void load() { Blocks.packed_ice.setHarvestLevel("pickaxe", 0); }
});
}
public static void loadNonIngameTweaks()
{
tweaks.add(new SlabRecipes());
tweaks.add(new Tweak("bookToPaperRecipe", "Adds shapeless recipe from 1 book to 2 paper") {
@Override
public void load() { GameRegistry.addShapelessRecipe(new ItemStack(Items.paper, 2), Items.book); }
});
tweaks.add(new Tweak("shapelessPaperRecipe","Adds a shapeless recipe for paper") {
@Override
public void load() { GameRegistry.addShapelessRecipe(new ItemStack(Items.paper, 3), Items.reeds, Items.reeds, Items.reeds); }
});
}
}
@@ -0,0 +1,91 @@
package com.enderio.core.common.util;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.experimental.Wither;
import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
@AllArgsConstructor
@EqualsAndHashCode
public class BlockCoord
{
@Wither
public int x, y, z;
public BlockCoord(Entity e)
{
this(MathHelper.floor_double(e.posX), MathHelper.floor_double(e.posY), MathHelper.floor_double(e.posZ));
}
public BlockCoord(TileEntity te)
{
this(te.xCoord, te.yCoord, te.zCoord);
}
public BlockCoord(BlockCoord other)
{
this(other.x, other.y, other.z);
}
public Block getBlock(World world)
{
return world.getBlock(x, y, z);
}
public int getMetadata(World world)
{
return world.getBlockMetadata(x, y, z);
}
public TileEntity getTileEntity(World world)
{
return world.getTileEntity(x, y, z);
}
public double getDistSq(BlockCoord other)
{
double xDiff = x + 0.5D - other.x;
double yDiff = y + 0.5D - other.y;
double zDiff = z + 0.5D - other.z;
return xDiff * xDiff + yDiff * yDiff + zDiff * zDiff;
}
public double getDistSq(TileEntity other)
{
return other.getDistanceFrom(x + 0.5, y + 0.5, z + 0.5);
}
public void writeToNBT(NBTTagCompound tag)
{
tag.setInteger("blockCoordx", x);
tag.setInteger("blockCoordy", y);
tag.setInteger("blockCoordz", z);
}
public static BlockCoord readFromNBT(NBTTagCompound tag)
{
int x = tag.getInteger("blockCoordx");
int y = tag.getInteger("blockCoordy");
int z = tag.getInteger("blockCoordz");
return new BlockCoord(x, y, z);
}
public void setPosition(double x, double y, double z)
{
this.x = MathHelper.floor_double(x);
this.y = MathHelper.floor_double(y);
this.z = MathHelper.floor_double(z);
}
@Override
public String toString()
{
return "X: " + x + " Y: " + y + " Z: " + z;
}
}
@@ -0,0 +1,29 @@
package com.enderio.core.common.util;
import javax.annotation.concurrent.Immutable;
import lombok.AllArgsConstructor;
import lombok.Value;
import lombok.experimental.Wither;
/**
* An object to represent a bounds limit on a property.
*
* @param <T>
* The type of the bound.
*/
@Immutable
@Value
@AllArgsConstructor(staticName = "of")
public class Bound<T extends Number & Comparable<T>>
{
public static final Bound<Double> MAX_BOUND = Bound.of(Double.MIN_VALUE, Double.MAX_VALUE);
@Wither
public T min, max;
public T clamp(T val)
{
return val.compareTo(min) < 0 ? min : val.compareTo(max) > 0 ? max : val;
}
}
@@ -0,0 +1,56 @@
package com.enderio.core.common.util;
import lombok.NonNull;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
public class CreativeTabsCustom extends CreativeTabs
{
@NonNull
private ItemStack displayStack;
public CreativeTabsCustom(String unloc)
{
super(unloc);
}
/**
* @param item Item to display
*/
public CreativeTabsCustom setDisplay(Item item)
{
return setDisplay(item, 0);
}
/**
* @param item Item to display
* @param damage Damage of item to display
*/
public CreativeTabsCustom setDisplay(Item item, int damage)
{
return setDisplay(new ItemStack(item, 1, damage));
}
/**
* @param display ItemStack to display
*/
public CreativeTabsCustom setDisplay(ItemStack display)
{
this.displayStack = display.copy();
return this;
}
@Override
public ItemStack getIconItemStack()
{
return displayStack == null ? new ItemStack(Items.diamond) : displayStack;
}
@Override
public Item getTabIconItem()
{
return null; // defaults to getIconItemStack()
}
}
@@ -0,0 +1,31 @@
package com.enderio.core.common.util;
import lombok.experimental.UtilityClass;
import org.lwjgl.opengl.GL11;
@UtilityClass
public class EnderColorUtils
{
/**
* Turns an int into a glColor4f function
*
* @author Buildcraft team
*/
public void setGLColorFromInt(int color)
{
float red = (color >> 16 & 255) / 255.0F;
float green = (color >> 8 & 255) / 255.0F;
float blue = (color & 255) / 255.0F;
GL11.glColor4f(red, green, blue, 1.0F);
}
public int toHex(int r, int g, int b)
{
int hex = 0;
hex = hex | ((r) << 16);
hex = hex | ((g) << 8);
hex = hex | ((b));
return hex;
}
}
@@ -0,0 +1,98 @@
package com.enderio.core.common.util;
import java.util.Random;
import lombok.experimental.UtilityClass;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityFireworkRocket;
import net.minecraft.init.Items;
import net.minecraft.item.ItemDye;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.world.World;
import net.minecraftforge.common.DimensionManager;
@UtilityClass
public class EnderEntityUtils
{
private static final Random rand = new Random();
public void setEntityVelocity(Entity entity, double velX, double velY, double velZ)
{
entity.motionX = velX;
entity.motionY = velY;
entity.motionZ = velZ;
}
public EntityFireworkRocket getRandomFirework(World world)
{
return getRandomFirework(world, new BlockCoord(0, 0, 0));
}
public EntityFireworkRocket getRandomFirework(World world, BlockCoord pos)
{
ItemStack firework = new ItemStack(Items.fireworks);
firework.stackTagCompound = new NBTTagCompound();
NBTTagCompound expl = new NBTTagCompound();
expl.setBoolean("Flicker", true);
expl.setBoolean("Trail", true);
int[] colors = new int[rand.nextInt(8) + 1];
for (int i = 0; i < colors.length; i++)
{
colors[i] = ItemDye.field_150922_c[rand.nextInt(16)];
}
expl.setIntArray("Colors", colors);
byte type = (byte) (rand.nextInt(3) + 1);
type = type == 3 ? 4 : type;
expl.setByte("Type", type);
NBTTagList explosions = new NBTTagList();
explosions.appendTag(expl);
NBTTagCompound fireworkTag = new NBTTagCompound();
fireworkTag.setTag("Explosions", explosions);
fireworkTag.setByte("Flight", (byte) 1);
firework.stackTagCompound.setTag("Fireworks", fireworkTag);
EntityFireworkRocket e = new EntityFireworkRocket(world, pos.x + 0.5, pos.y + 0.5, pos.z + 0.5, firework);
return e;
}
public void spawnFirework(BlockCoord block, int dimID)
{
spawnFirework(block, dimID, 0);
}
public void spawnFirework(BlockCoord block, int dimID, int range)
{
World world = DimensionManager.getWorld(dimID);
BlockCoord pos = new BlockCoord(0, 0, 0);
pos.setPosition(block.x, block.y, block.z);
// don't bother if there's no randomness at all
if (range > 0)
{
pos.setPosition(moveRandomly(block.x, range), block.y, moveRandomly(block.z, range));
int tries = -1;
while (!world.isAirBlock(pos.x, pos.y, pos.z) && !world.getBlock(pos.x, pos.y, pos.z).isReplaceable(world, pos.x, pos.y, pos.z))
{
tries++;
if (tries > 100)
{
return;
}
}
}
world.spawnEntityInWorld(getRandomFirework(world, pos));
}
private double moveRandomly(double base, double range)
{
return base + 0.5 + rand.nextDouble() * range - (range / 2);
}
}
@@ -0,0 +1,384 @@
package com.enderio.core.common.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Deque;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import lombok.NonNull;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import net.minecraft.util.StringTranslate;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;
import com.enderio.core.EnderCore;
import com.enderio.core.common.config.ConfigHandler;
@UtilityClass
public class EnderFileUtils
{
public final FileFilter pngFilter = FileFilterUtils.suffixFileFilter(".png");
public final FileFilter langFilter = FileFilterUtils.suffixFileFilter(".lang");
/**
* @param jarClass
* - A class from the jar in question
* @param filename
* - Name of the file to copy, automatically prepended with "/assets/"
* @param to
* - File to copy to
*/
public void copyFromJar(Class<?> jarClass, String filename, File to)
{
EnderCore.logger.info("Copying file " + filename + " from jar");
URL url = jarClass.getResource("/assets/" + filename);
try
{
FileUtils.copyURLToFile(url, to);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
/**
* @author Ilias Tsagklis
* <p>
* From <a href= "http://examples.javacodegeeks.com/core-java/util/zip/extract-zip-file-with-subdirectories/" > this site.</a>
*
* @param zip
* - The zip file to extract
*
* @return The folder extracted to
*/
@NonNull
public File extractZip(File zip)
{
String zipPath = zip.getParent() + "/extracted";
File temp = new File(zipPath);
temp.mkdir();
ZipFile zipFile = null;
try
{
zipFile = new ZipFile(zip);
// get an enumeration of the ZIP file entries
Enumeration<? extends ZipEntry> e = zipFile.entries();
while (e.hasMoreElements())
{
ZipEntry entry = e.nextElement();
File destinationPath = new File(zipPath, entry.getName());
// create parent directories
destinationPath.getParentFile().mkdirs();
// if the entry is a file extract it
if (entry.isDirectory())
{
continue;
}
else
{
EnderCore.logger.info("Extracting file: " + destinationPath);
BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
int b;
byte buffer[] = new byte[1024];
FileOutputStream fos = new FileOutputStream(destinationPath);
BufferedOutputStream bos = new BufferedOutputStream(fos, 1024);
while ((b = bis.read(buffer, 0, 1024)) != -1)
{
bos.write(buffer, 0, b);
}
bos.close();
bis.close();
}
}
}
catch (IOException e)
{
EnderCore.logger.error("Error opening zip file" + e);
}
finally
{
try
{
if (zipFile != null)
{
zipFile.close();
}
}
catch (IOException e)
{
EnderCore.logger.error("Error while closing zip file" + e);
}
}
return temp;
}
/**
* @author McDowell - http://stackoverflow.com/questions/1399126/java-util-zip -recreating-directory-structure
*
* @param directory
* The directory to zip the contents of. Content structure will be preserved.
* @param zipfile
* The zip file to output to.
* @throws IOException
*/
@SuppressWarnings("resource")
public void zipFolderContents(File directory, File zipfile) throws IOException
{
URI base = directory.toURI();
Deque<File> queue = new LinkedList<File>();
queue.push(directory);
OutputStream out = new FileOutputStream(zipfile);
Closeable res = out;
try
{
ZipOutputStream zout = new ZipOutputStream(out);
res = zout;
while (!queue.isEmpty())
{
directory = queue.pop();
for (File child : directory.listFiles())
{
String name = base.relativize(child.toURI()).getPath();
if (child.isDirectory())
{
queue.push(child);
name = name.endsWith("/") ? name : name + "/";
zout.putNextEntry(new ZipEntry(name));
}
else
{
zout.putNextEntry(new ZipEntry(name));
copy(child, zout);
zout.closeEntry();
}
}
}
}
finally
{
res.close();
}
}
/** @see #zipFolderContents(File, File) */
private void copy(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
while (true)
{
int readCount = in.read(buffer);
if (readCount < 0)
{
break;
}
out.write(buffer, 0, readCount);
}
}
/** @see #zipFolderContents(File, File) */
private void copy(File file, OutputStream out) throws IOException
{
InputStream in = new FileInputStream(file);
try
{
copy(in, out);
}
finally
{
in.close();
}
}
@NonNull
public File writeToFile(String filepath, String json)
{
File file = new File(filepath);
try
{
file.createNewFile();
FileWriter fw = new FileWriter(file);
fw.write(json);
fw.flush();
fw.close();
return file;
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
@NonNull
public void safeDelete(File file)
{
try
{
file.delete();
}
catch (Exception e)
{
EnderCore.logger.error("Deleting file " + file.getAbsolutePath() + " failed.");
}
}
@NonNull
public void safeDeleteDirectory(File file)
{
try
{
FileUtils.deleteDirectory(file);
}
catch (Exception e)
{
EnderCore.logger.error("Deleting directory " + file.getAbsolutePath() + " failed.");
}
}
@SneakyThrows
@NonNull
public void loadLangFiles(File directory)
{
for (File file : directory.listFiles(langFilter))
{
StringTranslate.inject(new FileInputStream(file));
}
}
/**
* Same as <code>manuallyChangeConfigValue(String, String, String)</code>, but with an additional parameter for <i>what</i> config file to edit
*
* @param filePathFromConfigFolder
* - the full path to the files, including extensions, from inside config/
* @param prefix
* - The prefix of the config option (anything before '='), must match exactly.
* @param from
* - The setting to change it from
* @param to
* - The setting to change it to
* @return whether anything changed
*/
public boolean manuallyChangeConfigValue(String filePathFromConfigFolder, String prefix, String from, String to)
{
File config = new File(ConfigHandler.configFolder.getAbsolutePath() + "/" + filePathFromConfigFolder);
boolean found = false;
try
{
FileReader fr1 = new FileReader(config);
BufferedReader read = new BufferedReader(fr1);
ArrayList<String> strings = new ArrayList<String>();
while (read.ready())
{
strings.add(read.readLine());
}
fr1.close();
read.close();
FileWriter fw = new FileWriter(config);
BufferedWriter bw = new BufferedWriter(fw);
for (String s : strings)
{
if (!found && s.contains(prefix + "=" + from) && !s.contains("=" + to))
{
s = s.replace(prefix + "=" + from, prefix + "=" + to);
EnderCore.logger.info("Successfully changed config value " + prefix + " from " + from + " to " + to);
found = true;
}
fw.write(s + "\n");
}
bw.flush();
bw.close();
}
catch (Throwable t)
{
t.printStackTrace();
}
return found;
}
/**
* Finds the config value in the file specified (path starting after config/), and for the key specified
*
* @param filePathFromConfigFolder
* - The path to the file, everything up to config/ is calculated for you
* @param key
* - A key to find the value by, does not need to match exactly
* @return A parseable string that can be transformed into any of the types of config values, for instance using
* <code>Boolean.parseBoolean(String)</code>
*/
public String manuallyGetConfigValue(String filePathFromConfigFolder, String key)
{
File config = new File(ConfigHandler.configFolder.getAbsolutePath() + "/" + filePathFromConfigFolder);
Scanner scan = null;
try
{
scan = new Scanner(config);
}
catch (FileNotFoundException e)
{
return "";
}
while (scan.hasNext())
{
String s = scan.next();
if (s.contains(key))
{
scan.close();
return s.substring(s.indexOf("=") + 1, s.length());
}
}
scan.close();
return "";
}
}
@@ -0,0 +1,292 @@
package com.enderio.core.common.util;
import java.util.Random;
import lombok.experimental.UtilityClass;
import net.minecraft.block.Block;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.minecraftforge.oredict.ShapelessOreRecipe;
@UtilityClass
public class EnderItemUtils
{
private final Random rand = new Random();
/**
* Turns a String into an item that can be used in a recipe. This is one of:
* <ul>
* <li>String</li>
* <li>Item</li>
* <li>Block</li>
* <li>ItemStack</li>
* </ul>
* Because this method can return a String, it is highly recommended that you use the result in a {@link ShapedOreRecipe} or
* {@link ShapelessOreRecipe}.
*
* @param string
* The String to parse.
* @return An object for use in recipes.
*/
public Object parseStringIntoRecipeItem(String string)
{
return parseStringIntoRecipeItem(string, false);
}
/**
* Turns a String into an item that can be used in a recipe. This is one of:
* <ul>
* <li>String</li>
* <li>Item</li>
* <li>Block</li>
* <li>ItemStack</li>
* </ul>
* Because this method can return a String, it is highly recommended that you use the result in a {@link ShapedOreRecipe} or
* {@link ShapelessOreRecipe}.
*
* @see #parseStringIntoItemStack(String)
* @param string
* The String to parse.
* @param forceItemStack
* True if the result should be forced to be an ItemStack.
* @return AN object for use in recipes.
*/
public Object parseStringIntoRecipeItem(String string, boolean forceItemStack)
{
if ("null".equals(string))
{
return null;
}
else if (OreDictionary.getOres(string).isEmpty())
{
ItemStack stack = null;
String[] info = string.split(";");
Object temp = null;
int damage = OreDictionary.WILDCARD_VALUE;
temp = Item.itemRegistry.getObject(info[0]);
if (info.length > 1)
{
damage = Integer.parseInt(info[1]);
}
if (temp instanceof Item)
{
stack = new ItemStack((Item) temp, 1, damage);
}
else if (temp instanceof Block)
{
stack = new ItemStack((Block) temp, 1, damage);
}
else if (temp instanceof ItemStack)
{
stack = ((ItemStack) temp).copy();
stack.setItemDamage(damage);
}
else
{
throw new IllegalArgumentException(string
+ " is not a vaild string. Strings should be either an oredict name, or in the format objectname;damage (damage is optional)");
}
return stack;
}
else if (forceItemStack)
{
return OreDictionary.getOres(string).get(0).copy();
}
else
{
return string;
}
}
/**
* Turns a string into an ItemStack.
* <p>
* This is basically a convenience method that casts the result of {@link #parseStringIntoRecipeItem(String, boolean)}, but with one extra
* feature.
* <p>
* A '#' character may be used at the end of the string to signify stack size, e.g. "minecraft:diamond#2" would be a stack of 2 diamonds.
* <p>
* The stack size will automatically be clamped to be below the give Item's max stack size.
*
* @param string
* The String to parse.
* @return An ItemStack the string represents.
*/
public ItemStack parseStringIntoItemStack(String string)
{
int size = 1;
int idx = string.indexOf('#');
if (idx != -1)
{
String num = string.substring(idx + 1);
try
{
size = Integer.parseInt(num);
}
catch (NumberFormatException e)
{
throw new IllegalArgumentException(num + " is not a valid stack size");
}
string = string.substring(0, idx);
}
ItemStack stack = (ItemStack) parseStringIntoRecipeItem(string, true);
stack.stackSize = MathHelper.clamp_int(size, 1, stack.getMaxStackSize());
return stack;
}
/**
* Returns the appropriate config string for the given {@link ItemStack}
* <p>
* This does not take into account ore dict.
*
* @param stack
* The {@link ItemStack} to serialize
* @param damage
* If damage should be taken into account
* @param size
* If stack size should be taken into account
* @return A string that will be the equivalent of if {@link ItemStack stack} was constructed from it using
* {@link #parseStringIntoItemStack(String)}
*/
public String getStringForItemStack(ItemStack stack, boolean damage, boolean size)
{
if (stack == null)
{
return null;
}
String base = Item.itemRegistry.getNameForObject(stack.getItem());
if (damage)
{
base += ";" + stack.getItemDamage();
}
if (size)
{
base += "#" + stack.stackSize;
}
return base;
}
/**
* Tests if two {@link ItemStack}s are completely equal, forgoing stack size. This means that for this method to return true, Item type, damage
* value, and NBT data of both ItemStacks must be identical.
*
* @param s1
* The first ItemStack to compare.
* @param s2
* The second ItemStack to compare.
* @author powercrystals
*/
public boolean stacksEqual(ItemStack s1, ItemStack s2)
{
if (s1 == null && s2 == null)
return true;
if (s1 == null || s2 == null)
return false;
if (!s1.isItemEqual(s2))
return false;
if (s1.getTagCompound() == null && s2.getTagCompound() == null)
return true;
if (s1.getTagCompound() == null || s2.getTagCompound() == null)
return false;
return s1.getTagCompound().equals(s2.getTagCompound());
}
/**
* Spawns an ItemStack into the world with motion that simulates a normal block drop.
*
* @param world
* The world object.
* @param item
* The ItemStack to spawn.
* @param x
* X coordinate of the block in which to spawn the entity.
* @param y
* Y coordinate of the block in which to spawn the entity.
* @param z
* Z coordinate of the block in which to spawn the entity.
*/
public void spawnItemInWorldWithRandomMotion(World world, ItemStack item, int x, int y, int z)
{
if (item != null)
{
spawnItemInWorldWithRandomMotion(new EntityItem(world, x + 0.5, y + 0.5, z + 0.5, item));
}
}
/**
* Spawns an EntityItem into the world with motion that simulates a normal block drop.
*
* @param entity
* The entity to spawn.
*/
public void spawnItemInWorldWithRandomMotion(EntityItem entity)
{
entity.delayBeforeCanPickup = 10;
float f = (rand.nextFloat() * 0.1f) - 0.05f;
float f1 = (rand.nextFloat() * 0.1f) - 0.05f;
float f2 = (rand.nextFloat() * 0.1f) - 0.05f;
entity.motionX += f;
entity.motionY += f1;
entity.motionZ += f2;
entity.worldObj.spawnEntityInWorld(entity);
}
/**
* Returns true if the given stack has the given Ore Dictionary name applied to it.
*
* @param stack
* The ItemStack to check.
* @param oredict
* The oredict name.
* @return True if the ItemStack matches the name passed.
*/
public boolean itemStackMatchesOredict(ItemStack stack, String oredict)
{
int[] ids = OreDictionary.getOreIDs(stack);
for (int i : ids)
{
String name = OreDictionary.getOreName(i);
if (name.equals(oredict))
{
return true;
}
}
return false;
}
/**
* Gets an NBT tag from an ItemStack, creating it if needed. The tag returned will always be the same as the one on the stack.
*
* @param stack
* The ItemStack to get the tag from.
* @return An NBTTagCompound from the stack.
*/
public NBTTagCompound getNBTTag(ItemStack stack)
{
if (!stack.hasTagCompound())
{
stack.stackTagCompound = new NBTTagCompound();
}
return stack.stackTagCompound;
}
}
@@ -0,0 +1,135 @@
package com.enderio.core.common.util;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import org.apache.logging.log4j.Level;
import com.google.common.collect.ObjectArrays;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.LoaderException;
import cpw.mods.fml.common.LoaderState;
import cpw.mods.fml.common.registry.GameData;
/**
* This class provides a few utility methods to regain the ability to register items/blocks to a modid other than the active mod's. This is useful
* when registering items/blocks inside Compat classes (as the active mod at that time is always ttCore).
*/
@UtilityClass
public class EnderRegistryUtils
{
private Method getMain;
private Method registerItem;
private Method registerBlock;
static
{
try
{
getMain = GameData.class.getDeclaredMethod("getMain");
getMain.setAccessible(true);
registerItem = GameData.class.getDeclaredMethod("registerItem", Item.class, String.class, int.class);
registerItem.setAccessible(true);
registerBlock = GameData.class.getDeclaredMethod("registerBlock", Block.class, String.class, int.class);
registerBlock.setAccessible(true);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
/**
* Registers an item with a custom modid prefix. This method exists due to the fact that FML dropped support for registering items to modids other
* than the currently active container.
*
* @param item
* The item to register
* @param modid
* The modid to register the item to
* @param name
* The name of the item
*/
@SneakyThrows
public void registerItem(Item item, String modid, String name)
{
registerItem.invoke(getMain.invoke(null), item, modid + ":" + name, -1);
}
/**
* Registers a block with a custom modid prefix. This method exists due to the fact that FML dropped support for registering blocks to modids
* other than the currently active container.
*
* @param block
* The block to register
* @param modid
* The modid to register the block to
* @param name
* The name of the block
*/
public void registerBlock(Block block, String modid, String name)
{
registerBlock(block, null, modid, name);
}
/**
* Registers a block with a custom modid prefix. This method exists due to the fact that FML dropped support for registering blocks to modids
* other than the currently active container.
*
* @param block
* The block to register
* @param itemclass
* The class of the ItemBlock to associate with this block
* @param modid
* The modid to register the block to
* @param name
* The name of the block
* @param itemCtorArgs
* Objects to pass as arguments to the ItemBlock.
*/
@SneakyThrows
public void registerBlock(Block block, Class<? extends ItemBlock> itemclass, String modid, String name, Object... itemCtorArgs)
{
if (Loader.instance().isInState(LoaderState.CONSTRUCTING))
{
FMLLog.warning(
"The mod %s is attempting to register a block whilst it it being constructed. This is bad modding practice - please use a proper mod lifecycle event.",
Loader.instance().activeModContainer());
}
try
{
assert block != null : "registerBlock: block cannot be null";
ItemBlock i = null;
if (itemclass != null)
{
Class<?>[] ctorArgClasses = new Class<?>[itemCtorArgs.length + 1];
ctorArgClasses[0] = Block.class;
for (int idx = 1; idx < ctorArgClasses.length; idx++)
{
ctorArgClasses[idx] = itemCtorArgs[idx - 1].getClass();
}
Constructor<? extends ItemBlock> itemCtor = itemclass.getConstructor(ctorArgClasses);
i = itemCtor.newInstance(ObjectArrays.concat(block, itemCtorArgs));
}
// block registration has to happen first
registerBlock.invoke(getMain.invoke(null), block, modid + ":" + name, -1);
if (i != null)
{
registerItem(i, modid, name);
}
}
catch (Exception e)
{
FMLLog.log(Level.ERROR, e, "Caught an exception during block registration");
throw new LoaderException(e);
}
}
}
@@ -0,0 +1,131 @@
package com.enderio.core.common.util;
import lombok.experimental.UtilityClass;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.EnumChatFormatting;
import com.enderio.core.EnderCore;
@UtilityClass
public class EnderStringUtils
{
/**
* Formats a string and number for use in GUIs and tooltips
*
* @param prefix
* - The string to put before the formatted number
* @param suffix
* - The string to put after the formatted number
* @param amnt
* - The number to be formatted
* @param useDecimals
* - Whether or not to use decimals in the representation
* @param formatK
* - Whether or not to format the thousands
* @return A string numeric formatted to use SI suffixes
*/
public String formatString(String prefix, String suffix, long amnt, boolean useDecimals, boolean formatK)
{
if (formatK && Long.toString(amnt).length() < 7 && Long.toString(amnt).length() > 3)
{
return formatSmallerNumber(prefix, suffix, amnt, useDecimals);
}
switch (Long.toString(amnt).length())
{
case 7:
prefix += Long.toString(amnt).substring(0, 1) + (useDecimals ? "." + Long.toString(amnt).substring(1, 3) : "") + "M" + suffix;
return prefix;
case 8:
prefix += Long.toString(amnt).substring(0, 2) + (useDecimals ? "." + Long.toString(amnt).substring(2, 4) : "") + "M" + suffix;
return prefix;
case 9:
prefix += Long.toString(amnt).substring(0, 3) + (useDecimals ? "." + Long.toString(amnt).substring(3, 5) : "") + "M" + suffix;
return prefix;
case 10:
prefix += Long.toString(amnt).substring(0, 1) + (useDecimals ? "." + Long.toString(amnt).substring(1, 3) : "") + "B" + suffix;
return prefix;
case 11:
prefix += Long.toString(amnt).substring(0, 2) + (useDecimals ? "." + Long.toString(amnt).substring(2, 4) : "") + "B" + suffix;
return prefix;
case 12:
prefix += Long.toString(amnt).substring(0, 3) + (useDecimals ? "." + Long.toString(amnt).substring(3, 5) : "") + "B" + suffix;
return prefix;
case 13:
prefix += Long.toString(amnt).substring(0, 1) + (useDecimals ? "." + Long.toString(amnt).substring(1, 5) : "") + "T" + suffix;
return prefix;
default:
prefix += "" + amnt + suffix;
return prefix;
}
}
/**
* Formats a string and number for use in GUIs and tooltips
*
* @param prefix
* - The string to put before the formatted number
* @param suffix
* - The string to put after the formatted number
* @param amnt
* - The number to be formatted
* @param useDecimals
* - Whether or not to use decimals in the representation
* @return A string numeric formatted to use SI suffixes
*/
public String formatString(String prefix, String suffix, long amnt, boolean useDecimals)
{
return formatString(prefix, suffix, amnt, useDecimals, false);
}
private String formatSmallerNumber(String prefix, String suffix, long amnt, boolean useDecimals)
{
switch (Long.toString(amnt).length())
{
case 4:
prefix += Long.toString(amnt).substring(0, 1) + (useDecimals ? "." + Long.toString(amnt).substring(1, 3) : "") + "K" + suffix;
return prefix;
case 5:
prefix += Long.toString(amnt).substring(0, 2) + (useDecimals ? "." + Long.toString(amnt).substring(2, 4) : "") + "K" + suffix;
return prefix;
case 6:
prefix += Long.toString(amnt).substring(0, 3) + (useDecimals ? "." + Long.toString(amnt).substring(3, 5) : "") + "K" + suffix;
return prefix;
}
return "";
}
/**
* Returns a color for the number passed, based on its percentage of the max
*
* @param num
* The number to compare
* @param max
* The max number
*
* @return if num <= 10% of max : RED<br>
* if 10% < num <= 25% of max: GOLD (orange-ish)<br>
* if num > 25% of max: GREEN
*/
public EnumChatFormatting getColorFor(double num, double max)
{
if (num / max <= .1)
return EnumChatFormatting.RED;
else if (num / max <= .25)
return EnumChatFormatting.GOLD;
else
return EnumChatFormatting.GREEN;
}
public String getEffectNameWithLevel(PotionEffect effect)
{
String name = EnderCore.lang.localize(effect.getEffectName(), false);
if (effect.getAmplifier() > 0)
{
name += " " + EnderCore.lang.localize("enchantment.level." + (effect.getAmplifier() + 1), false);
}
return name;
}
}
@@ -0,0 +1,27 @@
package com.enderio.core.common.util;
import lombok.AllArgsConstructor;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLStateEvent;
@AllArgsConstructor
public enum RegisterTime
{
PREINIT(FMLPreInitializationEvent.class), INIT(FMLInitializationEvent.class), POSTINIT(FMLPostInitializationEvent.class);
private Class<? extends FMLStateEvent> clazz;
public static RegisterTime timeFor(FMLStateEvent event)
{
for (RegisterTime time : values())
{
if (time.clazz == event.getClass())
{
return time;
}
}
return null;
}
}
@@ -0,0 +1,258 @@
package com.enderio.core.common.util;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import lombok.AllArgsConstructor;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.FileResourcePack;
import net.minecraft.client.resources.IResourcePack;
import org.apache.commons.io.FileUtils;
import com.enderio.core.EnderCore;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.ReflectionHelper;
/**
* A class that can be used to inject resources from files/folders outside your
* mod resources. Useful for loading textures and other assets from the config
* dir or elsewhere.
* <p>
* To use, first construct an instance of this class, then add all your assets
* using {@link #addIcon(File)}, {@link #addLang(File)}, and
* {@link #addCustomFile(String, File)}.
* <p>
* Once all files have been added, {@link #assemble()} Will create a zip of all
* the files in the {@link File directory} passed into the constructor.
* <p>
* Finally, {@link #inject()} will insert this resource pack into the game.
* <p>
* Also, {@link #setHasPackPng(Class)} allows your resource pack to have a logo.
*/
public class ResourcePackAssembler
{
@AllArgsConstructor
private class CustomFile
{
private String ext;
private File file;
}
private List<File> icons = new ArrayList<File>();
private List<File> langs = new ArrayList<File>();
private List<CustomFile> customs = new ArrayList<CustomFile>();
private static List<IResourcePack> defaultResourcePacks;
private static final String MC_META_BASE = "{\"pack\":{\"pack_format\":1,\"description\":\"%s\"}}";
private File dir;
private File zip;
private String name;
private String mcmeta;
private String modid;
private boolean hasPackPng = false;
private Class<?> jarClass;
/**
* @param directory
* The directory to assemble the resource pack in. The name of
* the zip created will be the same as this folder, and it will
* be created on the same level as the folder. This folder will
* be <strong>WIPED</strong> on every call of {@link #assemble()}
* .
* @param packName
* The name of the resource pack.
* @param modid
* Your mod's mod ID.
*/
public ResourcePackAssembler(File directory, String packName, String modid)
{
this.dir = directory;
this.zip = new File(dir.getAbsolutePath() + ".zip");
this.name = packName;
this.modid = modid.toLowerCase();
this.mcmeta = String.format(MC_META_BASE, this.name);
}
/**
* Enables the use of a pack.png.
* <p>
* Will cause your mod's jar to be searched for a resource pack logo at
* assets/[modid]/pack.png.
*
* @param jarClass
* A class in your jar file.
* @return The {@link ResourcePackAssembler} instance.
*/
public ResourcePackAssembler setHasPackPng(Class<?> jarClass)
{
this.jarClass = jarClass;
hasPackPng = true;
return this;
}
/**
* Adds an icon file. This file will be inserted into both the block and
* item texture folders.
*
* @param icon
* The icon file.
*/
public void addIcon(File icon)
{
icons.add(icon);
}
/**
* Adds a language file. This file will be inserted into the lang dir only.
*
* @param lang
* A language file (e.g. en_US.lang)
*/
public void addLang(File lang)
{
langs.add(lang);
}
/**
* Adds a custom file to the pack. This can be added into any folder in the
* pack you desire. Useful for one-off files such as sounds.json.
*
* @param path
* The path inside the resource pack to this file.
* @param file
* The file to add.
*/
public void addCustomFile(String path, File file)
{
customs.add(new CustomFile(path, file));
}
/**
* Adds the custom file at the base directory.
*
* @see #addCustomFile(String, File)
*
* @param file
* The file to add.
*/
public void addCustomFile(File file)
{
addCustomFile(null, file);
}
/**
* Assembles the resource pack. This creates a zip file with the name of the
* {@link File directory} that was passed into the constructor on the same
* level as that folder.
*
* @return The {@link ResourcePackAssembler} instance.
*/
public ResourcePackAssembler assemble()
{
EnderFileUtils.safeDeleteDirectory(dir);
dir.mkdirs();
String pathToDir = dir.getAbsolutePath();
File metaFile = new File(pathToDir + "/pack.mcmeta");
try
{
writeNewFile(metaFile, mcmeta);
if (hasPackPng)
{
EnderFileUtils.copyFromJar(jarClass, modid + "/" + "pack.png", new File(dir.getAbsolutePath() + "/pack.png"));
}
String itemsDir = pathToDir + "/assets/" + modid + "/textures/items";
String blocksDir = pathToDir + "/assets/" + modid + "/textures/blocks";
String langDir = pathToDir + "/assets/" + modid + "/lang";
for (File icon : icons)
{
FileUtils.copyFile(icon, new File(itemsDir + "/" + icon.getName()));
FileUtils.copyFile(icon, new File(blocksDir + "/" + icon.getName()));
}
for (File lang : langs)
{
FileUtils.copyFile(lang, new File(langDir + "/" + lang.getName()));
}
for (CustomFile custom : customs)
{
File directory = new File(pathToDir + (custom.ext != null ? "/" + custom.ext : ""));
directory.mkdirs();
FileUtils.copyFile(custom.file, new File(directory.getAbsolutePath() + "/" + custom.file.getName()));
}
EnderFileUtils.zipFolderContents(dir, zip);
EnderFileUtils.safeDeleteDirectory(dir);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
return this;
}
/**
* Inserts the resource pack into the game. Enabling the resource pack will
* not be required, it will load automatically.
* <p>
* A cache of the pack zip will be kept in "resourcepack/[pack name].zip"
* where "resourcepack" is a folder at the same level as the directory
* passed into the constructor.
*/
public void inject()
{
if (FMLCommonHandler.instance().getEffectiveSide().isClient())
{
try
{
if (defaultResourcePacks == null)
{
defaultResourcePacks = ReflectionHelper.getPrivateValue(Minecraft.class, Minecraft.getMinecraft(), "defaultResourcePacks",
"field_110449_ao", "ap");
}
File dest = new File(dir.getParent() + "/resourcepack/" + zip.getName());
EnderFileUtils.safeDelete(dest);
FileUtils.copyFile(zip, dest);
EnderFileUtils.safeDelete(zip);
writeNewFile(new File(dest.getParent() + "/readme.txt"),
EnderCore.lang.localize("resourcepack.readme") + "\n\n" + EnderCore.lang.localize("resourcepack.readme2"));
defaultResourcePacks.add(new FileResourcePack(dest));
}
catch (Exception e)
{
EnderCore.logger.error("Failed to inject resource pack for mod {}", modid, e);
}
}
else
{
EnderCore.logger.info("Skipping resource pack, we are on a dedicated server.");
}
}
private void writeNewFile(File file, String defaultText) throws IOException
{
EnderFileUtils.safeDelete(file);
file.delete();
file.getParentFile().mkdirs();
file.createNewFile();
FileWriter fw = new FileWriter(file);
fw.write(defaultText);
fw.flush();
fw.close();
}
}
@@ -0,0 +1,137 @@
package com.enderio.core.common.util;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.enderio.core.EnderCore;
import com.enderio.core.common.Handlers.Handler;
import com.enderio.core.common.Handlers.Handler.HandlerType;
import com.enderio.core.common.Handlers.Handler.Inst;
import lombok.AllArgsConstructor;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.common.gameevent.TickEvent.ClientTickEvent;
import cpw.mods.fml.common.gameevent.TickEvent.Phase;
import cpw.mods.fml.common.gameevent.TickEvent.ServerTickEvent;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
/**
* Convenience helper to schedule events to happen in the future.
*/
@Handler(value = HandlerType.FML, getInstFrom = Inst.METHOD)
public class Scheduler
{
@AllArgsConstructor
private static final class Task
{
private int delay;
private Runnable toRun;
private Side side;
private boolean run()
{
if (delay <= 0)
{
toRun.run();
return true;
}
delay--;
return false;
}
}
private final List<Task> tasks = new ArrayList<Task>();
/**
* Schedules a task to be called later
*
* @param delay
* The amount of ticks to delay the call
* @param task
* The {@link Runnable} to be run when the delay is up
*
* @see {@link #schedule(int, Runnable, Side)} for more details.
*/
public void schedule(int delay, Runnable task)
{
schedule(delay, task, Side.SERVER);
}
/**
* Schedules a task to be called later
*
* @param delay
* The amount of ticks to delay the call
* @param task
* The {@link Runnable} to be run when the delay is up
* @param side
* The side to schedule the task on.
* <p>
* You will get a different {@link TickEvent} depending on the
* side. <br>
* {@link Side#CLIENT} will be passed a {@link ClientTickEvent} <br>
* {@link Side#SERVER} will be passed a {@link ServerTickEvent}
* <p>
* Note: passing in {@link Side#CLIENT} on a dedicated server
* will work, but your task will never be called. Please avoid
* doing this to save processing.
*/
public void schedule(int delay, Runnable task, Side side)
{
tasks.add(new Task(delay, task, side));
}
/**
* Returns the {@link Scheduler} instance for the current side.
*
* @see {@link Scheduler#schedule(int, Runnable)} for scheduling
* information.
*
* @return The {@link Scheduler} instance.
*/
public static Scheduler instance()
{
return EnderCore.proxy.getScheduler();
}
/**
* For internal use only. Do not call.
*/
@SubscribeEvent
public void onServerTick(ServerTickEvent event)
{
if (event.phase == Phase.END)
{
runTasks(Side.SERVER);
}
}
/**
* For internal use only. Do not call.
*/
@SideOnly(Side.CLIENT)
@SubscribeEvent
public void onClientTick(ClientTickEvent event)
{
if (event.phase == Phase.END)
{
runTasks(Side.CLIENT);
}
}
private void runTasks(Side side)
{
Iterator<Task> iter = tasks.iterator();
while (iter.hasNext())
{
Task next = iter.next();
if (next.side == side && next.run())
{
iter.remove();
}
}
}
}
@@ -0,0 +1,76 @@
package com.enderio.core.common.util;
import java.io.FileNotFoundException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import net.minecraft.client.renderer.texture.TextureMap;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.core.Logger;
import org.apache.logging.log4j.message.FormattedMessage;
import org.apache.logging.log4j.message.Message;
import com.enderio.core.EnderCore;
import com.enderio.core.common.config.ConfigHandler;
import cpw.mods.fml.relauncher.ReflectionHelper;
public class TextureErrorRemover extends Logger
{
private static TextureErrorRemover INSTANCE;
private int removed = 0;
private TextureErrorRemover(Logger other)
{
super(other.getContext(), other.getName(), other.getMessageFactory());
}
@Override
public void log(Marker marker, String fqcn, Level level, Message data, Throwable t)
{
if (ConfigHandler.textureErrorRemover != 0)
{
if (t instanceof FileNotFoundException)
{
if (ConfigHandler.textureErrorRemover == 1)
{
super.log(marker, fqcn, level, data, null);
}
removed++;
}
else
{
super.log(marker, fqcn, level, data, t);
}
if (data.getFormat().startsWith("Created:"))
{
EnderCore.logger.info(ConfigHandler.textureErrorRemover == 1 ? new FormattedMessage("Removed %d missing texture stacktraces. Tada!",
removed) : new FormattedMessage("There were %d missing texture errors here. They're gone now.", removed));
removed = 0;
}
return;
}
super.log(marker, fqcn, level, data, t);
}
public static void beginIntercepting()
{
EnderCore.logger.info("Attempting to initialize texture error message interceptor.");
try
{
Field f = ReflectionHelper.findField(TextureMap.class, "logger", "field_147635_d", "d");
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(f, f.getModifiers() & ~Modifier.FINAL);
f.setAccessible(true);
INSTANCE = new TextureErrorRemover((Logger) f.get(null));
f.set(null, INSTANCE);
}
catch (Exception e)
{
EnderCore.logger.error("Failed to initialize texture error interceptor!", e);
}
}
}
@@ -0,0 +1,39 @@
package com.enderio.core.common.util;
import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import lombok.SneakyThrows;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.world.WorldEvent;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
public class WorldCache<K, V> extends HashMap<K, V>
{
private static final Gson gson = new GsonBuilder().setPrettyPrinting().create();
private transient File saveFile;
public WorldCache(String ident)
{
super();
saveFile = new File(DimensionManager.getCurrentSaveRootDirectory().getAbsolutePath() + "/" + ident + ".json");
MinecraftForge.EVENT_BUS.register(this);
}
@SubscribeEvent
@SneakyThrows
public void onWorldSave(WorldEvent.Save event)
{
new FileWriter(saveFile).write(gson.toJson(this));
}
private void readData(){}
}
@@ -0,0 +1,27 @@
package com.enderio.core.common.util.blockiterators;
import java.util.Iterator;
import com.enderio.core.common.util.BlockCoord;
public abstract class AbstractBlockIterator implements Iterable<BlockCoord>, Iterator<BlockCoord>
{
protected BlockCoord base;
protected AbstractBlockIterator(BlockCoord base)
{
this.base = base;
}
@Override
public void remove()
{
throw new UnsupportedOperationException("You can't remove blocks silly!");
}
@Override
public Iterator<BlockCoord> iterator()
{
return this;
}
}
@@ -0,0 +1,41 @@
package com.enderio.core.common.util.blockiterators;
import com.enderio.core.common.util.BlockCoord;
public class CubicBlockIterator extends AbstractBlockIterator
{
protected int radius;
protected int minX, minY, minZ;
protected int curX, curY, curZ;
protected int maxX, maxY, maxZ;
public CubicBlockIterator(BlockCoord base, int radius)
{
super(base);
this.radius = radius;
curX = minX = base.x - radius;
curY = minY = base.y - radius;
curZ = minZ = base.z - radius;
maxX = base.x + radius;
maxY = base.y + radius;
maxZ = base.z + radius;
}
@Override
public BlockCoord next()
{
BlockCoord ret = new BlockCoord(curX, curY, curZ);
curX = curX == maxX ? minX : curX + 1;
curY = curX == minX ? curY == maxY ? minY : curY + 1 : curY;
curZ = curY == minY && curX == minX ? curZ + 1 : curZ;
return ret;
}
@Override
public boolean hasNext()
{
return curZ <= maxZ;
}
}
@@ -0,0 +1,65 @@
package com.enderio.core.common.util.blockiterators;
import com.enderio.core.common.util.BlockCoord;
import net.minecraftforge.common.util.ForgeDirection;
public class PlanarBlockIterator extends CubicBlockIterator
{
public static enum Orientation
{
EAST_WEST, NORTH_SOUTH, HORIZONTAL;
public static Orientation perpendicular(ForgeDirection dir)
{
switch (dir)
{
case DOWN:
case UP:
return HORIZONTAL;
case NORTH:
case SOUTH:
return EAST_WEST;
case EAST:
case WEST:
return NORTH_SOUTH;
default:
return null;
}
}
}
private Orientation orientation;
public PlanarBlockIterator(BlockCoord base, Orientation orientation, int radius)
{
super(base, radius);
this.orientation = orientation;
}
@Override
public BlockCoord next()
{
BlockCoord coord = new BlockCoord(curX, curY, curZ);
switch (orientation)
{
case EAST_WEST:
curY = curY == maxY ? minY : curY + 1;
curX = curY == minY ? curX + 1 : curX;
case NORTH_SOUTH:
curY = curY == maxY ? minY : curY + 1;
curZ = curY == minY ? curZ + 1 : curZ;
case HORIZONTAL:
curX = curX == maxX ? minX : curX + 1;
curZ = curX == minX ? curZ + 1 : curZ;
}
return coord;
}
@Override
public boolean hasNext()
{
return curX <= maxX && curY <= maxY && curZ <= maxZ;
}
}