diff --git a/gradle.properties b/gradle.properties index 1be9c1372..4a90b61d8 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,5 +1,5 @@ mcversion=1.12.2 -forgeversion=14.23.1.2582 +forgeversion=14.23.2.2611 mcp_mappings=snapshot_20170918 curse_project_id=59751 diff --git a/lang b/lang index 0bd2017ef..f3a9713e1 160000 --- a/lang +++ b/lang @@ -1 +1 @@ -Subproject commit 0bd2017ef3acc40f0f8ab9bb39a21b237ede3a6b +Subproject commit f3a9713e1f71aea6254401381c025206871f8ae8 diff --git a/src/main/java/forestry/api/book/BookContent.java b/src/main/java/forestry/api/book/BookContent.java new file mode 100644 index 000000000..cf0dd91fb --- /dev/null +++ b/src/main/java/forestry/api/book/BookContent.java @@ -0,0 +1,50 @@ +/******************************************************************************* + * Copyright 2011-2014 SirSengir + * + * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. + ******************************************************************************/ +package forestry.api.book; + +import javax.annotation.Nullable; + +import forestry.api.gui.IElementGroup; +import forestry.api.gui.IGuiElement; +import forestry.api.gui.IGuiElementFactory; + +/** + * The deserialized content data of a book page. It creates a gui element at the moment the entry gets opened. + */ +public abstract class BookContent { + public String type; + + /** + * A data object that was deserialized from the json object of this content. + * Can be everything from an image to a crafting recipe. + */ + @Nullable + public D data = null; + + /** + * The class of the data field. Used for the deserialization. If the result of this method is null the data field + * will be null too. + */ + @Nullable + public abstract Class getDataClass(); + + /** + * Called after the deserialization. + */ + public void onDeserialization() { + } + + /** + * Adds the content to the page by adding a {@link IGuiElement} or at the content to the previous element. + * + * @param page The gui element that represents a book page + * @param previous The content of the previous element. + * @param previousElement The element that was previously added to the page. + * @param pageHeight The max height of the current page. + * @return True if you added an element. + */ + public abstract boolean addElements(IElementGroup page, IGuiElementFactory factory, @Nullable BookContent previous, @Nullable IGuiElement previousElement, int pageHeight); +} diff --git a/src/main/java/forestry/api/core/GuiElementAlignment.java b/src/main/java/forestry/api/book/BookManager.java similarity index 67% rename from src/main/java/forestry/api/core/GuiElementAlignment.java rename to src/main/java/forestry/api/book/BookManager.java index dcc4bcd0f..608fc680d 100644 --- a/src/main/java/forestry/api/core/GuiElementAlignment.java +++ b/src/main/java/forestry/api/book/BookManager.java @@ -3,11 +3,8 @@ * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ -package forestry.api.core; +package forestry.api.book; -/** - * The alignment of the text in a text gui element. - */ -public enum GuiElementAlignment { - LEFT, CENTER, RIGHT +public class BookManager { + public static IBookLoader loader; } diff --git a/src/main/java/forestry/api/book/IBookCategory.java b/src/main/java/forestry/api/book/IBookCategory.java new file mode 100644 index 000000000..2f44cdef8 --- /dev/null +++ b/src/main/java/forestry/api/book/IBookCategory.java @@ -0,0 +1,80 @@ +/******************************************************************************* + * Copyright 2011-2014 SirSengir + * + * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. + ******************************************************************************/ +package forestry.api.book; + +import javax.annotation.Nullable; +import java.util.Collection; + +import net.minecraft.item.ItemStack; + +public interface IBookCategory { + /** + * @return the {@link ItemStack} that represents this category at the front page. + */ + ItemStack getStack(); + + IBookCategory setStack(ItemStack stack); + + /** + * Adds an custom entry to the category. + */ + IBookCategory addEntry(IBookEntry entry); + + /** + * Adds an entry with the given name and the given icon to the category. + * + * @param name A unique name for this entry. + * @param stack The stack that will be displayed next to the entry title at the category page. + */ + IBookCategory addEntry(String name, ItemStack stack); + + /** + * Creates a entry builder with the given name. + *

+ * At the end of your creation you have to call {@link IBookEntryBuilder#addToCategory()} to add the entry to this + * category. + * + * @param name A unique name for this entry. + */ + IBookEntryBuilder createEntry(String name); + + /** + * Creates a entry builder with the given name and the given icon. + *

+ * At the end of your creation you have to call {@link IBookEntryBuilder#addToCategory()} to add the entry to this + * category. + * + * @param name A unique name for this entry. + * @param stack The stack that will be displayed next to the entry title at the category page. + */ + IBookEntryBuilder createEntry(String name, ItemStack stack); + + /** + * @return a collection that contains all entries of this category. + */ + Collection getEntries(); + + /** + * @return the entry with the given unique name. + */ + @Nullable + IBookEntry getEntry(String name); + + /** + * @return the localized name of this category. + */ + String getLocalizedName(); + + /** + * Currently unused + */ + String getTooltip(); + + /** + * @return the unique name of this category + */ + String getName(); +} diff --git a/src/main/java/forestry/api/book/IBookContent.java b/src/main/java/forestry/api/book/IBookContent.java new file mode 100644 index 000000000..449aa74f2 --- /dev/null +++ b/src/main/java/forestry/api/book/IBookContent.java @@ -0,0 +1,26 @@ +package forestry.api.book; + +import javax.annotation.Nullable; + +import forestry.api.gui.IElementGroup; +import forestry.api.gui.IGuiElement; +import forestry.api.gui.IGuiElementFactory; + +public interface IBookContent { + /** + * Called after the deserialization. + */ + default void onDeserialization() { + } + + /** + * Adds the content to the page by adding a {@link IGuiElement} or at the content to the previous element. + * + * @param page The gui element that represents a book page + * @param previous The content of the previous element. + * @param previousElement The element that was previously added to the page. + * @param pageHeight The max height of the current page. + * @return True if you added an element. + */ + boolean addElements(IElementGroup page, IGuiElementFactory factory, @Nullable BookContent previous, @Nullable IGuiElement previousElement, int pageHeight); +} diff --git a/src/main/java/forestry/api/book/IBookEntry.java b/src/main/java/forestry/api/book/IBookEntry.java new file mode 100644 index 000000000..97f8aa382 --- /dev/null +++ b/src/main/java/forestry/api/book/IBookEntry.java @@ -0,0 +1,56 @@ +/******************************************************************************* + * Copyright 2011-2014 SirSengir + * + * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. + ******************************************************************************/ +package forestry.api.book; + +import javax.annotation.Nullable; + +import net.minecraft.item.ItemStack; + +/** + * A entry in the {@link IForesterBook}. + *

+ * Forestry crates them with the help of json file, but you can add you own custom ones with + * {@link IBookCategory#addEntry(IBookEntry)}. + */ +public interface IBookEntry { + + /** + * @return The stack that is displayed before the entry name. + */ + ItemStack getStack(); + + /** + * @return A unique string identifier for this entry. + */ + String getName(); + + /** + * @return the object that creates the book pages at the moment the bock opens. + */ + IBookPageFactory getPageFactory(); + + /** + * All sub entries of this entry are reachable over the buttons on the left side of the book. + */ + IBookEntry[] getSubEntries(); + + /** + * The parent of the entry if this entry is a sub entry. Null if the entry is no sub entry. + */ + @Nullable + IBookEntry getParent(); + + /** + * @return the localized title of this entry. + */ + String getTitle(); + + /** + * @return the content that was deserialized from the json file of this entry. + */ + BookContent[][] getContent(); + +} diff --git a/src/main/java/forestry/api/book/IBookEntryBuilder.java b/src/main/java/forestry/api/book/IBookEntryBuilder.java new file mode 100644 index 000000000..c53a06223 --- /dev/null +++ b/src/main/java/forestry/api/book/IBookEntryBuilder.java @@ -0,0 +1,62 @@ +/******************************************************************************* + * Copyright 2011-2014 SirSengir + * + * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. + ******************************************************************************/ +package forestry.api.book; + +import javax.annotation.Nullable; + +import net.minecraft.item.ItemStack; + +public interface IBookEntryBuilder { + + /** + * Sets the content of the entry. + */ + IBookEntryBuilder setContent(BookContent[][] content); + + /** + * Sets the localized name of entry. + */ + IBookEntryBuilder setTitle(String title); + + IBookEntryBuilder setStack(ItemStack stack); + + IBookEntryBuilder setLoader(IBookPageFactory loader); + + /** + * Creates a sub entry. + *

+ * Important: You not have to call {@link #addToCategory()} at the end of the creation of the sub entry + * + * @param name The unique name of the sub entry. + * @return The entry builder of the sub entry. + */ + default IBookEntryBuilder createSubEntry(String name) { + return createSubEntry(name, ItemStack.EMPTY); + } + + /** + * Creates a sub entry. + *

+ * Important: You not have to call {@link #addToCategory()} at the end of the creation of the sub entry + * + * @param name The unique name of the sub entry. + * @param stack The stack that represents the sub entry. + * @return The entry builder of the sub entry. + */ + IBookEntryBuilder createSubEntry(String name, ItemStack stack); + + IBookEntry build(@Nullable IBookEntry parent); + + /** + * Builds a entry with the current information. + */ + IBookEntry build(); + + /** + * Builds the entry and adds it to the category. + */ + IBookCategory addToCategory(); +} diff --git a/src/main/java/forestry/api/book/IBookLoader.java b/src/main/java/forestry/api/book/IBookLoader.java new file mode 100644 index 000000000..5ab5d13f6 --- /dev/null +++ b/src/main/java/forestry/api/book/IBookLoader.java @@ -0,0 +1,35 @@ +/******************************************************************************* + * Copyright 2011-2014 SirSengir + * + * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. + ******************************************************************************/ +package forestry.api.book; + +public interface IBookLoader { + + /** + * Adds a content type. + * + * @param name The name of the content type. + * @param contentClass The class for the deserialization of the content. + */ + void registerContentType(String name, Class contentClass); + + void registerPageFactory(String name, IBookPageFactory factory); + + IBookPageFactory getPageFactory(String name); + + /** + * Loads the book if it was not loaded already or if it was invalidated. Otherwise it returns the last loaded + * instance. + * + * @return The current instance of the forestry guide book. + */ + IForesterBook loadBook(); + + /** + * Invalidates the current instance of the book. + * The next time {@link #loadBook()} gets called a new instance of the book will be loaded. + */ + void invalidateBook(); +} diff --git a/src/main/java/forestry/api/book/IBookPageFactory.java b/src/main/java/forestry/api/book/IBookPageFactory.java new file mode 100644 index 000000000..bb5114112 --- /dev/null +++ b/src/main/java/forestry/api/book/IBookPageFactory.java @@ -0,0 +1,27 @@ +/******************************************************************************* + * Copyright 2011-2014 SirSengir + * + * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. + ******************************************************************************/ +package forestry.api.book; + +import java.util.Collection; + +import forestry.api.gui.IGuiElement; + +/** + * A factory that creates book pages for a book entry. + */ +public interface IBookPageFactory { + /** + * Usually called at the moment the player opens the given entry. + * Creates a collection of gui elements that represent a page of the book. + * + * @param entry The opened book entry. + * @param leftPageHeight The height of a page on the left side of the book. + * @param rightPageHeight The height of a page on the right side of the book. + * @param pageWidth The width of a book page. + * @return A collection where every member represent a page of the book. + */ + Collection load(IBookEntry entry, int leftPageHeight, int rightPageHeight, int pageWidth); +} diff --git a/src/main/java/forestry/api/book/IForesterBook.java b/src/main/java/forestry/api/book/IForesterBook.java new file mode 100644 index 000000000..cbda26a05 --- /dev/null +++ b/src/main/java/forestry/api/book/IForesterBook.java @@ -0,0 +1,52 @@ +/******************************************************************************* + * Copyright 2011-2014 SirSengir + * + * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. + ******************************************************************************/ +package forestry.api.book; + +import javax.annotation.Nullable; +import java.util.Collection; + +/** + * IForesterBook is the interface that the forestry guide book class implements. + *

+ * You can get the current instance of the guide book from {@link IBookLoader#loadBook()}. + */ +public interface IForesterBook { + + /** + * Creates a category, add it to this book and returns it. + * + * @param name A unique identifier for the category. + * @return The created category. + */ + IBookCategory addCategory(String name); + + /** + * @return The category with the given unique name. + */ + @Nullable + IBookCategory getCategory(String name); + + /** + * @return All categories of this book. + */ + Collection getCategories(); + + /** + * @return A collection that contains all unique names of the categories + */ + Collection getCategoryNames(); + + /** + * @return A collection that contains all entries of the category with the given name. + */ + Collection getEntries(String category); + + /** + * @return the entry with the given unique name. + */ + @Nullable + IBookEntry getEntry(String name); +} diff --git a/src/main/java/forestry/api/book/package-info.java b/src/main/java/forestry/api/book/package-info.java new file mode 100644 index 000000000..88ea9e56a --- /dev/null +++ b/src/main/java/forestry/api/book/package-info.java @@ -0,0 +1,15 @@ +/******************************************************************************* + * Copyright 2011-2014 SirSengir + * + * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. + ******************************************************************************/ +@ParametersAreNonnullByDefault +@MethodsReturnNonnullByDefault +@API(apiVersion = "5.8.1", owner = "ForestryAPI|core", provides = "ForestryAPI|book") +package forestry.api.book; + +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; + +import net.minecraftforge.fml.common.API; \ No newline at end of file diff --git a/src/main/java/forestry/api/core/IGuiElement.java b/src/main/java/forestry/api/core/IGuiElement.java deleted file mode 100644 index 4efc60dd3..000000000 --- a/src/main/java/forestry/api/core/IGuiElement.java +++ /dev/null @@ -1,43 +0,0 @@ -/******************************************************************************* - * Copyright 2011-2014 SirSengir - * - * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. - ******************************************************************************/ -package forestry.api.core; - -import javax.annotation.Nullable; -import java.util.Collections; -import java.util.List; - -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -@SideOnly(Side.CLIENT) -public interface IGuiElement { - int getX(); - - int getY(); - - int getWidth(); - - int getHeight(); - - void setXOffset(int xOffset); - - void setYOffset(int yOffset); - - @Nullable - IGuiElement getParent(); - - void setParent(@Nullable IGuiElement parent); - - void draw(int startX, int startY); - - @SideOnly(Side.CLIENT) - default List getToolTip(int mouseX, int mouseY){ - return Collections.emptyList(); - } - - @SideOnly(Side.CLIENT) - boolean isMouseOver(int mouseX, int mouseY); -} diff --git a/src/main/java/forestry/api/core/IGuiElementHelper.java b/src/main/java/forestry/api/core/IGuiElementHelper.java deleted file mode 100644 index b0773eabe..000000000 --- a/src/main/java/forestry/api/core/IGuiElementHelper.java +++ /dev/null @@ -1,98 +0,0 @@ -/******************************************************************************* - * Copyright 2011-2014 SirSengir - * - * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. - ******************************************************************************/ -package forestry.api.core; - -import java.util.function.Function; - -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -import forestry.api.core.IGuiElementLayoutHelper.LayoutFactory; -import forestry.api.genetics.IAllele; -import forestry.api.genetics.IAlleleInteger; -import forestry.api.genetics.IAlleleSpecies; -import forestry.api.genetics.IAlleleTolerance; -import forestry.api.genetics.IBreedingTracker; -import forestry.api.genetics.IChromosomeType; -import forestry.api.genetics.IIndividual; -import forestry.api.genetics.IMutation; - -/** - * A helper interface to add gui elements. - */ -@SideOnly(Side.CLIENT) -public interface IGuiElementHelper { - /** - * Adds a {@link IGuiElement} to the parent of this. - */ - void add(IGuiElement element); - - /** - * Centers a element to the center of the x axis of the parent element. - * - * @return the element - */ - IGuiElement centerElement(IGuiElement element); - - /** - * Creates and adds an item gui element. - */ - void addItem(int x, ItemStack itemStack); - - IGuiElementLayoutHelper layoutHelper(LayoutFactory layoutFactory, int width, int height); - - /** - * Adds the chromosomeName and the name of the active/not active allele, of the chromosome, with {@link #addText}. - */ - void addAllele(String chromosomeName, IIndividual individual, IChromosomeType chromosome, boolean active); - - /** - * Adds the chromosomeName and the result of toString with {@link #addText}. - */ - void addAllele(String chromosomeName, Function toString, IIndividual individual, IChromosomeType chromosome, boolean active); - - void addFertilityInfo(IAlleleInteger fertilityAllele, int x, int texOffset); - - void addToleranceInfo(IAlleleTolerance toleranceAllele, IAlleleSpecies species, String text); - - void addMutation(int x, int y, int width, int height, IMutation mutation, IAllele species, IBreedingTracker breedingTracker); - - void addMutationResultant(int x, int y, int width, int height, IMutation mutation, IBreedingTracker breedingTracker); - - /** - * Adds a text element with the default color,the align {@link GuiElementAlignment#LEFT} and the height 12. - */ - void addText(String text); - - /** - * Adds a text element with the align {@link GuiElementAlignment#LEFT} and the height 12. - */ - void addText(String text, int color); - - /** - * Adds a text element with the default color and the height 12. - */ - void addText(String text, GuiElementAlignment align); - - /** - * Adds a text element with the height 12. - */ - void addText(String text,GuiElementAlignment align, int color); - - /** - * Adds a text element. - */ - void addText(int x, int height, String text, GuiElementAlignment align, int color); - - /** - * @return The element to which all elements are added. - */ - IGuiElement getParent(); - - IGuiElementFactory factory(); -} diff --git a/src/main/java/forestry/api/core/IGuiElementLayout.java b/src/main/java/forestry/api/core/IGuiElementLayout.java deleted file mode 100644 index fb9557125..000000000 --- a/src/main/java/forestry/api/core/IGuiElementLayout.java +++ /dev/null @@ -1,67 +0,0 @@ -/******************************************************************************* - * Copyright 2011-2014 SirSengir - * - * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. - ******************************************************************************/ -package forestry.api.core; - -import java.util.Collection; -import java.util.List; - -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -@SideOnly(Side.CLIENT) -public interface IGuiElementLayout extends IGuiElement { - /** - * Adds a element to this layout. - */ - IGuiElementLayout addElement(IGuiElement element); - - /** - * Removes a element from this layout. - */ - IGuiElementLayout removeElement(IGuiElement element); - - default IGuiElementLayout addElements(IGuiElement... elements){ - for(IGuiElement element : elements){ - addElement(element); - } - return this; - } - - default IGuiElementLayout removeElements(IGuiElement... elements){ - for(IGuiElement element : elements){ - removeElement(element); - } - return this; - } - - default IGuiElementLayout addElements(Collection elements){ - elements.forEach(element -> addElement(element)); - return this; - } - - default IGuiElementLayout removeElements(Collection elements){ - elements.forEach(element -> removeElement(element)); - return this; - } - - List getElements(); - - IGuiElementLayout setDistance(int distance); - - void addTooltip(String line); - - /** - * @return The tooltip that is displayed if the mouse is over this element and no element of this layout is under it. - */ - List getTooltip(); - - /** - * @return The distance between the different elements of this layout. - */ - int getDistance(); - - int getSize(); -} diff --git a/src/main/java/forestry/api/core/IStateMapperRegister.java b/src/main/java/forestry/api/core/IStateMapperRegister.java index 2ba27074d..a4ffdbac1 100644 --- a/src/main/java/forestry/api/core/IStateMapperRegister.java +++ b/src/main/java/forestry/api/core/IStateMapperRegister.java @@ -8,6 +8,10 @@ package forestry.api.core; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; +/** + * @deprecated TODO Remove in 1.13: Not needed in the api + */ +@Deprecated public interface IStateMapperRegister { @SideOnly(Side.CLIENT) diff --git a/src/main/java/forestry/api/genetics/IAlleleRegistry.java b/src/main/java/forestry/api/genetics/IAlleleRegistry.java index b651ad529..4df96227b 100644 --- a/src/main/java/forestry/api/genetics/IAlleleRegistry.java +++ b/src/main/java/forestry/api/genetics/IAlleleRegistry.java @@ -9,10 +9,12 @@ import javax.annotation.Nullable; import java.util.Collection; import java.util.Map; -import com.mojang.authlib.GameProfile; -import forestry.api.genetics.IClassification.EnumClassLevel; import net.minecraft.item.ItemStack; +import com.mojang.authlib.GameProfile; + +import forestry.api.genetics.IClassification.EnumClassLevel; + /** * Manages {@link ISpeciesRoot}, {@link IAllele}s, {@link IFruitFamily}s, {@link IClassification}, the blacklist and allows creation of research notes. * diff --git a/src/main/java/forestry/api/genetics/IAlyzerPlugin.java b/src/main/java/forestry/api/genetics/IAlyzerPlugin.java index 8a020b462..1c8f6857b 100644 --- a/src/main/java/forestry/api/genetics/IAlyzerPlugin.java +++ b/src/main/java/forestry/api/genetics/IAlyzerPlugin.java @@ -10,9 +10,12 @@ import java.util.Map; import net.minecraft.client.gui.GuiScreen; import net.minecraft.item.ItemStack; + import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; +import forestry.api.gui.IElementGenetic; + public interface IAlyzerPlugin { @SideOnly(Side.CLIENT) @@ -24,7 +27,40 @@ public interface IAlyzerPlugin { @SideOnly(Side.CLIENT) void drawAnalyticsPage3(GuiScreen gui, ItemStack itemStack); + /** + * Creates the first page of the alyzer. + * + * @param gui A instance of the alyzer gui. + * @param container A helper to create the gui elements. + * @param individual The individual that is currently in the alyzer slot. + */ + default void createFirstPage(GuiScreen gui, IElementGenetic container, IIndividual individual){ + } + + /** + * Creates the second page of the alyzer. + * + * @param gui A instance of the alyzer gui. + * @param container A helper to create the gui elements. + * @param individual The individual that is currently in the alyzer slot. + */ + default void createSecondPage(GuiScreen gui, IElementGenetic container, IIndividual individual){ + } + + /** + * Creates the third page of the alyzer. This page is usually used to display the products of the individual. + * + * @param gui A instance of the alyzer gui. + * @param container A helper to create the gui elements. + * @param individual The individual that is currently in the alyzer slot. + */ + default void createThirdPage(GuiScreen gui, IElementGenetic container, IIndividual individual){ + } + Map getIconStacks(); + /** + * The hints that will be shown in the alyzer gui. + */ List getHints(); } diff --git a/src/main/java/forestry/api/genetics/IDatabasePlugin.java b/src/main/java/forestry/api/genetics/IDatabasePlugin.java new file mode 100644 index 000000000..e679650c1 --- /dev/null +++ b/src/main/java/forestry/api/genetics/IDatabasePlugin.java @@ -0,0 +1,35 @@ +/******************************************************************************* + * Copyright 2011-2014 SirSengir + * + * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. + ******************************************************************************/ +package forestry.api.genetics; + +import java.util.List; +import java.util.Map; + +import net.minecraft.item.ItemStack; + +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +/** + * An ISpeciesPlugin provides methods that are used in the alyzer and database to display information about an + * individual. + */ +@SideOnly(Side.CLIENT) +public interface IDatabasePlugin { + + /** + * A map that contains a {@link ItemStack} for every possible {@link IAlleleSpecies}. + * This item stack represents the species in the database and alyzer gui. + * + * The key of the map is the uid of the species. + */ + Map getIndividualStacks(); + + /* ALYZER */ + List getHints(); + + IDatabaseTab[] getTabs(); +} diff --git a/src/main/java/forestry/api/genetics/IDatabaseTab.java b/src/main/java/forestry/api/genetics/IDatabaseTab.java index ad28743cd..0c920c702 100644 --- a/src/main/java/forestry/api/genetics/IDatabaseTab.java +++ b/src/main/java/forestry/api/genetics/IDatabaseTab.java @@ -7,7 +7,7 @@ import net.minecraft.item.ItemStack; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.core.IGuiElementHelper; +import forestry.api.gui.IElementGenetic; /** * A tab of the database screen that shows some information about a {@link IIndividual}. @@ -18,14 +18,11 @@ public interface IDatabaseTab { * Creates the gui elements that are displayed if this tab is selected in the database. * * @param individual The individual that is currently in the database selected. - * @param elementHelper A helper to create the gui elements. + * @param container A helper to create the gui elements. */ - void createElements(IGuiElementHelper elementHelper, I individual, ItemStack itemStack); + void createElements(IElementGenetic container, I individual, ItemStack itemStack); - /** - * @return The slot of this tab. - */ - EnumDatabaseTab getTab(); + ItemStack getIconStack(); /** * Can be used to give the tab a custom tooltip. diff --git a/src/main/java/forestry/api/genetics/IGeneticAnalyzer.java b/src/main/java/forestry/api/genetics/IGeneticAnalyzer.java new file mode 100644 index 000000000..a3a260e85 --- /dev/null +++ b/src/main/java/forestry/api/genetics/IGeneticAnalyzer.java @@ -0,0 +1,43 @@ +package forestry.api.genetics; + +import net.minecraft.client.gui.GuiScreen; + +import forestry.api.gui.IGuiElement; + +public interface IGeneticAnalyzer extends IGuiElement { + IGeneticAnalyzerProvider getProvider(); + + /** + * @return True if the analyzer is currently visible. + */ + boolean isVisible(); + + void setVisible(boolean visible); + + /** + * Called at the end of the constructor of the analyzer provider. + */ + void init(); + + /** + * Updates the displayed content of the analyzer. + */ + void update(); + + /** + * Draws the tooltip of the element that is under the mouse. + */ + void drawTooltip(GuiScreen gui, int mouseX, int mouseY); + + /** + * + * @return + */ + IGuiElement getItemElement(); + + void updateSelected(); + + void setSelectedSlot(int selectedSlot); + + int getSelected(); +} diff --git a/src/main/java/forestry/api/genetics/IGeneticAnalyzerProvider.java b/src/main/java/forestry/api/genetics/IGeneticAnalyzerProvider.java new file mode 100644 index 000000000..342810b82 --- /dev/null +++ b/src/main/java/forestry/api/genetics/IGeneticAnalyzerProvider.java @@ -0,0 +1,18 @@ +package forestry.api.genetics; + +import net.minecraft.item.ItemStack; + +public interface IGeneticAnalyzerProvider { + + ItemStack getSpecimen(int index); + + boolean onUpdateSelected(); + + void onSelection(int index, boolean changed); + + int getSelectedSlot(int index); + + int getSlotCount(); + + int getFirstSlot(); +} diff --git a/src/main/java/forestry/api/genetics/IGeneticPlugin.java b/src/main/java/forestry/api/genetics/IGeneticPlugin.java new file mode 100644 index 000000000..cb1d12bae --- /dev/null +++ b/src/main/java/forestry/api/genetics/IGeneticPlugin.java @@ -0,0 +1,5 @@ +package forestry.api.genetics; + +public class IGeneticPlugin { + +} diff --git a/src/main/java/forestry/api/genetics/ISpeciesDisplayHelper.java b/src/main/java/forestry/api/genetics/ISpeciesDisplayHelper.java new file mode 100644 index 000000000..6d157ffa4 --- /dev/null +++ b/src/main/java/forestry/api/genetics/ISpeciesDisplayHelper.java @@ -0,0 +1,31 @@ +package forestry.api.genetics; + +import java.util.Optional; + +import net.minecraft.item.ItemStack; + +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +@SideOnly(Side.CLIENT) +public interface ISpeciesDisplayHelper { + /** + * Plugin to add information for the genetic database. + */ + Optional getDatabasePlugin(); + + /** + * Plugin to add information for the handheld genetic analyzer. + */ + Optional getAlyzerPlugin(); + + /** + * Retrieves a stack that can and should only be used on the client side in a gui. + * + * @return A empty stack, if the species was not registered before the creation of this handler or if the species is + * not a species of the {@link ISpeciesRoot}. + */ + ItemStack getDisplayStack(IAlleleSpecies species, ISpeciesType type); + + ItemStack getDisplayStack(IAlleleSpecies species); +} diff --git a/src/main/java/forestry/api/genetics/ISpeciesPlugin.java b/src/main/java/forestry/api/genetics/ISpeciesPlugin.java deleted file mode 100644 index 4002ff408..000000000 --- a/src/main/java/forestry/api/genetics/ISpeciesPlugin.java +++ /dev/null @@ -1,107 +0,0 @@ -/******************************************************************************* - * Copyright 2011-2014 SirSengir - * - * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. - ******************************************************************************/ -package forestry.api.genetics; - -import javax.annotation.Nullable; -import java.util.List; -import java.util.Map; - -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -import forestry.api.core.IGuiElementHelper; - -/** - * An ISpeciesPlugin provides methods that are used in the alyzer and database to display information about an - * individual. - */ -@SideOnly(Side.CLIENT) -public interface ISpeciesPlugin { - - /** - * A map that contains a {@link ItemStack} for every possible {@link IAlleleSpecies}. - * This item stack represents the species in the database and alyzer gui. - * - * The key of the map is the uid of the species. - */ - Map getIndividualStacks(); - - - /* ALYZER */ - /** - * Creates the first page of the alyzer. - * - * @param gui A instance of the alyzer gui. - * @param elementHelper A helper to create the gui elements. - * @param individual The individual that is currently in the alyzer slot. - */ - default void createFirstPage(GuiScreen gui, IGuiElementHelper elementHelper, I individual){ - } - - /** - * Creates the second page of the alyzer. - * - * @param gui A instance of the alyzer gui. - * @param elementHelper A helper to create the gui elements. - * @param individual The individual that is currently in the alyzer slot. - */ - default void createSecondPage(GuiScreen gui, IGuiElementHelper elementHelper, I individual){ - } - - /** - * Creates the third page of the alyzer. This page is usually used to display the products of the individual. - * - * @param gui A instance of the alyzer gui. - * @param elementHelper A helper to create the gui elements. - * @param individual The individual that is currently in the alyzer slot. - */ - default void createThirdPage(GuiScreen gui, IGuiElementHelper elementHelper, I individual){ - } - - /** - * The hints that will be shown in the alyzer gui. - */ - List getHints(); - - /* DATABASE */ - /** - * Provides a instance of a {@link IDatabaseTab} that is used to display information about the species of a individual in the - * database. - * - * @param active True if this tab is used to display the active species of the individual. - * - * @return null if this plugin does not support the database. - */ - default IDatabaseTab getSpeciesTab(boolean active){ - return null; - } - - /** - * Can be used to provide a custom products tab for the database. - * If this is Null forestry uses the default mutation tab to display the products. - */ - @Nullable - default IDatabaseTab getProductsTab(){ - return null; - } - - /** - * Can be used to provide a custom mutation tab for the database. - * If this is Null forestry uses the default mutation tab to display the mutations. - */ - @Nullable - default IDatabaseTab getMutationTab(){ - return null; - } - - /** - * A item stack that represents the database tab in the database gui. - */ - ItemStack getTabDatabaseIconItem(EnumDatabaseTab tab); -} diff --git a/src/main/java/forestry/api/genetics/ISpeciesRoot.java b/src/main/java/forestry/api/genetics/ISpeciesRoot.java index ceca13a8f..276f12d3d 100644 --- a/src/main/java/forestry/api/genetics/ISpeciesRoot.java +++ b/src/main/java/forestry/api/genetics/ISpeciesRoot.java @@ -86,8 +86,20 @@ public interface ISpeciesRoot { */ ISpeciesType getIconType(); + default ISpeciesType[] getTypes(){ + return new ISpeciesType[0]; + } + ItemStack getMemberStack(IIndividual individual, ISpeciesType type); + default ItemStack getMemberStack(IAlleleSpecies species, ISpeciesType type){ + return getMemberStack(getTemplate(species), type); + } + + default ItemStack getMemberStack(IAllele[] template, ISpeciesType type){ + return getMemberStack(templateAsIndividual(template), type); + } + /* BREEDING TRACKER */ IBreedingTracker getBreedingTracker(World world, @Nullable GameProfile player); @@ -148,6 +160,15 @@ public interface ISpeciesRoot { List getIndividualTemplates(); + /** + * The type of the species that will be used at the given position of the mutation recipe in the gui. + * + * @param position 0 = first parent, 1 = second parent, 2 = result + */ + default ISpeciesType getTypeForMutation(int position){ + return getIconType(); + } + /* MUTATIONS */ /** @@ -210,18 +231,13 @@ public interface ISpeciesRoot { */ IAlyzerPlugin getAlyzerPlugin(); - /** - * A array with the size of 4. With the database tabs of this {@link IIndividual}. - */ - //IDatabaseTab[] getDatabaseTabs(); - /** * Plugin to add information for the handheld genetic analyzer and the database. * @since 5.7 */ @Nullable @SideOnly(Side.CLIENT) - default ISpeciesPlugin getSpeciesPlugin(){ + default IDatabasePlugin getSpeciesPlugin(){ return null; } } diff --git a/src/main/java/forestry/api/gui/GuiElementAlignment.java b/src/main/java/forestry/api/gui/GuiElementAlignment.java new file mode 100644 index 000000000..4163991fe --- /dev/null +++ b/src/main/java/forestry/api/gui/GuiElementAlignment.java @@ -0,0 +1,37 @@ +/******************************************************************************* + * Copyright 2011-2014 SirSengir + * + * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. + ******************************************************************************/ +package forestry.api.gui; + +/** + * The alignment of a gui element. + */ +public enum GuiElementAlignment { + TOP_LEFT(0.0f, 0.0f), + TOP_CENTER(0.5f, 0.0f), + TOP_RIGHT(1.0f, 0.0f), + MIDDLE_LEFT(0.0f, 0.5f), + MIDDLE_CENTER(0.5f, 0.5f), + MIDDLE_RIGHT(1.0f, 0.5f), + BOTTOM_LEFT(0.0f, 1.0f), + BOTTOM_CENTER(0.5f, 1.0f), + BOTTOM_RIGHT(1.0f, 1.0f); + + private final float xOffset; + private final float yOffset; + + GuiElementAlignment(float xOffset, float yOffset) { + this.xOffset = xOffset; + this.yOffset = yOffset; + } + + public float getXOffset() { + return xOffset; + } + + public float getYOffset() { + return yOffset; + } +} diff --git a/src/main/java/forestry/api/gui/IElementGenetic.java b/src/main/java/forestry/api/gui/IElementGenetic.java new file mode 100644 index 000000000..0da598268 --- /dev/null +++ b/src/main/java/forestry/api/gui/IElementGenetic.java @@ -0,0 +1,37 @@ +package forestry.api.gui; + +import java.util.function.Function; + +import forestry.api.genetics.IAllele; +import forestry.api.genetics.IAlleleInteger; +import forestry.api.genetics.IAlleleSpecies; +import forestry.api.genetics.IAlleleTolerance; +import forestry.api.genetics.IBreedingTracker; +import forestry.api.genetics.IChromosomeType; +import forestry.api.genetics.IIndividual; +import forestry.api.genetics.IMutation; + +public interface IElementGenetic extends IElementGroup { + + /** + * Adds the chromosomeName and the name of the active/not active allele, of the chromosome, with {@link #text}. + */ + void addAlleleRow(String chromosomeName, IIndividual individual, IChromosomeType chromosome, boolean active); + + /** + * Adds the chromosomeName and the result of toString with {@link #text}. + */ + void addAlleleRow(String chromosomeName, Function toString, IIndividual individual, IChromosomeType chromosome, boolean active); + + void addFertilityInfo(String chromosomeName, IAlleleInteger fertilityAllele, int texOffset); + + void addToleranceInfo(String chromosomeName, IAlleleTolerance toleranceAllele, IAlleleSpecies species, String text); + + void addMutation(int x, int y, int width, int height, IMutation mutation, IAllele species, IBreedingTracker breedingTracker); + + void addMutationResultant(int x, int y, int width, int height, IMutation mutation, IBreedingTracker breedingTracker); + + void addRow(String firstText, String secondText, int firstColor, int secondColor); + + void addRow(String leftText, String rightText, boolean dominant); +} diff --git a/src/main/java/forestry/api/gui/IElementGroup.java b/src/main/java/forestry/api/gui/IElementGroup.java new file mode 100644 index 000000000..8e452c9f2 --- /dev/null +++ b/src/main/java/forestry/api/gui/IElementGroup.java @@ -0,0 +1,115 @@ +package forestry.api.gui; + +import javax.annotation.Nullable; +import java.util.Collection; +import java.util.List; + +import net.minecraft.item.ItemStack; + +public interface IElementGroup extends IGuiElement { + /** + * Adds a element to this layout. + */ + E add(E element); + + /** + * Removes a element from this layout. + */ + E remove(E element); + + default IElementGroup add(IGuiElement... elements) { + for (IGuiElement element : elements) { + add(element); + } + return this; + } + + default IElementGroup remove(IGuiElement... elements) { + for (IGuiElement element : elements) { + remove(element); + } + return this; + } + + default IElementGroup add(Collection elements) { + elements.forEach(this::add); + return this; + } + + default IElementGroup remove(Collection elements) { + elements.forEach(this::remove); + return this; + } + + void clear(); + + @Nullable + IGuiElement getLastElement(); + + /** + * @return All elements that this layout contains. + */ + List getElements(); + + IGuiElement item(int xPos, int yPos, ItemStack itemStack); + + default IGuiElement item(ItemStack itemStack) { + return item(0, 0, itemStack); + } + + /** + * Adds a text element with the default color,the align {@link GuiElementAlignment#TOP_LEFT} and the height 12. + */ + IGuiElement text(String text); + + /** + * Adds a text element with the align {@link GuiElementAlignment#TOP_LEFT} and the height 12. + */ + IGuiElement text(String text, int color); + + /** + * Adds a text element with the default color and the height 12. + */ + IGuiElement text(String text, GuiElementAlignment align); + + IGuiElement text(String text, GuiElementAlignment align, int color, boolean unicode); + + /** + * Adds a text element with the height 12. + */ + IGuiElement text(String text, GuiElementAlignment align, int color); + + IGuiElement text(int x, String text, GuiElementAlignment align, int color); + + /** + * Adds a text element. + */ + IGuiElement text(int x, int height, String text, GuiElementAlignment align, int color); + + IGuiElement text(int x, int y, int width, int height, String text); + + /** + * Adds a text element. + */ + IGuiElement text(int x, int height, String text, GuiElementAlignment align, int color, boolean unicode); + + default IElementLayout vertical(int width) { + return vertical(0, 0, width); + } + + IElementLayout vertical(int xPos, int yPos, int width); + + IElementLayout horizontal(int xPos, int yPos, int height); + + default IElementLayout horizontal(int height) { + return horizontal(0, 0, height); + } + + IElementGroup panel(int xPos, int yPos, int width, int height); + + default IElementGroup panel(int width, int height) { + return panel(0, 0, width, height); + } + + IElementLayoutHelper layoutHelper(IElementLayoutHelper.LayoutFactory layoutFactory, int width, int height); +} diff --git a/src/main/java/forestry/api/gui/IElementLayout.java b/src/main/java/forestry/api/gui/IElementLayout.java new file mode 100644 index 000000000..d2768cf34 --- /dev/null +++ b/src/main/java/forestry/api/gui/IElementLayout.java @@ -0,0 +1,25 @@ +/******************************************************************************* + * Copyright 2011-2014 SirSengir + * + * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. + ******************************************************************************/ +package forestry.api.gui; + +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +@SideOnly(Side.CLIENT) +public interface IElementLayout extends IElementGroup { + /** + * @param distance + * @return + */ + IElementLayout setDistance(int distance); + + /** + * @return The distance between the different elements of this layout. + */ + int getDistance(); + + int getSize(); +} diff --git a/src/main/java/forestry/api/core/IGuiElementLayoutHelper.java b/src/main/java/forestry/api/gui/IElementLayoutHelper.java similarity index 73% rename from src/main/java/forestry/api/core/IGuiElementLayoutHelper.java rename to src/main/java/forestry/api/gui/IElementLayoutHelper.java index 76215794e..3d615b41b 100644 --- a/src/main/java/forestry/api/core/IGuiElementLayoutHelper.java +++ b/src/main/java/forestry/api/gui/IElementLayoutHelper.java @@ -3,7 +3,7 @@ * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ -package forestry.api.core; +package forestry.api.gui; import java.util.Collection; @@ -11,7 +11,7 @@ import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) -public interface IGuiElementLayoutHelper { +public interface IElementLayoutHelper { /** * @return Only false if the helper has no space to add this element. */ @@ -23,19 +23,23 @@ public interface IGuiElementLayoutHelper { void clear(); /** - * Adds the layouts to the parent of the {@link IGuiElementHelper}. And calls {@link #clear()} + * Adds the layouts to the parent of the {@link IElementGroup}. And calls {@link #clear()} */ - void finish(); + void finish(boolean centerX); + + default void finish() { + finish(false); + } /** * @return All layouts that were created with the help of this helper since the last {@link #clear()} or {@link #finish()}. */ - Collection layouts(); + Collection layouts(); interface LayoutFactory { /** * A factory method to create new layouts if the last layout is full. */ - IGuiElementLayout createLayout(int xOffset, int yOffset); + IElementLayout createLayout(int xOffset, int yOffset); } } diff --git a/src/main/java/forestry/api/gui/IGuiElement.java b/src/main/java/forestry/api/gui/IGuiElement.java new file mode 100644 index 000000000..dbb76deea --- /dev/null +++ b/src/main/java/forestry/api/gui/IGuiElement.java @@ -0,0 +1,135 @@ +/******************************************************************************* + * Copyright 2011-2014 SirSengir + * + * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. + ******************************************************************************/ +package forestry.api.gui; + +import javax.annotation.Nullable; +import java.util.Collection; +import java.util.List; + +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +@SideOnly(Side.CLIENT) +public interface IGuiElement { + /* Position and Size*/ + /** + * @return the x position of this element relative to the position of the top widget. + */ + int getX(); + + /** + * @return the y position of this element relative to the position of the top widget. + */ + int getY(); + + void setAlign(GuiElementAlignment align); + + GuiElementAlignment getAlign(); + + int getAbsoluteX(); + + int getAbsoluteY(); + + /** + * @return the size of the element on the x-axis. + */ + int getWidth(); + + /** + * @return the size of the element on the y-axis. + */ + int getHeight(); + + void setSize(int width, int height); + + void setLocation(int xPos, int yPos); + + void setBounds(int xPos, int yPos, int width, int height); + + /** + * Sets the x-axis offset to the original x-axis position. + */ + void setXPosition(int xPos); + + /** + * Sets the y-axis offset to the original y-axis position. + */ + void setYPosition(int yPos); + + /* Parent */ + /** + * @return the element that contains this element and handles all events. + */ + @Nullable + IGuiElement getParent(); + + void setParent(@Nullable IGuiElement parent); + + /* Rendering */ + /** + * Draws the element and his children. + * + * @param mouseX The x position of the mouse relative to the parent of the element. + * @param mouseY The y position of the mouse relative to the parent of the element. + */ + void draw(int mouseX, int mouseY); + + /** + * Draws the element itself at the current position. + */ + void drawElement(int mouseX, int mouseY); + + /* Events */ + /** + * @param mouseX The x position of the mouse relative to the parent of the element. + * @param mouseY The y position of the mouse relative to the parent of the element. + * @param mouseButton The pressed mouse button. + */ + void mouseClicked(int mouseX, int mouseY, int mouseButton); + + /** + * @param mouseX The x position of the mouse relative to the parent of the element. + * @param mouseY The y position of the mouse relative to the parent of the element. + * @param mouseButton The pressed mouse button. + */ + void mouseReleased(int mouseX, int mouseY, int mouseButton); + + void mouseClickMove(int mouseX, int mouseY, int mouseButton); + + boolean keyTyped(char typedChar, int keyCode); + + /** + * @param mouseX The x position of the mouse relative to the parent of the element. + * @param mouseY The y position of the mouse relative to the parent of the element. + * @return True if the mouse is currently over the element. + */ + boolean isMouseOver(int mouseX, int mouseY); + + /** + * @return True if the mouse is currently over the element. + */ + boolean isMouseOver(); + + /* Tooltip */ + IGuiElement addTooltip(String line); + + IGuiElement addTooltip(Collection lines); + + void clearTooltip(); + + /** + * Returns the tooltip that this element provides at the given mouse position. + * + * @param mouseX The x position of the mouse relative to the parent of the element. + * @param mouseY The y position of the mouse relative to the parent of the element. + */ + List getTooltip(int mouseX, int mouseY); + + List getTooltip(); + + @Nullable + IGuiState getGuiState(); +} diff --git a/src/main/java/forestry/api/core/IGuiElementFactory.java b/src/main/java/forestry/api/gui/IGuiElementFactory.java similarity index 70% rename from src/main/java/forestry/api/core/IGuiElementFactory.java rename to src/main/java/forestry/api/gui/IGuiElementFactory.java index b57a6eb31..e14b94d58 100644 --- a/src/main/java/forestry/api/core/IGuiElementFactory.java +++ b/src/main/java/forestry/api/gui/IGuiElementFactory.java @@ -3,7 +3,9 @@ * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ -package forestry.api.core; +package forestry.api.gui; + +import javax.annotation.Nullable; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @@ -13,6 +15,8 @@ import forestry.api.genetics.IAlleleInteger; import forestry.api.genetics.IAlleleSpecies; import forestry.api.genetics.IAlleleTolerance; import forestry.api.genetics.IBreedingTracker; +import forestry.api.genetics.IGeneticAnalyzer; +import forestry.api.genetics.IGeneticAnalyzerProvider; import forestry.api.genetics.IMutation; /** @@ -21,12 +25,12 @@ import forestry.api.genetics.IMutation; @SideOnly(Side.CLIENT) public interface IGuiElementFactory { - IGuiElementHelper createHelper(IGuiElementLayout element); + IGeneticAnalyzer createAnalyzer(int xPos, int yPos, boolean rightBoarder, IGeneticAnalyzerProvider provider); /* GENETIC*/ + /** - * @param dominant True if you want the dominant color and false if you want the recessive color. - * + * @param dominant True if you want the dominant color and false if you want the recessive color. * @return The color code that forestry uses to show if a allele is dominant (true) or recessive (false). */ int getColorCoding(boolean dominant); @@ -34,21 +38,25 @@ public interface IGuiElementFactory { /** * @return Null if the mutation is secret and undiscovered. {@link IMutation#isSecret()} */ + @Nullable IGuiElement createMutation(int x, int y, int width, int height, IMutation mutation, IAllele species, IBreedingTracker breedingTracker); /** * @return Null if the mutation is secret and undiscovered. {@link IMutation#isSecret()} */ + @Nullable IGuiElement createMutationResultant(int x, int y, int width, int height, IMutation mutation, IBreedingTracker breedingTracker); - IGuiElement createFertilityInfo(IAlleleInteger fertilityAllele, int x, int texOffset); + IGuiElement createFertilityInfo(IAlleleInteger fertilityAllele, int texOffset); IGuiElement createToleranceInfo(IAlleleTolerance toleranceAllele, IAlleleSpecies species, String text); + IGuiElement createToleranceInfo(IAlleleTolerance toleranceAllele); + /* LAYOUTS */ - IGuiElementLayout createHorizontal(int xPos, int yPos, int height); + IElementLayout createHorizontal(int xPos, int yPos, int height); - IGuiElementLayout createVertical(int xPos, int yPos, int width); + IElementLayout createVertical(int xPos, int yPos, int width); - IGuiElementLayout createPanel(int xPos, int yPos, int width, int height); + IElementGroup createPanel(int xPos, int yPos, int width, int height); } diff --git a/src/main/java/forestry/api/gui/IGuiState.java b/src/main/java/forestry/api/gui/IGuiState.java new file mode 100644 index 000000000..242bee5ca --- /dev/null +++ b/src/main/java/forestry/api/gui/IGuiState.java @@ -0,0 +1,59 @@ +package forestry.api.gui; + +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.renderer.texture.TextureManager; + +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +@SideOnly(Side.CLIENT) +public interface IGuiState { + + /** + * Returns the mouse position. + */ + int getMouseX(); + + /** + * Returns the mouse position. + */ + int getMouseY(); + + /** + * Returns the mouse position relative to the given element. + */ + int getRelativeMouseX(IGuiElement element); + + /** + * Returns the mouse position relative to the given element. + */ + int getRelativeMouseY(IGuiElement element); + + /** + * Returns the current screen width. + */ + int getScreenWidth(); + + /** + * Returns the current screen height. + */ + int getScreenHeight(); + + /** + * Returns the current gui height. + */ + int getGuiHeight(); + + /** + * Returns the current gui width. + */ + int getGuiWidth(); + + int getGuiLeft(); + + int getGuiTop(); + + TextureManager getTextureManager(); + + FontRenderer getFontRenderer(); +} diff --git a/src/main/java/forestry/api/gui/package-info.java b/src/main/java/forestry/api/gui/package-info.java new file mode 100644 index 000000000..debf3fecd --- /dev/null +++ b/src/main/java/forestry/api/gui/package-info.java @@ -0,0 +1,15 @@ +/******************************************************************************* + * Copyright 2011-2014 SirSengir + * + * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. + ******************************************************************************/ +@ParametersAreNonnullByDefault +@MethodsReturnNonnullByDefault +@API(apiVersion = "5.8.0", owner = "ForestryAPI|core", provides = "ForestryAPI|gui") +package forestry.api.gui; + +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; + +import net.minecraftforge.fml.common.API; diff --git a/src/main/java/forestry/apiculture/ApiaristAI.java b/src/main/java/forestry/apiculture/ApiaristAI.java index 8828684c0..8b80370ef 100644 --- a/src/main/java/forestry/apiculture/ApiaristAI.java +++ b/src/main/java/forestry/apiculture/ApiaristAI.java @@ -11,13 +11,6 @@ package forestry.apiculture; -import forestry.api.apiculture.EnumBeeType; -import forestry.apiculture.blocks.BlockApiculture; -import forestry.apiculture.items.ItemBeeGE; -import forestry.apiculture.tiles.TileBeeHouse; -import forestry.core.tiles.TileUtil; -import forestry.core.utils.InventoryUtil; - import net.minecraft.block.Block; import net.minecraft.entity.ai.EntityAIMoveToBlock; import net.minecraft.entity.passive.EntityVillager; @@ -26,6 +19,13 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; +import forestry.api.apiculture.EnumBeeType; +import forestry.apiculture.blocks.BlockApiculture; +import forestry.apiculture.items.ItemBeeGE; +import forestry.apiculture.tiles.TileBeeHouse; +import forestry.core.tiles.TileUtil; +import forestry.core.utils.InventoryUtil; + public class ApiaristAI extends EntityAIMoveToBlock { private final EntityVillager villager; private boolean hasDrone; diff --git a/src/main/java/forestry/apiculture/ModuleApiculture.java b/src/main/java/forestry/apiculture/ModuleApiculture.java index 6ffb1d4c0..45340bb9f 100644 --- a/src/main/java/forestry/apiculture/ModuleApiculture.java +++ b/src/main/java/forestry/apiculture/ModuleApiculture.java @@ -135,7 +135,7 @@ import forestry.food.ModuleFood; import forestry.food.items.ItemRegistryFood; import forestry.modules.BlankForestryModule; import forestry.modules.ForestryModuleUids; -import forestry.modules.ModuleManager; +import forestry.modules.ModuleHelper; @ForestryModule(containerID = Constants.MOD_ID, moduleID = ForestryModuleUids.APICULTURE, name = "Apiculture", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.module.apiculture.description", lootTable = "apiculture") public class ModuleApiculture extends BlankForestryModule { @@ -237,7 +237,7 @@ public class ModuleApiculture extends BlankForestryModule { // Commands ModuleCore.rootCommand.addChildCommand(new CommandBee()); - if (ModuleManager.getInstance().isModuleEnabled(Constants.MOD_ID, ForestryModuleUids.SORTING)) { + if(ModuleHelper.isEnabled(ForestryModuleUids.SORTING)){ ApicultureFilterRuleType.init(); ApicultureFilterRule.init(); } @@ -550,7 +550,7 @@ public class ModuleApiculture extends BlankForestryModule { } // FOOD STUFF - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FOOD))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.FOOD)) { ItemRegistryFood foodItems = ModuleFood.getItems(); RecipeUtil.addRecipe("honeyed_slice", new ItemStack(foodItems.honeyedSlice, 4), "###", "#X#", "###", @@ -607,7 +607,7 @@ public class ModuleApiculture extends BlankForestryModule { '#', coreItems.beeswax); // / ALVEARY - ItemStack alvearyPlainBlock = blocks.getAlvearyBlock(BlockAlvearyType.PLAIN); + ItemStack alvearyPlainBlock = blocks.getAlvearyBlockStack(BlockAlvearyType.PLAIN); RecipeUtil.addRecipe("alveary_plain", alvearyPlainBlock, "###", "#X#", @@ -615,7 +615,7 @@ public class ModuleApiculture extends BlankForestryModule { 'X', coreItems.impregnatedCasing, '#', coreItems.craftingMaterial.getScentedPaneling()); // SWARMER - RecipeUtil.addRecipe("alveary_swarmer", blocks.getAlvearyBlock(BlockAlvearyType.SWARMER), + RecipeUtil.addRecipe("alveary_swarmer", blocks.getAlvearyBlockStack(BlockAlvearyType.SWARMER), "#G#", " X ", "#G#", @@ -623,7 +623,7 @@ public class ModuleApiculture extends BlankForestryModule { 'X', alvearyPlainBlock, 'G', OreDictUtil.INGOT_GOLD); // FAN - RecipeUtil.addRecipe("alveary_fan", blocks.getAlvearyBlock(BlockAlvearyType.FAN), + RecipeUtil.addRecipe("alveary_fan", blocks.getAlvearyBlockStack(BlockAlvearyType.FAN), "I I", " X ", "I#I", @@ -631,7 +631,7 @@ public class ModuleApiculture extends BlankForestryModule { 'X', alvearyPlainBlock, 'I', OreDictUtil.INGOT_IRON); // HEATER - RecipeUtil.addRecipe("alveary_heater", blocks.getAlvearyBlock(BlockAlvearyType.HEATER), + RecipeUtil.addRecipe("alveary_heater", blocks.getAlvearyBlockStack(BlockAlvearyType.HEATER), "#I#", " X ", "YYY", @@ -639,7 +639,7 @@ public class ModuleApiculture extends BlankForestryModule { 'X', alvearyPlainBlock, 'I', OreDictUtil.INGOT_IRON, 'Y', OreDictUtil.STONE); // HYGROREGULATOR - RecipeUtil.addRecipe("alveary_hygro", blocks.getAlvearyBlock(BlockAlvearyType.HYGRO), + RecipeUtil.addRecipe("alveary_hygro", blocks.getAlvearyBlockStack(BlockAlvearyType.HYGRO), "GIG", "GXG", "GIG", @@ -647,14 +647,14 @@ public class ModuleApiculture extends BlankForestryModule { 'I', OreDictUtil.INGOT_IRON, 'G', OreDictUtil.BLOCK_GLASS); // STABILISER - RecipeUtil.addRecipe("alveary_stabiliser", blocks.getAlvearyBlock(BlockAlvearyType.STABILISER), + RecipeUtil.addRecipe("alveary_stabiliser", blocks.getAlvearyBlockStack(BlockAlvearyType.STABILISER), "G G", "GXG", "G G", 'X', alvearyPlainBlock, 'G', OreDictUtil.GEM_QUARTZ); // SIEVE - RecipeUtil.addRecipe("alveary_sieve", blocks.getAlvearyBlock(BlockAlvearyType.SIEVE), + RecipeUtil.addRecipe("alveary_sieve", blocks.getAlvearyBlockStack(BlockAlvearyType.SIEVE), "III", " X ", "WWW", @@ -662,7 +662,7 @@ public class ModuleApiculture extends BlankForestryModule { 'I', OreDictUtil.INGOT_IRON, 'W', coreItems.craftingMaterial.getWovenSilk()); - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FACTORY))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.FACTORY)) { // / SQUEEZER FluidStack honeyDropFluid = Fluids.FOR_HONEY.getFluid(Constants.FLUID_PER_HONEY_DROP); RecipeManagers.squeezerManager.addRecipe(10, items.honeyDrop.getItemStack(), honeyDropFluid, items.propolis.getItemStack(), 5); diff --git a/src/main/java/forestry/apiculture/blocks/BlockRegistryApiculture.java b/src/main/java/forestry/apiculture/blocks/BlockRegistryApiculture.java index c7d605440..8b69086b8 100644 --- a/src/main/java/forestry/apiculture/blocks/BlockRegistryApiculture.java +++ b/src/main/java/forestry/apiculture/blocks/BlockRegistryApiculture.java @@ -12,14 +12,15 @@ package forestry.apiculture.blocks; import java.util.Map; +import net.minecraft.block.material.Material; +import net.minecraft.item.ItemStack; + import forestry.api.core.Tabs; import forestry.apiculture.items.ItemBlockCandle; import forestry.apiculture.items.ItemBlockHoneyComb; import forestry.core.blocks.BlockBase; import forestry.core.blocks.BlockRegistry; import forestry.core.items.ItemBlockForestry; -import net.minecraft.block.material.Material; -import net.minecraft.item.ItemStack; public class BlockRegistryApiculture extends BlockRegistry { public final BlockApiculture apiary; @@ -63,7 +64,12 @@ public class BlockRegistryApiculture extends BlockRegistry { } } - public ItemStack getAlvearyBlock(BlockAlvearyType type) { + public BlockAlveary getAlvearyBlock(BlockAlvearyType type) { + BlockAlveary alvearyBlock = alvearyBlockMap.get(type); + return alvearyBlock; + } + + public ItemStack getAlvearyBlockStack(BlockAlvearyType type) { BlockAlveary alvearyBlock = alvearyBlockMap.get(type); return new ItemStack(alvearyBlock); } diff --git a/src/main/java/forestry/apiculture/genetics/BeeDatabaseTab.java b/src/main/java/forestry/apiculture/genetics/BeeDatabaseTab.java index 0bffda328..09c023b7e 100644 --- a/src/main/java/forestry/apiculture/genetics/BeeDatabaseTab.java +++ b/src/main/java/forestry/apiculture/genetics/BeeDatabaseTab.java @@ -1,7 +1,6 @@ package forestry.apiculture.genetics; import net.minecraft.item.ItemStack; -import net.minecraft.util.text.TextFormatting; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @@ -10,14 +9,13 @@ import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeChromosome; import forestry.api.apiculture.EnumBeeType; import forestry.api.apiculture.IBee; -import forestry.api.core.GuiElementAlignment; -import forestry.api.core.IGuiElementHelper; import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.EnumDatabaseTab; import forestry.api.genetics.IAlleleInteger; import forestry.api.genetics.IAlleleSpecies; import forestry.api.genetics.IAlleleTolerance; import forestry.api.genetics.IDatabaseTab; +import forestry.api.gui.GuiElementAlignment; +import forestry.api.gui.IElementGenetic; import forestry.api.lepidopterology.EnumButterflyChromosome; import forestry.core.genetics.alleles.AlleleBoolean; import forestry.core.render.ColourProperties; @@ -26,49 +24,45 @@ import forestry.core.utils.Translator; @SideOnly(Side.CLIENT) public class BeeDatabaseTab implements IDatabaseTab { - private final EnumDatabaseTab tab; + private final boolean active; - BeeDatabaseTab(EnumDatabaseTab tab) { - this.tab = tab; + BeeDatabaseTab(boolean active) { + this.active = active; } @Override - public void createElements(IGuiElementHelper elementHelper, IBee bee, ItemStack itemStack) { + public void createElements(IElementGenetic container, IBee bee, ItemStack itemStack) { EnumBeeType type = BeeManager.beeRoot.getType(itemStack); if (type == null) { return; } IAlleleSpecies primarySpecies = bee.getGenome().getPrimary(); - boolean active = tab == EnumDatabaseTab.ACTIVE_SPECIES; - elementHelper.addText(Translator.translateToLocal("for.gui.database.tab." + tab.name().toLowerCase() + ".name"), GuiElementAlignment.CENTER, 0xcfb53b); + container.text(Translator.translateToLocal("for.gui.database.tab." + (active ? "active" : "inactive") + "_species.name"), GuiElementAlignment.TOP_CENTER, 0xcfb53b); - elementHelper.addAllele(Translator.translateToLocal("for.gui.species"), bee, EnumBeeChromosome.SPECIES, active); + container.addAlleleRow(Translator.translateToLocal("for.gui.species"), bee, EnumBeeChromosome.SPECIES, active); IAlleleTolerance tempTolerance = (IAlleleTolerance) (active ? bee.getGenome().getActiveAllele(EnumBeeChromosome.TEMPERATURE_TOLERANCE) : bee.getGenome().getInactiveAllele(EnumBeeChromosome.TEMPERATURE_TOLERANCE)); - elementHelper.addText(TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.climate"), GuiElementAlignment.CENTER); - elementHelper.addToleranceInfo(tempTolerance, primarySpecies, AlleleManager.climateHelper.toDisplay(primarySpecies.getTemperature())); + //container.text(TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.climate"), GuiElementAlignment.CENTER); + container.addToleranceInfo(Translator.translateToLocal("for.gui.climate"), tempTolerance, primarySpecies, AlleleManager.climateHelper.toDisplay(primarySpecies.getTemperature())); IAlleleTolerance humidTolerance = (IAlleleTolerance) (active ? bee.getGenome().getActiveAllele(EnumBeeChromosome.HUMIDITY_TOLERANCE) : bee.getGenome().getInactiveAllele(EnumBeeChromosome.HUMIDITY_TOLERANCE)); - elementHelper.addText(TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.humidity"), GuiElementAlignment.CENTER); - elementHelper.addToleranceInfo(humidTolerance, primarySpecies, AlleleManager.climateHelper.toDisplay(primarySpecies.getHumidity())); + //container.text(TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.humidity"), GuiElementAlignment.CENTER); + container.addToleranceInfo(Translator.translateToLocal("for.gui.humidity"), humidTolerance, primarySpecies, AlleleManager.climateHelper.toDisplay(primarySpecies.getHumidity())); - elementHelper.addAllele(Translator.translateToLocal("for.gui.lifespan"), bee, EnumBeeChromosome.LIFESPAN, active); + container.addAlleleRow(Translator.translateToLocal("for.gui.lifespan"), bee, EnumBeeChromosome.LIFESPAN, active); - elementHelper.addAllele(Translator.translateToLocal("for.gui.speed"), bee, EnumBeeChromosome.SPEED, active); - elementHelper.addAllele(Translator.translateToLocal("for.gui.pollination"), bee, EnumBeeChromosome.FLOWERING, active); - elementHelper.addAllele(Translator.translateToLocal("for.gui.flowers"), bee, EnumBeeChromosome.FLOWER_PROVIDER, active); + container.addAlleleRow(Translator.translateToLocal("for.gui.speed"), bee, EnumBeeChromosome.SPEED, active); + container.addAlleleRow(Translator.translateToLocal("for.gui.pollination"), bee, EnumBeeChromosome.FLOWERING, active); + container.addAlleleRow(Translator.translateToLocal("for.gui.flowers"), bee, EnumBeeChromosome.FLOWER_PROVIDER, active); IAlleleInteger primaryFertility = (IAlleleInteger) (active ? bee.getGenome().getActiveAllele(EnumBeeChromosome.FERTILITY) : bee.getGenome().getInactiveAllele(EnumBeeChromosome.FERTILITY)); + container.addFertilityInfo(Translator.translateToLocal("for.gui.fertility"), primaryFertility, 0); - elementHelper.addText(TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.fertility"), GuiElementAlignment.CENTER); - - elementHelper.addFertilityInfo(primaryFertility, 0, 0); - - elementHelper.addAllele(Translator.translateToLocal("for.gui.area"), bee, EnumBeeChromosome.TERRITORY, active); - elementHelper.addAllele(Translator.translateToLocal("for.gui.effect"), bee, EnumBeeChromosome.EFFECT, active); + container.addAlleleRow(Translator.translateToLocal("for.gui.area"), bee, EnumBeeChromosome.TERRITORY, active); + container.addAlleleRow(Translator.translateToLocal("for.gui.effect"), bee, EnumBeeChromosome.EFFECT, active); String yes = Translator.translateToLocal("for.yes"); String no = Translator.translateToLocal("for.no"); @@ -90,17 +84,21 @@ public class BeeDatabaseTab implements IDatabaseTab { } } - elementHelper.addText(TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.diurnal"), GuiElementAlignment.CENTER); - elementHelper.addText(diurnal, GuiElementAlignment.CENTER, elementHelper.factory().getColorCoding(false)); + container.addRow(Translator.translateToLocal("for.gui.diurnal"), diurnal, false); - elementHelper.addText(TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.nocturnal"), GuiElementAlignment.CENTER); - elementHelper.addText(nocturnal, GuiElementAlignment.CENTER, elementHelper.factory().getColorCoding(false)); + //elementHelper.addText(TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.diurnal"), GuiElementAlignment.CENTER); + //elementHelper.addText(diurnal, GuiElementAlignment.CENTER, elementHelper.factory().getColorCoding(false)); + + container.addRow(Translator.translateToLocal("for.gui.nocturnal"), nocturnal, false); + + //elementHelper.addText(TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.nocturnal"), GuiElementAlignment.CENTER); + //elementHelper.addText(nocturnal, GuiElementAlignment.CENTER, elementHelper.factory().getColorCoding(false)); String flyer = StringUtil.readableBoolean(active ? bee.getGenome().getToleratesRain() : ((AlleleBoolean) bee.getGenome().getInactiveAllele(EnumBeeChromosome.TOLERATES_RAIN)).getValue(), yes, no); - elementHelper.addAllele(Translator.translateToLocal("for.gui.flyer"), (a) -> flyer, bee, EnumButterflyChromosome.TOLERANT_FLYER, active); + container.addAlleleRow(Translator.translateToLocal("for.gui.flyer"), (a) -> flyer, bee, EnumButterflyChromosome.TOLERANT_FLYER, active); String cave = StringUtil.readableBoolean(active ? bee.getGenome().getCaveDwelling() : ((AlleleBoolean) bee.getGenome().getInactiveAllele(EnumBeeChromosome.CAVE_DWELLING)).getValue(), yes, no); - elementHelper.addAllele(Translator.translateToLocal("for.gui.fireresist"), (a) -> cave, bee, EnumButterflyChromosome.FIRE_RESIST, active); + container.addAlleleRow(Translator.translateToLocal("for.gui.cave"), (a) -> cave, bee, EnumButterflyChromosome.FIRE_RESIST, active); String displayText; if (type == EnumBeeType.PRINCESS || type == EnumBeeType.QUEEN) { @@ -109,12 +107,12 @@ public class BeeDatabaseTab implements IDatabaseTab { displayTextKey = "for.bees.stock.ignoble"; } displayText = Translator.translateToLocal(displayTextKey); - elementHelper.addText(displayText, GuiElementAlignment.CENTER, ColourProperties.INSTANCE.get("gui.beealyzer.binomial")); + container.text(displayText, GuiElementAlignment.TOP_CENTER, ColourProperties.INSTANCE.get("gui.beealyzer.binomial")); } } @Override - public EnumDatabaseTab getTab() { - return tab; + public ItemStack getIconStack() { + return BeeDefinition.MEADOWS.getMemberStack(active ? EnumBeeType.PRINCESS : EnumBeeType.DRONE); } } diff --git a/src/main/java/forestry/apiculture/genetics/BeePlugin.java b/src/main/java/forestry/apiculture/genetics/BeePlugin.java index 20a9898eb..3b87cf9f3 100644 --- a/src/main/java/forestry/apiculture/genetics/BeePlugin.java +++ b/src/main/java/forestry/apiculture/genetics/BeePlugin.java @@ -10,26 +10,26 @@ import net.minecraft.util.NonNullList; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.apiculture.EnumBeeType; import forestry.api.apiculture.IAlleleBeeSpecies; import forestry.api.apiculture.IBee; -import forestry.api.genetics.EnumDatabaseTab; -import forestry.api.genetics.IDatabaseTab; -import forestry.api.genetics.ISpeciesPlugin; import forestry.apiculture.ModuleApiculture; import forestry.apiculture.items.EnumHoneyComb; import forestry.core.config.Config; +import forestry.core.genetics.analyzer.DatabasePlugin; +import forestry.core.genetics.analyzer.MutationsTab; +import forestry.core.genetics.analyzer.ProductsTab; -//TODO: Add support for the alyzer @SideOnly(Side.CLIENT) -public class BeePlugin implements ISpeciesPlugin { +public class BeePlugin extends DatabasePlugin { public static final BeePlugin INSTANCE = new BeePlugin(); - private static final BeeDatabaseTab ACTIVE = new BeeDatabaseTab(EnumDatabaseTab.ACTIVE_SPECIES); - private static final BeeDatabaseTab INACTIVE = new BeeDatabaseTab(EnumDatabaseTab.INACTIVE_SPECIES); protected final Map iconStacks = new HashMap<>(); private BeePlugin() { + super(new BeeDatabaseTab(true), + new BeeDatabaseTab(false), + new ProductsTab(()->ModuleApiculture.getItems().beeComb.get(EnumHoneyComb.HONEY, 1)), + new MutationsTab(()-> ModuleApiculture.getItems().frameImpregnated.getItemStack())); NonNullList beeList = NonNullList.create(); ModuleApiculture.getItems().beeDroneGE.addCreativeItems(beeList, false); for (ItemStack beeStack : beeList) { @@ -47,25 +47,4 @@ public class BeePlugin implements ISpeciesPlugin { public List getHints() { return Config.hints.get("beealyzer"); } - - @Override - public IDatabaseTab getSpeciesTab(boolean active) { - if(active){ - return ACTIVE; - } - return INACTIVE; - } - - @Override - public ItemStack getTabDatabaseIconItem(EnumDatabaseTab tab) { - switch (tab){ - case ACTIVE_SPECIES: - return BeeDefinition.MEADOWS.getMemberStack(EnumBeeType.QUEEN); - case PRODUCTS: - return ModuleApiculture.getItems().beeComb.get(EnumHoneyComb.HONEY, 1); - case MUTATIONS: - return ModuleApiculture.getItems().frameImpregnated.getItemStack(); - } - return BeeDefinition.MEADOWS.getMemberStack(EnumBeeType.DRONE); - } } diff --git a/src/main/java/forestry/apiculture/genetics/BeeRoot.java b/src/main/java/forestry/apiculture/genetics/BeeRoot.java index 0168d929f..624d48f26 100644 --- a/src/main/java/forestry/apiculture/genetics/BeeRoot.java +++ b/src/main/java/forestry/apiculture/genetics/BeeRoot.java @@ -49,9 +49,9 @@ import forestry.api.genetics.IAllele; import forestry.api.genetics.IAlyzerPlugin; import forestry.api.genetics.IChromosome; import forestry.api.genetics.IChromosomeType; +import forestry.api.genetics.IDatabasePlugin; import forestry.api.genetics.IIndividual; import forestry.api.genetics.IMutation; -import forestry.api.genetics.ISpeciesPlugin; import forestry.api.genetics.ISpeciesType; import forestry.apiculture.BeeHousingListener; import forestry.apiculture.BeeHousingModifier; @@ -176,6 +176,24 @@ public class BeeRoot extends SpeciesRoot implements IBeeRoot { return EnumBeeType.DRONE; } + @Override + public ISpeciesType[] getTypes() { + return EnumBeeType.values(); + } + + @Override + public ISpeciesType getTypeForMutation(int position) { + switch (position){ + case 0: + return EnumBeeType.PRINCESS; + case 1: + return EnumBeeType.DRONE; + case 2: + return EnumBeeType.QUEEN; + } + return getIconType(); + } + @Override public boolean isDrone(ItemStack stack) { return getType(stack) == EnumBeeType.DRONE; @@ -385,7 +403,7 @@ public class BeeRoot extends SpeciesRoot implements IBeeRoot { @Override @SideOnly(Side.CLIENT) - public ISpeciesPlugin getSpeciesPlugin() { + public IDatabasePlugin getSpeciesPlugin() { return BeePlugin.INSTANCE; } } diff --git a/src/main/java/forestry/apiculture/gui/ContainerBeeHousing.java b/src/main/java/forestry/apiculture/gui/ContainerBeeHousing.java index 483a01fb9..5a79d7082 100644 --- a/src/main/java/forestry/apiculture/gui/ContainerBeeHousing.java +++ b/src/main/java/forestry/apiculture/gui/ContainerBeeHousing.java @@ -10,13 +10,14 @@ ******************************************************************************/ package forestry.apiculture.gui; -import forestry.apiculture.tiles.TileBeeHousingBase; -import forestry.core.gui.ContainerTile; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.packets.PacketGuiUpdate; import net.minecraft.entity.player.InventoryPlayer; -public class ContainerBeeHousing extends ContainerTile implements IContainerBeeHousing { +import forestry.apiculture.tiles.TileBeeHousingBase; +import forestry.core.gui.ContainerAnalyzerProvider; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.packets.PacketGuiUpdate; + +public class ContainerBeeHousing extends ContainerAnalyzerProvider implements IContainerBeeHousing { public ContainerBeeHousing(InventoryPlayer player, TileBeeHousingBase tile, boolean hasFrames) { super(tile, player, 8, 108); diff --git a/src/main/java/forestry/apiculture/gui/GuiBeeHousing.java b/src/main/java/forestry/apiculture/gui/GuiBeeHousing.java index 8a12282d6..361eb87dd 100644 --- a/src/main/java/forestry/apiculture/gui/GuiBeeHousing.java +++ b/src/main/java/forestry/apiculture/gui/GuiBeeHousing.java @@ -10,12 +10,16 @@ ******************************************************************************/ package forestry.apiculture.gui; -import forestry.core.config.Constants; -import forestry.core.gui.GuiForestryTitled; -import forestry.core.render.EnumTankLevel; -import net.minecraft.inventory.Container; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; -public class GuiBeeHousing extends GuiForestryTitled { +import forestry.core.config.Constants; +import forestry.core.gui.ContainerForestry; +import forestry.core.gui.GuiAnalyzerProvider; +import forestry.core.gui.slots.SlotWatched; +import forestry.core.render.EnumTankLevel; + +public class GuiBeeHousing extends GuiAnalyzerProvider { private final IGuiBeeHousingDelegate delegate; public enum Icon { @@ -30,18 +34,36 @@ public class GuiBeeHousing extends G } public GuiBeeHousing(IGuiBeeHousingDelegate delegate, C container, Icon icon) { - super(Constants.TEXTURE_PATH_GUI + icon.path, container, delegate); + super(Constants.TEXTURE_PATH_GUI + icon.path, container, delegate, 25, 7, 2, 0); this.delegate = delegate; this.ySize = 190; + + for(int i = 0;i < 2;i++) { + Slot queenSlot = container.getForestrySlot(1 + i); + if (queenSlot instanceof SlotWatched) { + SlotWatched watched = (SlotWatched) queenSlot; + watched.setChangeWatcher(this); + } + } + analyzer.init(); } @Override protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + bindTexture(textureFile); drawHealthMeter(guiLeft + 20, guiTop + 37, delegate.getHealthScaled(46), EnumTankLevel.rateTankLevel(delegate.getHealthScaled(100))); } + @Override + protected void drawSelectedSlot(int selectedSlot) { + Slot slot = container.getForestrySlot(1 + selectedSlot); + if(slot != null){ + SELECTED_COMB_SLOT.draw(guiLeft + slot.xPos -3, guiTop + slot.yPos - 3); + } + } + private void drawHealthMeter(int x, int y, int height, EnumTankLevel rated) { int i = 176 + rated.getLevelScaled(16); int k = 0; @@ -56,4 +78,25 @@ public class GuiBeeHousing extends G addHintLedger(delegate.getHintKey()); addOwnerLedger(delegate); } + + @Override + public ItemStack getSpecimen(int index) { + Slot slot = container.getForestrySlot(getSelectedSlot(index)); + return slot.getStack(); + } + + @Override + protected boolean hasErrors() { + return delegate.getErrorLogic().hasErrors(); + } + + @Override + public boolean onUpdateSelected() { + return false; + } + + @Override + public void onSelection(int index, boolean changed) { + + } } diff --git a/src/main/java/forestry/apiculture/gui/GuiImprinter.java b/src/main/java/forestry/apiculture/gui/GuiImprinter.java index 255260fb4..ba0897d5a 100755 --- a/src/main/java/forestry/apiculture/gui/GuiImprinter.java +++ b/src/main/java/forestry/apiculture/gui/GuiImprinter.java @@ -93,13 +93,13 @@ public class GuiImprinter extends GuiForestry { } @Override - protected void mouseClicked(int i, int j, int k) throws IOException { - super.mouseClicked(i, j, k); + protected void mouseClicked(int mouseX, int mouseY, int k) throws IOException { + super.mouseClicked(mouseX, mouseY, k); int cornerX = (width - xSize) / 2; int cornerY = (height - ySize) / 2; - int slot = getHabitatSlotAtPosition(i - cornerX, j - cornerY); + int slot = getHabitatSlotAtPosition(mouseX - cornerX, mouseY - cornerY); if (slot < 0) { return; } diff --git a/src/main/java/forestry/apiculture/worldgen/VillageApiaristHouse.java b/src/main/java/forestry/apiculture/worldgen/VillageApiaristHouse.java index 653fb69bd..d965bff85 100755 --- a/src/main/java/forestry/apiculture/worldgen/VillageApiaristHouse.java +++ b/src/main/java/forestry/apiculture/worldgen/VillageApiaristHouse.java @@ -26,7 +26,6 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; -import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.biome.Biome; @@ -53,7 +52,6 @@ import forestry.api.arboriculture.TreeManager; import forestry.api.arboriculture.WoodBlockKind; import forestry.api.core.EnumHumidity; import forestry.api.core.EnumTemperature; -import forestry.api.core.ForestryAPI; import forestry.api.genetics.AlleleManager; import forestry.apiculture.ModuleApiculture; import forestry.apiculture.flowers.Flower; @@ -65,6 +63,7 @@ import forestry.core.blocks.BlockBase; import forestry.core.config.Constants; import forestry.core.tiles.TileUtil; import forestry.modules.ForestryModuleUids; +import forestry.modules.ModuleHelper; public class VillageApiaristHouse extends StructureVillagePieces.House1 { @@ -383,7 +382,7 @@ public class VillageApiaristHouse extends StructureVillagePieces.House1 { if (villagerCount <= 0) { return registry.getID(ModuleApiculture.villagerApiarist); - } else if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.ARBORICULTURE))) { + } else if (ModuleHelper.isEnabled(ForestryModuleUids.ARBORICULTURE)) { return registry.getID(ModuleArboriculture.villagerArborist); } else { return currentVillagerProfession; @@ -408,7 +407,7 @@ public class VillageApiaristHouse extends StructureVillagePieces.House1 { IWoodType woodType; boolean fireproof; - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.ARBORICULTURE))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.ARBORICULTURE)) { woodType = EnumForestryWoodType.getRandom(random); fireproof = random.nextInt(4) == 0; } else { diff --git a/src/main/java/forestry/arboriculture/ModuleArboriculture.java b/src/main/java/forestry/arboriculture/ModuleArboriculture.java index f435c0332..0de3f26b9 100644 --- a/src/main/java/forestry/arboriculture/ModuleArboriculture.java +++ b/src/main/java/forestry/arboriculture/ModuleArboriculture.java @@ -14,7 +14,6 @@ import com.google.common.base.Preconditions; import javax.annotation.Nullable; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map.Entry; @@ -110,7 +109,7 @@ import forestry.core.utils.ItemStackUtil; import forestry.core.utils.VillagerTradeLists; import forestry.modules.BlankForestryModule; import forestry.modules.ForestryModuleUids; -import forestry.modules.ModuleManager; +import forestry.modules.ModuleHelper; @ForestryModule(containerID = Constants.MOD_ID, moduleID = ForestryModuleUids.ARBORICULTURE, name = "Arboriculture", author = "Binnie & SirSengir", url = Constants.URL, unlocalizedDescription = "for.module.arboriculture.description", lootTable = "arboriculture") public class ModuleArboriculture extends BlankForestryModule { @@ -215,7 +214,7 @@ public class ModuleArboriculture extends BlankForestryModule { // Commands ModuleCore.rootCommand.addChildCommand(new CommandTree()); - if(ModuleManager.getInstance().isModuleEnabled(Constants.MOD_ID, ForestryModuleUids.SORTING)){ + if(ModuleHelper.isEnabled( ForestryModuleUids.SORTING)){ ArboricultureFilterRuleType.init(); } } @@ -391,7 +390,7 @@ public class ModuleArboriculture extends BlankForestryModule { '#', fireproofPlanks.copy()); // Fabricator recipes - if (ForestryAPI.enabledModules.containsAll(Arrays.asList(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FACTORY), new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.APICULTURE)))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.FACTORY, ForestryModuleUids.APICULTURE)) { logs.setCount(1); fireproofLogs.setCount(1); RecipeManagers.fabricatorManager.addRecipe(ItemStack.EMPTY, Fluids.GLASS.getFluid(500), fireproofLogs.copy(), new Object[]{ @@ -412,7 +411,7 @@ public class ModuleArboriculture extends BlankForestryModule { } } - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FACTORY))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.FACTORY)) { // SQUEEZER RECIPES int seedOilMultiplier = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); diff --git a/src/main/java/forestry/arboriculture/genetics/CheckPollinatableTree.java b/src/main/java/forestry/arboriculture/genetics/CheckPollinatableTree.java index 2f9de3618..65680942e 100644 --- a/src/main/java/forestry/arboriculture/genetics/CheckPollinatableTree.java +++ b/src/main/java/forestry/arboriculture/genetics/CheckPollinatableTree.java @@ -10,13 +10,13 @@ ******************************************************************************/ package forestry.arboriculture.genetics; +import net.minecraftforge.common.EnumPlantType; + import forestry.api.arboriculture.ITree; import forestry.api.genetics.ICheckPollinatable; import forestry.api.genetics.IIndividual; import forestry.apiculture.ModuleApiculture; -import net.minecraftforge.common.EnumPlantType; - public class CheckPollinatableTree implements ICheckPollinatable { private final ITree tree; diff --git a/src/main/java/forestry/arboriculture/genetics/TreeDatabaseTab.java b/src/main/java/forestry/arboriculture/genetics/TreeDatabaseTab.java index 4a7a877b8..68febb20f 100644 --- a/src/main/java/forestry/arboriculture/genetics/TreeDatabaseTab.java +++ b/src/main/java/forestry/arboriculture/genetics/TreeDatabaseTab.java @@ -11,82 +11,80 @@ import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import forestry.api.arboriculture.EnumFruitFamily; +import forestry.api.arboriculture.EnumGermlingType; import forestry.api.arboriculture.EnumTreeChromosome; import forestry.api.arboriculture.IAlleleFruit; import forestry.api.arboriculture.IAlleleTreeSpecies; import forestry.api.arboriculture.ITree; -import forestry.api.core.GuiElementAlignment; -import forestry.api.core.IGuiElementHelper; -import forestry.api.genetics.EnumDatabaseTab; import forestry.api.genetics.IAlleleInteger; import forestry.api.genetics.IDatabaseTab; import forestry.api.genetics.IFruitFamily; +import forestry.api.gui.GuiElementAlignment; +import forestry.api.gui.IElementGenetic; import forestry.arboriculture.genetics.alleles.AlleleFruits; +import forestry.core.gui.elements.GuiElementFactory; import forestry.core.utils.Translator; @SideOnly(Side.CLIENT) public class TreeDatabaseTab implements IDatabaseTab { - private final EnumDatabaseTab tab; + private final boolean active; - TreeDatabaseTab(EnumDatabaseTab tab) { - this.tab = tab; + TreeDatabaseTab(boolean active) { + this.active = active; } @Override - public void createElements(IGuiElementHelper elementHelper, ITree tree, ItemStack itemStack) { + public void createElements(IElementGenetic container, ITree tree, ItemStack itemStack) { IAlleleTreeSpecies primarySpecies = tree.getGenome().getPrimary(); - boolean active = tab == EnumDatabaseTab.ACTIVE_SPECIES; IAlleleTreeSpecies species = active ? primarySpecies : tree.getGenome().getSecondary(); - int speciesColor = elementHelper.factory().getColorCoding(species.isDominant()); + int speciesColor = GuiElementFactory.INSTANCE.getColorCoding(species.isDominant()); - elementHelper.addText(Translator.translateToLocal("for.gui.database.tab." + tab.name().toLowerCase() + ".name"), GuiElementAlignment.CENTER, 0xcfb53b); + container.text(Translator.translateToLocal("for.gui.database.tab." + (active ? "active" : "inactive") + "_species.name"), GuiElementAlignment.TOP_CENTER, 0xcfb53b); - elementHelper.addAllele(Translator.translateToLocal("for.gui.species"), tree, EnumTreeChromosome.SPECIES, active); + container.addAlleleRow(Translator.translateToLocal("for.gui.species"), tree, EnumTreeChromosome.SPECIES, active); - elementHelper.addAllele(Translator.translateToLocal("for.gui.saplings"), tree, EnumTreeChromosome.FERTILITY, active); - elementHelper.addAllele(Translator.translateToLocal("for.gui.maturity"), tree, EnumTreeChromosome.MATURATION, active); - elementHelper.addAllele(Translator.translateToLocal("for.gui.height"), tree, EnumTreeChromosome.HEIGHT, active); + container.addAlleleRow(Translator.translateToLocal("for.gui.saplings"), tree, EnumTreeChromosome.FERTILITY, active); + container.addAlleleRow(Translator.translateToLocal("for.gui.maturity"), tree, EnumTreeChromosome.MATURATION, active); + container.addAlleleRow(Translator.translateToLocal("for.gui.height"), tree, EnumTreeChromosome.HEIGHT, active); IAlleleInteger girth = (IAlleleInteger) (active ? tree.getGenome().getActiveAllele(EnumTreeChromosome.GIRTH) : tree.getGenome().getInactiveAllele(EnumTreeChromosome.GIRTH)); - elementHelper.addText(TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.girth"), GuiElementAlignment.CENTER); - elementHelper.addText(String.format("%sx%s", girth.getValue(), girth.getValue()), GuiElementAlignment.CENTER, elementHelper.factory().getColorCoding(girth.isDominant())); + container.addRow(Translator.translateToLocal("for.gui.girth"), String.format("%sx%s", girth.getValue(), girth.getValue()), girth.isDominant()); - elementHelper.addAllele(Translator.translateToLocal("for.gui.yield"), tree, EnumTreeChromosome.YIELD, active); - elementHelper.addAllele(Translator.translateToLocal("for.gui.sappiness"), tree, EnumTreeChromosome.SAPPINESS, active); + container.addAlleleRow(Translator.translateToLocal("for.gui.yield"), tree, EnumTreeChromosome.YIELD, active); + container.addAlleleRow(Translator.translateToLocal("for.gui.sappiness"), tree, EnumTreeChromosome.SAPPINESS, active); - elementHelper.addAllele(Translator.translateToLocal("for.gui.effect"), tree, EnumTreeChromosome.EFFECT, active); + container.addAlleleRow(Translator.translateToLocal("for.gui.effect"), tree, EnumTreeChromosome.EFFECT, active); - elementHelper.addText(TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.native"), GuiElementAlignment.CENTER); - elementHelper.addText(Translator.translateToLocal("for.gui." + tree.getGenome().getPrimary().getPlantType().toString().toLowerCase(Locale.ENGLISH)), GuiElementAlignment.CENTER, speciesColor); + container.addRow(Translator.translateToLocal("for.gui.native"), Translator.translateToLocal("for.gui." + tree.getGenome().getPrimary().getPlantType().toString().toLowerCase(Locale.ENGLISH)), species.isDominant()); - elementHelper.addText(TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.supports"), GuiElementAlignment.CENTER); + container.text(TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.supports"), GuiElementAlignment.TOP_CENTER); List families = new ArrayList<>(tree.getGenome().getPrimary().getSuitableFruit()); for (IFruitFamily fruitFamily : families) { - elementHelper.addText(fruitFamily.getName(), GuiElementAlignment.CENTER, speciesColor); + container.text(fruitFamily.getName(), GuiElementAlignment.TOP_CENTER, speciesColor); } IAlleleFruit fruit = (IAlleleFruit) (active ? tree.getGenome().getActiveAllele(EnumTreeChromosome.FRUITS) : tree.getGenome().getInactiveAllele(EnumTreeChromosome.FRUITS)); - int colorCoding = elementHelper.factory().getColorCoding(tree.getGenome().getActiveAllele(EnumTreeChromosome.FRUITS).isDominant()); + int colorCoding = GuiElementFactory.INSTANCE.getColorCoding(tree.getGenome().getActiveAllele(EnumTreeChromosome.FRUITS).isDominant()); - elementHelper.addText(TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.fruits"), GuiElementAlignment.CENTER); + container.text(TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.fruits"), GuiElementAlignment.TOP_CENTER); String strike = ""; if (!species.getSuitableFruit().contains(fruit.getProvider().getFamily()) && fruit != AlleleFruits.fruitNone) { strike = TextFormatting.STRIKETHROUGH.toString(); } - elementHelper.addText(strike + fruit.getProvider().getDescription(), GuiElementAlignment.CENTER, colorCoding); + container.text(strike + fruit.getProvider().getDescription(), GuiElementAlignment.TOP_CENTER, colorCoding); IFruitFamily family = fruit.getProvider().getFamily(); if (family != null && !family.getUID().equals(EnumFruitFamily.NONE.getUID())) { - elementHelper.addText(TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.family"), GuiElementAlignment.CENTER); - elementHelper.addText(family.getName(), GuiElementAlignment.CENTER, colorCoding); + container.text(TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.family"), GuiElementAlignment.TOP_CENTER); + container.text(family.getName(), GuiElementAlignment.TOP_CENTER, colorCoding); } } @Override - public EnumDatabaseTab getTab() { - return tab; + public ItemStack getIconStack() { + return TreeDefinition.Cherry.getMemberStack(active ? EnumGermlingType.SAPLING : EnumGermlingType.POLLEN); } } diff --git a/src/main/java/forestry/arboriculture/genetics/TreePlugin.java b/src/main/java/forestry/arboriculture/genetics/TreePlugin.java index f14418b92..817c05ee3 100644 --- a/src/main/java/forestry/arboriculture/genetics/TreePlugin.java +++ b/src/main/java/forestry/arboriculture/genetics/TreePlugin.java @@ -10,26 +10,26 @@ import net.minecraft.util.NonNullList; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.arboriculture.EnumGermlingType; import forestry.api.arboriculture.IAlleleTreeSpecies; import forestry.api.arboriculture.ITree; -import forestry.api.genetics.EnumDatabaseTab; -import forestry.api.genetics.IDatabaseTab; -import forestry.api.genetics.ISpeciesPlugin; import forestry.arboriculture.ModuleArboriculture; import forestry.core.config.Config; +import forestry.core.genetics.analyzer.DatabasePlugin; +import forestry.core.genetics.analyzer.MutationsTab; +import forestry.core.genetics.analyzer.ProductsTab; import forestry.core.items.ItemFruit; //TODO: Add support for the alyzer @SideOnly(Side.CLIENT) -public class TreePlugin implements ISpeciesPlugin { +public class TreePlugin extends DatabasePlugin { public static final TreePlugin INSTANCE = new TreePlugin(); - private static final TreeDatabaseTab ACTIVE = new TreeDatabaseTab(EnumDatabaseTab.ACTIVE_SPECIES); - private static final TreeDatabaseTab INACTIVE = new TreeDatabaseTab(EnumDatabaseTab.INACTIVE_SPECIES); - protected final Map iconStacks = new HashMap<>(); private TreePlugin() { + super(new TreeDatabaseTab(true), + new TreeDatabaseTab(false), + new ProductsTab(()-> ItemFruit.EnumFruit.CHERRY.getStack()), + new MutationsTab(()->ModuleArboriculture.getItems().grafter.getItemStack())); NonNullList treeList = NonNullList.create(); ModuleArboriculture.getItems().sapling.addCreativeItems(treeList, false); for (ItemStack treeStack : treeList) { @@ -47,25 +47,4 @@ public class TreePlugin implements ISpeciesPlugin { public List getHints() { return Config.hints.get("treealyzer"); } - - @Override - public IDatabaseTab getSpeciesTab(boolean active) { - if(active){ - return ACTIVE; - } - return INACTIVE; - } - - @Override - public ItemStack getTabDatabaseIconItem(EnumDatabaseTab tab) { - switch (tab){ - case ACTIVE_SPECIES: - return TreeDefinition.Cherry.getMemberStack(EnumGermlingType.SAPLING); - case PRODUCTS: - return ItemFruit.EnumFruit.CHERRY.getStack(); - case MUTATIONS: - return ModuleArboriculture.getItems().grafter.getItemStack(); - } - return TreeDefinition.Cherry.getMemberStack(EnumGermlingType.POLLEN); - } } diff --git a/src/main/java/forestry/arboriculture/genetics/TreeRoot.java b/src/main/java/forestry/arboriculture/genetics/TreeRoot.java index 3d71770f8..24aa86996 100644 --- a/src/main/java/forestry/arboriculture/genetics/TreeRoot.java +++ b/src/main/java/forestry/arboriculture/genetics/TreeRoot.java @@ -60,11 +60,11 @@ import forestry.api.genetics.IAllele; import forestry.api.genetics.IAlyzerPlugin; import forestry.api.genetics.ICheckPollinatable; import forestry.api.genetics.IChromosomeType; +import forestry.api.genetics.IDatabasePlugin; import forestry.api.genetics.IFruitFamily; import forestry.api.genetics.IIndividual; import forestry.api.genetics.IMutation; import forestry.api.genetics.IPollinatable; -import forestry.api.genetics.ISpeciesPlugin; import forestry.api.genetics.ISpeciesType; import forestry.arboriculture.ModuleArboriculture; import forestry.arboriculture.blocks.BlockFruitPod; @@ -158,6 +158,11 @@ public class TreeRoot extends SpeciesRoot implements ITreeRoot { return EnumGermlingType.SAPLING; } + @Override + public ISpeciesType[] getTypes() { + return EnumGermlingType.values(); + } + @Override public ITree getTree(World world, BlockPos pos) { return TileUtil.getResultFromTile(world, pos, TileSapling.class, TileSapling::getTree); @@ -435,7 +440,7 @@ public class TreeRoot extends SpeciesRoot implements ITreeRoot { @Override @SideOnly(Side.CLIENT) - public ISpeciesPlugin getSpeciesPlugin() { + public IDatabasePlugin getSpeciesPlugin() { return TreePlugin.INSTANCE; } diff --git a/src/main/java/forestry/book/BookCategory.java b/src/main/java/forestry/book/BookCategory.java new file mode 100644 index 000000000..6d04f0712 --- /dev/null +++ b/src/main/java/forestry/book/BookCategory.java @@ -0,0 +1,84 @@ +package forestry.book; + +import javax.annotation.Nullable; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.Map; + +import net.minecraft.item.ItemStack; + +import forestry.api.book.IBookCategory; +import forestry.api.book.IBookEntry; +import forestry.api.book.IBookEntryBuilder; +import forestry.core.utils.Translator; + +public class BookCategory implements IBookCategory { + private final String name; + private final transient Map entries = new LinkedHashMap<>(); + private ItemStack stack = ItemStack.EMPTY; + + public BookCategory(String name) { + this.name = name; + } + + @Override + public ItemStack getStack() { + return stack; + } + + @Override + public IBookCategory setStack(ItemStack stack) { + this.stack = stack; + return this; + } + + @Override + public IBookCategory addEntry(IBookEntry entry) { + entries.put(entry.getName(), entry); + return this; + } + + @Override + public IBookCategory addEntry(String name, ItemStack stack) { + BookEntryBuilder builder = new BookEntryBuilder(this, name); + builder.setStack(stack); + builder.addToCategory(); + return this; + } + + @Override + public IBookEntryBuilder createEntry(String name) { + return new BookEntryBuilder(this, name); + } + + @Override + public IBookEntryBuilder createEntry(String name, ItemStack stack) { + return new BookEntryBuilder(this, name).setStack(stack); + } + + @Override + public Collection getEntries() { + return entries.values(); + } + + @Nullable + @Override + public IBookEntry getEntry(String name) { + return entries.get(name); + } + + @Override + public String getLocalizedName() { + return Translator.translateToLocal("for.gui.book.category." + name + ".title"); + } + + @Override + public String getTooltip() { + return "for.gui.book.category." + name + ".tooltip"; + } + + @Override + public String getName() { + return name; + } +} diff --git a/src/main/java/forestry/book/BookEntry.java b/src/main/java/forestry/book/BookEntry.java new file mode 100644 index 000000000..00ec95a32 --- /dev/null +++ b/src/main/java/forestry/book/BookEntry.java @@ -0,0 +1,67 @@ +package forestry.book; + +import javax.annotation.Nullable; +import java.util.function.Function; + +import net.minecraft.item.ItemStack; + +import forestry.api.book.BookContent; +import forestry.api.book.IBookEntry; +import forestry.api.book.IBookPageFactory; + +public class BookEntry implements IBookEntry { + private final String name; + private final ItemStack stack; + private final IBookPageFactory loader; + @Nullable + private final IBookEntry parent; + private final IBookEntry[] subEntries; + private final BookContent[][] content; + private final String title; + + BookEntry(String name, ItemStack stack, IBookPageFactory loader, Function subEntryFactory, BookContent[][] content, String title, @Nullable IBookEntry parent) { + this.name = name; + this.stack = stack; + this.loader = loader; + this.subEntries = subEntryFactory.apply(this); + this.content = content; + this.title = title; + this.parent = parent; + } + + @Override + public BookContent[][] getContent() { + return content; + } + + @Override + public IBookPageFactory getPageFactory() { + return loader; + } + + @Override + public ItemStack getStack() { + return stack; + } + + @Override + public String getTitle() { + return title; + } + + @Override + public String getName() { + return name; + } + + @Override + public IBookEntry[] getSubEntries() { + return subEntries; + } + + @Override + @Nullable + public IBookEntry getParent() { + return parent; + } +} diff --git a/src/main/java/forestry/book/BookEntryBuilder.java b/src/main/java/forestry/book/BookEntryBuilder.java new file mode 100644 index 000000000..b94f2ab6b --- /dev/null +++ b/src/main/java/forestry/book/BookEntryBuilder.java @@ -0,0 +1,76 @@ +package forestry.book; + +import javax.annotation.Nullable; +import java.util.LinkedList; +import java.util.List; + +import net.minecraft.item.ItemStack; + +import forestry.api.book.BookContent; +import forestry.api.book.IBookCategory; +import forestry.api.book.IBookEntry; +import forestry.api.book.IBookEntryBuilder; +import forestry.api.book.IBookPageFactory; +import forestry.book.pages.JsonPageFactory; + +public class BookEntryBuilder implements IBookEntryBuilder { + private final String name; + private final IBookCategory category; + private ItemStack stack = ItemStack.EMPTY; + private IBookPageFactory loader = JsonPageFactory.INSTANCE; + private List subEntries = new LinkedList<>(); + private String title = "missing.title"; + private BookContent[][] content = new BookContent[0][0]; + + BookEntryBuilder(IBookCategory category, String name) { + this.category = category; + this.name = name; + } + + @Override + public BookEntryBuilder setStack(ItemStack stack) { + this.stack = stack; + return this; + } + + @Override + public BookEntryBuilder setLoader(IBookPageFactory loader) { + this.loader = loader; + return this; + } + + @Override + public BookEntryBuilder createSubEntry(String name, ItemStack stack) { + BookEntryBuilder builder = new BookEntryBuilder(category, name).setStack(stack); + subEntries.add(builder); + return builder; + } + + @Override + public IBookEntryBuilder setContent(BookContent[][] content) { + this.content = content; + return this; + } + + @Override + public IBookEntryBuilder setTitle(String title) { + this.title = title; + return this; + } + + @Override + public IBookEntry build(@Nullable IBookEntry parent) { + return new BookEntry(name, stack, loader, entry -> subEntries.stream().map(builder -> builder.build(entry)).toArray(IBookEntry[]::new), content, title, parent); + } + + @Override + public IBookEntry build() { + return build(null); + } + + @Override + public IBookCategory addToCategory() { + category.addEntry(build()); + return category; + } +} diff --git a/src/main/java/forestry/book/BookLoader.java b/src/main/java/forestry/book/BookLoader.java new file mode 100644 index 000000000..790c08708 --- /dev/null +++ b/src/main/java/forestry/book/BookLoader.java @@ -0,0 +1,255 @@ +package forestry.book; + +import com.google.common.collect.MapMaker; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import javax.annotation.Nullable; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ForkJoinPool; + +import org.apache.commons.io.IOUtils; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.resources.IResource; +import net.minecraft.client.resources.IResourceManager; +import net.minecraft.client.resources.IResourceManagerReloadListener; +import net.minecraft.client.resources.Language; +import net.minecraft.item.ItemStack; +import net.minecraft.util.JsonUtils; +import net.minecraft.util.ResourceLocation; + +import forestry.api.book.BookContent; +import forestry.api.book.IBookEntryBuilder; +import forestry.api.book.IBookLoader; +import forestry.api.book.IBookPageFactory; +import forestry.api.book.IForesterBook; +import forestry.book.data.EntryData; +import forestry.book.data.content.CarpenterContent; +import forestry.book.data.content.CraftingContent; +import forestry.book.data.content.FabricatorContent; +import forestry.book.data.content.ImageContent; +import forestry.book.data.content.IndexContent; +import forestry.book.data.content.MutationContent; +import forestry.book.data.content.StructureContent; +import forestry.book.data.content.TextContent; +import forestry.book.data.deserializer.BookCategoryDeserializer; +import forestry.book.data.deserializer.BookContentDeserializer; +import forestry.book.pages.JsonPageFactory; +import forestry.core.utils.JsonUtil; +import forestry.core.utils.Log; +import forestry.core.utils.ResourceUtil; +import forestry.modules.ModuleHelper; + +public class BookLoader implements IResourceManagerReloadListener, IBookLoader { + public static final Gson GSON = new GsonBuilder() + .registerTypeAdapter(BookContent.class, new BookContentDeserializer()) + .registerTypeAdapter(BookCategory.class, new BookCategoryDeserializer()) + .registerTypeAdapter(ResourceLocation.class, (JsonDeserializer) (json, typeOfT, context) -> new ResourceLocation(JsonUtils.getString(json, "location"))) + .registerTypeAdapter(ItemStack.class, (JsonDeserializer) (json, typeOfT, context) -> JsonUtil.deserializeItemStack(json.getAsJsonObject(), ItemStack.EMPTY)) + .registerTypeAdapter(Entries.class, new EntriesDeserializer()) + .create(); + public static final BookLoader INSTANCE = new BookLoader(); + private static final String BOOK_LOCATION = "forestry:manual/"; + private static final String BOOK_LOCATION_LANG = BOOK_LOCATION + "%s/%s"; + private final Map> contentByType = new HashMap<>(); + private final Map factoryByName = new HashMap<>(); + @Nullable + private ForesterBook book = null; + + private BookLoader() { + registerContentType("text", TextContent.class); + registerContentType("image", ImageContent.class); + registerContentType("crafting", CraftingContent.class); + registerContentType("mutation", MutationContent.class); + registerContentType("carpenter", CarpenterContent.class); + registerContentType("structure", StructureContent.class); + registerContentType("index", IndexContent.class); + registerContentType("fabricator", FabricatorContent.class); + registerPageFactory(JsonPageFactory.NAME, JsonPageFactory.INSTANCE); + } + + @Override + public void registerContentType(String name, Class contentClass) { + contentByType.put(name, contentClass); + } + + @Override + public void registerPageFactory(String name, IBookPageFactory factory) { + factoryByName.put(name, factory); + } + + @Override + public IBookPageFactory getPageFactory(String name) { + IBookPageFactory factory = factoryByName.get(name); + if (factory == null) { + return JsonPageFactory.INSTANCE; + } + return factory; + } + + public IForesterBook loadBook() { + if (book != null) { + return book; + } + book = new ForesterBook(); + BookCategory[] categories = fromJson(new ResourceLocation(BOOK_LOCATION + "categories.json"), BookCategory[].class, new BookCategory[0]); + if (categories != null) { + book.addCategories(categories); + for (BookCategory category : categories) { + loadCategory(category); + } + } + return book; + } + + @Override + public void invalidateBook() { + book = null; + } + + @Nullable + public static ResourceLocation getResourceLocation(String path) { + if (!path.contains(":")) { + Language currentLanguage = Minecraft.getMinecraft().getLanguageManager().getCurrentLanguage(); + String lang = currentLanguage.getLanguageCode(); + String defaultLang = "en_US"; + + ResourceLocation location = new ResourceLocation(String.format(BOOK_LOCATION_LANG, lang, path)); + if (ResourceUtil.resourceExists(location)) { + return location; + } + location = new ResourceLocation(String.format(BOOK_LOCATION_LANG, defaultLang, path)); + if (ResourceUtil.resourceExists(location)) { + return location; + } + location = new ResourceLocation(BOOK_LOCATION + path); + if (ResourceUtil.resourceExists(location)) { + return location; + } + return null; + } + ResourceLocation location = new ResourceLocation(path); + if (ResourceUtil.resourceExists(location)) { + return location; + } + return null; + } + + @Nullable + public Class getContentType(String name) { + return contentByType.get(name); + } + + private void loadCategory(BookCategory category) { + ResourceLocation entriesLocation = new ResourceLocation(BOOK_LOCATION + "entries/" + category.getName() + ".json"); + Set entryNames = new HashSet<>(); + for (IResource entryResource : ResourceUtil.getResources(entriesLocation)) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(entryResource.getInputStream(), StandardCharsets.UTF_8))) { + Entries entries = GSON.fromJson(reader, Entries.class); + entryNames.addAll(entries.names); + } catch (IOException e) { + Log.error("Failed to parse entries file {}.{}", entriesLocation, e); + } finally { + IOUtils.closeQuietly(entryResource); + } + } + Map entries = new MapMaker().concurrencyLevel(ForkJoinPool.commonPool().getPoolSize() + 1).initialCapacity(entryNames.size()).makeMap(); + entryNames.parallelStream().forEach(entry -> loadEntries(entries, entry)); + entryNames.parallelStream().forEach(entry -> { + EntryData data = entries.get(entry); + if (data != null) { + IBookEntryBuilder builder = category.createEntry(entry); + builder.setStack(data.icon); + builder.setContent(data.content); + builder.setTitle(data.title); + builder.setLoader(BookLoader.INSTANCE.getPageFactory(data.loader)); + for (String subEntry : data.subEntries) { + EntryData subData = entries.get(subEntry); + if (subData != null) { + IBookEntryBuilder subBuilder = builder.createSubEntry(subEntry, subData.icon); + subBuilder.setContent(subData.content); + subBuilder.setTitle(subData.title); + builder.setLoader(BookLoader.INSTANCE.getPageFactory(subData.loader)); + } + } + builder.addToCategory(); + } + }); + } + + private void loadEntries(Map entries, String entry) { + ResourceLocation location = getResourceLocation(entry + ".json"); + EntryData data = fromJson(location, EntryData.class, null); + if (data != null) { + entries.put(entry, data); + for (String subEntry : data.subEntries) { + loadEntries(entries, subEntry); + } + } + } + + @Nullable + private T fromJson(@Nullable ResourceLocation location, Class classOfT, @Nullable T fallback) { + if (location == null) { + return fallback; + } + IResource resource = ResourceUtil.getResource(location); + if (resource == null) { + return fallback; + } + try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))) { + return GSON.fromJson(reader, classOfT); + } catch (Exception e) { + Log.error("Failed to load resource {}: {}", location, e); + return fallback; + } finally { + IOUtils.closeQuietly(resource); + } + } + + @Override + public void onResourceManagerReload(IResourceManager resourceManager) { + invalidateBook(); + } + + private static class Entries { + private final Set names = new HashSet<>(); + } + + private static class EntriesDeserializer implements JsonDeserializer { + @Override + public Entries deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { + Entries entries = new Entries(); + parseElement(entries, json, context); + return entries; + } + + private void parseElement(Entries entries, JsonElement element, JsonDeserializationContext context) { + if (element.isJsonArray()) { + String[] array = context.deserialize(element, String[].class); + entries.names.addAll(Arrays.asList(array)); + } else { + JsonObject object = element.getAsJsonObject(); + for (Map.Entry member : object.entrySet()) { + if (ModuleHelper.isEnabled(member.getKey())) { + parseElement(entries, member.getValue(), context); + } + } + } + } + } +} diff --git a/src/main/java/forestry/book/EventHandlerBook.java b/src/main/java/forestry/book/EventHandlerBook.java new file mode 100644 index 000000000..15addc043 --- /dev/null +++ b/src/main/java/forestry/book/EventHandlerBook.java @@ -0,0 +1,31 @@ +package forestry.book; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; + +import net.minecraftforge.items.ItemHandlerHelper; + +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.gameevent.PlayerEvent; + +import forestry.core.config.Config; + +public class EventHandlerBook { + + private static final String HAS_BOOK = "forestry.spawned_book"; + + @SubscribeEvent + public void onPlayerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) { + if (Config.spawnWithBook) { + NBTTagCompound playerData = event.player.getEntityData(); + NBTTagCompound data = playerData.hasKey(EntityPlayer.PERSISTED_NBT_TAG) ? playerData.getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG) : new NBTTagCompound(); + + if (!data.getBoolean(HAS_BOOK)) { + ItemHandlerHelper.giveItemToPlayer(event.player, new ItemStack(ModuleBook.getItems().book)); + data.setBoolean(HAS_BOOK, true); + playerData.setTag(EntityPlayer.PERSISTED_NBT_TAG, data); + } + } + } +} diff --git a/src/main/java/forestry/book/ForesterBook.java b/src/main/java/forestry/book/ForesterBook.java new file mode 100644 index 000000000..79e316cc9 --- /dev/null +++ b/src/main/java/forestry/book/ForesterBook.java @@ -0,0 +1,66 @@ +package forestry.book; + +import javax.annotation.Nullable; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import forestry.api.book.IBookCategory; +import forestry.api.book.IBookEntry; +import forestry.api.book.IForesterBook; + +public class ForesterBook implements IForesterBook { + + private final Map categoriesByName = new HashMap<>(); + + @Override + public Collection getCategoryNames() { + return categoriesByName.keySet(); + } + + @Override + public IBookCategory addCategory(String name) { + IBookCategory category = getCategory(name); + if (category == null) { + categoriesByName.put(name, category = new BookCategory(name)); + } + return category; + } + + void addCategories(IBookCategory[] categories) { + for (IBookCategory category : categories) { + categoriesByName.put(category.getName(), category); + } + } + + @Nullable + @Override + public IBookCategory getCategory(String name) { + return categoriesByName.get(name); + } + + @Override + public Collection getCategories() { + return categoriesByName.values(); + } + + @Override + public Collection getEntries(String category) { + IBookCategory c = getCategory(category); + return c == null ? Collections.emptySet() : c.getEntries(); + } + + @Nullable + @Override + public IBookEntry getEntry(String name) { + for (IBookCategory category : categoriesByName.values()) { + for (IBookEntry entry : category.getEntries()) { + if (entry.getName().equalsIgnoreCase(name)) { + return entry; + } + } + } + return null; + } +} diff --git a/src/main/java/forestry/book/ModuleBook.java b/src/main/java/forestry/book/ModuleBook.java new file mode 100644 index 000000000..f6949deeb --- /dev/null +++ b/src/main/java/forestry/book/ModuleBook.java @@ -0,0 +1,72 @@ +package forestry.book; + +import com.google.common.base.Preconditions; + +import javax.annotation.Nullable; + +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; + +import net.minecraftforge.common.MinecraftForge; + +import net.minecraftforge.fml.common.SidedProxy; + +import forestry.api.book.BookManager; +import forestry.api.modules.ForestryModule; +import forestry.book.items.ItemRegistryBook; +import forestry.book.proxy.ProxyBook; +import forestry.core.config.Constants; +import forestry.core.recipes.RecipeUtil; +import forestry.core.utils.OreDictUtil; +import forestry.lepidopterology.ModuleLepidopterology; +import forestry.lepidopterology.items.ItemRegistryLepidopterology; +import forestry.modules.BlankForestryModule; +import forestry.modules.ForestryModuleUids; +import forestry.modules.ModuleHelper; +import forestry.modules.ModuleManager; + +@ForestryModule(containerID = Constants.MOD_ID, moduleID = ForestryModuleUids.BOOK, name = "Book", author = "Nedelosk", url = Constants.URL, unlocalizedDescription = "for.module.book.description") +public class ModuleBook extends BlankForestryModule { + @SuppressWarnings("NullableProblems") + @SidedProxy(clientSide = "forestry.book.proxy.ProxyBookClient", serverSide = "forestry.book.proxy.ProxyBook") + public static ProxyBook proxy; + + @Nullable + private static ItemRegistryBook items; + + public static ItemRegistryBook getItems() { + Preconditions.checkState(items != null); + return items; + } + + @Override + public void setupAPI() { + BookManager.loader = BookLoader.INSTANCE; + } + + @Override + public void registerItemsAndBlocks() { + items = new ItemRegistryBook(); + } + + @Override + public void preInit() { + proxy.preInit(); + MinecraftForge.EVENT_BUS.register(new EventHandlerBook()); + } + + @Override + public void registerRecipes() { + RecipeUtil.addShapelessRecipe("book_honey", new ItemStack(getItems().book), Items.BOOK, OreDictUtil.DROP_HONEY); + RecipeUtil.addShapelessRecipe("book_tree", new ItemStack(getItems().book), Items.BOOK, OreDictUtil.TREE_SAPLING); + if (ModuleHelper.isEnabled(ForestryModuleUids.LEPIDOPTEROLOGY)) { + ItemRegistryLepidopterology itemsLepi = ModuleLepidopterology.getItems(); + RecipeUtil.addShapelessRecipe("book_butterfly", new ItemStack(getItems().book), Items.BOOK, itemsLepi.butterflyGE); + } + } + + @Override + public void postInit() { + ModuleManager.getInternalHandler().runBookInit(); + } +} diff --git a/src/main/java/forestry/book/data/CraftingData.java b/src/main/java/forestry/book/data/CraftingData.java new file mode 100644 index 000000000..df7ab6d8c --- /dev/null +++ b/src/main/java/forestry/book/data/CraftingData.java @@ -0,0 +1,19 @@ +package forestry.book.data; + +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; + +public class CraftingData { + /** + * The {@link ResourceLocation}s of the recipes of this crafting data. + */ + public ResourceLocation[] locations = new ResourceLocation[0]; + /** + * The result stack of the recipes of this crafting data. + */ + public ItemStack stack = ItemStack.EMPTY; + /** + * The result stacks of the recipes of this crafting data. + */ + public ItemStack[] stacks = new ItemStack[0]; +} diff --git a/src/main/java/forestry/book/data/EntryData.java b/src/main/java/forestry/book/data/EntryData.java new file mode 100644 index 000000000..6a4434599 --- /dev/null +++ b/src/main/java/forestry/book/data/EntryData.java @@ -0,0 +1,31 @@ +package forestry.book.data; + +import net.minecraft.item.ItemStack; + +import forestry.api.book.BookContent; + +public class EntryData { + /** + * The localized title of the entry. + */ + public String title = ""; + /** + * The content that gets displayed on the pages of the entry. + */ + public BookContent[][] content = new BookContent[0][0]; + /** + * All sub entries of this entry. + */ + public String[] subEntries = new String[0]; + /** + * The name of the page factory. + */ + public String loader; + /** + * The item that will be displayed next to the title. + */ + public ItemStack icon = ItemStack.EMPTY; + + public EntryData() { + } +} diff --git a/src/main/java/forestry/book/data/IndexData.java b/src/main/java/forestry/book/data/IndexData.java new file mode 100644 index 000000000..c30d20a11 --- /dev/null +++ b/src/main/java/forestry/book/data/IndexData.java @@ -0,0 +1,8 @@ +package forestry.book.data; + +public class IndexData { + /** + * All entries of this index. + */ + public IndexEntry[] entries = new IndexEntry[0]; +} diff --git a/src/main/java/forestry/book/data/IndexEntry.java b/src/main/java/forestry/book/data/IndexEntry.java new file mode 100644 index 000000000..95a69b406 --- /dev/null +++ b/src/main/java/forestry/book/data/IndexEntry.java @@ -0,0 +1,15 @@ +package forestry.book.data; + +/** + * A entry of an index. + */ +public class IndexEntry { + /** + * The localized name of the entry. + */ + public String title; + /** + * The page that a mouse click on this entry opens. + */ + public int page; +} diff --git a/src/main/java/forestry/book/data/TextData.java b/src/main/java/forestry/book/data/TextData.java new file mode 100644 index 000000000..52e707f1b --- /dev/null +++ b/src/main/java/forestry/book/data/TextData.java @@ -0,0 +1,25 @@ +package forestry.book.data; + +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +@SideOnly(Side.CLIENT) +public class TextData { + public String text = ""; + + public String color = "black"; + public boolean bold = false; + public boolean italic = false; + public boolean underlined = false; + public boolean strikethrough = false; + public boolean obfuscated = false; + public boolean paragraph = false; + public boolean dropshadow = false; + + public TextData() { + } + + public TextData(String text) { + this.text = text; + } +} diff --git a/src/main/java/forestry/book/data/content/CarpenterContent.java b/src/main/java/forestry/book/data/content/CarpenterContent.java new file mode 100644 index 000000000..9227cf760 --- /dev/null +++ b/src/main/java/forestry/book/data/content/CarpenterContent.java @@ -0,0 +1,35 @@ +package forestry.book.data.content; + +import javax.annotation.Nullable; + +import forestry.api.book.BookContent; +import forestry.api.gui.IElementGroup; +import forestry.api.gui.IGuiElement; +import forestry.api.gui.IGuiElementFactory; +import forestry.book.data.CraftingData; +import forestry.book.gui.elements.CarpenterElement; + +/** + * A book content that displays a carpenter recipe. + */ +public class CarpenterContent extends BookContent { + + @Nullable + @Override + public Class getDataClass() { + return CraftingData.class; + } + + @Override + public boolean addElements(IElementGroup page, IGuiElementFactory factory, @Nullable BookContent previous, @Nullable IGuiElement previousElement, int pageHeight) { + if (data == null || (data.stack.isEmpty() && data.stacks.length == 0)) { + return false; + } + if (!data.stack.isEmpty()) { + page.add(new CarpenterElement(0, 0, data.stack)); + } else { + page.add(new CarpenterElement(0, 0, data.stacks)); + } + return true; + } +} diff --git a/src/main/java/forestry/book/data/content/CraftingContent.java b/src/main/java/forestry/book/data/content/CraftingContent.java new file mode 100644 index 000000000..9a7a90f8e --- /dev/null +++ b/src/main/java/forestry/book/data/content/CraftingContent.java @@ -0,0 +1,43 @@ +package forestry.book.data.content; + +import javax.annotation.Nullable; +import java.util.LinkedList; +import java.util.List; + +import net.minecraft.item.crafting.IRecipe; +import net.minecraft.util.ResourceLocation; + +import net.minecraftforge.fml.common.registry.ForgeRegistries; + +import forestry.api.book.BookContent; +import forestry.api.gui.IElementGroup; +import forestry.api.gui.IGuiElement; +import forestry.api.gui.IGuiElementFactory; +import forestry.book.data.CraftingData; +import forestry.book.gui.elements.CraftingElement; + +/** + * A book content that displays one ore more crafting recipes. + */ +public class CraftingContent extends BookContent { + @Override + public Class getDataClass() { + return CraftingData.class; + } + + @Override + public boolean addElements(IElementGroup page, IGuiElementFactory factory, @Nullable BookContent previous, @Nullable IGuiElement previousElement, int pageHeight) { + if (data == null || data.locations.length == 0) { + return false; + } + List recipes = new LinkedList<>(); + for (ResourceLocation location : data.locations) { + IRecipe recipe = ForgeRegistries.RECIPES.getValue(location); + if (recipe != null) { + recipes.add(recipe); + } + } + page.add(new CraftingElement(0, 0, recipes.toArray(new IRecipe[0]))); + return true; + } +} diff --git a/src/main/java/forestry/book/data/content/FabricatorContent.java b/src/main/java/forestry/book/data/content/FabricatorContent.java new file mode 100644 index 000000000..74f246804 --- /dev/null +++ b/src/main/java/forestry/book/data/content/FabricatorContent.java @@ -0,0 +1,51 @@ +package forestry.book.data.content; + +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import net.minecraftforge.fluids.Fluid; + +import forestry.api.book.BookContent; +import forestry.api.gui.IElementGroup; +import forestry.api.gui.IGuiElement; +import forestry.api.gui.IGuiElementFactory; +import forestry.api.recipes.IFabricatorSmeltingRecipe; +import forestry.book.data.CraftingData; +import forestry.book.gui.elements.FabricatorElement; +import forestry.factory.recipes.FabricatorSmeltingRecipeManager; + +public class FabricatorContent extends BookContent { + + @Override + public Class getDataClass() { + return CraftingData.class; + } + + @Override + public boolean addElements(IElementGroup page, IGuiElementFactory factory, @Nullable BookContent previous, @Nullable IGuiElement previousElement, int pageHeight) { + if (data == null || (data.stack.isEmpty() && data.stacks.length == 0)) { + return false; + } + if (!data.stack.isEmpty()) { + page.add(new FabricatorElement(0, 0, data.stack)); + } else { + page.add(new FabricatorElement(0, 0, data.stacks)); + } + return true; + } + + private static Map> getSmeltingInputs() { + Map> smeltingInputs = new HashMap<>(); + for (IFabricatorSmeltingRecipe smelting : FabricatorSmeltingRecipeManager.recipes) { + Fluid fluid = smelting.getProduct().getFluid(); + if (!smeltingInputs.containsKey(fluid)) { + smeltingInputs.put(fluid, new ArrayList<>()); + } + smeltingInputs.get(fluid).add(smelting); + } + return smeltingInputs; + } +} diff --git a/src/main/java/forestry/book/data/content/ImageContent.java b/src/main/java/forestry/book/data/content/ImageContent.java new file mode 100644 index 000000000..8283fa43f --- /dev/null +++ b/src/main/java/forestry/book/data/content/ImageContent.java @@ -0,0 +1,41 @@ +package forestry.book.data.content; + +import javax.annotation.Nullable; + +import forestry.api.book.BookContent; +import forestry.api.gui.GuiElementAlignment; +import forestry.api.gui.IElementGroup; +import forestry.api.gui.IGuiElement; +import forestry.api.gui.IGuiElementFactory; +import forestry.core.gui.Drawable; +import forestry.core.gui.elements.DrawableElement; + +/** + * A book content that displays a image. + */ +public class ImageContent extends BookContent { + //The size fo the gui element. + private int width; + private int height; + //Centers the element between the end of the page and the last element + private boolean center; + + @Override + public Class getDataClass() { + return Drawable.class; + } + + @Override + public boolean addElements(IElementGroup page, IGuiElementFactory factory, @Nullable BookContent previous, @Nullable IGuiElement previousElement, int pageHeight) { + if (data == null) { + return false; + } + if (center) { + page.panel(page.getWidth(), pageHeight - page.getHeight()) + .add(new DrawableElement(0, 0, width, height, data)).setAlign(GuiElementAlignment.MIDDLE_CENTER); + } else { + page.add(new DrawableElement(0, 0, width, height, data)).setAlign(GuiElementAlignment.TOP_CENTER); + } + return true; + } +} diff --git a/src/main/java/forestry/book/data/content/IndexContent.java b/src/main/java/forestry/book/data/content/IndexContent.java new file mode 100644 index 000000000..eca6b3584 --- /dev/null +++ b/src/main/java/forestry/book/data/content/IndexContent.java @@ -0,0 +1,30 @@ +package forestry.book.data.content; + +import javax.annotation.Nullable; + +import forestry.api.book.BookContent; +import forestry.api.gui.IElementGroup; +import forestry.api.gui.IGuiElement; +import forestry.api.gui.IGuiElementFactory; +import forestry.book.data.IndexData; +import forestry.book.gui.elements.IndexElement; + +/** + * A book + */ +public class IndexContent extends BookContent { + @Nullable + @Override + public Class getDataClass() { + return IndexData.class; + } + + @Override + public boolean addElements(IElementGroup page, IGuiElementFactory factory, @Nullable BookContent previous, @Nullable IGuiElement previousElement, int pageHeight) { + if (data == null || data.entries.length <= 0) { + return false; + } + page.add(new IndexElement(0, 0, data.entries)); + return true; + } +} diff --git a/src/main/java/forestry/book/data/content/MutationContent.java b/src/main/java/forestry/book/data/content/MutationContent.java new file mode 100644 index 000000000..f0a3561ca --- /dev/null +++ b/src/main/java/forestry/book/data/content/MutationContent.java @@ -0,0 +1,39 @@ +package forestry.book.data.content; + +import javax.annotation.Nullable; + +import forestry.api.book.BookContent; +import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.IAllele; +import forestry.api.genetics.IAlleleSpecies; +import forestry.api.genetics.IMutation; +import forestry.api.genetics.ISpeciesRoot; +import forestry.api.gui.IElementGroup; +import forestry.api.gui.IGuiElement; +import forestry.api.gui.IGuiElementFactory; +import forestry.book.gui.elements.MutationElement; + +/** + * A book content that displays one or more mutations. + */ +public class MutationContent extends BookContent { + public String species = ""; + + @Nullable + @Override + public Class getDataClass() { + return null; + } + + @Override + public boolean addElements(IElementGroup page, IGuiElementFactory factory, @Nullable BookContent previous, @Nullable IGuiElement previousElement, int pageHeight) { + IAllele allele = AlleleManager.alleleRegistry.getAllele(species); + if (!(allele instanceof IAlleleSpecies)) { + return false; + } + IAlleleSpecies s = (IAlleleSpecies) allele; + ISpeciesRoot root = s.getRoot(); + page.add(new MutationElement(0, 0, root.getResultantMutations(s).toArray(new IMutation[0]))); + return true; + } +} diff --git a/src/main/java/forestry/book/data/content/StructureContent.java b/src/main/java/forestry/book/data/content/StructureContent.java new file mode 100644 index 000000000..79f473941 --- /dev/null +++ b/src/main/java/forestry/book/data/content/StructureContent.java @@ -0,0 +1,113 @@ +/******************************************************************************* + * The MIT License (MIT) + * Copyright (c) 2013-2014 Slime Knights (mDiyo, fuj1n, Sunstrike, progwml6, pillbox, alexbegt) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * Any alternate licenses are noted where appropriate. + ******************************************************************************/ +package forestry.book.data.content; + +import javax.annotation.Nullable; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; + +import org.apache.commons.io.IOUtils; + +import net.minecraft.client.resources.IResource; +import net.minecraft.util.ResourceLocation; + +import forestry.api.book.BookContent; +import forestry.api.gui.IElementGroup; +import forestry.api.gui.IGuiElement; +import forestry.api.gui.IGuiElementFactory; +import forestry.book.BookLoader; +import forestry.book.data.structure.BlockData; +import forestry.book.data.structure.StructureData; +import forestry.book.gui.elements.MultiblockElement; +import forestry.core.utils.Log; +import forestry.core.utils.ResourceUtil; + +/** + * A book content that displays a multiblock structure. + */ +public class StructureContent extends BookContent { + @Nullable + private String structureFile = null; + private transient StructureData structureData; + + @Nullable + @Override + public Class getDataClass() { + return null; + } + + @Override + public void onDeserialization() { + if (structureFile == null || structureFile.isEmpty()) { + return; + } + + ResourceLocation location = BookLoader.getResourceLocation(structureFile); + + if (location != null && ResourceUtil.resourceExists(location)) { + IResource resource = ResourceUtil.getResource(location); + if (resource == null) { + return; + } + try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))) { + structureData = BookLoader.GSON.fromJson(reader, StructureData.class); + } catch (IOException e) { + Log.error("Failed to load structure file {}.{}", location, e); + } finally { + IOUtils.closeQuietly(resource); + } + } + } + + @Override + public boolean addElements(IElementGroup page, IGuiElementFactory factory, @Nullable BookContent previous, @Nullable IGuiElement previousElement, int pageHeight) { + if (structureFile == null) { + return false; + } + + int offset = 0; + int structureSizeX = page.getWidth(); + int structureSizeY = 155 - 10; + + int[] size = structureData.size; + BlockData[] structure = structureData.structure; + + if (size.length == 3 && structure.length > 0) { + boolean showButtons = size[1] > 1; + if (showButtons) { + //structureSizeX -= GuiArrow.ArrowType.REFRESH.w; + } + MultiblockElement elementStructure = new MultiblockElement(offset, 0, structureSizeX, structureSizeY, size, structure); + page.add(elementStructure); + + /*if(showButtons) { + int col = book.appearance.structureButtonColor; + int colHover = book.appearance.structureButtonColorHovered; + int colToggled = book.appearance.structureButtonColorToggled; + + int midY = y + structureSizeY / 2 - (GuiArrow.ArrowType.UP.h + GuiArrow.ArrowType.DOWN.h) / 2; + + int dx = (GuiArrow.ArrowType.REFRESH.w - GuiArrow.ArrowType.UP.w) / 2; + + //list.add(new ElementArrow(ElementStructure.BUTTON_ID_LAYER_UP, elementStructure, structureSizeX + offset + dx, midY, GuiArrow.ArrowType.UP, col, colHover)); + //midY += GuiArrow.ArrowType.UP.h + 2; + //list.add(new ElementArrow(ElementStructure.BUTTON_ID_LAYER_DOWN, elementStructure, structureSizeX + offset + dx, midY, GuiArrow.ArrowType.DOWN, col, colHover)); + + list.add(new ElementAnimationToggle(ElementStructure.BUTTON_ID_ANIMATE, elementStructure, GuiBook.PAGE_WIDTH - GuiArrow.ArrowType.REFRESH.w, 0, GuiArrow.ArrowType.REFRESH, col, colHover, colToggled)); + }*/ + } + return true; + } +} diff --git a/src/main/java/forestry/book/data/content/TextContent.java b/src/main/java/forestry/book/data/content/TextContent.java new file mode 100644 index 000000000..916adffb9 --- /dev/null +++ b/src/main/java/forestry/book/data/content/TextContent.java @@ -0,0 +1,36 @@ +package forestry.book.data.content; + +import javax.annotation.Nullable; + +import forestry.api.book.BookContent; +import forestry.api.gui.IElementGroup; +import forestry.api.gui.IGuiElement; +import forestry.api.gui.IGuiElementFactory; +import forestry.book.data.TextData; +import forestry.book.gui.elements.TextDataElement; + +/** + * A book content that displays one or more texts. + */ +public class TextContent extends BookContent { + @Override + public Class getDataClass() { + return TextData.class; + } + + @Override + public boolean addElements(IElementGroup page, IGuiElementFactory factory, @Nullable BookContent previous, @Nullable IGuiElement previousElement, int pageHeight) { + if (data == null) { + return false; + } + TextDataElement element; + if (previousElement instanceof TextDataElement) { + element = (TextDataElement) previousElement; + } else { + element = new TextDataElement(0, 0, page.getWidth(), 0); + page.add(element); + } + element.addData(data); + return true; + } +} diff --git a/src/main/java/forestry/book/data/content/package-info.java b/src/main/java/forestry/book/data/content/package-info.java new file mode 100644 index 000000000..ec05b9b2c --- /dev/null +++ b/src/main/java/forestry/book/data/content/package-info.java @@ -0,0 +1,10 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.book.data.content; + +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/book/data/deserializer/BookCategoryDeserializer.java b/src/main/java/forestry/book/data/deserializer/BookCategoryDeserializer.java new file mode 100644 index 000000000..1fac2ad3f --- /dev/null +++ b/src/main/java/forestry/book/data/deserializer/BookCategoryDeserializer.java @@ -0,0 +1,26 @@ +package forestry.book.data.deserializer; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.lang.reflect.Type; + +import net.minecraft.item.ItemStack; +import net.minecraft.util.JsonUtils; + +import forestry.book.BookCategory; +import forestry.core.utils.JsonUtil; + +public class BookCategoryDeserializer implements JsonDeserializer { + @Override + public BookCategory deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { + JsonObject object = json.getAsJsonObject(); + String name = JsonUtils.getString(object, "name"); + ItemStack stack = JsonUtil.deserializeItemStack(JsonUtils.getJsonObject(object, "icon")); + BookCategory category = new BookCategory(name); + category.setStack(stack); + return category; + } +} diff --git a/src/main/java/forestry/book/data/deserializer/BookContentDeserializer.java b/src/main/java/forestry/book/data/deserializer/BookContentDeserializer.java new file mode 100644 index 000000000..347c53a2e --- /dev/null +++ b/src/main/java/forestry/book/data/deserializer/BookContentDeserializer.java @@ -0,0 +1,30 @@ +package forestry.book.data.deserializer; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.lang.reflect.Type; + +import net.minecraft.util.JsonUtils; + +import forestry.api.book.BookContent; +import forestry.book.BookLoader; +import forestry.book.data.content.TextContent; + +public class BookContentDeserializer implements JsonDeserializer { + @Override + public BookContent deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { + JsonObject object = json.getAsJsonObject(); + String type = JsonUtils.getString(object, "type", "text"); + Class typeClass = BookLoader.INSTANCE.getContentType(type); + BookContent content = context.deserialize(object, typeClass == null ? TextContent.class : typeClass); + content.type = type; + if (content.getDataClass() != null) { + content.data = context.deserialize(object, content.getDataClass()); + } + content.onDeserialization(); + return content; + } +} diff --git a/src/main/java/forestry/book/data/deserializer/package-info.java b/src/main/java/forestry/book/data/deserializer/package-info.java new file mode 100644 index 000000000..94db3ce9f --- /dev/null +++ b/src/main/java/forestry/book/data/deserializer/package-info.java @@ -0,0 +1,10 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.book.data.deserializer; + +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/book/data/package-info.java b/src/main/java/forestry/book/data/package-info.java new file mode 100644 index 000000000..a808229cb --- /dev/null +++ b/src/main/java/forestry/book/data/package-info.java @@ -0,0 +1,10 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.book.data; + +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/book/data/structure/BlockData.java b/src/main/java/forestry/book/data/structure/BlockData.java new file mode 100644 index 000000000..dadfa58e5 --- /dev/null +++ b/src/main/java/forestry/book/data/structure/BlockData.java @@ -0,0 +1,26 @@ +/******************************************************************************* + * The MIT License (MIT) + * Copyright (c) 2013-2014 Slime Knights (mDiyo, fuj1n, Sunstrike, progwml6, pillbox, alexbegt) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * Any alternate licenses are noted where appropriate. + ******************************************************************************/ +package forestry.book.data.structure; + +import com.google.gson.JsonObject; + +import java.util.Map; + +public class BlockData { + public int[] pos; + public int[] endPos; + public String block; + public byte meta; + public JsonObject nbt; + public Map state; +} diff --git a/src/main/java/forestry/book/data/structure/StructureBlockAccess.java b/src/main/java/forestry/book/data/structure/StructureBlockAccess.java new file mode 100644 index 000000000..88d4d439a --- /dev/null +++ b/src/main/java/forestry/book/data/structure/StructureBlockAccess.java @@ -0,0 +1,91 @@ +/******************************************************************************* + * The MIT License (MIT) + * Copyright (c) 2013-2014 Slime Knights (mDiyo, fuj1n, Sunstrike, progwml6, pillbox, alexbegt) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * Any alternate licenses are noted where appropriate. + ******************************************************************************/ +package forestry.book.data.structure; + +import javax.annotation.Nullable; + +import net.minecraft.block.state.IBlockState; +import net.minecraft.init.Blocks; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.WorldType; +import net.minecraft.world.biome.Biome; + +public class StructureBlockAccess implements IBlockAccess { + + private final StructureInfo data; + private final IBlockState[][][] structure; + + public StructureBlockAccess(StructureInfo data) { + this.data = data; + this.structure = data.data; + } + + @Nullable + @Override + public TileEntity getTileEntity(BlockPos pos) { + return null; + } + + @Override + public int getCombinedLight(BlockPos pos, int lightValue) { + // full brightness always + return 15 << 20 | 15 << 4; + } + + @Override + public IBlockState getBlockState(BlockPos pos) { + int x = pos.getX(); + int y = pos.getY(); + int z = pos.getZ(); + + if (y >= 0 && y < structure.length) { + if (x >= 0 && x < structure[y].length) { + if (z >= 0 && z < structure[y][x].length) { + int index = y * (data.structureLength * data.structureWidth) + x * data.structureWidth + z; + if (index <= data.getLimiter()) { + return structure[y][x][z] != null ? structure[y][x][z] : Blocks.AIR.getDefaultState(); + } + } + } + } + return Blocks.AIR.getDefaultState(); + } + + @Override + public boolean isAirBlock(BlockPos pos) { + return getBlockState(pos).getBlock() == Blocks.AIR; + } + + @Override + public Biome getBiome(BlockPos pos) { + return null; + } + + @Override + public int getStrongPower(BlockPos pos, EnumFacing direction) { + return 0; + } + + @Override + public WorldType getWorldType() { + return null; + } + + @Override + public boolean isSideSolid(BlockPos pos, EnumFacing side, boolean _default) { + return false; + } +} diff --git a/src/main/java/forestry/book/data/structure/StructureData.java b/src/main/java/forestry/book/data/structure/StructureData.java new file mode 100644 index 000000000..4b432f800 --- /dev/null +++ b/src/main/java/forestry/book/data/structure/StructureData.java @@ -0,0 +1,9 @@ +package forestry.book.data.structure; + +public class StructureData { + public int[] size = new int[0]; + public BlockData[] structure = new BlockData[0]; + + public StructureData() { + } +} diff --git a/src/main/java/forestry/book/data/structure/StructureInfo.java b/src/main/java/forestry/book/data/structure/StructureInfo.java new file mode 100644 index 000000000..80b8af976 --- /dev/null +++ b/src/main/java/forestry/book/data/structure/StructureInfo.java @@ -0,0 +1,141 @@ +/******************************************************************************* + * The MIT License (MIT) + * Copyright (c) 2013-2014 Slime Knights (mDiyo, fuj1n, Sunstrike, progwml6, pillbox, alexbegt) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * Any alternate licenses are noted where appropriate. + ******************************************************************************/ +package forestry.book.data.structure; + +import java.util.Map; +import java.util.Optional; + +import net.minecraft.block.Block; +import net.minecraft.block.properties.IProperty; +import net.minecraft.block.state.IBlockState; +import net.minecraft.init.Blocks; + +public class StructureInfo { + public IBlockState[][][] data; + public int blockCount = 0; + public int[] countPerLevel; + public int structureHeight = 0; + public int structureLength = 0; + public int structureWidth = 0; + public int showLayer = -1; + + private int blockIndex = 0; + private int maxBlockIndex; + + public StructureInfo(int length, int height, int width, BlockData[] blockData) { + this.structureWidth = width; + this.structureHeight = height; + this.structureLength = length; + IBlockState[][][] states = new IBlockState[height][length][width]; + + for (int y = 0; y < height; y++) { + for (int x = 0; x < length; x++) { + for (int z = 0; z < width; z++) { + for (BlockData data : blockData) { + if (inside(x, y, z, data.pos, data.endPos)) { + states[y][x][z] = convert(data); + break; + } + } + } + } + } + + data = states; + maxBlockIndex = blockIndex = structureHeight * structureLength * structureWidth; + } + + private IBlockState convert(BlockData data) { + Block block = Block.getBlockFromName(data.block); + if (block == null) { + return Blocks.AIR.getDefaultState(); + } + IBlockState state; + if (data.state == null || data.state.isEmpty()) { + state = block.getStateFromMeta(data.meta); + } else { + state = block.getDefaultState(); + + for (Map.Entry entry : data.state.entrySet()) { + Optional> property = state.getPropertyKeys().stream().filter(iProperty -> entry.getKey().equals(iProperty.getName())).findFirst(); + + if (property.isPresent()) { + state = setProperty(state, property.get(), entry.getValue()); + } + } + } + return state; + } + + private > IBlockState setProperty(IBlockState state, IProperty prop, String valueString) { + com.google.common.base.Optional value = prop.parseValue(valueString); + if (value.isPresent()) { + state = state.withProperty(prop, value.get()); + } + return state; + } + + + private boolean inside(int x, int y, int z, int[] rangeStart, int[] rangeEnd) { + if (x >= rangeStart[0] && x <= rangeEnd[0]) { + if (y >= rangeStart[1] && y <= rangeEnd[1]) { + if (z >= rangeStart[2] && z <= rangeEnd[2]) { + return true; + } + } + } + + return false; + } + + public void setShowLayer(int layer) { + showLayer = layer; + blockIndex = (layer + 1) * (structureLength * structureWidth) - 1; + } + + public void reset() { + blockIndex = maxBlockIndex; + } + + public boolean canStep() { + int index = blockIndex; + do { + if (++index >= maxBlockIndex) { + return false; + } + } while (isEmpty(index)); + return true; + } + + public void step() { + int start = blockIndex; + do { + if (++blockIndex >= maxBlockIndex) { + blockIndex = 0; + } + } while (isEmpty(blockIndex) && blockIndex != start); + } + + private boolean isEmpty(int index) { + int y = index / (structureLength * structureWidth); + int r = index % (structureLength * structureWidth); + int x = r / structureWidth; + int z = r % structureWidth; + + return data[y][x][z] == null || data[y][x][z].getBlock() == Blocks.AIR; + } + + public int getLimiter() { + return blockIndex; + } +} diff --git a/src/main/java/forestry/book/data/structure/package-info.java b/src/main/java/forestry/book/data/structure/package-info.java new file mode 100644 index 000000000..935306c10 --- /dev/null +++ b/src/main/java/forestry/book/data/structure/package-info.java @@ -0,0 +1,10 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.book.data.structure; + +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/book/gui/GuiForesterBook.java b/src/main/java/forestry/book/gui/GuiForesterBook.java new file mode 100644 index 000000000..812813e99 --- /dev/null +++ b/src/main/java/forestry/book/gui/GuiForesterBook.java @@ -0,0 +1,174 @@ +package forestry.book.gui; + +import javax.annotation.Nullable; +import java.io.IOException; +import java.util.Collections; +import java.util.List; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.gui.ScaledResolution; +import net.minecraft.client.renderer.texture.TextureManager; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.text.TextFormatting; + +import net.minecraftforge.fml.client.config.GuiUtils; + +import forestry.api.book.IForesterBook; +import forestry.book.gui.buttons.GuiButtonBack; +import forestry.book.gui.buttons.GuiButtonPage; +import forestry.core.config.Constants; +import forestry.core.gui.GuiUtil; +import forestry.core.gui.IGuiSizable; +import forestry.core.gui.elements.ElementManager; + +public abstract class GuiForesterBook extends GuiScreen implements IGuiSizable { + public static final ResourceLocation TEXTURE = new ResourceLocation(Constants.MOD_ID, Constants.TEXTURE_PATH_GUI + "/almanac/almanac.png"); + static final int LEFT_PAGE_START_X = 16; + static final int RIGHT_PAGE_START_X = 132; + static final int PAGE_START_Y = 12; + static final int LEFT_PAGE_START_Y = 25; + static final int RIGHT_PAGE_START_Y = PAGE_START_Y; + public static final int PAGE_WIDTH = 108; + public static final int PAGE_HEIGHT = 155; + + private static final int X_SIZE = 256; + private static final int Y_SIZE = 181; + @Nullable + public static GuiForesterBook guiScreen; + protected final IForesterBook book; + final ElementManager elementManager; + + protected int guiLeft; + protected int guiTop; + + protected GuiForesterBook(IForesterBook book) { + this.book = book; + setGuiScreen(this); + this.elementManager = new ElementManager<>(this); + } + + @Override + public void initGui() { + super.initGui(); + this.guiLeft = (this.width - X_SIZE) / 2; + this.guiTop = (this.height - Y_SIZE) / 2; + elementManager.init(guiLeft, guiTop); + this.buttonList.clear(); + if (hasButtons()) { + GuiButtonPage leftButton = addButton(new GuiButtonPage(0, guiLeft + 24, guiTop + Y_SIZE - 20, true)); + GuiButtonPage rightButton = addButton(new GuiButtonPage(1, guiLeft + X_SIZE - 44, guiTop + Y_SIZE - 20, false)); + GuiButtonBack backButton = addButton(new GuiButtonBack(2, guiLeft + X_SIZE / 2 - 12, guiTop + Y_SIZE - 20)); + initButtons(leftButton, rightButton, backButton); + } + } + + protected boolean hasButtons() { + return true; + } + + protected void initButtons(GuiButtonPage leftButton, GuiButtonPage rightButton, GuiButtonBack backButton) { + } + + @Override + public boolean doesGuiPauseGame() { + return false; + } + + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + TextureManager manager = mc.renderEngine; + + manager.bindTexture(TEXTURE); + drawTexturedModalRect(guiLeft, guiTop, 0, 0, X_SIZE, Y_SIZE); + + super.drawScreen(mouseX, mouseY, partialTicks); + + boolean unicode = fontRenderer.getUnicodeFlag(); + fontRenderer.setUnicodeFlag(true); + drawCenteredString(fontRenderer, TextFormatting.UNDERLINE + getTitle(), guiLeft + LEFT_PAGE_START_X + 52, guiTop + PAGE_START_Y, 0xD3D3D3); + + drawText(); + + fontRenderer.setUnicodeFlag(unicode); + + elementManager.draw(mouseX, mouseY); + + InventoryPlayer playerInv = mc.player.inventory; + + if (playerInv.getItemStack().isEmpty()) { + GuiUtil.drawToolTips(this, buttonList, mouseX, mouseY); + elementManager.drawTooltip(mouseX, mouseY); + List tooltip = getTooltip(mouseX, mouseY); + if (!tooltip.isEmpty()) { + ScaledResolution scaledresolution = new ScaledResolution(mc); + GuiUtils.drawHoveringText(tooltip, mouseX, mouseY, scaledresolution.getScaledWidth(), scaledresolution.getScaledHeight(), -1, fontRenderer); + } + } + } + + protected void drawText() { + } + + protected List getTooltip(int mouseX, int mouseY) { + return Collections.emptyList(); + } + + protected abstract String getTitle(); + + @Override + protected void keyTyped(char typedChar, int keyCode) throws IOException { + if (elementManager.keyTyped(typedChar, keyCode)) { + return; + } + super.keyTyped(typedChar, keyCode); + } + + @Override + protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { + super.mouseClicked(mouseX, mouseY, mouseButton); + elementManager.mouseClicked(mouseX, mouseY, mouseButton); + } + + @Override + protected void mouseClickMove(int mouseX, int mouseY, int clickedMouseButton, long timeSinceLastClick) { + super.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick); + elementManager.mouseClickMove(mouseX, mouseY, clickedMouseButton); + } + + @Override + protected void mouseReleased(int mouseX, int mouseY, int state) { + super.mouseReleased(mouseX, mouseY, state); + elementManager.mouseReleased(mouseX, mouseY, state); + } + + @Override + public int getGuiLeft() { + return guiLeft; + } + + @Override + public int getGuiTop() { + return guiTop; + } + + @Override + public int getSizeX() { + return X_SIZE; + } + + @Override + public int getSizeY() { + return Y_SIZE; + } + + @Override + public Minecraft getMC() { + return mc; + } + + public static void setGuiScreen(@Nullable GuiForesterBook guiScreen) { + GuiForesterBook.guiScreen = guiScreen; + } +} diff --git a/src/main/java/forestry/book/gui/GuiForestryBookCategories.java b/src/main/java/forestry/book/gui/GuiForestryBookCategories.java new file mode 100644 index 000000000..4608fb1ea --- /dev/null +++ b/src/main/java/forestry/book/gui/GuiForestryBookCategories.java @@ -0,0 +1,67 @@ +package forestry.book.gui; + +import java.io.IOException; + +import net.minecraft.client.gui.GuiButton; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.text.TextFormatting; + +import forestry.api.book.IBookCategory; +import forestry.api.book.IForesterBook; +import forestry.book.gui.buttons.GuiButtonBookCategory; +import forestry.core.config.Constants; +import forestry.core.gui.Drawable; +import forestry.core.utils.Translator; + +public class GuiForestryBookCategories extends GuiForesterBook { + public static final Drawable LOGO = new Drawable(new ResourceLocation(Constants.MOD_ID, "textures/gui/almanac/logo.png"), 0, 0, 256, 58, 256, 58); + + public GuiForestryBookCategories(IForesterBook book) { + super(book); + } + + @Override + public void initGui() { + super.initGui(); + int x = 0; + int y = 0; + for (IBookCategory category : book.getCategories()) { + if (category.getEntries().isEmpty()) { + continue; + } + buttonList.add(new GuiButtonBookCategory(y * 3 + x, guiLeft + LEFT_PAGE_START_X + x * 36, guiTop + 25 + y * 36, category)); + x++; + if (x == 3) { + y++; + x = 0; + } + } + } + + @Override + protected boolean hasButtons() { + return false; + } + + @Override + protected void drawText() { + drawCenteredString(fontRenderer, TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.book.about.title"), guiLeft + RIGHT_PAGE_START_X + 52, guiTop + PAGE_START_Y, 0xD3D3D3); + String about = Translator.translateToLocal("for.gui.book.about"); + fontRenderer.drawSplitString(about, guiLeft + RIGHT_PAGE_START_X, guiTop + LEFT_PAGE_START_Y, 108, 0); + fontRenderer.drawString(Translator.translateToLocal("for.gui.book.about.author"), guiLeft + RIGHT_PAGE_START_X, guiTop + LEFT_PAGE_START_Y + fontRenderer.getWordWrappedHeight(about, 108), 0); + LOGO.draw(guiLeft + RIGHT_PAGE_START_X, guiTop + LEFT_PAGE_START_Y + 110, 108, 24); + } + + @Override + protected void actionPerformed(GuiButton button) throws IOException { + if (button instanceof GuiButtonBookCategory) { + GuiButtonBookCategory buttonCategory = (GuiButtonBookCategory) button; + mc.displayGuiScreen(new GuiForestryBookEntries(book, buttonCategory.category)); + } + } + + @Override + protected String getTitle() { + return Translator.translateToLocal("for.gui.book.categories"); + } +} diff --git a/src/main/java/forestry/book/gui/GuiForestryBookEntries.java b/src/main/java/forestry/book/gui/GuiForestryBookEntries.java new file mode 100644 index 000000000..7bf6e4571 --- /dev/null +++ b/src/main/java/forestry/book/gui/GuiForestryBookEntries.java @@ -0,0 +1,84 @@ +package forestry.book.gui; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.client.gui.GuiButton; + +import forestry.api.book.IBookCategory; +import forestry.api.book.IBookEntry; +import forestry.api.book.IForesterBook; +import forestry.book.gui.buttons.GuiButtonBack; +import forestry.book.gui.buttons.GuiButtonEntry; +import forestry.book.gui.buttons.GuiButtonPage; + +public class GuiForestryBookEntries extends GuiForesterBook { + private final IBookCategory category; + private int entryIndex = 0; + + public GuiForestryBookEntries(IForesterBook book, IBookCategory category) { + super(book); + this.category = category; + } + + @Override + public void initGui() { + super.initGui(); + int offset = entryIndex * 24; + int yOffset = 0; + List entries = new ArrayList<>(category.getEntries()); + for (IBookEntry entry : entries.subList(offset, entries.size() > offset + 12 ? offset + 12 : entries.size())) { + addButton(new GuiButtonEntry(yOffset, guiLeft + LEFT_PAGE_START_X, guiTop + LEFT_PAGE_START_Y + yOffset * (fontRenderer.FONT_HEIGHT + 2), entry)); + yOffset++; + } + offset += 12; + yOffset = 0; + if (entries.size() > offset) { + for (IBookEntry entry : entries.subList(offset, entries.size() > offset + 12 ? offset + 12 : entries.size())) { + addButton(new GuiButtonEntry(yOffset, guiLeft + RIGHT_PAGE_START_X, guiTop + LEFT_PAGE_START_Y + yOffset * (fontRenderer.FONT_HEIGHT + 2), entry)); + yOffset++; + } + } + elementManager.init(guiLeft, guiTop); + elementManager.clear(); + } + + @Override + protected void initButtons(GuiButtonPage leftButton, GuiButtonPage rightButton, GuiButtonBack backButton) { + leftButton.visible = entryIndex > 0; + rightButton.visible = category.getEntries().size() > (entryIndex + 1) * 24; + } + + @Override + protected void actionPerformed(GuiButton button) throws IOException { + if (button instanceof GuiButtonPage) { + GuiButtonPage pageButton = (GuiButtonPage) button; + if (pageButton.left) { + entryIndex--; + } else { + entryIndex++; + } + initGui(); + } else if (button instanceof GuiButtonBack) { + displayCategories(); + } else if (button instanceof GuiButtonEntry) { + GuiButtonEntry entry = (GuiButtonEntry) button; + mc.displayGuiScreen(new GuiForestryBookPages(book, category, entry.entry, null)); + } + } + + @Override + protected List getTooltip(int mouseX, int mouseY) { + return elementManager.getTooltip(mouseX, mouseY); + } + + private void displayCategories() { + mc.displayGuiScreen(new GuiForestryBookCategories(book)); + } + + @Override + protected String getTitle() { + return category.getLocalizedName(); + } +} diff --git a/src/main/java/forestry/book/gui/GuiForestryBookPages.java b/src/main/java/forestry/book/gui/GuiForestryBookPages.java new file mode 100644 index 000000000..ff37feb18 --- /dev/null +++ b/src/main/java/forestry/book/gui/GuiForestryBookPages.java @@ -0,0 +1,144 @@ +package forestry.book.gui; + +import com.google.common.collect.ImmutableList; + +import javax.annotation.Nullable; +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +import net.minecraft.client.gui.GuiButton; + +import forestry.api.book.IBookCategory; +import forestry.api.book.IBookEntry; +import forestry.api.book.IForesterBook; +import forestry.api.gui.IElementGroup; +import forestry.api.gui.IGuiElement; +import forestry.book.gui.buttons.GuiButtonBack; +import forestry.book.gui.buttons.GuiButtonPage; +import forestry.book.gui.buttons.GuiButtonSubEntry; +import forestry.core.gui.elements.layouts.ElementGroup; + +public class GuiForestryBookPages extends GuiForesterBook { + private final IBookCategory category; + private final IBookEntry entry; + @Nullable + private final IBookEntry parent; + private final List subButtons = new ArrayList<>(); + private List pages; + private int pageIndex = 0; + private IElementGroup leftPage; + private IElementGroup rightPage; + private int nextPage = -1; + private int lastPage = -1; + + public GuiForestryBookPages(IForesterBook book, IBookCategory category, IBookEntry entry, @Nullable IBookEntry parent) { + super(book); + this.category = category; + this.entry = entry; + this.parent = parent; + ElementGroup group = elementManager.group(); + leftPage = group.panel(LEFT_PAGE_START_X, LEFT_PAGE_START_Y, PAGE_WIDTH, PAGE_HEIGHT); + rightPage = group.panel(RIGHT_PAGE_START_X, RIGHT_PAGE_START_Y, PAGE_WIDTH, PAGE_HEIGHT); + pages = ImmutableList.copyOf(entry.getPageFactory().load(entry, GuiForesterBook.PAGE_HEIGHT - 13, GuiForesterBook.PAGE_HEIGHT, GuiForesterBook.PAGE_WIDTH)); + setPages(0); + } + + private void setPages(int index) { + leftPage.clear(); + rightPage.clear(); + if (index < 0 || index >= pages.size()) { + pageIndex = 0; + return; + } + leftPage.add(pages.get(index)); + if (pages.size() > index + 1) { + rightPage.add(pages.get(index + 1)); + } + pageIndex = index; + } + + public void switchPage(int page) { + if (page % 2 == 1) { + page -= 1; + } + this.nextPage = page; + } + + @Override + public void updateScreen() { + super.updateScreen(); + if (nextPage >= 0) { + lastPage = pageIndex; + setPages(nextPage); + nextPage = -1; + initGui(); + } + } + + @Override + protected void initButtons(GuiButtonPage leftButton, GuiButtonPage rightButton, GuiButtonBack backButton) { + leftButton.visible = pageIndex > 0; + rightButton.visible = pages.size() > (pageIndex + 2); + } + + @Override + public void initGui() { + super.initGui(); + IBookEntry firstEntry = parent != null ? parent : entry; + subButtons.add(addButton(new GuiButtonSubEntry(buttonList.size(), guiLeft + -24, guiTop + 12, firstEntry, entry))); + IBookEntry[] subEntries = firstEntry.getSubEntries(); + for (int i = 0; i < subEntries.length; i++) { + IBookEntry subEntry = subEntries[i]; + subButtons.add(addButton(new GuiButtonSubEntry(buttonList.size(), guiLeft + -24, guiTop + 12 + ((i + 1) * 22), subEntry, entry))); + } + } + + @Override + protected List getTooltip(int mouseX, int mouseY) { + List tooltip = new LinkedList<>(); + for (GuiButtonSubEntry subEntry : subButtons) { + if (subEntry.isMouseOver(mouseX, mouseY)) { + tooltip.addAll(subEntry.getToolTip()); + } + } + return tooltip; + } + + @Override + protected String getTitle() { + return entry.getTitle(); + } + + @Override + protected void actionPerformed(GuiButton button) throws IOException { + if (button instanceof GuiButtonPage) { + GuiButtonPage pageButton = (GuiButtonPage) button; + if (pageButton.left) { + setPages(pageIndex - 2); + } else { + setPages(pageIndex + 2); + } + initGui(); + if (lastPage >= 0) { + lastPage = -1; + } + } else if (button instanceof GuiButtonSubEntry) { + GuiButtonSubEntry subEntry = (GuiButtonSubEntry) button; + mc.displayGuiScreen(new GuiForestryBookPages(book, category, subEntry.subEntry, parent != null ? parent : entry)); + } else if (button instanceof GuiButtonBack || pages.isEmpty()) { + if (lastPage >= 0) { + setPages(lastPage); + lastPage = -1; + initGui(); + } else { + displayEntries(); + } + } + } + + private void displayEntries() { + mc.displayGuiScreen(new GuiForestryBookEntries(book, category)); + } +} diff --git a/src/main/java/forestry/book/gui/buttons/GuiButtonBack.java b/src/main/java/forestry/book/gui/buttons/GuiButtonBack.java new file mode 100644 index 000000000..0e7c9df49 --- /dev/null +++ b/src/main/java/forestry/book/gui/buttons/GuiButtonBack.java @@ -0,0 +1,46 @@ +package forestry.book.gui.buttons; + +import javax.annotation.Nullable; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.texture.TextureManager; + +import forestry.book.gui.GuiForesterBook; +import forestry.core.gui.tooltips.IToolTipProvider; +import forestry.core.gui.tooltips.ToolTip; + +public class GuiButtonBack extends GuiButton implements IToolTipProvider { + public GuiButtonBack(int buttonId, int x, int y) { + super(buttonId, x, y, 18, 9, ""); + } + + @Override + public void drawButton(Minecraft mc, int mouseX, int mouseY, float partialTicks) { + if (visible) { + this.hovered = mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.width && mouseY < this.y + this.height; + + TextureManager manager = mc.renderEngine; + manager.bindTexture(GuiForesterBook.TEXTURE); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + drawTexturedModalRect(x, y, 36 + (hovered ? 18 : 0), 181, 18, 9); + } + } + + @Nullable + @Override + public ToolTip getToolTip(int mouseX, int mouseY) { + return null; + } + + @Override + public boolean isToolTipVisible() { + return false; + } + + @Override + public boolean isMouseOver(int mouseX, int mouseY) { + return false; + } +} diff --git a/src/main/java/forestry/book/gui/buttons/GuiButtonBookCategory.java b/src/main/java/forestry/book/gui/buttons/GuiButtonBookCategory.java new file mode 100644 index 000000000..c602ab296 --- /dev/null +++ b/src/main/java/forestry/book/gui/buttons/GuiButtonBookCategory.java @@ -0,0 +1,60 @@ +package forestry.book.gui.buttons; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.RenderHelper; + +import forestry.api.book.IBookCategory; +import forestry.core.gui.GuiUtil; +import forestry.core.gui.tooltips.IToolTipProvider; +import forestry.core.gui.tooltips.ToolTip; + +public class GuiButtonBookCategory extends GuiButton implements IToolTipProvider { + public final IBookCategory category; + + public GuiButtonBookCategory(int buttonId, int x, int y, IBookCategory category) { + super(buttonId, x, y, 32, 32, ""); + this.category = category; + } + + @Override + public void drawButton(Minecraft mc, int mouseX, int mouseY, float partialTicks) { + if (visible) { + this.hovered = mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.width && mouseY < this.y + this.height; + FontRenderer fontRenderer = mc.fontRenderer; + GlStateManager.pushMatrix(); + GlStateManager.translate(x, y, zLevel); + GlStateManager.scale(2F, 2F, 2F); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + RenderHelper.enableGUIStandardItemLighting(); + GlStateManager.enableRescaleNormal(); + GuiUtil.drawItemStack(fontRenderer, category.getStack(), 0, 0); + RenderHelper.disableStandardItemLighting(); + GlStateManager.popMatrix(); + } + } + + @Override + public ToolTip getToolTip(int mouseX, int mouseY) { + ToolTip toolTip = new ToolTip(); + toolTip.add(category.getLocalizedName()); + return toolTip; + } + + @Override + public boolean isToolTipVisible() { + return true; + } + + @Override + public boolean isMouseOver(int mouseX, int mouseY) { + return mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.width && mouseY < this.y + this.height; + } + + @Override + public boolean isRelativeToGui() { + return false; + } +} diff --git a/src/main/java/forestry/book/gui/buttons/GuiButtonEntry.java b/src/main/java/forestry/book/gui/buttons/GuiButtonEntry.java new file mode 100644 index 000000000..1ea8ab14f --- /dev/null +++ b/src/main/java/forestry/book/gui/buttons/GuiButtonEntry.java @@ -0,0 +1,54 @@ +package forestry.book.gui.buttons; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.item.ItemStack; +import net.minecraft.util.text.TextFormatting; + +import forestry.api.book.IBookEntry; +import forestry.core.gui.GuiUtil; + +public class GuiButtonEntry extends GuiButton { + public final IBookEntry entry; + + public GuiButtonEntry(int buttonId, int x, int y, IBookEntry entry) { + super(buttonId, x, y, Minecraft.getMinecraft().fontRenderer.getStringWidth(entry.getTitle()) + 9, 11, entry.getTitle()); + this.entry = entry; + } + + @Override + public void drawButton(Minecraft mc, int mouseX, int mouseY, float partialTicks) { + if (this.visible) { + FontRenderer fontRenderer = mc.fontRenderer; + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + this.hovered = mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.width && mouseY < this.y + this.height; + + String text = displayString; + if (hovered) { + text = TextFormatting.GOLD + text; + } else { + text = TextFormatting.DARK_GRAY + text; + } + + boolean unicode = fontRenderer.getUnicodeFlag(); + fontRenderer.setUnicodeFlag(true); + fontRenderer.drawString(text, this.x + 9, this.y, 0); + fontRenderer.setUnicodeFlag(unicode); + + ItemStack stack = entry.getStack(); + if (!stack.isEmpty()) { + GlStateManager.pushMatrix(); + GlStateManager.translate(x, y, zLevel); + RenderHelper.enableGUIStandardItemLighting(); + GlStateManager.enableRescaleNormal(); + GlStateManager.scale(0.5F, 0.5F, 0.5F); + GuiUtil.drawItemStack(fontRenderer, stack, 0, 0); + RenderHelper.disableStandardItemLighting(); + GlStateManager.popMatrix(); + } + } + } +} diff --git a/src/main/java/forestry/book/gui/buttons/GuiButtonPage.java b/src/main/java/forestry/book/gui/buttons/GuiButtonPage.java new file mode 100644 index 000000000..bb8d0f009 --- /dev/null +++ b/src/main/java/forestry/book/gui/buttons/GuiButtonPage.java @@ -0,0 +1,53 @@ +package forestry.book.gui.buttons; + +import javax.annotation.Nullable; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.texture.TextureManager; + +import forestry.book.gui.GuiForesterBook; +import forestry.core.gui.tooltips.IToolTipProvider; +import forestry.core.gui.tooltips.ToolTip; + +public class GuiButtonPage extends GuiButton implements IToolTipProvider { + public boolean left; + + public GuiButtonPage(int buttonId, int x, int y, boolean left) { + super(buttonId, x, y, 18, 10, ""); + this.left = left; + } + + @Override + public void drawButton(Minecraft mc, int mouseX, int mouseY, float partialTicks) { + if (visible) { + this.hovered = mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.width && mouseY < this.y + this.height; + + TextureManager manager = mc.renderEngine; + manager.bindTexture(GuiForesterBook.TEXTURE); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + GlStateManager.enableAlpha(); + GlStateManager.disableBlend(); + drawTexturedModalRect(x, y, hovered ? 18 : 0, 181 + (left ? 10 : 0), 18, 10); + GlStateManager.enableBlend(); + GlStateManager.disableAlpha(); + } + } + + @Nullable + @Override + public ToolTip getToolTip(int mouseX, int mouseY) { + return null; + } + + @Override + public boolean isToolTipVisible() { + return false; + } + + @Override + public boolean isMouseOver(int mouseX, int mouseY) { + return false; + } +} diff --git a/src/main/java/forestry/book/gui/buttons/GuiButtonSubEntry.java b/src/main/java/forestry/book/gui/buttons/GuiButtonSubEntry.java new file mode 100644 index 000000000..f19af3603 --- /dev/null +++ b/src/main/java/forestry/book/gui/buttons/GuiButtonSubEntry.java @@ -0,0 +1,57 @@ +package forestry.book.gui.buttons; + +import java.util.Collections; +import java.util.List; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.client.renderer.texture.TextureManager; + +import forestry.api.book.IBookEntry; +import forestry.book.gui.GuiForesterBook; +import forestry.core.gui.GuiUtil; + +public class GuiButtonSubEntry extends GuiButton { + public final IBookEntry selectedEntry; + public final IBookEntry subEntry; + + public GuiButtonSubEntry(int buttonId, int x, int y, IBookEntry subEntry, IBookEntry selectedEntry) { + super(buttonId, x, y, 24, 21, ""); + this.subEntry = subEntry; + this.selectedEntry = selectedEntry; + } + + @Override + public void drawButton(Minecraft mc, int mouseX, int mouseY, float partialTicks) { + if (!visible) { + return; + } + boolean active = subEntry == selectedEntry; + TextureManager manager = mc.renderEngine; + manager.bindTexture(GuiForesterBook.TEXTURE); + GlStateManager.pushMatrix(); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + + drawTexturedModalRect(x, y, 48 + (active ? 24 : 0), 201, 24, 21); + + GlStateManager.translate(x + 8.0F, y + 4.0F, zLevel); + GlStateManager.scale(0.85F, 0.85F, 0.85F); + RenderHelper.enableGUIStandardItemLighting(); + GlStateManager.enableRescaleNormal(); + + GuiUtil.drawItemStack(mc.fontRenderer, subEntry.getStack(), 0, 0); + + RenderHelper.disableStandardItemLighting(); + GlStateManager.popMatrix(); + } + + public List getToolTip() { + return Collections.singletonList(subEntry.getTitle()); + } + + public boolean isMouseOver(int mouseX, int mouseY) { + return mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.width && mouseY < this.y + this.height; + } +} diff --git a/src/main/java/forestry/book/gui/buttons/package-info.java b/src/main/java/forestry/book/gui/buttons/package-info.java new file mode 100644 index 000000000..38eccb69c --- /dev/null +++ b/src/main/java/forestry/book/gui/buttons/package-info.java @@ -0,0 +1,10 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.book.gui.buttons; + +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/book/gui/elements/CarpenterElement.java b/src/main/java/forestry/book/gui/elements/CarpenterElement.java new file mode 100644 index 000000000..3664ecd2d --- /dev/null +++ b/src/main/java/forestry/book/gui/elements/CarpenterElement.java @@ -0,0 +1,59 @@ +package forestry.book.gui.elements; + +import java.util.Collection; +import java.util.stream.Stream; + +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.Ingredient; +import net.minecraft.util.NonNullList; +import net.minecraft.util.ResourceLocation; + +import net.minecraftforge.fluids.FluidTankInfo; + +import forestry.api.recipes.ICarpenterRecipe; +import forestry.api.recipes.IDescriptiveRecipe; +import forestry.core.config.Constants; +import forestry.core.gui.Drawable; +import forestry.core.gui.elements.IngredientElement; +import forestry.core.gui.elements.TankElement; +import forestry.factory.recipes.CarpenterRecipeManager; + +public class CarpenterElement extends SelectionElement { + private static final ResourceLocation BOOK_CRAFTING_TEXTURE = new ResourceLocation(Constants.MOD_ID, Constants.TEXTURE_PATH_GUI + "/almanac/crafting.png"); + private static final Drawable CARPENTER_BACKGROUND = new Drawable(BOOK_CRAFTING_TEXTURE, 0, 0, 108, 60); + private static final Drawable CARPENTER_TANK_OVERLAY = new Drawable(BOOK_CRAFTING_TEXTURE, 109, 1, 16, 58); + + public CarpenterElement(int xPos, int yPos, ItemStack stack) { + this(0, 0, new ItemStack[]{stack}); + } + + public CarpenterElement(int xPos, int yPos, ItemStack[] stacks) { + this(0, 0, Stream.of(stacks).map(CarpenterRecipeManager::getRecipes).flatMap(Collection::stream).toArray(ICarpenterRecipe[]::new)); + } + + public CarpenterElement(int xPos, int yPos, ICarpenterRecipe[] recipes) { + super(xPos, yPos, 108, 62, recipes, 2); + + drawable(0, 2, CARPENTER_BACKGROUND); + add(selectedElement); + setIndex(0); + } + + @Override + protected void onIndexUpdate(int index, ICarpenterRecipe recipe) { + selectedElement.add(new TankElement(91, 1, null, () -> new FluidTankInfo(recipe.getFluidResource(), Constants.PROCESSOR_TANK_CAPACITY), CARPENTER_TANK_OVERLAY)); + IDescriptiveRecipe gridRecipe = recipe.getCraftingGridRecipe(); + NonNullList> ingredients = gridRecipe.getRawIngredients(); + for (int x = 0; x < 3; x++) { + for (int y = 0; y < 3; y++) { + int ingredientIndex = y * 3 + x; + if (ingredientIndex >= ingredients.size()) { + continue; + } + NonNullList items = ingredients.get(ingredientIndex); + selectedElement.add(new IngredientElement(1 + x * 19, 3 + y * 19, Ingredient.fromStacks(items.toArray(new ItemStack[items.size()])))); + } + } + selectedElement.item(71, 41, gridRecipe.getOutput()); + } +} diff --git a/src/main/java/forestry/book/gui/elements/CraftingElement.java b/src/main/java/forestry/book/gui/elements/CraftingElement.java new file mode 100644 index 000000000..aebbb8b8b --- /dev/null +++ b/src/main/java/forestry/book/gui/elements/CraftingElement.java @@ -0,0 +1,42 @@ +package forestry.book.gui.elements; + +import net.minecraft.item.crafting.IRecipe; +import net.minecraft.item.crafting.Ingredient; +import net.minecraft.util.NonNullList; + +import forestry.api.gui.GuiElementAlignment; +import forestry.book.gui.GuiForesterBook; +import forestry.core.gui.Drawable; +import forestry.core.gui.elements.IngredientElement; + +public class CraftingElement extends SelectionElement { + private static final Drawable CRAFTING_GRID = new Drawable(GuiForesterBook.TEXTURE, 158, 181, 98, 58); + + public CraftingElement(int xPos, int yPos, IRecipe[] recipes) { + super(xPos, yPos, 98, 62, recipes, 2); + + setAlign(GuiElementAlignment.TOP_CENTER); + //Background + drawable(0, 2, CRAFTING_GRID); + add(selectedElement); + setIndex(0); + } + + protected void onIndexUpdate(int index, IRecipe recipe) { + NonNullList ingredients = recipe.getIngredients(); + //Output + selectedElement.item(81, 21, recipe.getRecipeOutput()); + //Grid + for (int x = 0; x < 3; x++) { + for (int y = 0; y < 3; y++) { + int i = y * 3 + x; + if (ingredients.size() <= i) { + continue; + } + Ingredient ingredient = ingredients.get(i); + selectedElement.add(new IngredientElement(1 + x * 20, 1 + y * 20, ingredient)); + } + } + } + +} diff --git a/src/main/java/forestry/book/gui/elements/FabricatorElement.java b/src/main/java/forestry/book/gui/elements/FabricatorElement.java new file mode 100644 index 000000000..07cb08863 --- /dev/null +++ b/src/main/java/forestry/book/gui/elements/FabricatorElement.java @@ -0,0 +1,88 @@ +package forestry.book.gui.elements; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.Ingredient; +import net.minecraft.util.NonNullList; +import net.minecraft.util.ResourceLocation; + +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidTankInfo; + +import forestry.api.recipes.IFabricatorRecipe; +import forestry.api.recipes.IFabricatorSmeltingRecipe; +import forestry.core.config.Constants; +import forestry.core.gui.Drawable; +import forestry.core.gui.elements.IngredientElement; +import forestry.core.gui.elements.TankElement; +import forestry.factory.recipes.FabricatorRecipeManager; +import forestry.factory.recipes.FabricatorSmeltingRecipeManager; + +public class FabricatorElement extends SelectionElement { + private static final ResourceLocation BOOK_CRAFTING_TEXTURE = new ResourceLocation(Constants.MOD_ID, Constants.TEXTURE_PATH_GUI + "/almanac/crafting.png"); + private static final Drawable FABRICATOR_BACKGROUND = new Drawable(BOOK_CRAFTING_TEXTURE, 0, 60, 108, 56); + private static final Drawable FABRICATOR_TANK_OVERLAY = new Drawable(BOOK_CRAFTING_TEXTURE, 109, 61, 16, 16); + + public FabricatorElement(int xPos, int yPos, ItemStack stack) { + this(0, 0, new ItemStack[]{stack}); + } + + public FabricatorElement(int xPos, int yPos, ItemStack[] stacks) { + this(0, 0, Stream.of(stacks).map(FabricatorRecipeManager::getRecipes).flatMap(Collection::stream).toArray(IFabricatorRecipe[]::new)); + } + + public FabricatorElement(int xPos, int yPos, IFabricatorRecipe[] recipes) { + super(xPos, yPos, 108, 58, recipes, 2); + + drawable(0, 2, FABRICATOR_BACKGROUND); + add(selectedElement); + setIndex(0); + } + + @Override + protected void onIndexUpdate(int index, IFabricatorRecipe recipe) { + selectedElement.add(new TankElement(1, 33, null, () -> new FluidTankInfo(recipe.getLiquid(), 2000), FABRICATOR_TANK_OVERLAY, 16, 16)); + NonNullList> ingredients = recipe.getIngredients(); + for (int x = 0; x < 3; x++) { + for (int y = 0; y < 3; y++) { + int ingredientIndex = y * 3 + x; + if (ingredientIndex >= ingredients.size()) { + continue; + } + NonNullList items = ingredients.get(ingredientIndex); + selectedElement.add(new IngredientElement(21 + x * 19, 1 + y * 19, Ingredient.fromStacks(items.toArray(new ItemStack[items.size()])))); + } + } + ItemStack plan = recipe.getPlan(); + if (!plan.isEmpty()) { + selectedElement.item(91, 1, plan); + } + selectedElement.item(91, 39, recipe.getRecipeOutput()); + NonNullList smeltingInput = NonNullList.create(); + Fluid recipeFluid = recipe.getLiquid().getFluid(); + for (IFabricatorSmeltingRecipe s : getSmeltingInputs().get(recipeFluid)) { + smeltingInput.add(s.getResource()); + } + if (!smeltingInput.isEmpty()) { + selectedElement.add(new IngredientElement(1, 6, smeltingInput)); + } + } + + private static Map> getSmeltingInputs() { + Map> smeltingInputs = new HashMap<>(); + for (IFabricatorSmeltingRecipe smelting : FabricatorSmeltingRecipeManager.recipes) { + Fluid fluid = smelting.getProduct().getFluid(); + if (!smeltingInputs.containsKey(fluid)) { + smeltingInputs.put(fluid, new ArrayList<>()); + } + smeltingInputs.get(fluid).add(smelting); + } + return smeltingInputs; + } +} diff --git a/src/main/java/forestry/book/gui/elements/IndexElement.java b/src/main/java/forestry/book/gui/elements/IndexElement.java new file mode 100644 index 000000000..1182f303d --- /dev/null +++ b/src/main/java/forestry/book/gui/elements/IndexElement.java @@ -0,0 +1,49 @@ +package forestry.book.gui.elements; + +import net.minecraft.util.text.TextFormatting; + +import forestry.api.gui.GuiElementAlignment; +import forestry.book.data.IndexEntry; +import forestry.book.gui.GuiForesterBook; +import forestry.book.gui.GuiForestryBookPages; +import forestry.core.gui.elements.TextElement; +import forestry.core.gui.elements.layouts.VerticalLayout; + +public class IndexElement extends VerticalLayout { + public IndexElement(int xPos, int yPos, IndexEntry[] data) { + super(xPos, yPos, 108); + for (IndexEntry index : data) { + add(new IndexEntryElement(index)); + } + } + + private class IndexEntryElement extends TextElement { + private final IndexEntry data; + + public IndexEntryElement(IndexEntry data) { + super(-1, 9, data.title, GuiElementAlignment.TOP_LEFT, 0, true); + width += TextElement.FONT_RENDERER.getStringWidth(" > "); + this.data = data; + } + + @Override + public void drawElement(int mouseX, int mouseY) { + boolean mouseOver = isMouseOver(mouseX, mouseY); + boolean unicode = FONT_RENDERER.getUnicodeFlag(); + String preFix = mouseOver ? TextFormatting.GOLD + " > " : TextFormatting.DARK_GRAY + "- "; + FONT_RENDERER.setUnicodeFlag(this.unicode); + FONT_RENDERER.drawString(preFix + text, 0, 0, color); + FONT_RENDERER.setUnicodeFlag(unicode); + } + + @Override + public void mouseClicked(int mouseX, int mouseY, int mouseButton) { + super.mouseClicked(mouseX, mouseY, mouseButton); + GuiForesterBook bookGui = GuiForesterBook.guiScreen; + if (bookGui instanceof GuiForestryBookPages) { + GuiForestryBookPages pagesGui = (GuiForestryBookPages) bookGui; + pagesGui.switchPage(data.page); + } + } + } +} diff --git a/src/main/java/forestry/book/gui/elements/MultiblockElement.java b/src/main/java/forestry/book/gui/elements/MultiblockElement.java new file mode 100644 index 000000000..6aa130b55 --- /dev/null +++ b/src/main/java/forestry/book/gui/elements/MultiblockElement.java @@ -0,0 +1,167 @@ +/******************************************************************************* + * The MIT License (MIT) + * Copyright (c) 2013-2014 Slime Knights (mDiyo, fuj1n, Sunstrike, progwml6, pillbox, alexbegt) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * Any alternate licenses are noted where appropriate. + ******************************************************************************/ +package forestry.book.gui.elements; + +import javax.annotation.Nullable; +import java.util.stream.IntStream; + +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.BlockRendererDispatcher; +import net.minecraft.client.renderer.BufferBuilder; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.texture.TextureManager; +import net.minecraft.client.renderer.texture.TextureMap; +import net.minecraft.client.renderer.vertex.DefaultVertexFormats; +import net.minecraft.util.math.BlockPos; + +import forestry.book.data.structure.BlockData; +import forestry.book.data.structure.StructureBlockAccess; +import forestry.book.data.structure.StructureInfo; +import forestry.book.gui.GuiForesterBook; +import forestry.core.gui.elements.GuiElement; + +import org.lwjgl.input.Mouse; +import org.lwjgl.opengl.GL11; + +public class MultiblockElement extends GuiElement { + private float scale = 50.0F; + private float xTranslate = 0F; + private float yTranslate = 0F; + private boolean canTick = false; + private int tick = 0; + + private float rotX = 0; + private float rotY = 0; + + private StructureInfo structureData; + private StructureBlockAccess blockAccess; + + @Nullable + private int[] lastClick = null; + private int fullStructureSteps = 5; + + public MultiblockElement(int x, int y, int width, int height, int[] size, BlockData[] structure) { + super(x, y, width, height); + if (size.length == 3) { + scale = 100f / (float) IntStream.of(size).max().getAsInt(); + + float sx = (float) width / (float) GuiForesterBook.PAGE_WIDTH; + float sy = (float) height / (float) GuiForesterBook.PAGE_HEIGHT; + + scale *= Math.min(sx, sy); + + xTranslate = x + (float) width / 2.0F; + yTranslate = y + (float) height / 2.0F; + } + structureData = new StructureInfo(size[0], size[1], size[2], structure); + blockAccess = new StructureBlockAccess(structureData); + + + rotX = 25; + rotY = -45; + } + + @Override + public void drawElement(int mouseX, int mouseY) { + if (lastClick != null) { + if (Mouse.isButtonDown(0) || Mouse.isButtonDown(1)) { + int dx = mouseX - lastClick[0]; + int dy = mouseY - lastClick[1]; + float maxSpeed = 10f; + float changeY = Math.min(maxSpeed, dx / 10f); + float changeX = Math.min(maxSpeed, dy / 10f); + + rotY += changeY; + rotX += changeX; + } else { + lastClick = null; + } + } + + if (canTick) { + if (++tick % 20 == 0 && (structureData.canStep() || ++fullStructureSteps >= 5)) { + structureData.step(); + fullStructureSteps = 0; + } + } else { + structureData.reset(); + structureData.setShowLayer(9); + } + + int structureLength = structureData.structureLength; + int structureWidth = structureData.structureWidth; + int structureHeight = structureData.structureHeight; + + GlStateManager.enableRescaleNormal(); + GlStateManager.pushMatrix(); + RenderHelper.disableStandardItemLighting(); + + final BlockRendererDispatcher blockRender = Minecraft.getMinecraft().getBlockRendererDispatcher(); + final TextureManager textureManager = Minecraft.getMinecraft().getTextureManager(); + + GlStateManager.translate(xTranslate, yTranslate, Math.max(structureHeight, Math.max(structureWidth, structureLength))); + GlStateManager.scale(scale, -scale, 1); + GlStateManager.rotate(rotX, 1, 0, 0); + GlStateManager.rotate(rotY, 0, 1, 0); + + GlStateManager.translate((float) structureLength / -2f, (float) structureHeight / -2f, (float) structureWidth / -2f); + + GlStateManager.disableLighting(); + + if (Minecraft.isAmbientOcclusionEnabled()) { + GlStateManager.shadeModel(GL11.GL_SMOOTH); + } else { + GlStateManager.shadeModel(GL11.GL_FLAT); + } + + textureManager.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE); + for (int h = 0; h < structureData.structureHeight; h++) { + for (int l = 0; l < structureData.structureLength; l++) { + for (int w = 0; w < structureData.structureWidth; w++) { + BlockPos pos = new BlockPos(l, h, w); + if (!blockAccess.isAirBlock(pos)) { + IBlockState state = blockAccess.getBlockState(pos); + Tessellator tessellator = Tessellator.getInstance(); + BufferBuilder buffer = tessellator.getBuffer(); + buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.BLOCK); + blockRender.renderBlock(state, pos, blockAccess, buffer); + tessellator.draw(); + } + } + } + } + GlStateManager.popMatrix(); + + RenderHelper.disableStandardItemLighting(); + GlStateManager.disableRescaleNormal(); + GlStateManager.shadeModel(GL11.GL_FLAT); + GlStateManager.enableBlend(); + RenderHelper.disableStandardItemLighting(); + } + + @Override + public void mouseClicked(int mouseX, int mouseY, int mouseButton) { + super.mouseClicked(mouseX, mouseY, mouseButton); + + lastClick = new int[]{mouseX, mouseY}; + } + + @Override + public void mouseReleased(int mouseX, int mouseY, int clickedMouseButton) { + super.mouseReleased(mouseX, mouseY, clickedMouseButton); + lastClick = null; + } +} diff --git a/src/main/java/forestry/book/gui/elements/MutationElement.java b/src/main/java/forestry/book/gui/elements/MutationElement.java new file mode 100644 index 000000000..ff7b4e3b6 --- /dev/null +++ b/src/main/java/forestry/book/gui/elements/MutationElement.java @@ -0,0 +1,47 @@ +package forestry.book.gui.elements; + +import java.util.Collection; + +import forestry.api.genetics.IMutation; +import forestry.api.genetics.ISpeciesRoot; +import forestry.api.gui.GuiElementAlignment; +import forestry.book.gui.GuiForesterBook; +import forestry.core.gui.Drawable; + +public class MutationElement extends SelectionElement { + private static final Drawable SLOT = new Drawable(GuiForesterBook.TEXTURE, 0, 223, 18, 18); + private static final Drawable MUTATION_PLUS = new Drawable(GuiForesterBook.TEXTURE, 0, 241, 15, 15); + private static final Drawable MUTATION_ARROW = new Drawable(GuiForesterBook.TEXTURE, 15, 241, 18, 15); + + public MutationElement(int xPos, int yPos, IMutation[] mutations) { + super(xPos, yPos, 108, 20, mutations, 2); + + setAlign(GuiElementAlignment.TOP_CENTER); + + drawable(0, 2, SLOT); + drawable(21, 4, MUTATION_PLUS); + drawable(39, 2, SLOT); + drawable(84, 2, SLOT); + add(selectedElement); + setIndex(0); + } + + @Override + protected void onIndexUpdate(int index, IMutation mutation) { + ISpeciesRoot root = mutation.getRoot(); + // + Collection conditions = mutation.getSpecialConditions(); + String conditionText; + if (!conditions.isEmpty()) { + conditionText = String.format("[%.0f%%]", mutation.getBaseChance()); + } else { + conditionText = String.format("%.0f%%", mutation.getBaseChance()); + } + selectedElement.text(58, conditionText, GuiElementAlignment.TOP_LEFT, 0).addTooltip(conditions); + selectedElement.drawable(62, 6, MUTATION_ARROW).addTooltip(conditions); + // + selectedElement.item(1, 1, root.getMemberStack(mutation.getAllele0(), root.getTypeForMutation(0))); + selectedElement.item(40, 1, root.getMemberStack(mutation.getAllele1(), root.getTypeForMutation(1))); + selectedElement.item(85, 1, root.getMemberStack(mutation.getTemplate(), root.getTypeForMutation(2))); + } +} diff --git a/src/main/java/forestry/book/gui/elements/SelectionElement.java b/src/main/java/forestry/book/gui/elements/SelectionElement.java new file mode 100644 index 000000000..bffa44120 --- /dev/null +++ b/src/main/java/forestry/book/gui/elements/SelectionElement.java @@ -0,0 +1,74 @@ +package forestry.book.gui.elements; + +import javax.annotation.Nullable; + +import net.minecraft.util.text.TextFormatting; + +import forestry.api.gui.GuiElementAlignment; +import forestry.book.gui.GuiForesterBook; +import forestry.core.gui.Drawable; +import forestry.core.gui.elements.ButtonElement; +import forestry.core.gui.elements.GuiElementFactory; +import forestry.core.gui.elements.layouts.ElementGroup; +import forestry.core.gui.elements.layouts.PaneLayout; + +public abstract class SelectionElement extends PaneLayout { + private static final Drawable CRAFTING_COUNT = new Drawable(GuiForesterBook.TEXTURE, 104, 181, 34, 14); + private static final Drawable RIGHT_BUTTON = new Drawable(GuiForesterBook.TEXTURE, 138, 181, 10, 9); + private static final Drawable LEFT_BUTTON = new Drawable(GuiForesterBook.TEXTURE, 148, 181, 10, 9); + + private int index = -1; + + @Nullable + protected final ButtonElement leftButton; + @Nullable + protected final ButtonElement rightButton; + @Nullable + protected final ElementGroup text; + protected final ElementGroup selectedElement; + protected final R[] recipes; + + protected SelectionElement(int xPos, int yPos, int width, int height, R[] recipes) { + this(xPos, yPos, width, height, recipes, 0); + } + + protected SelectionElement(int xPos, int yPos, int width, int height, R[] recipes, int yOffset) { + super(xPos, yPos, width, height + (recipes.length > 1 ? 16 : 0)); + this.recipes = recipes; + if (recipes.length > 1) { + drawable(0, 0, CRAFTING_COUNT).setAlign(GuiElementAlignment.BOTTOM_CENTER); + text = panel(width, this.height); + leftButton = add(new ButtonElement(-27, -2, LEFT_BUTTON, e -> setIndex(index - 1))); + leftButton.setAlign(GuiElementAlignment.BOTTOM_CENTER); + + rightButton = add(new ButtonElement(27, -2, RIGHT_BUTTON, e -> setIndex(index + 1))); + rightButton.setAlign(GuiElementAlignment.BOTTOM_CENTER); + } else { + text = null; + leftButton = null; + rightButton = null; + } + selectedElement = GuiElementFactory.INSTANCE.createPanel(0, 2, width, this.height); + } + + protected final void setIndex(int index) { + if (index == this.index || index >= recipes.length || index < 0) { + return; + } + this.index = index; + selectedElement.clear(); + onIndexUpdate(index, recipes[index]); + if (text != null) { + text.clear(); + text.text(TextFormatting.BLACK.toString() + (index + 1) + "/" + recipes.length, GuiElementAlignment.BOTTOM_CENTER, 0).setYPosition(2); + } + if (leftButton != null) { + leftButton.setEnabled(index > 0); + } + if (rightButton != null) { + rightButton.setEnabled(index < recipes.length - 1); + } + } + + protected abstract void onIndexUpdate(int index, R recipe); +} diff --git a/src/main/java/forestry/book/gui/elements/TextDataElement.java b/src/main/java/forestry/book/gui/elements/TextDataElement.java new file mode 100644 index 000000000..ee1113ea3 --- /dev/null +++ b/src/main/java/forestry/book/gui/elements/TextDataElement.java @@ -0,0 +1,131 @@ +package forestry.book.gui.elements; + +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.util.text.TextFormatting; + +import forestry.book.data.TextData; +import forestry.core.gui.elements.GuiElement; + +public class TextDataElement extends GuiElement { + + private final List textElements = new ArrayList<>(); + + public TextDataElement(int xPos, int yPos, int width, int height) { + super(xPos, yPos, width, height); + } + + @Override + public int getHeight() { + if (height >= 0) { + return height; + } + FontRenderer fontRenderer = Minecraft.getMinecraft().fontRenderer; + boolean unicode = fontRenderer.getUnicodeFlag(); + fontRenderer.setUnicodeFlag(true); + boolean lastEmpty = false; + for (TextData data : textElements) { + if (data.text.equals("\n")) { + if (lastEmpty) { + height += fontRenderer.FONT_HEIGHT; + } + lastEmpty = true; + continue; + } + lastEmpty = false; + + if (data.paragraph) { + height += fontRenderer.FONT_HEIGHT * 1.6D; + } + + String modifiers = ""; + + modifiers += TextFormatting.getValueByName(data.color); + + if (data.bold) { + modifiers += TextFormatting.BOLD; + } + if (data.italic) { + modifiers += TextFormatting.ITALIC; + } + if (data.underlined) { + modifiers += TextFormatting.UNDERLINE; + } + if (data.strikethrough) { + modifiers += TextFormatting.STRIKETHROUGH; + } + if (data.obfuscated) { + modifiers += TextFormatting.OBFUSCATED; + } + height += fontRenderer.getWordWrappedHeight(modifiers + data.text, width); + } + fontRenderer.setUnicodeFlag(unicode); + return height; + } + + @Override + public void drawElement(int mouseX, int mouseY) { + FontRenderer fontRenderer = Minecraft.getMinecraft().fontRenderer; + boolean unicode = fontRenderer.getUnicodeFlag(); + fontRenderer.setUnicodeFlag(true); + int x = 0; + int y = 0; + for (TextData data : textElements) { + if (data.text.equals("\n")) { + x = 0; + y += fontRenderer.FONT_HEIGHT; + continue; + } + + if (data.paragraph) { + x = 0; + y += fontRenderer.FONT_HEIGHT * 1.6D; + } + + String text = getFormattedString(data); + List split = fontRenderer.listFormattedStringToWidth(text, width); + for (int i = 0; i < split.size(); i++) { + String s = split.get(i); + int textLength = fontRenderer.drawString(s, x, y, 0, data.dropshadow); + if (i == split.size() - 1) { + x += textLength; + } else { + y += fontRenderer.FONT_HEIGHT; + } + } + } + fontRenderer.setUnicodeFlag(unicode); + } + + private String getFormattedString(TextData data) { + StringBuilder modifiers = new StringBuilder(); + + modifiers.append(TextFormatting.getValueByName(data.color)); + + if (data.bold) { + modifiers.append(TextFormatting.BOLD); + } + if (data.italic) { + modifiers.append(TextFormatting.ITALIC); + } + if (data.underlined) { + modifiers.append(TextFormatting.UNDERLINE); + } + if (data.strikethrough) { + modifiers.append(TextFormatting.STRIKETHROUGH); + } + if (data.obfuscated) { + modifiers.append(TextFormatting.OBFUSCATED); + } + modifiers.append(data.text); + return modifiers.toString(); + } + + public void addData(TextData textData) { + textElements.add(textData); + height = -1; + } +} diff --git a/src/main/java/forestry/book/gui/elements/package-info.java b/src/main/java/forestry/book/gui/elements/package-info.java new file mode 100644 index 000000000..dcfa9dea3 --- /dev/null +++ b/src/main/java/forestry/book/gui/elements/package-info.java @@ -0,0 +1,10 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.book.gui.elements; + +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/book/gui/package-info.java b/src/main/java/forestry/book/gui/package-info.java new file mode 100644 index 000000000..6290fd8fe --- /dev/null +++ b/src/main/java/forestry/book/gui/package-info.java @@ -0,0 +1,10 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.book.gui; + +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/book/items/ItemForesterBook.java b/src/main/java/forestry/book/items/ItemForesterBook.java new file mode 100644 index 000000000..5b28eff8a --- /dev/null +++ b/src/main/java/forestry/book/items/ItemForesterBook.java @@ -0,0 +1,44 @@ +package forestry.book.items; + +import javax.annotation.Nullable; + +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ActionResult; +import net.minecraft.util.EnumActionResult; +import net.minecraft.util.EnumHand; +import net.minecraft.world.World; + +import forestry.api.book.IForesterBook; +import forestry.book.BookLoader; +import forestry.book.gui.GuiForesterBook; +import forestry.book.gui.GuiForestryBookCategories; +import forestry.core.items.ItemWithGui; + +public class ItemForesterBook extends ItemWithGui { + public ItemForesterBook() { + + } + + @Override + public ActionResult onItemRightClick(World worldIn, EntityPlayer playerIn, EnumHand handIn) { + openGui(playerIn); + + ItemStack stack = playerIn.getHeldItem(handIn); + return ActionResult.newResult(EnumActionResult.SUCCESS, stack); + } + + @Override + public GuiScreen getGui(EntityPlayer player, ItemStack heldItem, int data) { + IForesterBook book = BookLoader.INSTANCE.loadBook(); + return GuiForesterBook.guiScreen != null ? GuiForesterBook.guiScreen : new GuiForestryBookCategories(book); + } + + @Nullable + @Override + public Container getContainer(EntityPlayer player, ItemStack heldItem, int data) { + return null; + } +} diff --git a/src/main/java/forestry/book/items/ItemRegistryBook.java b/src/main/java/forestry/book/items/ItemRegistryBook.java new file mode 100644 index 000000000..abaf0d17f --- /dev/null +++ b/src/main/java/forestry/book/items/ItemRegistryBook.java @@ -0,0 +1,11 @@ +package forestry.book.items; + +import forestry.core.items.ItemRegistry; + +public class ItemRegistryBook extends ItemRegistry { + public final ItemForesterBook book; + + public ItemRegistryBook() { + book = registerItem(new ItemForesterBook(), "book_forester"); + } +} diff --git a/src/main/java/forestry/book/items/package-info.java b/src/main/java/forestry/book/items/package-info.java new file mode 100644 index 000000000..0a082b0e7 --- /dev/null +++ b/src/main/java/forestry/book/items/package-info.java @@ -0,0 +1,10 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.book.items; + +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/book/package-info.java b/src/main/java/forestry/book/package-info.java new file mode 100644 index 000000000..a5117d798 --- /dev/null +++ b/src/main/java/forestry/book/package-info.java @@ -0,0 +1,10 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.book; + +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/book/pages/JsonPageFactory.java b/src/main/java/forestry/book/pages/JsonPageFactory.java new file mode 100644 index 000000000..cbf4caf42 --- /dev/null +++ b/src/main/java/forestry/book/pages/JsonPageFactory.java @@ -0,0 +1,47 @@ +package forestry.book.pages; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import forestry.api.book.BookContent; +import forestry.api.book.IBookEntry; +import forestry.api.book.IBookPageFactory; +import forestry.api.gui.IGuiElement; +import forestry.book.gui.GuiForesterBook; +import forestry.core.gui.elements.GuiElementFactory; +import forestry.core.gui.elements.layouts.VerticalLayout; + +public class JsonPageFactory implements IBookPageFactory { + + public static final String NAME = "json"; + public static final JsonPageFactory INSTANCE = new JsonPageFactory(); + + private JsonPageFactory() { + } + + @Override + public Collection load(IBookEntry entry, int leftPageHeight, int rightPageHeight, int pageWidth) { + List pages = new ArrayList<>(); + BookContent previous = null; + IGuiElement previousElement = null; + + for (BookContent[] contentArray : entry.getContent()) { + VerticalLayout page = new VerticalLayout(108); + pages.add(page); + for (BookContent content : contentArray) { + if (content.addElements(page, GuiElementFactory.INSTANCE, previous, previousElement, GuiForesterBook.PAGE_HEIGHT - (pages.size() % 2 == 1 ? 13 : 0))) { + previous = content; + previousElement = page.getLastElement(); + page.layout(); + } else { + previous = null; + previousElement = null; + } + } + previous = null; + previousElement = null; + } + return pages; + } +} diff --git a/src/main/java/forestry/book/pages/package-info.java b/src/main/java/forestry/book/pages/package-info.java new file mode 100644 index 000000000..2c5854a89 --- /dev/null +++ b/src/main/java/forestry/book/pages/package-info.java @@ -0,0 +1,10 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.book.pages; + +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/book/proxy/ProxyBook.java b/src/main/java/forestry/book/proxy/ProxyBook.java new file mode 100644 index 000000000..89aff4636 --- /dev/null +++ b/src/main/java/forestry/book/proxy/ProxyBook.java @@ -0,0 +1,18 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.book.proxy; + +public class ProxyBook { + public void preInit() { + + } + +} diff --git a/src/main/java/forestry/book/proxy/ProxyBookClient.java b/src/main/java/forestry/book/proxy/ProxyBookClient.java new file mode 100644 index 000000000..0f273f302 --- /dev/null +++ b/src/main/java/forestry/book/proxy/ProxyBookClient.java @@ -0,0 +1,34 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.book.proxy; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.resources.IReloadableResourceManager; +import net.minecraft.client.resources.IResourceManager; + +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import forestry.book.BookLoader; + +@SuppressWarnings("unused") +@SideOnly(Side.CLIENT) +public class ProxyBookClient extends ProxyBook { + + @Override + public void preInit() { + IResourceManager resourceManager = Minecraft.getMinecraft().getResourceManager(); + if (resourceManager instanceof IReloadableResourceManager) { + IReloadableResourceManager manager = (IReloadableResourceManager) resourceManager; + manager.registerReloadListener(BookLoader.INSTANCE); + } + } +} diff --git a/src/main/java/forestry/core/CreativeTabForestry.java b/src/main/java/forestry/core/CreativeTabForestry.java index 9065cf657..bcb481ef6 100755 --- a/src/main/java/forestry/core/CreativeTabForestry.java +++ b/src/main/java/forestry/core/CreativeTabForestry.java @@ -21,7 +21,6 @@ import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeType; import forestry.api.arboriculture.EnumGermlingType; import forestry.api.arboriculture.TreeManager; -import forestry.api.core.ForestryAPI; import forestry.api.core.Tabs; import forestry.api.lepidopterology.ButterflyManager; import forestry.api.lepidopterology.EnumFlutterType; @@ -33,23 +32,24 @@ import forestry.core.config.Constants; import forestry.lepidopterology.genetics.Butterfly; import forestry.lepidopterology.genetics.ButterflyDefinition; import forestry.modules.ForestryModuleUids; +import forestry.modules.ModuleHelper; public class CreativeTabForestry extends CreativeTabs { static { - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FARMING))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.FARMING)) { Tabs.tabAgriculture = new CreativeTabForestry(1, "agriculture"); } - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.APICULTURE))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.APICULTURE)) { Tabs.tabApiculture = new CreativeTabForestry(2, "apiculture"); } - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.ARBORICULTURE))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.ARBORICULTURE)) { Tabs.tabArboriculture = new CreativeTabForestry(3, "arboriculture"); } - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.LEPIDOPTEROLOGY))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.LEPIDOPTEROLOGY)) { Tabs.tabLepidopterology = new CreativeTabForestry(4, "lepidopterology"); } } diff --git a/src/main/java/forestry/core/ModuleCore.java b/src/main/java/forestry/core/ModuleCore.java index 1e5e570bf..b07c8d235 100644 --- a/src/main/java/forestry/core/ModuleCore.java +++ b/src/main/java/forestry/core/ModuleCore.java @@ -31,6 +31,7 @@ import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.oredict.OreDictionary; + import net.minecraftforge.fml.common.event.FMLInterModComms.IMCMessage; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; @@ -76,6 +77,7 @@ import forestry.core.utils.OreDictUtil; import forestry.core.utils.World2ObjectMap; import forestry.modules.BlankForestryModule; import forestry.modules.ForestryModuleUids; +import forestry.modules.ModuleHelper; @ForestryModule(containerID = Constants.MOD_ID, moduleID = ForestryModuleUids.CORE, name = "Core", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.module.core.description", coreModule = true) public class ModuleCore extends BlankForestryModule { @@ -290,7 +292,7 @@ public class ModuleCore extends BlankForestryModule { // / WEB RecipeUtil.addRecipe("silk_wisp_to_web", new ItemStack(Blocks.WEB, 4), "# #", " # ", "# #", '#', items.craftingMaterial.getSilkWisp()); - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FACTORY))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.FACTORY)) { // / CARPENTER // Portable ANALYZER RecipeManagers.carpenterManager.addRecipe(100, new FluidStack(FluidRegistry.WATER, 2000), ItemStack.EMPTY, items.portableAlyzer.getItemStack(), @@ -330,7 +332,7 @@ public class ModuleCore extends BlankForestryModule { } // ANALYZER - RecipeUtil.addRecipe("alyzer", blocks.analyzer, + RecipeUtil.addRecipe("analyzer", blocks.analyzer, "XTX", " Y ", "X X", @@ -431,7 +433,7 @@ public class ModuleCore extends BlankForestryModule { RecipeUtil.addShapelessRecipe("block_to_bronze", ingotBronze, OreDictUtil.BLOCK_BRONZE); } - if(!ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.ARBORICULTURE))){ + if(!ModuleHelper.isEnabled(ForestryModuleUids.CHARCOAL)){ RecipeUtil.addSmelting(new ItemStack(items.ash, 2), new ItemStack(Items.COAL, 1, 1), 0.15F); } @@ -449,7 +451,7 @@ public class ModuleCore extends BlankForestryModule { '#', Items.BRICK); // alternate recipes - if (!ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.APICULTURE))) { + if (!ModuleHelper.isEnabled(ForestryModuleUids.APICULTURE)) { RecipeManagers.centrifugeManager.addRecipe(5, new ItemStack(Items.STRING), ImmutableMap.of( items.craftingMaterial.getSilkWisp(), 0.15f )); diff --git a/src/main/java/forestry/core/blocks/BlockRegistryCore.java b/src/main/java/forestry/core/blocks/BlockRegistryCore.java index 73e5e7012..816f05ce4 100644 --- a/src/main/java/forestry/core/blocks/BlockRegistryCore.java +++ b/src/main/java/forestry/core/blocks/BlockRegistryCore.java @@ -71,10 +71,10 @@ public class BlockRegistryCore extends BlockRegistry { OreDictionary.registerOre(OreDictUtil.BLOCK_BRONZE, resourceStorageBronze); ashBrick = new BlockAshBrick(); - registerBlock(ashBrick, new ItemBlockForestry(ashBrick), "ash_brick"); + registerBlock(ashBrick, new ItemBlockForestry<>(ashBrick), "ash_brick"); ashStairs = new BlockAshStairs(ashBrick.getDefaultState()); - registerBlock(ashStairs, new ItemBlockForestry(ashStairs), "ash_stairs"); + registerBlock(ashStairs, new ItemBlockForestry<>(ashStairs), "ash_stairs"); // register some common oreDict names for our recipes OreDictionary.registerOre(OreDictUtil.CRAFTING_TABLE_WOOD, Blocks.CRAFTING_TABLE); diff --git a/src/main/java/forestry/core/config/Config.java b/src/main/java/forestry/core/config/Config.java index 82c74c063..d77e536ef 100755 --- a/src/main/java/forestry/core/config/Config.java +++ b/src/main/java/forestry/core/config/Config.java @@ -112,6 +112,9 @@ public class Config { public static boolean ringFarms = true; public static int ringSize = 4; + // Book + public static boolean spawnWithBook = true; + // Mail public static boolean mailAlertEnabled = true; public static GuiMailboxInfo.XPosition mailAlertXPosition = GuiMailboxInfo.XPosition.LEFT; @@ -341,6 +344,8 @@ public class Config { isDebug = configCommon.getBooleanLocalized("debug", "enabled", isDebug); + spawnWithBook = configCommon.getBooleanLocalized("tweaks.book", "spawn", spawnWithBook); + configCommon.save(); } diff --git a/src/main/java/forestry/core/genetics/SpeciesDisplayHelper.java b/src/main/java/forestry/core/genetics/SpeciesDisplayHelper.java new file mode 100644 index 000000000..5984ab9a4 --- /dev/null +++ b/src/main/java/forestry/core/genetics/SpeciesDisplayHelper.java @@ -0,0 +1,59 @@ +package forestry.core.genetics; + +import com.google.common.collect.HashBasedTable; +import com.google.common.collect.Table; + +import javax.annotation.Nullable; +import java.util.Optional; +import java.util.function.Function; + +import net.minecraft.item.ItemStack; + +import forestry.api.genetics.IAlleleSpecies; +import forestry.api.genetics.IAlyzerPlugin; +import forestry.api.genetics.IDatabasePlugin; +import forestry.api.genetics.IIndividual; +import forestry.api.genetics.ISpeciesDisplayHelper; +import forestry.api.genetics.ISpeciesRoot; +import forestry.api.genetics.ISpeciesType; + +public class SpeciesDisplayHelper implements ISpeciesDisplayHelper { + private final Table iconStacks = HashBasedTable.create(); + @Nullable + private final IAlyzerPlugin alyzerPlugin; + @Nullable + private final IDatabasePlugin databasePlugin; + private final ISpeciesRoot root; + + public SpeciesDisplayHelper(ISpeciesRoot root, @Nullable Function alyzerPlugin, @Nullable Function databasePlugin) { + this.root = root; + for (IIndividual individual : root.getIndividualTemplates()) { + for (ISpeciesType type : root.getTypes()) { + ItemStack itemStack = root.getMemberStack(individual, type); + iconStacks.put(type, individual.getGenome().getPrimary().getUID(), itemStack); + } + } + this.alyzerPlugin = alyzerPlugin == null ? null : alyzerPlugin.apply(this); + this.databasePlugin = databasePlugin == null ? null : databasePlugin.apply(this); + } + + @Override + public Optional getDatabasePlugin() { + return Optional.ofNullable(databasePlugin); + } + + @Override + public Optional getAlyzerPlugin() { + return Optional.ofNullable(alyzerPlugin); + } + + @Override + public ItemStack getDisplayStack(IAlleleSpecies species, ISpeciesType type) { + return iconStacks.get(species.getUID(), type); + } + + @Override + public ItemStack getDisplayStack(IAlleleSpecies species) { + return getDisplayStack(species, root.getIconType()); + } +} diff --git a/src/main/java/forestry/core/genetics/alleles/AlleleHelper.java b/src/main/java/forestry/core/genetics/alleles/AlleleHelper.java index 5ce865241..da9418493 100644 --- a/src/main/java/forestry/core/genetics/alleles/AlleleHelper.java +++ b/src/main/java/forestry/core/genetics/alleles/AlleleHelper.java @@ -17,12 +17,10 @@ import java.util.HashMap; import java.util.Locale; import java.util.Map; -import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.Vec3i; import forestry.api.apiculture.EnumBeeChromosome; import forestry.api.arboriculture.EnumTreeChromosome; -import forestry.api.core.ForestryAPI; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.EnumTolerance; import forestry.api.genetics.IAllele; @@ -34,6 +32,7 @@ import forestry.api.lepidopterology.EnumButterflyChromosome; import forestry.apiculture.flowers.FlowerProvider; import forestry.core.config.Constants; import forestry.modules.ForestryModuleUids; +import forestry.modules.ModuleHelper; public class AlleleHelper implements IAlleleHelper { @@ -51,13 +50,13 @@ public class AlleleHelper implements IAlleleHelper { } public void init() { - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.APICULTURE))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.APICULTURE)) { createAlleles(EnumAllele.Fertility.class, EnumBeeChromosome.FERTILITY); createAlleles(EnumAllele.Flowering.class, EnumBeeChromosome.FLOWERING); createAlleles(EnumAllele.Territory.class, EnumBeeChromosome.TERRITORY); } - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.APICULTURE)) || ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.LEPIDOPTEROLOGY))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.APICULTURE, ForestryModuleUids.LEPIDOPTEROLOGY)) { createAlleles(EnumAllele.Speed.class, EnumBeeChromosome.SPEED, EnumButterflyChromosome.SPEED @@ -78,7 +77,7 @@ public class AlleleHelper implements IAlleleHelper { ); } - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.ARBORICULTURE))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.ARBORICULTURE)) { createAlleles(EnumAllele.Height.class, EnumTreeChromosome.HEIGHT); createAlleles(EnumAllele.Saplings.class, EnumTreeChromosome.FERTILITY); createAlleles(EnumAllele.Yield.class, EnumTreeChromosome.YIELD); @@ -87,7 +86,7 @@ public class AlleleHelper implements IAlleleHelper { createAlleles(EnumAllele.Sappiness.class, EnumTreeChromosome.SAPPINESS); } - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.LEPIDOPTEROLOGY))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.LEPIDOPTEROLOGY)) { createAlleles(EnumAllele.Size.class, EnumButterflyChromosome.SIZE); } diff --git a/src/main/java/forestry/core/genetics/alleles/AlleleSpecies.java b/src/main/java/forestry/core/genetics/alleles/AlleleSpecies.java index 88b13b12b..786c09959 100644 --- a/src/main/java/forestry/core/genetics/alleles/AlleleSpecies.java +++ b/src/main/java/forestry/core/genetics/alleles/AlleleSpecies.java @@ -18,14 +18,12 @@ import java.util.Map; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; -import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import com.mojang.authlib.GameProfile; import forestry.api.core.EnumHumidity; import forestry.api.core.EnumTemperature; -import forestry.api.core.ForestryAPI; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAlleleSpecies; import forestry.api.genetics.IAlleleSpeciesBuilder; @@ -35,11 +33,11 @@ import forestry.api.genetics.IIndividual; import forestry.api.genetics.IMutation; import forestry.apiculture.ModuleApiculture; import forestry.apiculture.items.ItemRegistryApiculture; -import forestry.core.config.Constants; import forestry.core.utils.GeneticsUtil; import forestry.core.utils.ItemStackUtil; import forestry.core.utils.Translator; import forestry.modules.ForestryModuleUids; +import forestry.modules.ModuleHelper; public abstract class AlleleSpecies extends Allele implements IAlleleSpeciesBuilder, IAlleleSpecies { private final String binomial; @@ -82,7 +80,7 @@ public abstract class AlleleSpecies extends Allele implements IAlleleSpeciesBuil return 0f; } - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.APICULTURE))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.APICULTURE)) { ItemRegistryApiculture beeItems = ModuleApiculture.getItems(); Item item = itemstack.getItem(); if (beeItems.honeyDrop == item) { diff --git a/src/main/java/forestry/core/genetics/analyzer/AnalyzerTab.java b/src/main/java/forestry/core/genetics/analyzer/AnalyzerTab.java new file mode 100644 index 000000000..626bc6028 --- /dev/null +++ b/src/main/java/forestry/core/genetics/analyzer/AnalyzerTab.java @@ -0,0 +1,27 @@ +package forestry.core.genetics.analyzer; + +import net.minecraft.item.ItemStack; +import net.minecraft.util.text.translation.I18n; + +import forestry.api.genetics.IDatabaseTab; +import forestry.api.genetics.IIndividual; +import forestry.api.gui.IElementGenetic; +import forestry.core.ModuleCore; + +public enum AnalyzerTab implements IDatabaseTab { + ANALYZE { + @Override + public void createElements(IElementGenetic container, IIndividual individual, ItemStack itemStack) { + + } + + @Override + public ItemStack getIconStack() { + return new ItemStack(ModuleCore.getItems().portableAlyzer); + } + }; + + public String getTooltip(IIndividual individual){ + return I18n.translateToLocal("for.gui.database.tab." + name().toLowerCase() + ".name"); + } +} diff --git a/src/main/java/forestry/core/genetics/analyzer/DatabasePlugin.java b/src/main/java/forestry/core/genetics/analyzer/DatabasePlugin.java new file mode 100644 index 000000000..65b14e198 --- /dev/null +++ b/src/main/java/forestry/core/genetics/analyzer/DatabasePlugin.java @@ -0,0 +1,33 @@ +package forestry.core.genetics.analyzer; + +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import forestry.api.genetics.IDatabasePlugin; +import forestry.api.genetics.IDatabaseTab; +import forestry.api.genetics.IIndividual; + +@SideOnly(Side.CLIENT) +public abstract class DatabasePlugin implements IDatabasePlugin { + private final IDatabaseTab activeTab; + private final IDatabaseTab inactiveTab; + private final IDatabaseTab productsTab; + private final IDatabaseTab mutationsTab; + + public DatabasePlugin(IDatabaseTab activeTab, IDatabaseTab inactiveTab, IDatabaseTab productsTab, IDatabaseTab mutationsTab) { + this.activeTab = activeTab; + this.inactiveTab = inactiveTab; + this.productsTab = productsTab; + this.mutationsTab = mutationsTab; + } + + @Override + public IDatabaseTab[] getTabs(){ + return new IDatabaseTab[]{ + activeTab, + inactiveTab, + productsTab, + mutationsTab + }; + } +} diff --git a/src/main/java/forestry/core/genetics/analyzer/DatabaseTab.java b/src/main/java/forestry/core/genetics/analyzer/DatabaseTab.java new file mode 100644 index 000000000..49042535a --- /dev/null +++ b/src/main/java/forestry/core/genetics/analyzer/DatabaseTab.java @@ -0,0 +1,29 @@ +package forestry.core.genetics.analyzer; + +import java.util.function.Supplier; + +import net.minecraft.item.ItemStack; +import net.minecraft.util.text.translation.I18n; + +import forestry.api.genetics.IDatabaseTab; +import forestry.api.genetics.IIndividual; + +public abstract class DatabaseTab implements IDatabaseTab { + private final Supplier stackSupplier; + private final String name; + + public DatabaseTab(String name, Supplier stackSupplier) { + this.name = name; + this.stackSupplier = stackSupplier; + } + + @Override + public ItemStack getIconStack() { + return stackSupplier.get(); + } + + @Override + public String getTooltip(IIndividual individual){ + return I18n.translateToLocal("for.gui.database.tab." + name + ".name"); + } +} diff --git a/src/main/java/forestry/core/genetics/analyzer/MutationsTab.java b/src/main/java/forestry/core/genetics/analyzer/MutationsTab.java new file mode 100644 index 000000000..c9fe91532 --- /dev/null +++ b/src/main/java/forestry/core/genetics/analyzer/MutationsTab.java @@ -0,0 +1,58 @@ +package forestry.core.genetics.analyzer; + +import java.util.Collection; +import java.util.List; +import java.util.function.Supplier; + +import net.minecraft.client.Minecraft; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.text.TextFormatting; + +import forestry.api.genetics.IAlleleSpecies; +import forestry.api.genetics.IBreedingTracker; +import forestry.api.genetics.IGenome; +import forestry.api.genetics.IIndividual; +import forestry.api.genetics.IMutation; +import forestry.api.genetics.ISpeciesRoot; +import forestry.api.gui.GuiElementAlignment; +import forestry.api.gui.IElementGenetic; +import forestry.api.gui.IElementLayoutHelper; +import forestry.core.gui.elements.GuiElementFactory; +import forestry.core.utils.Translator; + +public class MutationsTab extends DatabaseTab { + public MutationsTab(Supplier stackSupplier) { + super("mutations", stackSupplier); + } + + @Override + public void createElements(IElementGenetic container, IIndividual individual, ItemStack itemStack) { + IGenome genome = individual.getGenome(); + ISpeciesRoot speciesRoot = genome.getSpeciesRoot(); + IAlleleSpecies species = genome.getPrimary(); + + EntityPlayer player = Minecraft.getMinecraft().player; + IBreedingTracker breedingTracker = speciesRoot.getBreedingTracker(player.world, player.getGameProfile()); + + IElementLayoutHelper groupHelper = container.layoutHelper((x, y) -> GuiElementFactory.INSTANCE.createHorizontal(x + 1, y, 16), 100, 0); + Collection mutations = getValidMutations(speciesRoot.getCombinations(species)); + if(!mutations.isEmpty()) { + container.text(TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.database.mutations.further"), GuiElementAlignment.TOP_CENTER); + mutations.forEach(mutation -> groupHelper.add(GuiElementFactory.INSTANCE.createMutation(0, 0, 50, 16, mutation, species, breedingTracker))); + groupHelper.finish(true); + } + mutations = getValidMutations(speciesRoot.getResultantMutations(species)); + if(mutations.isEmpty()){ + return; + } + container.text(TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.database.mutations.resultant"), GuiElementAlignment.TOP_CENTER); + mutations.forEach(mutation -> groupHelper.add(GuiElementFactory.INSTANCE.createMutationResultant(0, 0, 50, 16, mutation, breedingTracker))); + groupHelper.finish(true); + } + + private Collection getValidMutations(List mutations){ + mutations.removeIf(IMutation::isSecret); + return mutations; + } +} diff --git a/src/main/java/forestry/core/genetics/analyzer/ProductsTab.java b/src/main/java/forestry/core/genetics/analyzer/ProductsTab.java new file mode 100644 index 000000000..84c77e58c --- /dev/null +++ b/src/main/java/forestry/core/genetics/analyzer/ProductsTab.java @@ -0,0 +1,65 @@ +package forestry.core.genetics.analyzer; + +import java.util.Collection; +import java.util.Collections; +import java.util.function.Supplier; + +import net.minecraft.item.ItemStack; + +import forestry.api.apiculture.IBee; +import forestry.api.arboriculture.ITree; +import forestry.api.genetics.IIndividual; +import forestry.api.gui.GuiElementAlignment; +import forestry.api.gui.IElementGenetic; +import forestry.api.gui.IElementLayoutHelper; +import forestry.core.gui.elements.GuiElementFactory; +import forestry.core.gui.elements.ItemElement; +import forestry.core.utils.Translator; + +public class ProductsTab extends DatabaseTab { + public ProductsTab(Supplier stackSupplier) { + super("products", stackSupplier); + } + + @Override + public void createElements(IElementGenetic container, IIndividual individual, ItemStack itemStack) { + IElementLayoutHelper groupHelper = container.layoutHelper((x, y) -> GuiElementFactory.INSTANCE.createHorizontal(x + 4, y, 18).setDistance(2), 90, 0); + Collection products = getProducts(individual); + if(!products.isEmpty()) { + container.text(Translator.translateToLocal("for.gui.beealyzer.produce"), GuiElementAlignment.TOP_CENTER); + products.forEach(product -> groupHelper.add(new ItemElement(0, 0, product))); + groupHelper.finish(); + } + + Collection specialties = getSpecialties(individual); + if(specialties.isEmpty()){ + return; + } + + container.text(Translator.translateToLocal("for.gui.beealyzer.specialty"), GuiElementAlignment.TOP_CENTER); + specialties.forEach(specialty -> groupHelper.add(new ItemElement(0, 0, specialty))); + groupHelper.finish(); + } + + private Collection getSpecialties(IIndividual individual){ + if(individual instanceof IBee){ + IBee bee = (IBee) individual; + return bee.getSpecialtyList(); + }else if(individual instanceof ITree){ + ITree tree = (ITree) individual; + return tree.getSpecialties().keySet(); + } + return Collections.emptyList(); + } + + private Collection getProducts(IIndividual individual){ + if(individual instanceof IBee){ + IBee bee = (IBee) individual; + return bee.getProduceList(); + }else if(individual instanceof ITree){ + ITree tree = (ITree) individual; + return tree.getProducts().keySet(); + } + return Collections.emptyList(); + } +} diff --git a/src/main/java/forestry/core/genetics/analyzer/package-info.java b/src/main/java/forestry/core/genetics/analyzer/package-info.java new file mode 100644 index 000000000..e3441c378 --- /dev/null +++ b/src/main/java/forestry/core/genetics/analyzer/package-info.java @@ -0,0 +1,10 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.genetics.analyzer; + +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/genetics/mutations/Mutation.java b/src/main/java/forestry/core/genetics/mutations/Mutation.java index ee2b6bd80..eb605a3c4 100644 --- a/src/main/java/forestry/core/genetics/mutations/Mutation.java +++ b/src/main/java/forestry/core/genetics/mutations/Mutation.java @@ -10,10 +10,18 @@ ******************************************************************************/ package forestry.core.genetics.mutations; +import com.google.common.base.MoreObjects; + import java.util.ArrayList; import java.util.Collection; import java.util.List; +import net.minecraft.block.state.IBlockState; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; + +import net.minecraftforge.common.BiomeDictionary; + import forestry.api.climate.IClimateProvider; import forestry.api.core.EnumHumidity; import forestry.api.core.EnumTemperature; @@ -23,10 +31,6 @@ import forestry.api.genetics.IGenome; import forestry.api.genetics.IMutation; import forestry.api.genetics.IMutationBuilder; import forestry.api.genetics.IMutationCondition; -import net.minecraft.block.state.IBlockState; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import net.minecraftforge.common.BiomeDictionary; public abstract class Mutation implements IMutation, IMutationBuilder { @@ -177,4 +181,15 @@ public abstract class Mutation implements IMutation, IMutationBuilder { return isSecret; } + @Override + public String toString() { + MoreObjects.ToStringHelper stringHelper = MoreObjects.toStringHelper(this) + .add("first", species0) + .add("second", species1) + .add("result", template[0]); + if(!specialConditions.isEmpty()){ + stringHelper.add("conditions", getSpecialConditions()); + } + return stringHelper.toString(); + } } diff --git a/src/main/java/forestry/core/gui/ContainerAnalyzerProvider.java b/src/main/java/forestry/core/gui/ContainerAnalyzerProvider.java new file mode 100644 index 000000000..2861eec42 --- /dev/null +++ b/src/main/java/forestry/core/gui/ContainerAnalyzerProvider.java @@ -0,0 +1,143 @@ +package forestry.core.gui; + +import javax.annotation.Nullable; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; + +import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.IBreedingTracker; +import forestry.api.genetics.IIndividual; +import forestry.api.genetics.ISpeciesRoot; +import forestry.core.ModuleCore; +import forestry.core.gui.slots.SlotAnalyzer; +import forestry.core.gui.slots.SlotLockable; +import forestry.core.inventory.ItemInventoryAlyzer; +import forestry.core.utils.GeneticsUtil; +import forestry.database.inventory.InventoryDatabaseAnalyzer; +import forestry.modules.ForestryModuleUids; +import forestry.modules.ModuleHelper; + +public class ContainerAnalyzerProvider extends ContainerTile implements IGuiSelectable { + /* Attributes - Final*/ + private final EntityPlayer player; + @Nullable + private final ItemInventoryAlyzer alyzerInventory; + private final int analyzerIndex; + + /* Constructors */ + public ContainerAnalyzerProvider(T tileForestry, InventoryPlayer playerInventory, int xInv, int yInv) { + super(tileForestry, playerInventory, xInv, yInv); + + this.player = playerInventory.player; + + ItemInventoryAlyzer alyzerInventory = null; + int analyzerIndex = -1; + for(int i = 0;i < playerInventory.getSizeInventory();i++){ + ItemStack stack = playerInventory.getStackInSlot(i); + if(stack.isEmpty() || stack.getItem() != ModuleCore.getItems().portableAlyzer){ + continue; + } + analyzerIndex = i; + alyzerInventory = new ItemInventoryAlyzer(playerInventory.player, stack); + Slot slot = getSlotFromInventory(playerInventory, i); + if(slot instanceof SlotLockable){ + SlotLockable lockable = (SlotLockable) slot; + lockable.lock(); + } + break; + } + this.analyzerIndex = analyzerIndex; + this.alyzerInventory = alyzerInventory; + + if(alyzerInventory != null) { + addSlotToContainer(new SlotAnalyzer(alyzerInventory, ItemInventoryAlyzer.SLOT_ENERGY, -110, 20)); + } + + } + + /* Methods */ + @Nullable + public Slot getAnalyzerSlot(){ + if(alyzerInventory == null){ + return null; + } + return getSlotFromInventory(alyzerInventory, 0); + } + + private ItemStack analyzeSpecimen(int selectedSlot) { + if(selectedSlot < 0 || alyzerInventory == null){ + return ItemStack.EMPTY; + } + Slot specimenSlot = getForestrySlot( selectedSlot); + ItemStack specimen = specimenSlot.getStack(); + if (specimen.isEmpty()) { + return ItemStack.EMPTY; + } + + ItemStack convertedSpecimen = GeneticsUtil.convertToGeneticEquivalent(specimen); + if (!ItemStack.areItemStacksEqual(specimen, convertedSpecimen)) { + specimenSlot.putStack(convertedSpecimen); + specimen = convertedSpecimen; + } + + ISpeciesRoot speciesRoot = AlleleManager.alleleRegistry.getSpeciesRoot(specimen); + + // No individual, abort + if (speciesRoot == null) { + return specimen; + } + + IIndividual individual = speciesRoot.getMember(specimen); + + // Analyze if necessary + if (individual != null && !individual.isAnalyzed()) { + final boolean requiresEnergy = ModuleHelper.isEnabled(ForestryModuleUids.APICULTURE); + if (requiresEnergy) { + // Requires energy + if (!ItemInventoryAlyzer.isAlyzingFuel(alyzerInventory.getStackInSlot(InventoryDatabaseAnalyzer.SLOT_ENERGY))) { + return specimen; + } + } + + if (individual.analyze()) { + IBreedingTracker breedingTracker = speciesRoot.getBreedingTracker(player.world, player.getGameProfile()); + breedingTracker.registerSpecies(individual.getGenome().getPrimary()); + breedingTracker.registerSpecies(individual.getGenome().getSecondary()); + + NBTTagCompound nbttagcompound = new NBTTagCompound(); + individual.writeToNBT(nbttagcompound); + specimen.setTagCompound(nbttagcompound); + + if (requiresEnergy) { + // Decrease energy + alyzerInventory.decrStackSize(InventoryDatabaseAnalyzer.SLOT_ENERGY, 1); + } + } + specimenSlot.putStack(specimen); + } + return specimen; + } + + /* Methods - Implement ContainerForestry */ + @Override + protected void addSlot(InventoryPlayer playerInventory, int slot, int x, int y) { + addSlotToContainer(new SlotLockable(playerInventory, slot, x, y)); + } + + @Override + protected void addHotbarSlot(InventoryPlayer playerInventory, int slot, int x, int y) { + addSlotToContainer(new SlotLockable(playerInventory, slot, x, y)); + } + + /* Methods - Implement IGuiSelectable */ + @Override + public void handleSelectionRequest(EntityPlayerMP player, int primary, int secondary) { + analyzeSpecimen(secondary); + } +} diff --git a/src/main/java/forestry/core/gui/ContainerForestry.java b/src/main/java/forestry/core/gui/ContainerForestry.java index dac040072..edcb79754 100644 --- a/src/main/java/forestry/core/gui/ContainerForestry.java +++ b/src/main/java/forestry/core/gui/ContainerForestry.java @@ -10,19 +10,12 @@ ******************************************************************************/ package forestry.core.gui; +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.Multimaps; + import java.util.List; import java.util.Map; -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.Multimaps; -import forestry.core.gui.slots.SlotFilteredInventory; -import forestry.core.gui.slots.SlotForestry; -import forestry.core.gui.slots.SlotLocked; -import forestry.core.network.IForestryPacketClient; -import forestry.core.utils.NetworkUtil; -import forestry.core.utils.SlotUtil; -import invtweaks.api.container.ContainerSection; -import invtweaks.api.container.ContainerSectionCallback; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.ClickType; @@ -31,13 +24,25 @@ import net.minecraft.inventory.IContainerListener; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; +import forestry.core.gui.slots.SlotFilteredInventory; +import forestry.core.gui.slots.SlotForestry; +import forestry.core.gui.slots.SlotLocked; +import forestry.core.network.IForestryPacketClient; +import forestry.core.utils.NetworkUtil; +import forestry.core.utils.SlotUtil; +import invtweaks.api.container.ContainerSection; +import invtweaks.api.container.ContainerSectionCallback; + @invtweaks.api.container.ChestContainer(showButtons = false) public abstract class ContainerForestry extends Container { + public static final int PLAYER_HOTBAR_OFFSET = 27; + public static final int PLAYER_INV_SLOTS = PLAYER_HOTBAR_OFFSET + 9; + protected final void addPlayerInventory(InventoryPlayer playerInventory, int xInv, int yInv) { // Player inventory for (int row = 0; row < 3; row++) { for (int column = 0; column < 9; column++) { - addSlotToContainer(new Slot(playerInventory, column + row * 9 + 9, xInv + column * 18, yInv + row * 18)); + addSlot(playerInventory, column + row * 9 + 9, xInv + column * 18, yInv + row * 18); } } // Player hotbar @@ -50,6 +55,10 @@ public abstract class ContainerForestry extends Container { addSlotToContainer(new Slot(playerInventory, slot, x, y)); } + protected void addSlot(InventoryPlayer playerInventory, int slot, int x, int y){ + addSlotToContainer(new Slot(playerInventory, slot, x, y)); + } + @Override public Slot addSlotToContainer(Slot p_75146_1_) { return super.addSlotToContainer(p_75146_1_); @@ -63,7 +72,7 @@ public abstract class ContainerForestry extends Container { if (clickTypeIn == ClickType.SWAP && dragType_or_button >= 0 && dragType_or_button < 9) { // hotkey used to move item from slot to hotbar - int hotbarSlotIndex = 27 + dragType_or_button; + int hotbarSlotIndex = PLAYER_HOTBAR_OFFSET + dragType_or_button; Slot hotbarSlot = getSlot(hotbarSlotIndex); if (hotbarSlot instanceof SlotLocked) { return ItemStack.EMPTY; @@ -81,6 +90,11 @@ public abstract class ContainerForestry extends Container { return super.slotClick(slotId, dragType_or_button, clickTypeIn, player); } + public Slot getForestrySlot(int slot){ + return getSlot(PLAYER_INV_SLOTS + slot); + } + + @Override public final ItemStack transferStackInSlot(EntityPlayer player, int slotIndex) { if (!canAccess(player)) { diff --git a/src/main/java/forestry/core/gui/Drawable.java b/src/main/java/forestry/core/gui/Drawable.java index 2b24c3c00..ba7909f51 100644 --- a/src/main/java/forestry/core/gui/Drawable.java +++ b/src/main/java/forestry/core/gui/Drawable.java @@ -11,46 +11,44 @@ import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class Drawable { + /* Final Attributes */ + //Position on the Texture public final int u; public final int v; - public final int width; - public final int height; - + //Rectangle Size + public final int uWidth; + public final int vHeight; + //Texture public final ResourceLocation textureLocation; - public int textureWidth = 256; - public int textureHeight = 256; + //Texture Size + private final int textureWidth; + private final int textureHeight; - public Drawable(ResourceLocation textureLocation, int u, int v, int width, int height) { - this.textureLocation = textureLocation; - this.u = u; - this.v = v; - this.width = width; - this.height = height; + public Drawable(ResourceLocation textureLocation, int u, int v, int uWidth, int vHeight) { + this(textureLocation, u, v, uWidth, vHeight, 256, 256); } - public Drawable(ResourceLocation textureLocation, int u, int v, int width, int height, int textureWidth, int textureHeight) { + public Drawable(ResourceLocation textureLocation, int u, int v, int uWidth, int vHeight, int textureWidth, int textureHeight) { this.u = u; this.v = v; - this.width = width; - this.height = height; + this.uWidth = uWidth; + this.vHeight = vHeight; this.textureLocation = textureLocation; this.textureWidth = textureWidth; this.textureHeight = textureHeight; } - public Drawable setTextureSize(int textureWidth, int textureHeight) { - this.textureWidth = textureWidth; - this.textureHeight = textureHeight; - return this; - } - public void draw(int xOffset, int yOffset) { + draw(xOffset, yOffset, uWidth, vHeight); + } + + public void draw(int xOffset, int yOffset, int width, int height) { TextureManager textureManager = Minecraft.getMinecraft().getTextureManager(); textureManager.bindTexture(textureLocation); // Enable correct lighting. GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - Gui.drawModalRectWithCustomSizedTexture(xOffset, yOffset, u, v, width, height, textureWidth, textureHeight); + Gui.drawScaledCustomSizeModalRect(xOffset, yOffset, u, v, uWidth, vHeight, width, height, textureWidth, textureHeight); } } diff --git a/src/main/java/forestry/core/gui/GuiAnalyzerProvider.java b/src/main/java/forestry/core/gui/GuiAnalyzerProvider.java new file mode 100644 index 000000000..ce6defb5c --- /dev/null +++ b/src/main/java/forestry/core/gui/GuiAnalyzerProvider.java @@ -0,0 +1,204 @@ +package forestry.core.gui; + +import javax.annotation.Nullable; +import java.io.IOException; + +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; + +import forestry.api.genetics.IGeneticAnalyzer; +import forestry.api.genetics.IGeneticAnalyzerProvider; +import forestry.api.gui.IGuiElement; +import forestry.core.gui.buttons.GuiToggleButton; +import forestry.core.gui.elements.GeneticAnalyzer; +import forestry.core.gui.elements.GuiElementFactory; +import forestry.core.gui.slots.SlotAnalyzer; +import forestry.core.inventory.watchers.ISlotChangeWatcher; +import forestry.core.tiles.ITitled; + +public abstract class GuiAnalyzerProvider extends GuiForestryTitled implements IGeneticAnalyzerProvider, ISlotChangeWatcher { + /* Attributes - Constants */ + protected static final Drawable SELECTED_COMB_SLOT = new Drawable(GeneticAnalyzer.TEXTURE, 163, 0, 22, 22); + protected static final Drawable TOGGLE_BUTTON = new Drawable(GeneticAnalyzer.TEXTURE, 35, 166, 18, 20); + /* Attributes - Global */ + protected static boolean analyzerVisible = false; + + /* Attributes - Final */ + public final IGeneticAnalyzer analyzer; + //The slot that contains the "energy" (honey drops) of the analyzer. + @Nullable + private final SlotAnalyzer slotAnalyzer; + //Position of the button that toggles the analyzer. + private final int buttonX; + private final int buttonY; + //The distance from the left side of the gui to the analyzer. + private final int screenDistance; + //The count of slots that the analyzer can select. + private final int slots; + //The slot that the analyzer selects at the creation of the gui. + private final int firstSlot; + //True if the error logic has any active error state. + protected boolean deactivated; + /* Attributes - State */ + //True if the visibility of the analyser changed. + private boolean dirtyAnalyzer = false; + //True if the individual or the error state changed. + private boolean dirty = true; + + /* Constructors */ + public GuiAnalyzerProvider(String texture, C container, ITitled titled, int buttonX, int buttonY, int slots, int firstSlot) { + this(texture, container, titled, buttonX, buttonY, 0, false, slots, firstSlot); + } + + public GuiAnalyzerProvider(String texture, C container, ITitled titled, int buttonX, int buttonY, int screenDistance, boolean hasBoarder, int slots, int firstSlot) { + super(texture, container, titled); + this.buttonX = buttonX; + this.buttonY = buttonY; + this.screenDistance = screenDistance; + this.slots = slots; + this.firstSlot = firstSlot; + + this.analyzer = GuiElementFactory.INSTANCE.createAnalyzer(-189 - screenDistance, 0, hasBoarder, this); + updateVisibility(); + this.elementManager.add(analyzer); + + SlotAnalyzer slotAnalyzer = null; + if (container instanceof ContainerAnalyzerProvider) { + ContainerAnalyzerProvider containerAnalyzer = (ContainerAnalyzerProvider) container; + Slot analyzerSlot = containerAnalyzer.getAnalyzerSlot(); + if (analyzerSlot instanceof SlotAnalyzer) { + ((SlotAnalyzer) analyzerSlot).setGui(this); + slotAnalyzer = (SlotAnalyzer) analyzerSlot; + } + } + this.slotAnalyzer = slotAnalyzer; + } + + /* Methods */ + protected boolean hasErrors() { + return false; + } + + private void updateVisibility() { + analyzer.setVisible(!deactivated && analyzerVisible); + } + + protected abstract void drawSelectedSlot(int selectedSlot); + + /* Methods - Implement GuiScreen */ + @Override + public void initGui() { + super.initGui(); + + if (analyzer.isVisible()) { + this.guiLeft = (this.width - this.xSize + analyzer.getWidth() + (screenDistance)) / 2; + } + elementManager.init(guiLeft, guiTop + (ySize - 166) / 2); + /*analyzer.setXOffset(guiLeft); + analyzer.setYOffset(guiTop + (ySize - 166) / 2);*/ + + /*GuiButtonToggle toggle = new GuiButtonToggle(0, guiLeft + buttonX, guiTop + buttonY, 18, 20, false); + toggle.initTextureValues(0, 192, 0, 20, GeneticAnalyzer.TEXTURE); + buttonList.add(toggle);*/ + addButton(new GuiToggleButton(0, guiLeft + buttonX, guiTop + buttonY, 18, 20, TOGGLE_BUTTON)).enabled = ((ContainerAnalyzerProvider) inventorySlots).getAnalyzerSlot() != null; + dirty = true; + + if (slotAnalyzer != null) { + IGuiElement element = analyzer.getItemElement(); + slotAnalyzer.setPosition(element.getAbsoluteX() - guiLeft + 6, element.getAbsoluteY() - guiTop + 9); + } + } + + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + boolean ledger = hasErrors(); + if (!deactivated && ledger || !ledger && deactivated) { + deactivated = ledger; + updateVisibility(); + dirtyAnalyzer = true; + } + if (dirtyAnalyzer) { + buttonList.clear(); + initGui(); + dirtyAnalyzer = false; + } + if (dirty) { + analyzer.update(); + dirty = false; + } + super.drawScreen(mouseX, mouseY, partialTicks); + //analyzer.drawTooltip(this, mouseX, mouseY); + } + + @Override + protected void actionPerformed(GuiButton button) throws IOException { + super.actionPerformed(button); + if (button instanceof GuiToggleButton) { + analyzerVisible = !analyzerVisible; + updateVisibility(); + dirtyAnalyzer = true; + } + } + + @Override + protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { + super.mouseClicked(mouseX, mouseY, mouseButton); + //analyzer.mouseClicked(mouseX, mouseY, mouseButton); + } + + @Override + protected void keyTyped(char typedChar, int keyCode) throws IOException { + /*if (analyzer.keyTyped(typedChar, keyCode)) { + return; + }*/ + super.keyTyped(typedChar, keyCode); + } + + /* Methods - Implement GuiContainer */ + @Override + protected void drawGuiContainerBackgroundLayer(float f, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(f, mouseX, mouseY); + GlStateManager.color(1.0F, 1.0F, 1.0F); + //analyzer.draw(0, 0, mouseX, mouseY); + if (analyzer.isVisible()) { + int selectedSlot = analyzer.getSelected(); + if (selectedSlot >= 0) { + drawSelectedSlot(selectedSlot); + } + } + } + + @Override + protected boolean hasClickedOutside(int mouseX, int mouseY, int guiLeft, int guiTop) { + return !analyzer.isMouseOver(mouseX, mouseY) && super.hasClickedOutside(mouseX, mouseY, guiLeft, guiTop); + } + + /* Methods - Implement ISlotChangeWatcher*/ + @Override + public void onSlotChanged(IInventory inventory, int slot) { + if (slot == analyzer.getSelected()) { + dirty = true; + } + } + + /* Methods - Implement IGeneticAnalyzerProvider */ + @Override + public int getSelectedSlot(int index) { + // + 1 Because the first slot is the energy slot. + return 1 + index; + } + + @Override + public int getSlotCount() { + return slots; + } + + @Override + public int getFirstSlot() { + return firstSlot; + } + +} diff --git a/src/main/java/forestry/core/gui/GuiForestry.java b/src/main/java/forestry/core/gui/GuiForestry.java index 0397b3d2b..c6380b0c6 100755 --- a/src/main/java/forestry/core/gui/GuiForestry.java +++ b/src/main/java/forestry/core/gui/GuiForestry.java @@ -32,6 +32,7 @@ import net.minecraftforge.fluids.IFluidTank; import forestry.api.core.IErrorLogicSource; import forestry.api.core.IErrorSource; import forestry.core.config.Config; +import forestry.core.gui.elements.ElementManager; import forestry.core.gui.ledgers.ClimateLedger; import forestry.core.gui.ledgers.HintLedger; import forestry.core.gui.ledgers.LedgerManager; @@ -46,12 +47,13 @@ import forestry.core.render.ForestryResource; import forestry.core.tiles.IClimatised; import forestry.energy.EnergyManager; -public abstract class GuiForestry extends GuiContainer { +public abstract class GuiForestry extends GuiContainer implements IGuiSizable { protected final C container; public final ResourceLocation textureFile; protected final WidgetManager widgetManager; protected final LedgerManager ledgerManager; + protected final ElementManager elementManager; protected final TextLayoutHelper textLayout; protected GuiForestry(String texture, C container) { @@ -63,6 +65,7 @@ public abstract class GuiForestry extends GuiContainer { this.widgetManager = new WidgetManager(this); this.ledgerManager = new LedgerManager(this); + this.elementManager = new ElementManager(this); this.textureFile = texture; @@ -81,6 +84,8 @@ public abstract class GuiForestry extends GuiContainer { this.ledgerManager.setMaxWidth(maxLedgerWidth); this.ledgerManager.clear(); + this.elementManager.init(guiLeft, guiTop); + addLedgers(); } @@ -144,20 +149,22 @@ public abstract class GuiForestry extends GuiContainer { } @Override - protected void mouseClicked(int xPos, int yPos, int mouseButton) throws IOException { - super.mouseClicked(xPos, yPos, mouseButton); + protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { + super.mouseClicked(mouseX, mouseY, mouseButton); // / Handle ledger clicks - ledgerManager.handleMouseClicked(xPos, yPos, mouseButton); - widgetManager.handleMouseClicked(xPos, yPos, mouseButton); + ledgerManager.handleMouseClicked(mouseX, mouseY, mouseButton); + widgetManager.handleMouseClicked(mouseX, mouseY, mouseButton); + elementManager.mouseClicked(mouseX, mouseY, mouseButton); } @Override - protected void mouseReleased(int mouseX, int mouseY, int state) { - if (widgetManager.handleMouseRelease(mouseX, mouseY, state)) { + protected void mouseReleased(int mouseX, int mouseY, int mouseButton) { + if (widgetManager.handleMouseRelease(mouseX, mouseY, mouseButton)) { return; } - super.mouseReleased(mouseX, mouseY, state); + elementManager.mouseReleased(mouseX, mouseY, mouseButton); + super.mouseReleased(mouseX, mouseY, mouseButton); } @Override @@ -168,6 +175,14 @@ public abstract class GuiForestry extends GuiContainer { super.mouseClickMove(mouseX, mouseY, mouseButton, time); } + @Override + protected void keyTyped(char typedChar, int keyCode) throws IOException { + if(elementManager.keyTyped(typedChar, keyCode)){ + return; + } + super.keyTyped(typedChar, keyCode); + } + @Nullable public FluidStack getFluidStackAtPosition(int mouseX, int mouseY) { for (Widget widget : widgetManager.getWidgets()) { @@ -209,6 +224,7 @@ public abstract class GuiForestry extends GuiContainer { GuiUtil.drawToolTips(this, widgetManager.getWidgets(), mouseX, mouseY); GuiUtil.drawToolTips(this, buttonList, mouseX, mouseY); GuiUtil.drawToolTips(this, inventorySlots.inventorySlots, mouseX, mouseY); + elementManager.drawTooltip(mouseX, mouseY); } } @@ -229,15 +245,18 @@ public abstract class GuiForestry extends GuiContainer { } GlStateManager.popMatrix(); + GlStateManager.color(1.0F, 1.0F, 1.0F); + elementManager.draw(mouseX, mouseY); + bindTexture(textureFile); } protected void drawBackground(){ bindTexture(textureFile); - int x = (width - xSize) / 2; - int y = (height - ySize) / 2; - drawTexturedModalRect(x, y, 0, 0, xSize, ySize); + //int x = (width - xSize) / 2; + //int y = (height - ySize) / 2; + drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize); } protected void drawWidgets() { @@ -255,10 +274,12 @@ public abstract class GuiForestry extends GuiContainer { this.zLevel = level; } + @Override public int getSizeX() { return xSize; } + @Override public int getSizeY() { return ySize; } @@ -273,6 +294,11 @@ public abstract class GuiForestry extends GuiContainer { return guiTop; } + @Override + public Minecraft getMC() { + return mc; + } + @Override public void drawGradientRect(int par1, int par2, int par3, int par4, int par5, int par6) { super.drawGradientRect(par1, par2, par3, par4, par5, par6); diff --git a/src/main/java/forestry/core/gui/GuiForestryTitled.java b/src/main/java/forestry/core/gui/GuiForestryTitled.java index 980351375..84652a5af 100644 --- a/src/main/java/forestry/core/gui/GuiForestryTitled.java +++ b/src/main/java/forestry/core/gui/GuiForestryTitled.java @@ -10,10 +10,11 @@ ******************************************************************************/ package forestry.core.gui; +import net.minecraft.inventory.Container; + import forestry.core.render.ColourProperties; import forestry.core.tiles.ITitled; import forestry.core.utils.Translator; -import net.minecraft.inventory.Container; public abstract class GuiForestryTitled extends GuiForestry { private final String unlocalizedTitle; @@ -29,7 +30,15 @@ public abstract class GuiForestryTitled extends GuiForestry String name = Translator.translateToLocal(this.unlocalizedTitle); textLayout.line = 6; - textLayout.drawCenteredLine(name, 0, ColourProperties.INSTANCE.get("gui.title")); + if(centeredTitle()) { + textLayout.drawCenteredLine(name, 0, ColourProperties.INSTANCE.get("gui.title")); + }else{ + textLayout.drawLine(name, 8, ColourProperties.INSTANCE.get("gui.title")); + } bindTexture(textureFile); } + + protected boolean centeredTitle(){ + return true; + } } diff --git a/src/main/java/forestry/core/gui/GuiIdRegistry.java b/src/main/java/forestry/core/gui/GuiIdRegistry.java index b5aec74d0..6ed5e2c54 100644 --- a/src/main/java/forestry/core/gui/GuiIdRegistry.java +++ b/src/main/java/forestry/core/gui/GuiIdRegistry.java @@ -25,6 +25,7 @@ import forestry.apiculture.multiblock.TileAlvearyHygroregulator; import forestry.apiculture.multiblock.TileAlvearySieve; import forestry.apiculture.tiles.TileApiary; import forestry.apiculture.tiles.TileBeeHouse; +import forestry.book.items.ItemForesterBook; import forestry.core.items.ItemAlyzer; import forestry.core.items.ItemSolderingIron; import forestry.core.tiles.TileAnalyzer; @@ -131,7 +132,8 @@ public class GuiIdRegistry { ItemImprinter.class, ItemLetter.class, ItemSolderingIron.class, - ItemCamouflageSprayCan.class + ItemCamouflageSprayCan.class, + ItemForesterBook.class )); registerGuiHandlers(GuiType.Entity, Arrays.asList( diff --git a/src/main/java/forestry/core/gui/GuiUtil.java b/src/main/java/forestry/core/gui/GuiUtil.java index 7e89b8c43..d9244008a 100755 --- a/src/main/java/forestry/core/gui/GuiUtil.java +++ b/src/main/java/forestry/core/gui/GuiUtil.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.core.gui; +import javax.annotation.Nullable; import java.util.Collection; import java.util.List; @@ -47,18 +48,20 @@ public class GuiUtil { itemRender.renderItemOverlayIntoGUI(font, stack, xPos, yPos, null); } - public static void drawToolTips(GuiForestry gui, ToolTip toolTips, int mouseX, int mouseY) { + public static void drawToolTips(IGuiSizable gui, @Nullable IToolTipProvider provider, ToolTip toolTips, int mouseX, int mouseY) { List lines = toolTips.getLines(); if (!lines.isEmpty()) { GlStateManager.pushMatrix(); - GlStateManager.translate(-gui.getGuiLeft(), -gui.getGuiTop(), 0); - ScaledResolution scaledresolution = new ScaledResolution(gui.mc); - GuiUtils.drawHoveringText(lines, mouseX, mouseY, scaledresolution.getScaledWidth(), scaledresolution.getScaledHeight(), -1, gui.mc.fontRenderer); + if(provider == null || provider.isRelativeToGui()) { + GlStateManager.translate(-gui.getGuiLeft(), -gui.getGuiTop(), 0); + } + ScaledResolution scaledresolution = new ScaledResolution(gui.getMC()); + GuiUtils.drawHoveringText(lines, mouseX, mouseY, scaledresolution.getScaledWidth(), scaledresolution.getScaledHeight(), -1, gui.getMC().fontRenderer); GlStateManager.popMatrix(); } } - public static void drawToolTips(GuiForestry gui, Collection objects, int mouseX, int mouseY) { + public static void drawToolTips(IGuiSizable gui, Collection objects, int mouseX, int mouseY) { for (Object obj : objects) { if (!(obj instanceof IToolTipProvider)) { continue; @@ -67,15 +70,21 @@ public class GuiUtil { if (!provider.isToolTipVisible()) { continue; } - ToolTip tips = provider.getToolTip(mouseX - gui.getGuiLeft(), mouseY - gui.getGuiTop()); + int mX = mouseX; + int mY = mouseY; + if(provider.isRelativeToGui()){ + mX-=gui.getGuiLeft(); + mY-=gui.getGuiTop(); + } + ToolTip tips = provider.getToolTip(mX, mY); if (tips == null) { continue; } - boolean mouseOver = provider.isMouseOver(mouseX - gui.getGuiLeft(), mouseY - gui.getGuiTop()); + boolean mouseOver = provider.isMouseOver(mX, mY); tips.onTick(mouseOver); if (mouseOver && tips.isReady()) { tips.refresh(); - drawToolTips(gui, tips, mouseX, mouseY); + drawToolTips(gui, provider, tips, mouseX, mouseY); } } } diff --git a/src/main/java/forestry/core/gui/IGuiHandlerItem.java b/src/main/java/forestry/core/gui/IGuiHandlerItem.java index ecb15ef98..73897f845 100644 --- a/src/main/java/forestry/core/gui/IGuiHandlerItem.java +++ b/src/main/java/forestry/core/gui/IGuiHandlerItem.java @@ -12,17 +12,18 @@ package forestry.core.gui; import javax.annotation.Nullable; -import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.client.gui.GuiScreen; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.item.ItemStack; + import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public interface IGuiHandlerItem extends IGuiHandlerForestry { @Nullable @SideOnly(Side.CLIENT) - GuiContainer getGui(EntityPlayer player, ItemStack heldItem, int data); + GuiScreen getGui(EntityPlayer player, ItemStack heldItem, int data); @Nullable Container getContainer(EntityPlayer player, ItemStack heldItem, int data); diff --git a/src/main/java/forestry/core/gui/IGuiSizable.java b/src/main/java/forestry/core/gui/IGuiSizable.java new file mode 100644 index 000000000..f163d4b0d --- /dev/null +++ b/src/main/java/forestry/core/gui/IGuiSizable.java @@ -0,0 +1,20 @@ +package forestry.core.gui; + +import net.minecraft.client.Minecraft; + +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +@SideOnly(Side.CLIENT) +public interface IGuiSizable { + + int getGuiLeft(); + + int getGuiTop(); + + int getSizeX(); + + int getSizeY(); + + Minecraft getMC(); +} diff --git a/src/main/java/forestry/core/gui/buttons/GuiBetterButton.java b/src/main/java/forestry/core/gui/buttons/GuiBetterButton.java index 23430cf7a..62181cf9d 100755 --- a/src/main/java/forestry/core/gui/buttons/GuiBetterButton.java +++ b/src/main/java/forestry/core/gui/buttons/GuiBetterButton.java @@ -29,7 +29,7 @@ import forestry.core.render.ForestryResource; @SideOnly(Side.CLIENT) public class GuiBetterButton extends GuiButton implements IToolTipProvider { - private static final ResourceLocation TEXTURE = new ForestryResource(Constants.TEXTURE_PATH_GUI + "/buttons.png"); + public static final ResourceLocation TEXTURE = new ForestryResource(Constants.TEXTURE_PATH_GUI + "/buttons.png"); protected IButtonTextureSet texture; @Nullable private ToolTip toolTip; diff --git a/src/main/java/forestry/core/gui/buttons/GuiToggleButton.java b/src/main/java/forestry/core/gui/buttons/GuiToggleButton.java new file mode 100644 index 000000000..a4354fa0b --- /dev/null +++ b/src/main/java/forestry/core/gui/buttons/GuiToggleButton.java @@ -0,0 +1,26 @@ +package forestry.core.gui.buttons; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiButton; + +import forestry.core.gui.Drawable; + +public class GuiToggleButton extends GuiButton { + /* attributes - Final */ + private final Drawable[] textures = new Drawable[3]; + + public GuiToggleButton(int buttonId, int x, int y, int widthIn, int heightIn, Drawable drawable) { + super(buttonId, x, y, widthIn, heightIn, ""); + for(int i = 0;i < 3;i++){ + textures[i] = new Drawable(drawable.textureLocation, drawable.u, drawable.v + drawable.vHeight * i, drawable.uWidth, drawable.vHeight); + } + } + + @Override + public void drawButton(Minecraft mc, int mouseX, int mouseY, float partialTicks) { + this.hovered = mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.width && mouseY < this.y + this.height; + int hoverState = this.getHoverState(this.hovered); + Drawable drawable = textures[hoverState]; + drawable.draw(x, y); + } +} diff --git a/src/main/java/forestry/core/gui/buttons/IButtonTextureSet.java b/src/main/java/forestry/core/gui/buttons/IButtonTextureSet.java index ddb88d9a0..810de465c 100755 --- a/src/main/java/forestry/core/gui/buttons/IButtonTextureSet.java +++ b/src/main/java/forestry/core/gui/buttons/IButtonTextureSet.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.core.gui.buttons; +import net.minecraft.util.ResourceLocation; + /** * @author CovertJaguar */ @@ -23,4 +25,5 @@ public interface IButtonTextureSet { int getWidth(); + ResourceLocation getTexture(); } diff --git a/src/main/java/forestry/core/gui/buttons/StandardButtonTextureSets.java b/src/main/java/forestry/core/gui/buttons/StandardButtonTextureSets.java index d9c74488b..fa2fe94a2 100755 --- a/src/main/java/forestry/core/gui/buttons/StandardButtonTextureSets.java +++ b/src/main/java/forestry/core/gui/buttons/StandardButtonTextureSets.java @@ -10,11 +10,12 @@ ******************************************************************************/ package forestry.core.gui.buttons; +import net.minecraft.util.ResourceLocation; + /** * @author CovertJaguar */ public enum StandardButtonTextureSets implements IButtonTextureSet { - LARGE_BUTTON(0, 0, 20, 200), SMALL_BUTTON(0, 80, 15, 200), LOCKED_BUTTON(224, 0, 16, 16), @@ -57,4 +58,8 @@ public enum StandardButtonTextureSets implements IButtonTextureSet { return width; } + @Override + public ResourceLocation getTexture() { + return GuiBetterButton.TEXTURE; + } } diff --git a/src/main/java/forestry/core/gui/elements/GuiElementItemStack.java b/src/main/java/forestry/core/gui/elements/AbstractItemElement.java similarity index 55% rename from src/main/java/forestry/core/gui/elements/GuiElementItemStack.java rename to src/main/java/forestry/core/gui/elements/AbstractItemElement.java index fe06595d4..5ef8cb8e1 100644 --- a/src/main/java/forestry/core/gui/elements/GuiElementItemStack.java +++ b/src/main/java/forestry/core/gui/elements/AbstractItemElement.java @@ -10,43 +10,46 @@ ******************************************************************************/ package forestry.core.gui.elements; -import java.util.ArrayList; import java.util.List; import net.minecraft.client.Minecraft; -import net.minecraft.client.util.ITooltipFlag; -import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.RenderHelper; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import forestry.core.gui.GuiUtil; +import forestry.core.utils.ItemTooltipUtil; -public class GuiElementItemStack extends GuiElement { - private final ItemStack itemStack; +public abstract class AbstractItemElement extends GuiElement { - public GuiElementItemStack(int xPos, int yPos, ItemStack itemStack) { + public AbstractItemElement(int xPos, int yPos, int width, int height) { + super(xPos, yPos, width, height); + } + + public AbstractItemElement(int xPos, int yPos) { super(xPos, yPos, 16, 16); - this.itemStack = itemStack; } @Override - public void draw(int startX, int startY) { + public void drawElement(int mouseX, int mouseY) { + ItemStack itemStack = getItemStack(); if (!itemStack.isEmpty()) { - GuiUtil.drawItemStack(Minecraft.getMinecraft().fontRenderer, itemStack, getX() + startX, getY() + startY); + RenderHelper.enableGUIStandardItemLighting(); + GlStateManager.enableRescaleNormal(); + GuiUtil.drawItemStack(Minecraft.getMinecraft().fontRenderer, itemStack, 0, 0); + RenderHelper.disableStandardItemLighting(); } } @SideOnly(Side.CLIENT) @Override - public List getToolTip(int mouseX, int mouseY) { - Minecraft minecraft = Minecraft.getMinecraft(); - EntityPlayer player = minecraft.player; - List tip = new ArrayList<>(); - if (!itemStack.isEmpty()) { - tip.addAll(itemStack.getTooltip(player, minecraft.gameSettings.advancedItemTooltips ? ITooltipFlag.TooltipFlags.ADVANCED : ITooltipFlag.TooltipFlags.NORMAL)); - } - return tip; + public List getTooltip(int mouseX, int mouseY) { + ItemStack itemStack = getItemStack(); + return ItemTooltipUtil.getInformation(itemStack); } + + protected abstract ItemStack getItemStack(); } diff --git a/src/main/java/forestry/core/gui/elements/ButtonElement.java b/src/main/java/forestry/core/gui/elements/ButtonElement.java new file mode 100644 index 000000000..6a9b68fe6 --- /dev/null +++ b/src/main/java/forestry/core/gui/elements/ButtonElement.java @@ -0,0 +1,75 @@ +package forestry.core.gui.elements; + +import java.util.function.Consumer; + +import forestry.core.gui.Drawable; +import forestry.core.gui.buttons.StandardButtonTextureSets; +import forestry.core.utils.SoundUtil; + +public class ButtonElement extends GuiElement { + /* Attributes - Final */ + private final Consumer onClicked; + private final Drawable[] textures = new Drawable[3]; + + /* Attributes - State */ + private boolean enabled = true; + + public ButtonElement(int xPos, int yPos, Drawable drawable, Consumer onClicked) { + super(xPos, yPos, drawable.uWidth, drawable.vHeight); + this.onClicked = onClicked; + for (int i = 0; i < 3; i++) { + textures[i] = new Drawable(drawable.textureLocation, drawable.u, drawable.v + drawable.vHeight * i, drawable.uWidth, drawable.vHeight); + } + } + + public ButtonElement(int xPos, int yPos, StandardButtonTextureSets textureSets, Consumer onClicked) { + super(xPos, yPos, textureSets.getWidth(), textureSets.getHeight()); + this.onClicked = onClicked; + for (int i = 0; i < 3; i++) { + textures[i] = new Drawable(textureSets.getTexture(), textureSets.getX(), textureSets.getY() + textureSets.getHeight() * i, textureSets.getWidth(), textureSets.getHeight()); + } + } + + @Override + public void drawElement(int mouseX, int mouseY) { + boolean mouseOver = isMouseOver(mouseX, mouseY); + int hoverState = getHoverState(mouseOver); + Drawable drawable = textures[hoverState]; + drawable.draw(0, 0); + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + protected int getHoverState(boolean mouseOver) { + int i = 1; + + if (!this.enabled) { + i = 0; + } else if (mouseOver) { + i = 2; + } + + return i; + } + + + @Override + public void mouseClicked(int mouseX, int mouseY, int mouseEvent) { + if (!enabled) { + return; + } + onPressed(); + SoundUtil.playButtonClick(); + } + + public void onPressed() { + onClicked.accept(this); + } + +} diff --git a/src/main/java/forestry/core/gui/elements/DrawableElement.java b/src/main/java/forestry/core/gui/elements/DrawableElement.java new file mode 100644 index 000000000..82830e706 --- /dev/null +++ b/src/main/java/forestry/core/gui/elements/DrawableElement.java @@ -0,0 +1,27 @@ +package forestry.core.gui.elements; + +import forestry.core.gui.Drawable; + +public class DrawableElement extends GuiElement { + /* Attributes - Final */ + private final Drawable drawable; + + public DrawableElement(Drawable drawable) { + this(0, 0, drawable); + } + + public DrawableElement(int xPos, int yPos, Drawable drawable) { + super(xPos, yPos, drawable.uWidth, drawable.vHeight); + this.drawable = drawable; + } + + public DrawableElement(int xPos, int yPos, int width, int height, Drawable drawable) { + super(xPos, yPos, width, height); + this.drawable = drawable; + } + + @Override + public void drawElement(int mouseX, int mouseY) { + drawable.draw(0, 0, width, height); + } +} diff --git a/src/main/java/forestry/core/gui/elements/ElementManager.java b/src/main/java/forestry/core/gui/elements/ElementManager.java new file mode 100644 index 000000000..37e66c7ce --- /dev/null +++ b/src/main/java/forestry/core/gui/elements/ElementManager.java @@ -0,0 +1,92 @@ +package forestry.core.gui.elements; + +import java.util.List; + +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.gui.ScaledResolution; +import net.minecraft.client.renderer.GlStateManager; + +import net.minecraftforge.fml.client.config.GuiUtils; + +import forestry.api.gui.IGuiElement; +import forestry.core.gui.IGuiSizable; +import forestry.core.gui.elements.layouts.ElementGroup; +import forestry.core.gui.elements.layouts.PaneLayout; + +public class ElementManager { + /* Attributes - Final */ + private final GuiState state; + private final ElementGroup container; + + public ElementManager(G gui) { + this.state = new GuiState<>(gui); + this.container = new PaneLayout(0, 0); + this.container.setGuiState(state); + } + + public ElementGroup group(){ + return container; + } + + public void add(IGuiElement element) { + container.add(element); + } + + public void remove(IGuiElement element) { + container.remove(element); + } + + public void clear() { + container.clear(); + } + + public void draw(int mouseX, int mouseY) { + state.setMouseX(mouseX); + state.setMouseY(mouseY); + container.draw(mouseX, mouseY); + } + + public void init(int guiLeft, int guiTop) { + container.setLocation(guiLeft, guiTop); + } + + public void mouseClicked(int mouseX, int mouseY, int mouseButton) { + container.mouseClicked(mouseX, mouseY, mouseButton); + } + + public void mouseClickMove(int mouseX, int mouseY, int mouseButton) { + container.mouseClickMove(mouseX, mouseY, mouseButton); + } + + public void mouseReleased(int mouseX, int mouseY, int mouseButton) { + container.mouseReleased(mouseX, mouseY, mouseButton); + } + + public boolean keyTyped(char typedChar, int keyCode) { + return container.keyTyped(typedChar, keyCode); + } + + public void drawTooltip(int mouseX, int mouseY) { + List lines = getTooltip(mouseX, mouseY); + if (!lines.isEmpty()) { + GlStateManager.pushMatrix(); + ScaledResolution scaledresolution = new ScaledResolution(state.getMinecraft()); + GuiUtils.drawHoveringText(lines, mouseX, mouseY, scaledresolution.getScaledWidth(), scaledresolution.getScaledHeight(), -1, state.getFontRenderer()); + GlStateManager.popMatrix(); + } + } + + public boolean isMouseOver(int mouseX, int mouseY) { + int mX = mouseX - container.getX(); + int mY = mouseY - container.getY(); + return getElements().stream().anyMatch(element -> element.isMouseOver(mX, mY)); + } + + public List getTooltip(int mouseX, int mouseY) { + return container.getTooltip(mouseX, mouseY); + } + + public List getElements() { + return container.getElements(); + } +} diff --git a/src/main/java/forestry/core/gui/elements/GeneticAnalyzer.java b/src/main/java/forestry/core/gui/elements/GeneticAnalyzer.java new file mode 100644 index 000000000..73587f98e --- /dev/null +++ b/src/main/java/forestry/core/gui/elements/GeneticAnalyzer.java @@ -0,0 +1,281 @@ +package forestry.core.gui.elements; + +import java.util.List; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; + +import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.IDatabasePlugin; +import forestry.api.genetics.IDatabaseTab; +import forestry.api.genetics.IGeneticAnalyzer; +import forestry.api.genetics.IGeneticAnalyzerProvider; +import forestry.api.genetics.IIndividual; +import forestry.api.genetics.ISpeciesRoot; +import forestry.api.gui.IGuiElement; +import forestry.core.config.Constants; +import forestry.core.gui.Drawable; +import forestry.core.gui.buttons.StandardButtonTextureSets; +import forestry.core.gui.elements.layouts.ElementGroup; +import forestry.core.gui.elements.layouts.ScrollableElement; +import forestry.core.gui.widgets.IScrollable; +import forestry.core.network.packets.PacketGuiSelectRequest; +import forestry.core.utils.NetworkUtil; +import forestry.core.utils.Translator; + +import org.lwjgl.input.Keyboard; + +public class GeneticAnalyzer extends ElementGroup implements IGeneticAnalyzer, IScrollable { + /* Textures */ + public static final ResourceLocation TEXTURE = new ResourceLocation(Constants.MOD_ID, Constants.TEXTURE_PATH_GUI + "/analyzer_screen.png"); + + /* Drawables */ + public static final Drawable SCROLLBAR_BACKGROUND = new Drawable(TEXTURE, 202, 0, 3, 142); + public static final Drawable SCROLLBAR_SLIDER = new Drawable(TEXTURE, 205, 0, 3, 5); + public static final Drawable SELECTION_BAR = new Drawable(GeneticAnalyzer.TEXTURE, 70, 166, 107, 32); + public static final Drawable ANALYZER_BUTTON = new Drawable(TEXTURE, 163, 40, 22, 25); + + /* Attributes- Final */ + private final IGeneticAnalyzerProvider provider; + + /*Attributes - Gui Elements */ + private final ScrollBarElement scrollBar; + private final ScrollableElement scrollable; + private final GeneticAnalyzerTabs tabs; + private final IGuiElement itemElement; + private final ButtonElement leftButton; + private final ButtonElement rightButton; + private final ButtonElement analyzeButton; + + /* Attributes - State */ + private boolean visible = true; + private int selectedSlot = -1; + + public GeneticAnalyzer(int xPos, int yPos, boolean rightBoarder, IGeneticAnalyzerProvider provider) { + super(xPos - (rightBoarder ? 6 : 0), yPos, 189 + (rightBoarder ? 6 : 0), 194); + this.provider = provider; + + //Background Texture + drawable(32, 0, new Drawable(TEXTURE, 0, 0, 163 + (rightBoarder ? 0 : -6), 166)); + //Text Area + scrollable = new ScrollableElement(32 + 10, 8, 145, 150); + add(scrollable); + //Scrollbar + scrollBar = new ScrollBarElement(width - 10 - (rightBoarder ? 6 : 0), 12, SCROLLBAR_BACKGROUND, false, SCROLLBAR_SLIDER); + scrollBar.setVisible(false); + add(scrollBar); + //Side Tabs + tabs = new GeneticAnalyzerTabs(0, 5, this); + add(tabs); + //Selection Bar at the bottom + itemElement = drawable((getWidth() + 32 - SELECTION_BAR.uWidth) / 2, 162, SELECTION_BAR); + + leftButton = add(new ButtonElement(itemElement.getX() + 30, itemElement.getY() + 9, StandardButtonTextureSets.LEFT_BUTTON, (button) -> subtract())); + rightButton = add(new ButtonElement(itemElement.getX() + 64, itemElement.getY() + 9, StandardButtonTextureSets.RIGHT_BUTTON, (button) -> add())); + analyzeButton = add(new ButtonElement(itemElement.getX() + 80, itemElement.getY() + 2, ANALYZER_BUTTON, (button) -> NetworkUtil.sendToServer(new PacketGuiSelectRequest(0, provider.getSelectedSlot(selectedSlot))))); + add(new AbstractItemElement(itemElement.getX() + 44, itemElement.getY() + 9) { + @Override + protected ItemStack getItemStack() { + return provider.getSpecimen(selectedSlot); + } + }); + } + + @Override + public void init() { + leftButton.setEnabled(canSubtract()); + rightButton.setEnabled(canAdd()); + updateSelected(); + } + + public boolean isVisible() { + return visible; + } + + public void setVisible(boolean visible) { + this.visible = visible; + } + + @Override + public IGeneticAnalyzerProvider getProvider() { + return provider; + } + + public IGuiElement getItemElement() { + return itemElement; + } + + @SuppressWarnings("unchecked") + @Override + public void update() { + if (!visible) { + return; + } + ItemStack stack = provider.getSpecimen(selectedSlot); + ISpeciesRoot root = AlleleManager.alleleRegistry.getSpeciesRoot(stack); + if (root != null) { + IDatabasePlugin databasePlugin = root.getSpeciesPlugin(); + if (databasePlugin != null) { + IIndividual individual = root.getMember(stack); + if (individual != null) { + if (individual.isAnalyzed()) { + tabs.setPlugin(databasePlugin); + IDatabaseTab tab = tabs.getSelected(); + //Clean the element area + scrollable.clear(); + //Create the new elements + tab.createElements(scrollable, individual, stack); + //Update the visible elements + scrollable.updateVisibleElements(0); + //Update the scrollbar + int invisibleElements = scrollable.getInvisibleElementCount(); + if (invisibleElements > 0) { + scrollBar.setParameters(this, 0, invisibleElements, 1); + scrollBar.setVisible(true); + } else { + scrollBar.setValue(0); + scrollBar.setVisible(false); + } + return; + } + tabs.setPlugin(null); + } + } + } + //Clean the element area + scrollable.clear(); + FontRenderer fontRenderer = Minecraft.getMinecraft().fontRenderer; + String key = "for.gui.portablealyzer.help"; + //if(state == DatabaseScreenLogic.ScreenState.NO_PLUGIN){ + //key = "for.gui.database.support"; + //} + List lines = fontRenderer.listFormattedStringToWidth(Translator.translateToLocal(key), scrollable.getWidth()); + for (String text : lines) { + scrollable.text(text); + } + //Disable the scrollbar + scrollBar.setVisible(false); + } + + @Override + public void draw(int mouseX, int mouseY) { + if (!visible) { + return; + } + super.draw(mouseX, mouseY); + } + + @Override + public void drawTooltip(GuiScreen gui, int mouseX, int mouseY) { + if (!visible) { + return; + } + /*List lines = getTooltip(mouseX, mouseY); + if (!lines.isEmpty()) { + GlStateManager.pushMatrix(); + ScaledResolution scaledresolution = new ScaledResolution(gui.mc); + GuiUtils.drawHoveringText(lines, mouseX, mouseY, scaledresolution.getScaledWidth(), scaledresolution.getScaledHeight(), -1, gui.mc.fontRenderer); + GlStateManager.popMatrix(); + }*/ + } + + /*@Override + public boolean mouseClicked(int mouseX, int mouseY, int mouseEvent, IGuiState state) { + if(!visible){ + return false; + } + return super.mouseClicked(mouseX, mouseY, mouseEvent); + }*/ + + @Override + public boolean keyTyped(char typedChar, int keyCode) { + if ((keyCode == Keyboard.KEY_DOWN || keyCode == Keyboard.KEY_RIGHT) && rightButton.isEnabled()) { + rightButton.onPressed(); + return true; + } else if ((keyCode == Keyboard.KEY_UP || keyCode == Keyboard.KEY_LEFT) && leftButton.isEnabled()) { + leftButton.onPressed(); + return true; + } + return false; + } + + @Override + public boolean isFocused(int mouseX, int mouseY) { + mouseX += getX(); + mouseY += getY(); + return isMouseOver(mouseX, mouseY); + } + + @Override + public void onScroll(int value) { + scrollable.onScroll(value); + } + + private boolean canAdd() { + return selectedSlot + 1 < getSlotCount(); + } + + private boolean canSubtract() { + int selectedSlot = this.selectedSlot - 1; + return selectedSlot < getSlotCount() && selectedSlot >= 0; + } + + public void add() { + setSelectedSlot(selectedSlot + 1); + } + + private void subtract() { + setSelectedSlot(selectedSlot - 1); + } + + private int getSlotCount() { + return provider.getSlotCount(); + } + + public void setSelectedSlot(int selectedSlot) { + int oldSelected = this.selectedSlot; + this.selectedSlot = selectedSlot; + onSelection(selectedSlot, oldSelected != selectedSlot); + } + + private void onSelection(int selectedSlot, boolean changed) { + leftButton.setEnabled(canSubtract()); + rightButton.setEnabled(canAdd()); + if (changed) { + update(); + } + provider.onSelection(selectedSlot, changed); + } + + public int getSelectedSlot() { + return selectedSlot; + } + + public void updateSelected() { + /*int index = sorted.indexOf(selected); + if(index >= 0) { + setSelectedSlot(sorted.indexOf(selected)); + return; + }*/ + if (provider.onUpdateSelected()) { + return; + } + int slotCount = getSlotCount(); + if (slotCount <= 0) { + setSelectedSlot(-1); + return; + } + if (slotCount > selectedSlot && selectedSlot != -1) { + return; + } + setSelectedSlot(provider.getFirstSlot()); + } + + @Override + public int getSelected() { + return selectedSlot; + } +} diff --git a/src/main/java/forestry/core/gui/elements/GeneticAnalyzerTabs.java b/src/main/java/forestry/core/gui/elements/GeneticAnalyzerTabs.java new file mode 100644 index 000000000..acdf13c99 --- /dev/null +++ b/src/main/java/forestry/core/gui/elements/GeneticAnalyzerTabs.java @@ -0,0 +1,128 @@ +package forestry.core.gui.elements; + +import javax.annotation.Nullable; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.item.ItemStack; + +import forestry.api.genetics.IDatabasePlugin; +import forestry.api.genetics.IDatabaseTab; +import forestry.api.gui.IGuiElement; +import forestry.core.genetics.analyzer.AnalyzerTab; +import forestry.core.gui.Drawable; +import forestry.core.gui.GuiUtil; +import forestry.core.gui.elements.layouts.VerticalLayout; +import forestry.core.utils.SoundUtil; + +public class GeneticAnalyzerTabs extends VerticalLayout { + private static final Drawable SELECTED_BACKGROUND = new Drawable(GeneticAnalyzer.TEXTURE, 0, 166, 35, 26); + private static final Drawable UNSELECTED_BACKGROUND = new Drawable(GeneticAnalyzer.TEXTURE, 0, 192, 35, 26); + @Nullable + public IDatabasePlugin databasePlugin; + public final GeneticAnalyzer analyzer; + private int selected = 0; + + public GeneticAnalyzerTabs(int xPos, int yPos, GeneticAnalyzer analyzer) { + super(xPos, yPos, 35); + setDistance(2); + this.analyzer = analyzer; + IDatabaseTab[] tabs = getTabs(); + for (int i = 0; i < 4; i++) { + IDatabaseTab tab = tabs.length > i ? tabs[i] : null; + Tab element = new Tab(0, 0, i); + element.setTab(tab); + add(element); + } + } + + private void select(int index) { + this.selected = index; + } + + public IDatabaseTab getSelected() { + IGuiElement element = elements.get(selected); + if (!(element instanceof Tab) || !((Tab) element).isVisible()) { + return AnalyzerTab.ANALYZE; + } + return ((Tab) element).tab; + } + + public void setPlugin(@Nullable IDatabasePlugin plugin) { + if (databasePlugin != plugin) { + this.selected = 0; + this.databasePlugin = plugin; + IDatabaseTab[] tabs = getTabs(); + for (int i = 0; i < elements.size(); i++) { + IGuiElement element = elements.get(i); + if (element instanceof Tab) { + IDatabaseTab tab = tabs.length > i ? tabs[i] : null; + Tab tabElement = (Tab) element; + tabElement.setTab(tab); + } + } + } + } + + private IDatabaseTab[] getTabs() { + if (databasePlugin == null) { + return new IDatabaseTab[]{AnalyzerTab.ANALYZE}; + } + return databasePlugin.getTabs(); + } + + private class Tab extends GuiElement { + private final int index; + @Nullable + public IDatabaseTab tab; + private ItemStack displayStack = ItemStack.EMPTY; + + public Tab(int xPos, int yPos, int index) { + super(xPos, yPos, 35, 26); + this.index = index; + } + + public boolean isVisible() { + return tab != null; + } + + public void setTab(@Nullable IDatabaseTab tab) { + this.tab = tab; + if (tab != null) { + this.displayStack = tab.getIconStack(); + } else { + this.displayStack = ItemStack.EMPTY; + } + } + + @Override + public void drawElement(int mouseX, int mouseY) { + if (!isVisible()) { + return; + } + int x = 0; + Drawable background = selected == index ? SELECTED_BACKGROUND : UNSELECTED_BACKGROUND; + if (selected != index) { + x += 2; + } + background.draw(x, 0); + if (!displayStack.isEmpty()) { + RenderHelper.enableGUIStandardItemLighting(); + GlStateManager.enableRescaleNormal(); + GuiUtil.drawItemStack(Minecraft.getMinecraft().fontRenderer, displayStack, x + 9, 5); + RenderHelper.disableStandardItemLighting(); + } + } + + @Override + public void mouseClicked(int mouseX, int mouseY, int mouseButton) { + if (isVisible() && isMouseOver(mouseX, mouseY)) { + select(index); + SoundUtil.playButtonClick(); + analyzer.update(); + } + } + } + +} diff --git a/src/main/java/forestry/core/gui/elements/GuiElement.java b/src/main/java/forestry/core/gui/elements/GuiElement.java index e72f63ed9..3137b956b 100644 --- a/src/main/java/forestry/core/gui/elements/GuiElement.java +++ b/src/main/java/forestry/core/gui/elements/GuiElement.java @@ -1,18 +1,38 @@ package forestry.core.gui.elements; import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; import net.minecraft.client.gui.Gui; +import net.minecraft.client.renderer.GlStateManager; -import forestry.api.core.IGuiElement; +import forestry.api.gui.GuiElementAlignment; +import forestry.api.gui.IGuiElement; +import forestry.api.gui.IGuiState; -public abstract class GuiElement extends Gui implements IGuiElement { - protected final int xPos; - protected final int yPos; - protected int xOffset = 0; - protected int yOffset = 0; +public class GuiElement extends Gui implements IGuiElement { + /* Attributes - Final */ + //Element Position + protected int xPos; + protected int yPos; + //Tooltip of the element + protected final List tooltip = new ArrayList<>(); + /* Attributes - State*/ + //Size of this element protected int width; protected int height; + protected GuiElementAlignment align = GuiElementAlignment.TOP_LEFT; + //The element container that contains this element + @Nullable + protected IGuiElement parent; + @Nullable + private IGuiState state; + + public GuiElement(int width, int height) { + this(0, 0, width, height); + } public GuiElement(int xPos, int yPos, int width, int height) { this.xPos = xPos; @@ -23,12 +43,59 @@ public abstract class GuiElement extends Gui implements IGuiElement { @Override public int getX() { - return xPos + xOffset; + int x = 0; + if (parent != null && parent.getWidth() > width) { + x = (int) ((parent.getWidth() - width) * align.getXOffset()); + } + return xPos + x; } @Override public int getY() { - return yPos + yOffset; + int y = 0; + if (parent != null && parent.getHeight() > height) { + y = (int) ((parent.getHeight() - height) * align.getYOffset()); + } + return yPos + y; + } + + public final int getAbsoluteX() { + return parent == null ? getX() : getX() + parent.getAbsoluteX(); + } + + public final int getAbsoluteY() { + return parent == null ? getY() : getY() + parent.getAbsoluteY(); + } + + @Override + public void draw(int mouseX, int mouseY) { + GlStateManager.pushMatrix(); + GlStateManager.translate(getX(), getY(), 0.0F); + + drawElement(mouseX, mouseY); + + GlStateManager.popMatrix(); + } + + public void drawElement(int mouseX, int mouseY) { + // + } + + @Override + public void mouseClicked(int mouseX, int mouseY, int mouseButton) { + } + + @Override + public void mouseReleased(int mouseX, int mouseY, int mouseButton) { + } + + @Override + public void mouseClickMove(int mouseX, int mouseY, int mouseButton) { + } + + @Override + public boolean keyTyped(char typedChar, int keyCode) { + return false; } @Override @@ -42,30 +109,115 @@ public abstract class GuiElement extends Gui implements IGuiElement { } @Override - public void setXOffset(int xOffset) { - this.xOffset = xOffset; + public void setSize(int width, int height) { + this.width = width; + this.height = height; } @Override - public void setYOffset(int yOffset) { - this.yOffset = yOffset; + public void setXPosition(int xPos) { + this.xPos = xPos; + } + + @Override + public void setYPosition(int yPos) { + this.yPos = yPos; + } + + @Override + public void setLocation(int xPos, int yPos) { + this.xPos = xPos; + this.yPos = yPos; + } + + @Override + public void setBounds(int xPos, int yPos, int width, int height) { + setLocation(xPos, yPos); + setSize(width, height); + } + + @Override + public void setAlign(GuiElementAlignment align) { + this.align = align; + } + + @Override + public GuiElementAlignment getAlign() { + return align; } @Override public boolean isMouseOver(int mouseX, int mouseY) { - int xPos = getX(); - int yPos = getY(); - return mouseX >= xPos && mouseX <= xPos + getWidth() && mouseY >= yPos && mouseY <= yPos + getHeight(); + int x = getX(); + int y = getY(); + return mouseX >= x && mouseX <= getWidth() + x && mouseY >= y && mouseY <= getHeight() + y; + } + + public final boolean isMouseOver() { + IGuiState guiState = getGuiState(); + if (guiState == null) { + return false; + } + int mouseX; + int mouseY; + if (parent != null) { + mouseX = guiState.getRelativeMouseX(parent); + mouseY = guiState.getRelativeMouseY(parent); + } else { + mouseX = guiState.getMouseX(); + mouseY = guiState.getMouseY(); + } + return isMouseOver(mouseX, mouseY); } @Nullable @Override public IGuiElement getParent() { - return null; + return parent; } @Override public void setParent(@Nullable IGuiElement parent) { + this.parent = parent; + } + @Override + public List getTooltip(int mouseX, int mouseY) { + return tooltip; + } + + @Override + public IGuiElement addTooltip(String line) { + tooltip.add(line); + return this; + } + + @Override + public IGuiElement addTooltip(Collection lines) { + tooltip.addAll(lines); + return this; + } + + @Override + public void clearTooltip() { + tooltip.clear(); + } + + @Override + public List getTooltip() { + return tooltip; + } + + @Nullable + @Override + public IGuiState getGuiState() { + if (state == null && parent != null) { + state = parent.getGuiState(); + } + return state; + } + + public void setGuiState(@Nullable IGuiState state) { + this.state = state; } } diff --git a/src/main/java/forestry/core/gui/elements/GuiElementDrawable.java b/src/main/java/forestry/core/gui/elements/GuiElementDrawable.java deleted file mode 100644 index 8f9d03b14..000000000 --- a/src/main/java/forestry/core/gui/elements/GuiElementDrawable.java +++ /dev/null @@ -1,17 +0,0 @@ -package forestry.core.gui.elements; - -import forestry.core.gui.Drawable; - -public class GuiElementDrawable extends GuiElement { - private final Drawable drawable; - - public GuiElementDrawable(int xPos, int yPos, Drawable drawable) { - super(xPos, yPos, drawable.width, drawable.height); - this.drawable = drawable; - } - - @Override - public void draw(int startX, int startY) { - drawable.draw(getX() + startX, getY() + startY); - } -} diff --git a/src/main/java/forestry/core/gui/elements/GuiElementFactory.java b/src/main/java/forestry/core/gui/elements/GuiElementFactory.java index 06a6d6125..9a1266302 100644 --- a/src/main/java/forestry/core/gui/elements/GuiElementFactory.java +++ b/src/main/java/forestry/core/gui/elements/GuiElementFactory.java @@ -1,17 +1,11 @@ package forestry.core.gui.elements; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; +import javax.annotation.Nullable; import java.util.Map; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; -import forestry.api.core.IGuiElement; -import forestry.api.core.IGuiElementFactory; -import forestry.api.core.IGuiElementHelper; -import forestry.api.core.IGuiElementLayout; import forestry.api.genetics.EnumTolerance; import forestry.api.genetics.IAllele; import forestry.api.genetics.IAlleleInteger; @@ -19,47 +13,60 @@ import forestry.api.genetics.IAlleleSpecies; import forestry.api.genetics.IAlleleTolerance; import forestry.api.genetics.IAlyzerPlugin; import forestry.api.genetics.IBreedingTracker; +import forestry.api.genetics.IDatabasePlugin; +import forestry.api.genetics.IGeneticAnalyzer; +import forestry.api.genetics.IGeneticAnalyzerProvider; import forestry.api.genetics.IMutation; -import forestry.api.genetics.ISpeciesPlugin; import forestry.api.genetics.ISpeciesRoot; +import forestry.api.gui.IElementGroup; +import forestry.api.gui.IElementLayout; +import forestry.api.gui.IGuiElement; +import forestry.api.gui.IGuiElementFactory; import forestry.core.config.Constants; import forestry.core.genetics.mutations.EnumMutateChance; import forestry.core.gui.Drawable; +import forestry.core.gui.elements.layouts.AbstractElementLayout; +import forestry.core.gui.elements.layouts.ElementGroup; +import forestry.core.gui.elements.layouts.HorizontalLayout; +import forestry.core.gui.elements.layouts.PaneLayout; +import forestry.core.gui.elements.layouts.VerticalLayout; import forestry.core.render.ColourProperties; public class GuiElementFactory implements IGuiElementFactory { - public static final ResourceLocation TEXTURE = new ResourceLocation(Constants.MOD_ID, Constants.TEXTURE_PATH_GUI + "/database_mutation_screen.png"); + /* Constants */ + private static final ResourceLocation TEXTURE = new ResourceLocation(Constants.MOD_ID, Constants.TEXTURE_PATH_GUI + "/database_mutation_screen.png"); - public static final Drawable QUESTION_MARK = new Drawable(TEXTURE, 78, 240, 16, 16); - public static final Drawable DOWN_SYMBOL = new Drawable(TEXTURE, 0, 247, 15, 9); - public static final Drawable UP_SYMBOL = new Drawable(TEXTURE, 15, 247, 15, 9); - public static final Drawable BOOTH_SYMBOL = new Drawable(TEXTURE, 30, 247, 15, 9); - public static final Drawable NONE_SYMBOL = new Drawable(TEXTURE, 45, 247, 15, 9); + /* Drawables */ + private static final Drawable QUESTION_MARK = new Drawable(TEXTURE, 78, 240, 16, 16); + private static final Drawable DOWN_SYMBOL = new Drawable(TEXTURE, 0, 247, 15, 9); + private static final Drawable UP_SYMBOL = new Drawable(TEXTURE, 15, 247, 15, 9); + private static final Drawable BOOTH_SYMBOL = new Drawable(TEXTURE, 30, 247, 15, 9); + private static final Drawable NONE_SYMBOL = new Drawable(TEXTURE, 45, 247, 15, 9); + /* Instance */ public static final GuiElementFactory INSTANCE = new GuiElementFactory(); private GuiElementFactory() { } - @Override - public IGuiElementHelper createHelper(IGuiElementLayout element) { - return new GuiElementHelper(element); + public IGeneticAnalyzer createAnalyzer(int xPos, int yPos, boolean rightBoarder, IGeneticAnalyzerProvider provider) { + return new GeneticAnalyzer(xPos, yPos, rightBoarder, provider); } @Override - public IGuiElementLayout createVertical(int xPos, int yPos, int width) { - return new GuiElementVertical(xPos, yPos, width); + public AbstractElementLayout createVertical(int xPos, int yPos, int width) { + return new VerticalLayout(xPos, yPos, width); } @Override - public IGuiElementLayout createHorizontal(int xPos, int yPos, int height) { - return new GuiElementHorizontal(xPos, yPos, height); + public AbstractElementLayout createHorizontal(int xPos, int yPos, int height) { + return new HorizontalLayout(xPos, yPos, height); } @Override - public IGuiElementLayout createPanel(int xPos, int yPos, int width, int height) { - return new GuiElementPanel(xPos, yPos, width, height); + public ElementGroup createPanel(int xPos, int yPos, int width, int height) { + return new PaneLayout(xPos, yPos, width, height); } public final int getColorCoding(boolean dominant) { @@ -70,28 +77,28 @@ public class GuiElementFactory implements IGuiElementFactory { } } - public IGuiElement createFertilityInfo(IAlleleInteger fertilityAllele, int x, int texOffset) { + public IGuiElement createFertilityInfo(IAlleleInteger fertilityAllele, int texOffset) { String fertilityString = Integer.toString(fertilityAllele.getValue()) + " x"; - IGuiElementLayout layout = createHorizontal(x, 0, 0).setDistance(2); - layout.addElement(new GuiElementText(0, 0, 12, fertilityString, getColorCoding(fertilityAllele.isDominant()))); - layout.addElement(new GuiElementDrawable(0, -1, new Drawable(TEXTURE, 60, 240 + texOffset, 12, 8))); + AbstractElementLayout layout = createHorizontal(0, 0, 0).setDistance(2); + layout.text(fertilityString, getColorCoding(fertilityAllele.isDominant())); + layout.drawable(0, -1, new Drawable(TEXTURE, 60, 240 + texOffset, 12, 8)); return layout; } - public IGuiElement createToleranceInfo(IAlleleTolerance toleranceAllele, IAlleleSpecies species, String text){ - IGuiElementLayout layout = createHorizontal(0, 0, 0).setDistance(0); - layout.addElement(new GuiElementText(0, 0, 12, text, getColorCoding(species.isDominant()))); - layout.addElement(createToleranceInfo(toleranceAllele, 0)); + public IGuiElement createToleranceInfo(IAlleleTolerance toleranceAllele, IAlleleSpecies species, String text) { + IElementLayout layout = createHorizontal(0, 0, 0).setDistance(0); + layout.text(text, getColorCoding(species.isDominant())); + layout.add(createToleranceInfo(toleranceAllele)); return layout; } - private IGuiElementLayout createToleranceInfo(IAlleleTolerance toleranceAllele, int x) { + public IElementLayout createToleranceInfo(IAlleleTolerance toleranceAllele) { int textColor = getColorCoding(toleranceAllele.isDominant()); EnumTolerance tolerance = toleranceAllele.getValue(); String text = "(" + toleranceAllele.getAlleleName() + ")"; - IGuiElementLayout layout = createHorizontal(x, 0, 0).setDistance(2); + IElementLayout layout = createHorizontal(0, 0, 0).setDistance(2); switch (tolerance) { case BOTH_1: @@ -99,42 +106,43 @@ public class GuiElementFactory implements IGuiElementFactory { case BOTH_3: case BOTH_4: case BOTH_5: - layout.addElement(createBothSymbol(0, -1)); - layout.addElement(new GuiElementText(0, 0, 12, text, textColor)); + layout.add(createBothSymbol(0, -1)); + layout.text(text, textColor); break; case DOWN_1: case DOWN_2: case DOWN_3: case DOWN_4: case DOWN_5: - layout.addElement(createDownSymbol(0, -1)); - layout.addElement(new GuiElementText(0, 0, 12, text, textColor)); + layout.add(createDownSymbol(0, -1)); + layout.text(text, textColor); break; case UP_1: case UP_2: case UP_3: case UP_4: case UP_5: - layout.addElement(createUpSymbol(0, -1)); - layout.addElement(new GuiElementText(0, 0, 12, text, textColor)); + layout.add(createUpSymbol(0, -1)); + layout.text(text, textColor); break; default: - layout.addElement(createNoneSymbol(0, -1)); - layout.addElement(new GuiElementText(0, 0, 12, "(0)", textColor)); + layout.add(createNoneSymbol(0, -1)); + layout.text("(0)", textColor); break; } return layout; } - public IGuiElementLayout createMutationResultant(int x, int y, int width, int height, IMutation mutation, IBreedingTracker breedingTracker){ + @Nullable + public IElementGroup createMutationResultant(int x, int y, int width, int height, IMutation mutation, IBreedingTracker breedingTracker) { if (breedingTracker.isDiscovered(mutation)) { - IGuiElementLayout element = new GuiElementPanel(x, y, width, height); + IElementGroup element = new PaneLayout(x, y, width, height); IAlyzerPlugin plugin = mutation.getRoot().getAlyzerPlugin(); Map iconStacks = plugin.getIconStacks(); ItemStack firstPartner = iconStacks.get(mutation.getAllele0().getUID()); ItemStack secondPartner = iconStacks.get(mutation.getAllele1().getUID()); - element.addElements(new GuiElementItemStack(0, 0, firstPartner), createProbabilityAdd(mutation, 21, 4), new GuiElementItemStack(33, 0, secondPartner)); + element.add(new ItemElement(0, 0, firstPartner), createProbabilityAdd(mutation, 21, 4), new ItemElement(33, 0, secondPartner)); return element; } // Do not display secret undiscovered mutations. @@ -145,19 +153,20 @@ public class GuiElementFactory implements IGuiElementFactory { return createUnknownMutationGroup(x, y, width, height, mutation); } - public IGuiElementLayout createMutation(int x, int y, int width, int height, IMutation mutation, IAllele species, IBreedingTracker breedingTracker){ + @Nullable + public IElementGroup createMutation(int x, int y, int width, int height, IMutation mutation, IAllele species, IBreedingTracker breedingTracker) { if (breedingTracker.isDiscovered(mutation)) { - GuiElementPanel element = new GuiElementPanel(x, y, width, height); + PaneLayout element = new PaneLayout(x, y, width, height); ISpeciesRoot speciesRoot = mutation.getRoot(); int speciesIndex = speciesRoot.getSpeciesChromosomeType().ordinal(); - ISpeciesPlugin plugin = mutation.getRoot().getSpeciesPlugin(); + IDatabasePlugin plugin = mutation.getRoot().getSpeciesPlugin(); Map iconStacks = plugin.getIndividualStacks(); ItemStack partner = iconStacks.get(mutation.getPartner(species).getUID()); IAllele resultAllele = mutation.getTemplate()[speciesIndex]; ItemStack result = iconStacks.get(resultAllele.getUID()); - element.addElements(new GuiElementItemStack(0, 0, partner), new GuiElementItemStack( 33, 0, result)); - element.addElements(createProbabilityArrow(mutation, 18, 4, breedingTracker)); + element.add(new ItemElement(0, 0, partner), new ItemElement(33, 0, result)); + createProbabilityArrow(element, mutation, 18, 4, breedingTracker); return element; } // Do not display secret undiscovered mutations. @@ -168,22 +177,22 @@ public class GuiElementFactory implements IGuiElementFactory { return createUnknownMutationGroup(x, y, width, height, mutation, breedingTracker); } - private static IGuiElementLayout createUnknownMutationGroup(int x, int y, int width, int height, IMutation mutation){ - GuiElementPanel element = new GuiElementPanel(x, y, width, height); + private static IElementGroup createUnknownMutationGroup(int x, int y, int width, int height, IMutation mutation) { + PaneLayout element = new PaneLayout(x, y, width, height); - element.addElements(createQuestionMark(0, 0), createProbabilityAdd(mutation, 21, 4), createQuestionMark( 32, 0)); + element.add(createQuestionMark(0, 0), createProbabilityAdd(mutation, 21, 4), createQuestionMark(32, 0)); return element; } - private static IGuiElementLayout createUnknownMutationGroup(int x, int y, int width, int height, IMutation mutation, IBreedingTracker breedingTracker){ - GuiElementPanel element = new GuiElementPanel(x, y, width, height); + private static IElementGroup createUnknownMutationGroup(int x, int y, int width, int height, IMutation mutation, IBreedingTracker breedingTracker) { + PaneLayout element = new PaneLayout(x, y, width, height); - element.addElements(createQuestionMark(0, 0), createQuestionMark( 32, 0)); - element.addElements(createProbabilityArrow(mutation, 18, 4, breedingTracker)); + element.add(createQuestionMark(0, 0), createQuestionMark(32, 0)); + createProbabilityArrow(element, mutation, 18, 4, breedingTracker); return element; } - private static Collection createProbabilityArrow(IMutation combination, int x, int y, IBreedingTracker breedingTracker) { + private static void createProbabilityArrow(PaneLayout element, IMutation combination, int x, int y, IBreedingTracker breedingTracker) { float chance = combination.getBaseChance(); int line = 247; int column = 100; @@ -205,23 +214,21 @@ public class GuiElementFactory implements IGuiElementFactory { break; case LOWEST: column = 100 + 15 * 5; + break; default: break; } - List elements = new ArrayList<>(); // Probability arrow - elements.add(new GuiElementDrawable(x, y, new Drawable(TEXTURE, column, line, 15, 9))); + element.drawable(x, y, new Drawable(TEXTURE, column, line, 15, 9)); boolean researched = breedingTracker.isResearched(combination); if (researched) { - elements.add(new GuiElementText(x + 9, y + 1, 10, 10, "+")); + element.text(x + 9, y + 1, 10, 10, "+"); } - - return elements; } - private static GuiElementDrawable createProbabilityAdd(IMutation mutation, int x, int y) { + private static DrawableElement createProbabilityAdd(IMutation mutation, int x, int y) { float chance = mutation.getBaseChance(); int line = 247; int column = 190; @@ -243,31 +250,32 @@ public class GuiElementFactory implements IGuiElementFactory { break; case LOWEST: column = 190 + 9 * 5; + break; default: break; } // Probability add - return new GuiElementDrawable(x, y, new Drawable(TEXTURE, column, line, 9, 9)); + return new DrawableElement(x, y, new Drawable(TEXTURE, column, line, 9, 9)); } - private static GuiElementDrawable createQuestionMark(int x, int y) { - return new GuiElementDrawable(x, y, QUESTION_MARK); + private static DrawableElement createQuestionMark(int x, int y) { + return new DrawableElement(x, y, QUESTION_MARK); } - private static GuiElementDrawable createDownSymbol(int x, int y) { - return new GuiElementDrawable(x, y, DOWN_SYMBOL); + private static DrawableElement createDownSymbol(int x, int y) { + return new DrawableElement(x, y, DOWN_SYMBOL); } - private static GuiElementDrawable createUpSymbol(int x, int y) { - return new GuiElementDrawable(x, y, UP_SYMBOL); + private static DrawableElement createUpSymbol(int x, int y) { + return new DrawableElement(x, y, UP_SYMBOL); } - private static GuiElementDrawable createBothSymbol(int x, int y) { - return new GuiElementDrawable(x, y, BOOTH_SYMBOL); + private static DrawableElement createBothSymbol(int x, int y) { + return new DrawableElement(x, y, BOOTH_SYMBOL); } - private static GuiElementDrawable createNoneSymbol(int x, int y) { - return new GuiElementDrawable(x, y, NONE_SYMBOL); + private static DrawableElement createNoneSymbol(int x, int y) { + return new DrawableElement(x, y, NONE_SYMBOL); } } diff --git a/src/main/java/forestry/core/gui/elements/GuiElementHelper.java b/src/main/java/forestry/core/gui/elements/GuiElementHelper.java deleted file mode 100644 index 97d03a4ae..000000000 --- a/src/main/java/forestry/core/gui/elements/GuiElementHelper.java +++ /dev/null @@ -1,137 +0,0 @@ -package forestry.core.gui.elements; - -import java.util.function.Function; - -import net.minecraft.item.ItemStack; -import net.minecraft.util.text.TextFormatting; - -import forestry.api.core.GuiElementAlignment; -import forestry.api.core.IGuiElement; -import forestry.api.core.IGuiElementFactory; -import forestry.api.core.IGuiElementHelper; -import forestry.api.core.IGuiElementLayout; -import forestry.api.core.IGuiElementLayoutHelper; -import forestry.api.core.IGuiElementLayoutHelper.LayoutFactory; -import forestry.api.genetics.IAllele; -import forestry.api.genetics.IAlleleInteger; -import forestry.api.genetics.IAlleleSpecies; -import forestry.api.genetics.IAlleleTolerance; -import forestry.api.genetics.IBreedingTracker; -import forestry.api.genetics.IChromosomeType; -import forestry.api.genetics.IIndividual; -import forestry.api.genetics.IMutation; -import forestry.core.render.ColourProperties; - -public class GuiElementHelper implements IGuiElementHelper { - private final IGuiElementLayout parent; - private final int defaultColor; - - public GuiElementHelper(IGuiElementLayout parent) { - this.parent = parent; - this.defaultColor = ColourProperties.INSTANCE.get("gui.screen"); - } - - public GuiElementLayoutHelper layoutHelper(LayoutFactory layoutFactory, int width, int height) { - return new GuiElementLayoutHelper(layoutFactory, width, height, this); - } - - public void add(IGuiElementLayoutHelper groupHelper) { - groupHelper.layouts().forEach(element -> add(element)); - } - - public void add(IGuiElement element) { - parent.addElement(element); - } - - public void addItem(int x, ItemStack itemStack) { - parent.addElement(new GuiElementItemStack(x, 0, itemStack)); - } - - @Override - public final void addAllele(String chromosomeName, IIndividual individual, IChromosomeType chromosome, boolean active) { - addAllele(chromosomeName, allele -> allele.getAlleleName(), individual, chromosome, active); - } - - @Override - public final void addAllele(String chromosomeName, Function toString, IIndividual individual, IChromosomeType chromosome, boolean active) { - A allele; - if (active) { - allele = (A) individual.getGenome().getActiveAllele(chromosome); - } else { - allele = (A) individual.getGenome().getInactiveAllele(chromosome); - } - addText(TextFormatting.UNDERLINE + chromosomeName, GuiElementAlignment.CENTER); - addText(toString.apply(allele), GuiElementAlignment.CENTER, factory().getColorCoding(allele.isDominant())); - } - - @Override - public void addMutation(int x, int y, int width, int height, IMutation mutation, IAllele species, IBreedingTracker breedingTracker) { - IGuiElement element = factory().createMutation(x, y, width, height, mutation, species, breedingTracker); - if(element == null){ - return; - } - add(element); - } - - @Override - public void addMutationResultant(int x, int y, int width, int height, IMutation mutation, IBreedingTracker breedingTracker) { - IGuiElement element = factory().createMutationResultant(x, y, width, height, mutation, breedingTracker); - if(element == null){ - return; - } - add(element); - } - - public void addFertilityInfo(IAlleleInteger fertilityAllele, int x, int texOffset) { - add(centerElement(factory().createFertilityInfo(fertilityAllele, x, texOffset))); - } - - public void addToleranceInfo(IAlleleTolerance toleranceAllele, IAlleleSpecies species, String text){ - add(centerElement(factory().createToleranceInfo(toleranceAllele, species, text))); - } - - public void addText(String text) { - addText(0, text, defaultColor); - } - - public void addText(String text, int color) { - addText(0, text, color); - } - - @Override - public void addText(String text, GuiElementAlignment align) { - addText(text, align, defaultColor); - } - - public void addText(String text, GuiElementAlignment align, int color) { - addText(0, text, align, color); - } - - public void addText(int x, String text, int color) { - addText(x, text, GuiElementAlignment.LEFT, color); - } - - public void addText(int x, String text, GuiElementAlignment align, int color) { - addText(x, 12, text, align, color); - } - - public void addText(int x, int height, String text, GuiElementAlignment align, int color) { - parent.addElement(new GuiElementText(x, 0, parent.getWidth(), height, text, align, color)); - } - - @Override - public IGuiElement centerElement(IGuiElement element) { - element.setXOffset((parent.getWidth() - element.getWidth()) / 2); - return element; - } - - @Override - public IGuiElementLayout getParent() { - return parent; - } - - @Override - public IGuiElementFactory factory() { - return GuiElementFactory.INSTANCE; - } -} diff --git a/src/main/java/forestry/core/gui/elements/GuiElementLayout.java b/src/main/java/forestry/core/gui/elements/GuiElementLayout.java deleted file mode 100644 index f38c52536..000000000 --- a/src/main/java/forestry/core/gui/elements/GuiElementLayout.java +++ /dev/null @@ -1,70 +0,0 @@ -package forestry.core.gui.elements; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import forestry.api.core.IGuiElement; -import forestry.api.core.IGuiElementLayout; - -public abstract class GuiElementLayout extends GuiElement implements IGuiElementLayout { - protected final List elements = new ArrayList<>(); - protected final List tooltip = new ArrayList<>(); - - /* The distance between the different elements of this group. */ - public int distance; - - public GuiElementLayout(int xPos, int yPos, int width, int height) { - super(xPos, yPos, width, height); - } - - public GuiElementLayout setDistance(int distance) { - this.distance = distance; - return this; - } - - public void addTooltip(String line){ - tooltip.add(line); - } - - public List getTooltip() { - return tooltip; - } - - @Override - public int getDistance() { - return distance; - } - - public List getElements() { - return elements; - } - - @Override - public int getSize() { - return elements.size(); - } - - @Override - public void draw(int startX, int startY) { - elements.forEach(element -> element.draw(startX + getX(), startY + getY())); - } - - @Override - public List getToolTip(int mouseX, int mouseY) { - mouseX -= getX(); - mouseY -= getY(); - for (IGuiElement element : elements) { - if (element.isMouseOver(mouseX, mouseY)) { - List toolTip = element.getToolTip(mouseX, mouseY); - if (!toolTip.isEmpty()) { - return toolTip; - } - } - } - if(!tooltip.isEmpty()){ - return tooltip; - } - return Collections.emptyList(); - } -} diff --git a/src/main/java/forestry/core/gui/elements/GuiElementScrollable.java b/src/main/java/forestry/core/gui/elements/GuiElementScrollable.java deleted file mode 100644 index fb6bf972d..000000000 --- a/src/main/java/forestry/core/gui/elements/GuiElementScrollable.java +++ /dev/null @@ -1,94 +0,0 @@ -package forestry.core.gui.elements; - -import com.google.common.collect.Lists; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import forestry.api.core.IGuiElement; -import forestry.core.gui.widgets.IScrollable; - -public class GuiElementScrollable extends GuiElementVertical implements IScrollable { - protected final List visibleElements = new ArrayList<>(); - protected final int sizeX; - protected int elementOffset; - - public GuiElementScrollable(int xPos, int yPos, int width, int height) { - super(xPos, yPos, width); - this.sizeX = height; - } - - public void updateVisibleElements(int offset) { - visibleElements.clear(); - int height = 0; - int widgetEnd = yPos + sizeX; - for (int i = 0; i < elements.size(); i++) { - IGuiElement element = elements.get(i); - if (i < offset) { - height += element.getHeight(); - continue; - } - elementOffset = -height; - int elementHeight = element.getY() + element.getHeight() + elementOffset; - if (elementHeight > widgetEnd) { - continue; - } - visibleElements.add(element); - } - } - - public int getInvisibleElementCount() { - int count = 0; - int widgetEnd = yPos + sizeX; - for (int i = 0; i < elements.size(); i++) { - IGuiElement element = elements.get(i); - int elementHeight = element.getY() + element.getHeight(); - if (elementHeight > widgetEnd) { - count++; - } - } - return count; - } - - @Override - public void draw(int startX, int startY) { - for (IGuiElement element : visibleElements) { - element.draw(startX + getX(), startY + getY() + elementOffset); - } - } - - @Override - public List getToolTip(int mouseX, int mouseY) { - mouseY -= getY() + elementOffset; - mouseX -= getX(); - for (IGuiElement element : visibleElements) { - if (element.isMouseOver(mouseX, mouseY)) { - List toolTip = element.getToolTip(mouseX, mouseY); - if (!toolTip.isEmpty()) { - return toolTip; - } - } - } - return Collections.emptyList(); - } - - @Override - public void onScroll(int value) { - updateVisibleElements(value); - } - - public void clear() { - removeElements(Lists.newArrayList(elements)); - } - - @Override - public boolean isFocused(int mouseX, int mouseY) { - return isMouseOver(mouseX, mouseY); - } - - @Override - public int getHeight() { - return sizeX; - } -} diff --git a/src/main/java/forestry/core/gui/elements/GuiElementText.java b/src/main/java/forestry/core/gui/elements/GuiElementText.java deleted file mode 100644 index d15f12f03..000000000 --- a/src/main/java/forestry/core/gui/elements/GuiElementText.java +++ /dev/null @@ -1,68 +0,0 @@ -package forestry.core.gui.elements; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.renderer.GlStateManager; - -import forestry.api.core.GuiElementAlignment; -import forestry.core.render.ColourProperties; - -public class GuiElementText extends GuiElement { - public static final FontRenderer FONT_RENDERER = Minecraft.getMinecraft().fontRenderer; - - protected final String text; - protected final int color; - protected final GuiElementAlignment align; - - public GuiElementText(int xPos, int yPos, int height, String text) { - this(xPos, yPos, FONT_RENDERER.getStringWidth(text), height, text, GuiElementAlignment.LEFT); - } - - public GuiElementText(int xPos, int yPos, int height, String text, int color) { - this(xPos, yPos, FONT_RENDERER.getStringWidth(text), height, text, GuiElementAlignment.LEFT, color); - } - - public GuiElementText(int xPos, int yPos, int width, int height, String text) { - this(xPos, yPos, width, height, text, GuiElementAlignment.LEFT); - } - - public GuiElementText(int xPos, int yPos, int width, int height, String text, GuiElementAlignment align) { - this(xPos, yPos, width, height, text, align, ColourProperties.INSTANCE.get("gui.screen")); - } - - public GuiElementText(String text, GuiElementAlignment align, int color) { - this(0, 0, FONT_RENDERER.getStringWidth(text), 12, text, align, color); - } - - public GuiElementText(int xPos, int yPos, int width, int height, String text, int color) { - this(xPos, yPos, width, height, text, GuiElementAlignment.LEFT, color); - } - - public GuiElementText(int xPos, int yPos, int width, int height, String text, GuiElementAlignment align, int color) { - super(xPos, yPos, width, height); - this.text = text; - this.align = align; - this.color = color; - } - - public String getText() { - return text; - } - - @Override - public void draw(int startX, int startY) { - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - FONT_RENDERER.drawString(text, getX() + getOffset() + startX, getY() + startY, color); - } - - public int getOffset() { - switch (align) { - case RIGHT: - return width - FONT_RENDERER.getStringWidth(text); - case CENTER: - return (width - FONT_RENDERER.getStringWidth(text)) / 2; - default: - return 0; - } - } -} diff --git a/src/main/java/forestry/core/gui/elements/GuiElementVertical.java b/src/main/java/forestry/core/gui/elements/GuiElementVertical.java deleted file mode 100644 index ccd97d356..000000000 --- a/src/main/java/forestry/core/gui/elements/GuiElementVertical.java +++ /dev/null @@ -1,43 +0,0 @@ -package forestry.core.gui.elements; - -import forestry.api.core.IGuiElement; -import forestry.api.core.IGuiElementLayout; - -public class GuiElementVertical extends GuiElementLayout { - public GuiElementVertical(int xPos, int yPos, int width) { - super(xPos, yPos, width, 0); - } - - public void setHeight(int height) { - this.height = height; - } - - public IGuiElementLayout addElement(IGuiElement element) { - elements.add(element); - element.setYOffset(height); - height += element.getHeight() + distance; - return this; - } - - public IGuiElementLayout removeElement(IGuiElement element) { - elements.remove(element); - height -= element.getHeight() + distance; - element.setYOffset(0); - return this; - } - - @Override - public int getWidth() { - if(width > 0){ - return width; - } - int width = 0; - for (IGuiElement element : elements) { - int elementWidth = element.getWidth(); - if (elementWidth > width) { - width = elementWidth; - } - } - return width; - } -} diff --git a/src/main/java/forestry/core/gui/elements/GuiElementWrapped.java b/src/main/java/forestry/core/gui/elements/GuiElementWrapped.java deleted file mode 100644 index 77ddf8b50..000000000 --- a/src/main/java/forestry/core/gui/elements/GuiElementWrapped.java +++ /dev/null @@ -1,49 +0,0 @@ -package forestry.core.gui.elements; - -import java.util.List; - -import forestry.api.core.GuiElementAlignment; -import forestry.api.core.IGuiElement; - -public class GuiElementWrapped extends GuiElement { - private final IGuiElement element; - private final GuiElementAlignment align; - - public GuiElementWrapped(int xPos, int yPos, int width, int height, IGuiElement element, GuiElementAlignment align) { - super(xPos, yPos, width, height); - this.element = element; - this.align = align; - } - - @Override - public void draw(int startX, int startY) { - - } - - @Override - public List getToolTip(int mouseX, int mouseY) { - return null; - } - - public int getXOffset() { - switch (align) { - case RIGHT: - return getWidth() - element.getWidth(); - case CENTER: - return (getWidth() - element.getWidth()) / 2; - default: - return 0; - } - } - - public int getYOffset() { - switch (align) { - case RIGHT: - return getHeight() - element.getHeight(); - case CENTER: - return (getHeight() - element.getHeight()) / 2; - default: - return 0; - } - } -} diff --git a/src/main/java/forestry/core/gui/elements/GuiState.java b/src/main/java/forestry/core/gui/elements/GuiState.java new file mode 100644 index 000000000..ce4560b52 --- /dev/null +++ b/src/main/java/forestry/core/gui/elements/GuiState.java @@ -0,0 +1,98 @@ +package forestry.core.gui.elements; + +import javax.annotation.Nullable; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.renderer.texture.TextureManager; + +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import forestry.api.gui.IGuiElement; +import forestry.api.gui.IGuiState; +import forestry.core.gui.IGuiSizable; + +@SideOnly(Side.CLIENT) +public class GuiState implements IGuiState { + private final G gui; + private int mouseX = -1; + private int mouseY = -1; + private int mouseButton = -1; + @Nullable + private Minecraft mc = null; + + public GuiState(G gui) { + this.gui = gui; + } + + public int getMouseX() { + return mouseX; + } + + public void setMouseX(int mouseX) { + this.mouseX = mouseX; + } + + @Override + public int getRelativeMouseX(IGuiElement element) { + return mouseX - element.getAbsoluteX(); + } + + public int getMouseY() { + return mouseY; + } + + public void setMouseY(int mouseY) { + this.mouseY = mouseY; + } + + @Override + public int getRelativeMouseY(IGuiElement element) { + return mouseX - element.getAbsoluteY(); + } + + public int getScreenWidth() { + return gui.width; + } + + public int getScreenHeight() { + return gui.height; + } + + public int getGuiLeft() { + return gui.getGuiLeft(); + } + + public int getGuiTop() { + return gui.getGuiTop(); + } + + @Override + public int getGuiHeight() { + return gui.getSizeX(); + } + + @Override + public int getGuiWidth() { + return gui.getSizeY(); + } + + public Minecraft getMinecraft() { + if (mc == null) { + mc = Minecraft.getMinecraft(); + } + return mc; + } + + @Override + public TextureManager getTextureManager() { + return getMinecraft().getTextureManager(); + } + + @Override + public FontRenderer getFontRenderer() { + return getMinecraft().fontRenderer; + } +} diff --git a/src/main/java/forestry/core/gui/elements/IngredientElement.java b/src/main/java/forestry/core/gui/elements/IngredientElement.java new file mode 100644 index 000000000..447cdd3a1 --- /dev/null +++ b/src/main/java/forestry/core/gui/elements/IngredientElement.java @@ -0,0 +1,38 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.gui.elements; + +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.Ingredient; +import net.minecraft.util.NonNullList; + +public class IngredientElement extends AbstractItemElement { + /* Attributes - Final */ + private final NonNullList items; + + public IngredientElement(int xPos, int yPos, Ingredient ingredient) { + super(xPos, yPos); + items = NonNullList.from(ItemStack.EMPTY, ingredient.getMatchingStacks()); + } + + public IngredientElement(int xPos, int yPos, NonNullList items) { + super(xPos, yPos); + this.items = items; + } + + protected ItemStack getItemStack() { + if (items.isEmpty()) { + return ItemStack.EMPTY; + } + int perm = (int) (System.currentTimeMillis() / 1000 % items.size()); + return items.get(perm); + } +} diff --git a/src/main/java/forestry/core/gui/elements/ItemElement.java b/src/main/java/forestry/core/gui/elements/ItemElement.java new file mode 100644 index 000000000..d03cf3f93 --- /dev/null +++ b/src/main/java/forestry/core/gui/elements/ItemElement.java @@ -0,0 +1,27 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.gui.elements; + +import net.minecraft.item.ItemStack; + +public class ItemElement extends AbstractItemElement { + /* Attributes - Final */ + private final ItemStack itemStack; + + public ItemElement(int xPos, int yPos, ItemStack itemStack) { + super(xPos, yPos); + this.itemStack = itemStack; + } + + protected ItemStack getItemStack() { + return itemStack; + } +} diff --git a/src/main/java/forestry/core/gui/elements/ScrollBarElement.java b/src/main/java/forestry/core/gui/elements/ScrollBarElement.java new file mode 100644 index 000000000..ce1962f57 --- /dev/null +++ b/src/main/java/forestry/core/gui/elements/ScrollBarElement.java @@ -0,0 +1,163 @@ +package forestry.core.gui.elements; + +import javax.annotation.Nullable; + +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.util.math.MathHelper; + +import forestry.core.gui.Drawable; +import forestry.core.gui.elements.layouts.ElementGroup; +import forestry.core.gui.widgets.IScrollable; + +import org.lwjgl.input.Mouse; + +public class ScrollBarElement extends ElementGroup { + /* Attributes - Final */ + private final GuiElement slider; + + /* Attributes - State */ + private boolean visible; + private boolean isScrolling; + private boolean wasClicked; + private int currentValue; + private int initialMouseClickY; + + /* Attributes - Parameters */ + @Nullable + private IScrollable listener; + private int minValue; + private int maxValue; + private int step; + + public ScrollBarElement(int xPos, int yPos, int width, int height, Drawable sliderTexture) { + super(xPos, yPos, width, height); + + this.width = width; + this.height = height; + + isScrolling = false; + wasClicked = false; + visible = true; + slider = drawable(sliderTexture); + } + + public ScrollBarElement(int xPos, int yPos, Drawable backgroundTexture, boolean hasBorder, Drawable sliderTexture) { + super(xPos, yPos, backgroundTexture.uWidth, backgroundTexture.vHeight); + + int offset = hasBorder ? 1 : 0; + + isScrolling = false; + wasClicked = false; + visible = true; + + drawable(backgroundTexture); + slider = drawable(offset, offset, sliderTexture); + } + + public void setParameters(IScrollable listener, int minValue, int maxValue, int step) { + this.listener = listener; + this.minValue = minValue; + this.maxValue = maxValue; + this.step = step; + + setValue(currentValue); + } + + public void setVisible(boolean visible) { + this.visible = visible; + } + + public boolean isVisible() { + return visible; + } + + public int getValue() { + return MathHelper.clamp(currentValue, minValue, maxValue); + } + + public int setValue(int value) { + currentValue = MathHelper.clamp(value, minValue, maxValue); + if (listener != null) { + listener.onScroll(currentValue); + } + int offset; + if (value >= maxValue) { + offset = height - slider.height; + } else if (value <= minValue) { + offset = 0; + } else { + offset = (int) (((float) (currentValue - minValue) / (maxValue - minValue)) * (float) (height - slider.height)); + } + slider.setYPosition(offset); + return currentValue; + } + + @Override + public void drawElement(int mouseX, int mouseY) { + if (!isVisible()) { + return; + } + updateSlider(mouseX, mouseY); + + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + super.drawElement(mouseX, mouseY); + } + + private void updateSlider(int mouseX, int mouseY) { + boolean mouseDown = Mouse.isButtonDown(0); + + if (listener == null || listener.isFocused(mouseX, mouseY)) { + int wheel = Mouse.getDWheel(); + if (wheel > 0) { + setValue(currentValue - step); + return; + } else if (wheel < 0) { + setValue(currentValue + step); + return; + } + } + + //Zhe position of the mouse relative to the position of the widget + int y = mouseY - yPos; + + if (!mouseDown && wasClicked) { + wasClicked = false; + } + + //Not clicked and scrolling -> stop scrolling + if (!mouseDown && isScrolling) { + this.isScrolling = false; + } + + //Clicked on the slider and scrolling + if (this.isScrolling) { + int range = maxValue - minValue; + float value = (float) (y - initialMouseClickY) / (float) (height - slider.height); + value *= (float) range; + if (value < (float) step / 2f) { + setValue(minValue); + } else if (value > maxValue - ((float) step / 2f)) { + setValue(maxValue); + } else { + setValue((int) (minValue + (float) step * Math.round(value))); + } + } else if (slider.isMouseOver(mouseX - getX(), mouseY - getY())) { //clicked on the slider + if (mouseDown) { + isScrolling = true; + initialMouseClickY = y - slider.getY(); + } + } else if (mouseDown && !wasClicked && isMouseOver(mouseX, mouseY)) { //clicked on the bar but not on the slider + int range = maxValue - minValue; + float value = ((float) y - (float) slider.height / 2.0F) / (float) (height - slider.height); + value *= (float) range; + if (value < (float) step / 2f) { + setValue(minValue); + } else if (value > maxValue - ((float) step / 2f)) { + setValue(maxValue); + } else { + setValue((int) (minValue + (float) step * Math.round(value))); + } + wasClicked = true; + } + } +} diff --git a/src/main/java/forestry/core/gui/elements/TankElement.java b/src/main/java/forestry/core/gui/elements/TankElement.java new file mode 100644 index 000000000..fce12855e --- /dev/null +++ b/src/main/java/forestry/core/gui/elements/TankElement.java @@ -0,0 +1,177 @@ +package forestry.core.gui.elements; + +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.function.Supplier; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.BufferBuilder; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.renderer.texture.TextureManager; +import net.minecraft.client.renderer.texture.TextureMap; +import net.minecraft.client.renderer.vertex.DefaultVertexFormats; +import net.minecraft.item.EnumRarity; +import net.minecraft.util.ResourceLocation; + +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; + +import forestry.core.gui.Drawable; +import forestry.core.utils.Translator; + +public class TankElement extends GuiElement { + /* Attributes - Final */ + @Nullable + private final Drawable background; + @Nullable + private final Drawable overlay; + private final Supplier tank; + + public TankElement(int xPos, int yPos, @Nullable Drawable background, Supplier tank) { + this(xPos, yPos, background, tank, null); + } + + public TankElement(int xPos, int yPos, @Nullable Drawable background, Supplier tank, @Nullable Drawable overlay) { + this(xPos, yPos, background, tank, overlay, 16, 58); + } + + public TankElement(int xPos, int yPos, @Nullable Drawable background, Supplier tank, @Nullable Drawable overlay, int width, int height) { + super(xPos, yPos, width, height); + this.background = background; + this.tank = tank; + this.overlay = overlay; + } + + @Nullable + private FluidTankInfo getTank() { + return tank.get(); + } + + @Override + public void drawElement(int mouseX, int mouseY) { + GlStateManager.disableBlend(); + if (background != null) { + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + background.draw(0, 0); + } + FluidTankInfo tankInfo = getTank(); + if (tankInfo == null || tankInfo.capacity <= 0) { + return; + } + + FluidStack contents = tankInfo.fluid; + Minecraft minecraft = Minecraft.getMinecraft(); + TextureManager textureManager = minecraft.getTextureManager(); + if (contents != null && contents.amount > 0 && contents.getFluid() != null) { + Fluid fluid = contents.getFluid(); + if (fluid != null) { + TextureMap textureMapBlocks = minecraft.getTextureMapBlocks(); + ResourceLocation fluidStill = fluid.getStill(); + TextureAtlasSprite fluidStillSprite = null; + if (fluidStill != null) { + fluidStillSprite = textureMapBlocks.getTextureExtry(fluidStill.toString()); + } + if (fluidStillSprite == null) { + fluidStillSprite = textureMapBlocks.getMissingSprite(); + } + + int fluidColor = fluid.getColor(contents); + + int scaledAmount = contents.amount * height / tankInfo.capacity; + if (contents.amount > 0 && scaledAmount < 1) { + scaledAmount = 1; + } + if (scaledAmount > height) { + scaledAmount = height; + } + + textureManager.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE); + setGLColorFromInt(fluidColor); + + final int xTileCount = width / 16; + final int xRemainder = width - xTileCount * 16; + final int yTileCount = scaledAmount / 16; + final int yRemainder = scaledAmount - yTileCount * 16; + + final int yStart = height; + + for (int xTile = 0; xTile <= xTileCount; xTile++) { + for (int yTile = 0; yTile <= yTileCount; yTile++) { + int width = xTile == xTileCount ? xRemainder : 16; + int height = yTile == yTileCount ? yRemainder : 16; + int x = xTile * 16; + int y = yStart - (yTile + 1) * 16; + if (width > 0 && height > 0) { + int maskTop = 16 - height; + int maskRight = 16 - width; + + drawFluidTexture(x, y, fluidStillSprite, maskTop, maskRight, 100); + } + } + } + } + } + + if (overlay != null) { + GlStateManager.disableDepth(); + overlay.draw(0, 0); + GlStateManager.enableDepth(); + } + + GlStateManager.color(1, 1, 1, 1); + } + + @Override + public List getTooltip(int mouseX, int mouseY) { + FluidTankInfo tankInfo = getTank(); + if (tankInfo == null) { + return Collections.emptyList(); + } + List toolTip = new ArrayList<>(); + int amount = 0; + FluidStack fluidStack = tankInfo.fluid; + if (fluidStack != null) { + Fluid fluidType = fluidStack.getFluid(); + EnumRarity rarity = fluidType.getRarity(); + if (rarity == null) { + rarity = EnumRarity.COMMON; + } + toolTip.add(rarity.rarityColor + fluidType.getLocalizedName(fluidStack)); + amount = fluidStack.amount; + } + String liquidAmount = Translator.translateToLocalFormatted("for.gui.tooltip.liquid.amount", amount, tankInfo.capacity); + toolTip.add(liquidAmount); + return toolTip; + } + + private static void setGLColorFromInt(int color) { + float red = (color >> 16 & 0xFF) / 255.0F; + float green = (color >> 8 & 0xFF) / 255.0F; + float blue = (color & 0xFF) / 255.0F; + + GlStateManager.color(red, green, blue, 1.0F); + } + + private static void drawFluidTexture(double xCoord, double yCoord, TextureAtlasSprite textureSprite, int maskTop, int maskRight, double zLevel) { + double uMin = textureSprite.getMinU(); + double uMax = textureSprite.getMaxU(); + double vMin = textureSprite.getMinV(); + double vMax = textureSprite.getMaxV(); + uMax = uMax - maskRight / 16.0 * (uMax - uMin); + vMax = vMax - maskTop / 16.0 * (vMax - vMin); + + Tessellator tessellator = Tessellator.getInstance(); + BufferBuilder buffer = tessellator.getBuffer(); + buffer.begin(7, DefaultVertexFormats.POSITION_TEX); + buffer.pos(xCoord, yCoord + 16, zLevel).tex(uMin, vMax).endVertex(); + buffer.pos(xCoord + 16 - maskRight, yCoord + 16, zLevel).tex(uMax, vMax).endVertex(); + buffer.pos(xCoord + 16 - maskRight, yCoord + maskTop, zLevel).tex(uMax, vMin).endVertex(); + buffer.pos(xCoord, yCoord + maskTop, zLevel).tex(uMin, vMin).endVertex(); + tessellator.draw(); + } +} diff --git a/src/main/java/forestry/core/gui/elements/TextElement.java b/src/main/java/forestry/core/gui/elements/TextElement.java new file mode 100644 index 000000000..d4b3e5fb7 --- /dev/null +++ b/src/main/java/forestry/core/gui/elements/TextElement.java @@ -0,0 +1,46 @@ +package forestry.core.gui.elements; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; + +import forestry.api.gui.GuiElementAlignment; + +public class TextElement extends GuiElement { + /* Constants */ + public static final FontRenderer FONT_RENDERER = Minecraft.getMinecraft().fontRenderer; + + /* Attributes - Final */ + protected final String text; + protected final int color; + protected final boolean unicode; + + public TextElement(int width, int height, String text, GuiElementAlignment align, int color, boolean unicode) { + this(0, 0, width, height, text, align, color, unicode); + } + + public TextElement(int xPos, int yPos, int width, int height, String text, GuiElementAlignment align, int color, boolean unicode) { + super(xPos, yPos, width, height); + this.text = text; + setAlign(align); + this.color = color; + this.unicode = unicode; + if (width < 0) { + boolean uni = FONT_RENDERER.getUnicodeFlag(); + FONT_RENDERER.setUnicodeFlag(this.unicode); + this.width = FONT_RENDERER.getStringWidth(text); + FONT_RENDERER.setUnicodeFlag(uni); + } + } + + public String getText() { + return text; + } + + @Override + public void drawElement(int mouseX, int mouseY) { + boolean unicode = FONT_RENDERER.getUnicodeFlag(); + FONT_RENDERER.setUnicodeFlag(this.unicode); + FONT_RENDERER.drawString(text, 0, 0, color); + FONT_RENDERER.setUnicodeFlag(unicode); + } +} diff --git a/src/main/java/forestry/core/gui/elements/layouts/AbstractElementLayout.java b/src/main/java/forestry/core/gui/elements/layouts/AbstractElementLayout.java new file mode 100644 index 000000000..800568e9a --- /dev/null +++ b/src/main/java/forestry/core/gui/elements/layouts/AbstractElementLayout.java @@ -0,0 +1,27 @@ +package forestry.core.gui.elements.layouts; + +import forestry.api.gui.IElementLayout; + +public abstract class AbstractElementLayout extends ElementGroup implements IElementLayout { + /* The distance between the different elements of this group. */ + public int distance; + + public AbstractElementLayout(int xPos, int yPos, int width, int height) { + super(xPos, yPos, width, height); + } + + public AbstractElementLayout setDistance(int distance) { + this.distance = distance; + return this; + } + + @Override + public int getDistance() { + return distance; + } + + @Override + public int getSize() { + return elements.size(); + } +} diff --git a/src/main/java/forestry/core/gui/elements/layouts/ElementGroup.java b/src/main/java/forestry/core/gui/elements/layouts/ElementGroup.java new file mode 100644 index 000000000..e2a861b8a --- /dev/null +++ b/src/main/java/forestry/core/gui/elements/layouts/ElementGroup.java @@ -0,0 +1,203 @@ +package forestry.core.gui.elements.layouts; + +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.item.ItemStack; + +import forestry.api.gui.GuiElementAlignment; +import forestry.api.gui.IElementGroup; +import forestry.api.gui.IElementLayoutHelper; +import forestry.api.gui.IGuiElement; +import forestry.core.gui.Drawable; +import forestry.core.gui.elements.DrawableElement; +import forestry.core.gui.elements.GuiElement; +import forestry.core.gui.elements.ItemElement; +import forestry.core.gui.elements.TextElement; + +public abstract class ElementGroup extends GuiElement implements IElementGroup { + protected final List elements = new ArrayList<>(); + + protected ElementGroup(int xPos, int yPos, int width, int height) { + super(xPos, yPos, width, height); + } + + public E add(E element) { + elements.add(element); + element.setParent(this); + return element; + } + + public E remove(E element) { + elements.remove(element); + return element; + } + + public void clear() { + elements.clear(); + } + + @Override + public List getElements() { + return elements; + } + + @Override + public void drawElement(int mouseX, int mouseY) { + int mX = mouseX - getX(); + int mY = mouseY - getY(); + elements.forEach(element -> element.draw(mX, mY)); + } + + @Override + public void mouseClicked(int mouseX, int mouseY, int mouseButton) { + int mX = mouseX - getX(); + int mY = mouseY - getY(); + elements.stream() + .filter(element -> element.isMouseOver(mX, mY)) + .forEach(element -> element.mouseClicked(mX, mY, mouseButton)); + } + + @Override + public void mouseReleased(int mouseX, int mouseY, int mouseButton) { + int mX = mouseX - getX(); + int mY = mouseY - getY(); + elements.stream() + .filter(element -> element.isMouseOver(mX, mY)) + .forEach(element -> element.mouseReleased(mX, mY, mouseButton)); + } + + @Override + public void mouseClickMove(int mouseX, int mouseY, int mouseButton) { + int mX = mouseX - getX(); + int mY = mouseY - getY(); + elements.stream() + .filter(element -> element.isMouseOver(mX, mY)) + .forEach(element -> element.mouseClickMove(mX, mY, mouseButton)); + } + + @Override + public boolean keyTyped(char typedChar, int keyCode) { + return elements.stream().anyMatch(element -> element.keyTyped(typedChar, keyCode)); + } + + @Override + public List getTooltip(int mouseX, int mouseY) { + mouseX -= getX(); + mouseY -= getY(); + for (IGuiElement element : elements) { + if (element.isMouseOver(mouseX, mouseY)) { + List tooltip = element.getTooltip(mouseX, mouseY); + if (!tooltip.isEmpty()) { + return tooltip; + } + } + } + return tooltip; + } + + @Nullable + @Override + public IGuiElement getLastElement() { + return elements.isEmpty() ? null : elements.get(elements.size() - 1); + } + + public DrawableElement drawable(Drawable drawable) { + return add(new DrawableElement(drawable)); + } + + public DrawableElement drawable(int x, int y, Drawable drawable) { + return add(new DrawableElement(x, y, drawable)); + } + + @Override + public IGuiElement item(int xPos, int yPos, ItemStack itemStack) { + IGuiElement element = new ItemElement(xPos, yPos, itemStack); + add(element); + return element; + } + + @Override + public IGuiElement text(String text) { + return text(0, text, 0xFFFFFF); + } + + @Override + public IGuiElement text(String text, int color) { + return text(0, text, color); + } + + @Override + public IGuiElement text(String text, GuiElementAlignment align) { + return text(text, align, 0xFFFFFF); + } + + @Override + public IGuiElement text(String text, GuiElementAlignment align, int color, boolean unicode) { + return text(0, 12, text, align, color, unicode); + } + + @Override + public IGuiElement text(String text, GuiElementAlignment align, int color) { + return text(0, text, align, color); + } + + public IGuiElement text(int x, String text, int color) { + return text(x, text, GuiElementAlignment.TOP_LEFT, color); + } + + public IGuiElement text(int x, String text, GuiElementAlignment align, int color) { + return text(x, 12, text, align, color); + } + + @Override + public IGuiElement text(int x, int height, String text, GuiElementAlignment align, int color) { + return text(x, height, text, align, color, false); + } + + @Override + public IGuiElement text(int x, int y, int width, int height, String text) { + return add(new TextElement(x, y, width, height, text, GuiElementAlignment.TOP_LEFT, 0xFFFFFF, false)); + } + + @Override + public IGuiElement text(int x, int height, String text, GuiElementAlignment align, int color, boolean unicode) { + return add(new TextElement(x, 0, -1, height, text, align, color, unicode)); + } + + @Override + public AbstractElementLayout vertical(int xPos, int yPos, int width) { + return add(new VerticalLayout(xPos, yPos, width)); + } + + @Override + public AbstractElementLayout vertical(int width) { + return add(new VerticalLayout(0, 0, width)); + } + + @Override + public AbstractElementLayout horizontal(int xPos, int yPos, int height) { + return add(new HorizontalLayout(xPos, yPos, height)); + } + + @Override + public AbstractElementLayout horizontal(int height) { + return add(new HorizontalLayout(0, 0, height)); + } + + @Override + public ElementGroup panel(int xPos, int yPos, int width, int height) { + return add(new PaneLayout(xPos, yPos, width, height)); + } + + @Override + public ElementGroup panel(int width, int height) { + return add(new PaneLayout(0, 0, width, height)); + } + + @Override + public ElementLayoutHelper layoutHelper(IElementLayoutHelper.LayoutFactory layoutFactory, int width, int height) { + return new ElementLayoutHelper(layoutFactory, width, height, this); + } +} diff --git a/src/main/java/forestry/core/gui/elements/GuiElementLayoutHelper.java b/src/main/java/forestry/core/gui/elements/layouts/ElementLayoutHelper.java similarity index 65% rename from src/main/java/forestry/core/gui/elements/GuiElementLayoutHelper.java rename to src/main/java/forestry/core/gui/elements/layouts/ElementLayoutHelper.java index b97948dab..e742087c1 100644 --- a/src/main/java/forestry/core/gui/elements/GuiElementLayoutHelper.java +++ b/src/main/java/forestry/core/gui/elements/layouts/ElementLayoutHelper.java @@ -1,26 +1,29 @@ -package forestry.core.gui.elements; +package forestry.core.gui.elements.layouts; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import forestry.api.core.IGuiElement; -import forestry.api.core.IGuiElementHelper; -import forestry.api.core.IGuiElementLayout; -import forestry.api.core.IGuiElementLayoutHelper; +import forestry.api.gui.GuiElementAlignment; +import forestry.api.gui.IElementGroup; +import forestry.api.gui.IElementLayout; +import forestry.api.gui.IElementLayoutHelper; +import forestry.api.gui.IGuiElement; -public class GuiElementLayoutHelper implements IGuiElementLayoutHelper { - private final List layouts = new ArrayList<>(); +public class ElementLayoutHelper implements IElementLayoutHelper { + private final List layouts = new ArrayList<>(); private final LayoutFactory layoutFactory; private final int width; private final int height; - private final IGuiElementHelper parent; + private final IElementGroup parent; private int xOffset; private int yOffset; - private IGuiElementLayout currentLayout; + @Nullable + private IElementLayout currentLayout; private boolean horizontal; - public GuiElementLayoutHelper(LayoutFactory layoutFactory, int width, int height, IGuiElementHelper parent) { + public ElementLayoutHelper(LayoutFactory layoutFactory, int width, int height, IElementGroup parent) { this.layoutFactory = layoutFactory; this.width = width; this.height = height; @@ -30,10 +33,11 @@ public class GuiElementLayoutHelper implements IGuiElementLayoutHelper { /** * @return Only false if the helper has no space to add this element. */ + @Override public boolean add(IGuiElement element) { if (currentLayout == null) { layouts.add(currentLayout = layoutFactory.createLayout(0, 0)); - this.horizontal = currentLayout instanceof GuiElementVertical; + this.horizontal = currentLayout instanceof VerticalLayout; } int groupWidth = currentLayout.getWidth(); int groupHeight = currentLayout.getHeight(); @@ -62,18 +66,22 @@ public class GuiElementLayoutHelper implements IGuiElementLayoutHelper { groupWidth += eleWidth; xOffset = groupWidth; } - currentLayout.addElement(element); + currentLayout.add(element); return true; } @Override - public void finish() { + public void finish(boolean center) { for (IGuiElement element : layouts) { + if (center) { + element.setAlign(GuiElementAlignment.TOP_CENTER); + } parent.add(element); } clear(); } + @Override public void clear() { layouts.clear(); currentLayout = null; @@ -81,7 +89,8 @@ public class GuiElementLayoutHelper implements IGuiElementLayoutHelper { yOffset = 0; } - public Collection layouts() { + @Override + public Collection layouts() { return layouts; } } diff --git a/src/main/java/forestry/core/gui/elements/GuiElementHorizontal.java b/src/main/java/forestry/core/gui/elements/layouts/HorizontalLayout.java similarity index 51% rename from src/main/java/forestry/core/gui/elements/GuiElementHorizontal.java rename to src/main/java/forestry/core/gui/elements/layouts/HorizontalLayout.java index 7a2abbdf8..c0869e5b7 100644 --- a/src/main/java/forestry/core/gui/elements/GuiElementHorizontal.java +++ b/src/main/java/forestry/core/gui/elements/layouts/HorizontalLayout.java @@ -1,10 +1,10 @@ -package forestry.core.gui.elements; +package forestry.core.gui.elements.layouts; -import forestry.api.core.IGuiElement; -import forestry.api.core.IGuiElementLayout; +import forestry.api.gui.IGuiElement; -public class GuiElementHorizontal extends GuiElementLayout { - public GuiElementHorizontal(int xPos, int yPos, int height) { +public class HorizontalLayout extends AbstractElementLayout { + + public HorizontalLayout(int xPos, int yPos, int height) { super(xPos, yPos, 0, height); } @@ -12,23 +12,24 @@ public class GuiElementHorizontal extends GuiElementLayout { this.width = width; } - public IGuiElementLayout addElement(IGuiElement element) { + public E add(E element) { elements.add(element); - element.setXOffset(width); + element.setParent(this); + element.setXPosition(width); width += element.getWidth() + distance; - return this; + return element; } - public IGuiElementLayout removeElement(IGuiElement element) { + public E remove(E element) { elements.remove(element); width -= element.getWidth() + distance; - element.setXOffset(0); - return this; + element.setXPosition(0); + return element; } @Override public int getHeight() { - if(height > 0){ + if (height > 0) { return height; } int height = 0; diff --git a/src/main/java/forestry/core/gui/elements/GuiElementPanel.java b/src/main/java/forestry/core/gui/elements/layouts/PaneLayout.java similarity index 52% rename from src/main/java/forestry/core/gui/elements/GuiElementPanel.java rename to src/main/java/forestry/core/gui/elements/layouts/PaneLayout.java index 141752092..63766d485 100644 --- a/src/main/java/forestry/core/gui/elements/GuiElementPanel.java +++ b/src/main/java/forestry/core/gui/elements/layouts/PaneLayout.java @@ -1,26 +1,19 @@ -package forestry.core.gui.elements; +package forestry.core.gui.elements.layouts; -import forestry.api.core.IGuiElement; -import forestry.api.core.IGuiElementLayout; +import forestry.api.gui.IGuiElement; -public class GuiElementPanel extends GuiElementLayout { - public GuiElementPanel(int xPos, int yPos, int width, int height) { +public class PaneLayout extends ElementGroup { + public PaneLayout(int width, int height) { + super(0, 0, width, height); + } + + public PaneLayout(int xPos, int yPos, int width, int height) { super(xPos, yPos, width, height); } - public IGuiElementLayout addElement(IGuiElement element) { - elements.add(element); - return this; - } - - public IGuiElementLayout removeElement(IGuiElement element) { - elements.remove(element); - return this; - } - @Override public int getWidth() { - if(width > 0){ + if (width > 0) { return width; } int width = 0; @@ -35,7 +28,7 @@ public class GuiElementPanel extends GuiElementLayout { @Override public int getHeight() { - if(height > 0){ + if (height > 0) { return height; } int height = 0; diff --git a/src/main/java/forestry/core/gui/elements/layouts/ScrollableElement.java b/src/main/java/forestry/core/gui/elements/layouts/ScrollableElement.java new file mode 100644 index 000000000..d2c5368cd --- /dev/null +++ b/src/main/java/forestry/core/gui/elements/layouts/ScrollableElement.java @@ -0,0 +1,210 @@ +package forestry.core.gui.elements.layouts; + +import com.google.common.collect.Lists; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.function.Function; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.ScaledResolution; +import net.minecraft.client.renderer.GlStateManager; + +import forestry.api.genetics.IAllele; +import forestry.api.genetics.IAlleleInteger; +import forestry.api.genetics.IAlleleSpecies; +import forestry.api.genetics.IAlleleTolerance; +import forestry.api.genetics.IBreedingTracker; +import forestry.api.genetics.IChromosomeType; +import forestry.api.genetics.IIndividual; +import forestry.api.genetics.IMutation; +import forestry.api.gui.GuiElementAlignment; +import forestry.api.gui.IElementGenetic; +import forestry.api.gui.IElementGroup; +import forestry.api.gui.IElementLayout; +import forestry.api.gui.IGuiElement; +import forestry.core.gui.elements.GuiElementFactory; +import forestry.core.gui.widgets.IScrollable; +import forestry.core.render.ColourProperties; +import forestry.core.utils.Translator; + +import org.lwjgl.opengl.GL11; + +public class ScrollableElement extends VerticalLayout implements IScrollable, IElementGenetic { + private final List visibleElements = new ArrayList<>(); + private final int sizeY; + private int elementOffset; + private float scrollPercentage; + private float step; + + public ScrollableElement(int xPos, int yPos, int width, int height) { + super(xPos, yPos, width); + this.sizeY = height; + } + + public void updateVisibleElements(int offset) { + visibleElements.clear(); + int height = 0; + + int widgetEnd = yPos + sizeY; + for (int i = 0; i < elements.size(); i++) { + IGuiElement element = elements.get(i); + if (i < offset) { + height += element.getHeight(); + continue; + } + elementOffset = -height; + int elementHeight = element.getY() + element.getHeight() + elementOffset; + if (elementHeight > widgetEnd) { + continue; + } + visibleElements.add(element); + } + } + + public int getInvisibleElementCount() { + step = (12 * 0.5F); + return (int) ((getHeight() - sizeY) / (step)); + } + + @Override + public void drawElement(int mouseX, int mouseY) { + GL11.glEnable(GL11.GL_SCISSOR_TEST); + Minecraft mc = Minecraft.getMinecraft(); + ScaledResolution res = new ScaledResolution(mc); + double scaleWidth = mc.displayWidth / res.getScaledWidth_double(); + double scaleHeight = mc.displayHeight / res.getScaledHeight_double(); + GL11.glScissor((int) ((getAbsoluteX()) * scaleWidth), (int) (mc.displayHeight - ((getAbsoluteY() + sizeY) * scaleHeight)), (int) (width * scaleWidth), (int) (sizeY * scaleHeight)); + GlStateManager.pushMatrix(); + GlStateManager.translate(0.0F, -((int) scrollPercentage), 0.0F); + for (IGuiElement element : elements) { + element.draw(mouseX, mouseY); + } + GlStateManager.popMatrix(); + GL11.glDisable(GL11.GL_SCISSOR_TEST); + } + + @Override + public List getTooltip(int mouseX, int mouseY) { + mouseX -= getX(); + mouseY -= getY(); + for (IGuiElement element : visibleElements) { + if (element.isMouseOver()) { + List toolTip = element.getTooltip(mouseX, mouseY); + if (!toolTip.isEmpty()) { + return toolTip; + } + } + } + return Collections.emptyList(); + } + + @Override + public void addFertilityInfo(String chromosomeName, IAlleleInteger fertilityAllele, int texOffset) { + addRow(chromosomeName, GuiElementFactory.INSTANCE.createFertilityInfo(fertilityAllele, texOffset)); + } + + @Override + public void addToleranceInfo(String chromosomeName, IAlleleTolerance toleranceAllele, IAlleleSpecies species, String text) { + addRow(chromosomeName, text, species.isDominant()); + addRow(" " + Translator.translateToLocal("for.gui.tolerance"), GuiElementFactory.INSTANCE.createToleranceInfo(toleranceAllele)); + } + + @Override + public void addMutation(int x, int y, int width, int height, IMutation mutation, IAllele species, IBreedingTracker breedingTracker) { + IGuiElement element = GuiElementFactory.INSTANCE.createMutation(x, y, width, height, mutation, species, breedingTracker); + if (element == null) { + return; + } + add(element); + } + + @Override + public void addMutationResultant(int x, int y, int width, int height, IMutation mutation, IBreedingTracker breedingTracker) { + IGuiElement element = GuiElementFactory.INSTANCE.createMutationResultant(x, y, width, height, mutation, breedingTracker); + if (element == null) { + return; + } + add(element); + } + + @Override + public void addRow(String firstText, String secondText, boolean dominant) { + addRow(firstText, secondText, ColourProperties.INSTANCE.get("gui.screen"), GuiElementFactory.INSTANCE.getColorCoding(dominant)); + } + + @Override + public final void addAlleleRow(String chromosomeName, IIndividual individual, IChromosomeType chromosome, boolean active) { + addAlleleRow(chromosomeName, IAllele::getAlleleName, individual, chromosome, active); + } + + @Override + public void addRow(String firstText, String secondText, int firstColor, int secondColor) { + IElementLayout first = addSplitText(width, firstText, GuiElementAlignment.TOP_LEFT, firstColor); + IElementLayout second = addSplitText(width, secondText, GuiElementAlignment.TOP_LEFT, secondColor); + addRow(first, second); + } + + private IElementLayout addSplitText(int width, String text, GuiElementAlignment alignment, int color) { + FontRenderer fontRenderer = Minecraft.getMinecraft().fontRenderer; + IElementLayout vertical = new VerticalLayout(width); + for (String splitText : fontRenderer.listFormattedStringToWidth(text, 70)) { + vertical.text(splitText, alignment, color); + } + return vertical; + } + + private void addRow(String chromosomeName, IGuiElement right) { + int center = width / 2; + IGuiElement first = addSplitText(center, chromosomeName, GuiElementAlignment.TOP_LEFT, ColourProperties.INSTANCE.get("gui.screen")); + addRow(first, right); + } + + private void addRow(IGuiElement first, IGuiElement second) { + int center = width / 2; + IElementGroup panel = new PaneLayout(width, 0); + if (first.getHeight() > second.getHeight()) { + first.setAlign(GuiElementAlignment.MIDDLE_LEFT); + } else if (second.getHeight() > first.getHeight()) { + second.setAlign(GuiElementAlignment.MIDDLE_LEFT); + } + panel.add(first); + panel.add(second); + second.setXPosition(center); + add(panel); + } + + @SuppressWarnings("unchecked") + @Override + public final void addAlleleRow(String chromosomeName, Function toString, IIndividual individual, IChromosomeType chromosome, boolean active) { + A allele; + if (active) { + allele = (A) individual.getGenome().getActiveAllele(chromosome); + } else { + allele = (A) individual.getGenome().getInactiveAllele(chromosome); + } + addRow(chromosomeName, toString.apply(allele), allele.isDominant()); + } + + @Override + public void onScroll(int value) { + scrollPercentage = (value * step); + } + + @Override + public void clear() { + remove(Lists.newArrayList(elements)); + } + + @Override + public boolean isFocused(int mouseX, int mouseY) { + return isMouseOver(mouseX, mouseY); + } + + /*@Override + public int getHeight() { + return sizeY; + }*/ +} diff --git a/src/main/java/forestry/core/gui/elements/layouts/VerticalLayout.java b/src/main/java/forestry/core/gui/elements/layouts/VerticalLayout.java new file mode 100644 index 000000000..bc1b38dbe --- /dev/null +++ b/src/main/java/forestry/core/gui/elements/layouts/VerticalLayout.java @@ -0,0 +1,55 @@ +package forestry.core.gui.elements.layouts; + +import forestry.api.gui.IGuiElement; + +public class VerticalLayout extends AbstractElementLayout { + public VerticalLayout(int width) { + this(0, 0, width); + } + + public VerticalLayout(int xPos, int yPos, int width) { + super(xPos, yPos, width, 0); + } + + public void setHeight(int height) { + this.height = height; + } + + public E add(E element) { + elements.add(element); + element.setParent(this); + element.setYPosition(height); + height += element.getHeight() + distance; + return element; + } + + public E remove(E element) { + elements.remove(element); + height -= element.getHeight() + distance; + element.setYPosition(0); + return element; + } + + public void layout(){ + height = 0; + for(IGuiElement element : elements){ + element.setYPosition(height); + height += element.getHeight() + distance; + } + } + + @Override + public int getWidth() { + if (width > 0) { + return width; + } + int width = 0; + for (IGuiElement element : elements) { + int elementWidth = element.getWidth(); + if (elementWidth > width) { + width = elementWidth; + } + } + return width; + } +} diff --git a/src/main/java/forestry/core/gui/elements/layouts/package-info.java b/src/main/java/forestry/core/gui/elements/layouts/package-info.java new file mode 100644 index 000000000..043ac5915 --- /dev/null +++ b/src/main/java/forestry/core/gui/elements/layouts/package-info.java @@ -0,0 +1,10 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.gui.elements.layouts; + +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/gui/elements/package-info.java b/src/main/java/forestry/core/gui/elements/package-info.java index c77b673aa..d94451202 100644 --- a/src/main/java/forestry/core/gui/elements/package-info.java +++ b/src/main/java/forestry/core/gui/elements/package-info.java @@ -5,6 +5,6 @@ package forestry.core.gui.elements; import javax.annotation.ParametersAreNonnullByDefault; -import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; -import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file +import forestry.core.utils.FieldsAreNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/gui/ledgers/LedgerManager.java b/src/main/java/forestry/core/gui/ledgers/LedgerManager.java index 1ba4b1d17..a481d21df 100755 --- a/src/main/java/forestry/core/gui/ledgers/LedgerManager.java +++ b/src/main/java/forestry/core/gui/ledgers/LedgerManager.java @@ -82,8 +82,8 @@ public class LedgerManager { @Nullable private Ledger getAtPosition(int mX, int mY) { if (!ledgers.isEmpty()) { - final int xShift = (gui.width - gui.getSizeX()) / 2 + gui.getSizeX(); - int yShift = (gui.height - gui.getSizeY()) / 2 + 8; + final int xShift = gui.getGuiLeft() + gui.getSizeX(); + int yShift = gui.getGuiTop() + 8; for (Ledger ledger : ledgers) { if (!ledger.isVisible()) { @@ -100,8 +100,8 @@ public class LedgerManager { } } - final int xShiftError = (gui.width - gui.getSizeX()) / 2; - int yShiftError = (gui.height - gui.getSizeY()) / 2 + 8; + final int xShiftError = gui.getGuiLeft(); + int yShiftError = gui.getGuiTop() + 8; for (ErrorLedger errorLedger : errorLedgers) { if (!errorLedger.isVisible()) { @@ -175,7 +175,7 @@ public class LedgerManager { if (ledger != null) { ToolTip toolTip = new ToolTip(); toolTip.add(ledger.getTooltip()); - GuiUtil.drawToolTips(gui, toolTip, mouseX, mouseY); + GuiUtil.drawToolTips(gui, null, toolTip, mouseX, mouseY); } } @@ -207,6 +207,15 @@ public class LedgerManager { } + public boolean hasOpenedLedger(){ + for (Ledger ledger : ledgers) { + if (ledger.isOpen()) { + return true; + } + } + return false; + } + public int getMaxWidth() { return maxWidth; } diff --git a/src/main/java/forestry/core/gui/slots/SlotAnalyzer.java b/src/main/java/forestry/core/gui/slots/SlotAnalyzer.java new file mode 100644 index 000000000..89b3fb075 --- /dev/null +++ b/src/main/java/forestry/core/gui/slots/SlotAnalyzer.java @@ -0,0 +1,33 @@ +package forestry.core.gui.slots; + +import javax.annotation.Nullable; + +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import forestry.core.gui.GuiAnalyzerProvider; +import forestry.core.inventory.ItemInventoryAlyzer; + +public class SlotAnalyzer extends SlotFiltered { + @Nullable + @SideOnly(Side.CLIENT) + private GuiAnalyzerProvider gui; + + public SlotAnalyzer(ItemInventoryAlyzer inventory, int slotIndex, int xPos, int yPos) { + super(inventory, slotIndex, xPos, yPos); + } + + public void setPosition(int xPos, int yPos){ + this.xPos = xPos; + this.yPos = yPos; + } + + public void setGui(@Nullable GuiAnalyzerProvider gui) { + this.gui = gui; + } + + @Override + public boolean isEnabled() { + return gui != null && gui.analyzer.isVisible(); + } +} diff --git a/src/main/java/forestry/core/gui/slots/SlotLockable.java b/src/main/java/forestry/core/gui/slots/SlotLockable.java new file mode 100644 index 000000000..a8862720c --- /dev/null +++ b/src/main/java/forestry/core/gui/slots/SlotLockable.java @@ -0,0 +1,52 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.gui.slots; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; + +public class SlotLockable extends SlotForestry { + + private boolean locked; + + public SlotLockable(IInventory inventory, int slotIndex, int xPos, int yPos) { + super(inventory, slotIndex, xPos, yPos); + } + + public void lock() { + this.locked = true; + setCanAdjustPhantom(false); + blockShift(); + setPhantom(); + } + + @Override + public ItemStack onTake(EntityPlayer player, ItemStack itemStack) { + if(!locked){ + return super.onTake(player, itemStack); + } + return ItemStack.EMPTY; + } + + @Override + public boolean isItemValid(ItemStack par1ItemStack) { + return !locked && super.isItemValid(par1ItemStack); + } + + @Override + public ItemStack decrStackSize(int i) { + if(!locked){ + return super.decrStackSize(i); + } + return ItemStack.EMPTY; + } +} diff --git a/src/main/java/forestry/core/gui/tooltips/IToolTipProvider.java b/src/main/java/forestry/core/gui/tooltips/IToolTipProvider.java index 323049c28..64670f6f5 100755 --- a/src/main/java/forestry/core/gui/tooltips/IToolTipProvider.java +++ b/src/main/java/forestry/core/gui/tooltips/IToolTipProvider.java @@ -28,4 +28,9 @@ public interface IToolTipProvider { @SideOnly(Side.CLIENT) boolean isMouseOver(int mouseX, int mouseY); + + @SideOnly(Side.CLIENT) + default boolean isRelativeToGui(){ + return true; + } } diff --git a/src/main/java/forestry/core/gui/widgets/ItemStackWidgetBase.java b/src/main/java/forestry/core/gui/widgets/ItemStackWidgetBase.java index 88c1a9af6..43bb2071f 100755 --- a/src/main/java/forestry/core/gui/widgets/ItemStackWidgetBase.java +++ b/src/main/java/forestry/core/gui/widgets/ItemStackWidgetBase.java @@ -10,9 +10,7 @@ ******************************************************************************/ package forestry.core.gui.widgets; -import net.minecraft.client.Minecraft; -import net.minecraft.client.util.ITooltipFlag; -import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.client.renderer.RenderHelper; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.relauncher.Side; @@ -20,6 +18,7 @@ import net.minecraftforge.fml.relauncher.SideOnly; import forestry.core.gui.GuiUtil; import forestry.core.gui.tooltips.ToolTip; +import forestry.core.utils.ItemTooltipUtil; public abstract class ItemStackWidgetBase extends Widget { public ItemStackWidgetBase(WidgetManager widgetManager, int xPos, int yPos) { @@ -32,19 +31,19 @@ public abstract class ItemStackWidgetBase extends Widget { public void draw(int startX, int startY) { ItemStack itemStack = getItemStack(); if (!itemStack.isEmpty()) { + RenderHelper.enableGUIStandardItemLighting(); GuiUtil.drawItemStack(manager.gui, itemStack, xPos + startX, yPos + startY); + RenderHelper.disableStandardItemLighting(); } } @SideOnly(Side.CLIENT) @Override public ToolTip getToolTip(int mouseX, int mouseY) { - Minecraft minecraft = Minecraft.getMinecraft(); - EntityPlayer player = minecraft.player; ItemStack itemStack = getItemStack(); ToolTip tip = new ToolTip(); if (!itemStack.isEmpty()) { - tip.add(itemStack.getTooltip(player, minecraft.gameSettings.advancedItemTooltips ? ITooltipFlag.TooltipFlags.ADVANCED : ITooltipFlag.TooltipFlags.NORMAL)); + tip.add(ItemTooltipUtil.getInformation(itemStack)); } return tip; } diff --git a/src/main/java/forestry/core/gui/widgets/SocketWidget.java b/src/main/java/forestry/core/gui/widgets/SocketWidget.java index c6ebda538..798a2a424 100755 --- a/src/main/java/forestry/core/gui/widgets/SocketWidget.java +++ b/src/main/java/forestry/core/gui/widgets/SocketWidget.java @@ -11,8 +11,6 @@ package forestry.core.gui.widgets; import net.minecraft.client.Minecraft; -import net.minecraft.client.util.ITooltipFlag; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; @@ -26,6 +24,7 @@ import forestry.core.circuits.ISolderingIron; import forestry.core.circuits.ItemCircuitBoard; import forestry.core.gui.IContainerSocketed; import forestry.core.gui.tooltips.ToolTip; +import forestry.core.utils.ItemTooltipUtil; import forestry.core.utils.Translator; public class SocketWidget extends Widget { @@ -60,9 +59,7 @@ public class SocketWidget extends Widget { toolTip.clear(); ItemStack stack = tile.getSocket(slot); if (!stack.isEmpty()) { - Minecraft minecraft = Minecraft.getMinecraft(); - EntityPlayer player = minecraft.player; - toolTip.add(stack.getTooltip(player, minecraft.gameSettings.advancedItemTooltips ? ITooltipFlag.TooltipFlags.ADVANCED : ITooltipFlag.TooltipFlags.NORMAL)); + toolTip.add(ItemTooltipUtil.getInformation(stack)); toolTip.add(TextFormatting.ITALIC + Translator.translateToLocal("for.gui.socket.remove")); } else { toolTip.add(Translator.translateToLocal("for.gui.emptysocket")); diff --git a/src/main/java/forestry/core/gui/widgets/WidgetElementProvider.java b/src/main/java/forestry/core/gui/widgets/WidgetElementProvider.java index f8c38444c..8a22c7471 100644 --- a/src/main/java/forestry/core/gui/widgets/WidgetElementProvider.java +++ b/src/main/java/forestry/core/gui/widgets/WidgetElementProvider.java @@ -1,16 +1,9 @@ package forestry.core.gui.widgets; -import javax.annotation.Nullable; +/*public class WidgetElementProvider extends Widget implements IScrollable{ + protected ScrollableElement scrollable; -import java.util.List; - -import forestry.core.gui.elements.GuiElementScrollable; -import forestry.core.gui.tooltips.ToolTip; - -public class WidgetElementProvider extends Widget implements IScrollable{ - protected GuiElementScrollable scrollable; - - public WidgetElementProvider(WidgetManager manager, int xPos, int yPos, int width, int height, GuiElementScrollable scrollable) { + public WidgetElementProvider(WidgetManager manager, int xPos, int yPos, int width, int height, ScrollableElement scrollable) { super(manager, xPos, yPos); this.scrollable = scrollable; this.width = width; @@ -19,7 +12,7 @@ public class WidgetElementProvider extends Widget implements IScrollable{ @Override public void draw(int startX, int startY) { - scrollable.draw(startX + xPos, startY + yPos); + scrollable.draw(startX + xPos, startY + yPos, 0, 0); } @Nullable @@ -27,7 +20,7 @@ public class WidgetElementProvider extends Widget implements IScrollable{ public ToolTip getToolTip(int mouseX, int mouseY) { mouseX-=xPos; mouseY-=yPos; - List tooltip = scrollable.getToolTip(mouseX, mouseY); + List tooltip = scrollable.getTooltip(mouseX, mouseY); if(tooltip.isEmpty()){ return null; } @@ -47,4 +40,4 @@ public class WidgetElementProvider extends Widget implements IScrollable{ public void onScroll(int value) { scrollable.onScroll(value); } -} +}*/ diff --git a/src/main/java/forestry/core/gui/widgets/WidgetScrollBar.java b/src/main/java/forestry/core/gui/widgets/WidgetScrollBar.java index 182734985..f884eb62d 100644 --- a/src/main/java/forestry/core/gui/widgets/WidgetScrollBar.java +++ b/src/main/java/forestry/core/gui/widgets/WidgetScrollBar.java @@ -1,16 +1,16 @@ package forestry.core.gui.widgets; -import java.util.Optional; +import javax.annotation.Nullable; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.util.math.MathHelper; +import forestry.core.gui.Drawable; import org.lwjgl.input.Mouse; -import forestry.core.gui.Drawable; - public class WidgetScrollBar extends Widget { - private Optional background; + @Nullable + private Drawable background; private WidgetSlider slider; private boolean visible; @@ -19,6 +19,7 @@ public class WidgetScrollBar extends Widget { private int step; private int currentValue; + @Nullable private IScrollable listener; private boolean isScrolling; @@ -29,7 +30,7 @@ public class WidgetScrollBar extends Widget { public WidgetScrollBar(WidgetManager manager, int xPos, int yPos, int width, int height, Drawable sliderTexture) { super(manager, xPos, yPos); - this.background = Optional.empty(); + this.background = null; this.width = width; this.height = height; @@ -44,9 +45,9 @@ public class WidgetScrollBar extends Widget { int offset = hasBorder ? 1 : 0; - this.background = Optional.of(backgroundTexture); - this.width = backgroundTexture.width; - this.height = backgroundTexture.height; + this.background = backgroundTexture; + this.width = backgroundTexture.uWidth; + this.height = backgroundTexture.vHeight; isScrolling = false; wasClicked = false; @@ -98,8 +99,8 @@ public class WidgetScrollBar extends Widget { return; } GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - if(background.isPresent()){ - background.get().draw(startX + xPos, startY + yPos); + if(background != null){ + background.draw(startX + xPos, startY + yPos); } slider.draw(startX, startY); } diff --git a/src/main/java/forestry/core/gui/widgets/WidgetSlider.java b/src/main/java/forestry/core/gui/widgets/WidgetSlider.java index ee8b0ba62..889f7ed73 100644 --- a/src/main/java/forestry/core/gui/widgets/WidgetSlider.java +++ b/src/main/java/forestry/core/gui/widgets/WidgetSlider.java @@ -13,8 +13,8 @@ public class WidgetSlider extends Widget { public WidgetSlider(WidgetManager manager, int xPos, int yPos, Drawable texture) { super(manager, xPos, yPos); this.texture = texture; - this.width = texture.width; - this.height = texture.height; + this.width = texture.uWidth; + this.height = texture.vHeight; } public void setOffset(int xOffset, int yOffset) { diff --git a/src/main/java/forestry/core/inventory/InventoryAnalyzer.java b/src/main/java/forestry/core/inventory/InventoryAnalyzer.java index 88b042781..ab281dab7 100644 --- a/src/main/java/forestry/core/inventory/InventoryAnalyzer.java +++ b/src/main/java/forestry/core/inventory/InventoryAnalyzer.java @@ -12,19 +12,17 @@ package forestry.core.inventory; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; -import net.minecraft.util.ResourceLocation; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidUtil; import forestry.api.arboriculture.TreeManager; -import forestry.api.core.ForestryAPI; import forestry.api.genetics.AlleleManager; -import forestry.core.config.Constants; import forestry.core.tiles.TileAnalyzer; import forestry.core.utils.GeneticsUtil; import forestry.core.utils.SlotUtil; import forestry.modules.ForestryModuleUids; +import forestry.modules.ModuleHelper; public class InventoryAnalyzer extends InventoryAdapterTile { public static final short SLOT_ANALYZE = 0; @@ -57,7 +55,7 @@ public class InventoryAnalyzer extends InventoryAdapterTile { @Override public void setInventorySlotContents(int slotId, ItemStack itemStack) { - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.ARBORICULTURE)) && !TreeManager.treeRoot.isMember(itemStack)) { + if (ModuleHelper.isEnabled(ForestryModuleUids.ARBORICULTURE) && !TreeManager.treeRoot.isMember(itemStack)) { itemStack = GeneticsUtil.convertToGeneticEquivalent(itemStack); } diff --git a/src/main/java/forestry/core/inventory/ItemInventory.java b/src/main/java/forestry/core/inventory/ItemInventory.java index 8a74b1bd2..2fbd6e6da 100755 --- a/src/main/java/forestry/core/inventory/ItemInventory.java +++ b/src/main/java/forestry/core/inventory/ItemInventory.java @@ -159,12 +159,16 @@ public abstract class ItemInventory implements IInventory, IFilterSlotDelegate, } nbt.setTag(KEY_SLOTS, slotsNbt); + onWriteNBT(nbt); } private static String getSlotNBTKey(int i) { return Integer.toString(i, Character.MAX_RADIX); } + protected void onWriteNBT(NBTTagCompound nbt){ + } + public void onSlotClick(int slotIndex, EntityPlayer player) { } diff --git a/src/main/java/forestry/core/inventory/ItemInventoryAlyzer.java b/src/main/java/forestry/core/inventory/ItemInventoryAlyzer.java index aa7babb65..e03757ed4 100644 --- a/src/main/java/forestry/core/inventory/ItemInventoryAlyzer.java +++ b/src/main/java/forestry/core/inventory/ItemInventoryAlyzer.java @@ -16,9 +16,7 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.ResourceLocation; -import forestry.api.core.ForestryAPI; import forestry.api.core.IErrorSource; import forestry.api.core.IErrorState; import forestry.api.genetics.AlleleManager; @@ -27,10 +25,10 @@ import forestry.api.genetics.IIndividual; import forestry.api.genetics.ISpeciesRoot; import forestry.apiculture.ModuleApiculture; import forestry.apiculture.items.ItemRegistryApiculture; -import forestry.core.config.Constants; import forestry.core.errors.EnumErrorCode; import forestry.core.utils.GeneticsUtil; import forestry.modules.ForestryModuleUids; +import forestry.modules.ModuleHelper; public class ItemInventoryAlyzer extends ItemInventory implements IErrorSource { public static final int SLOT_ENERGY = 0; @@ -50,7 +48,7 @@ public class ItemInventoryAlyzer extends ItemInventory implements IErrorSource { return false; } - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.APICULTURE))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.APICULTURE)) { ItemRegistryApiculture beeItems = ModuleApiculture.getItems(); Item item = itemstack.getItem(); @@ -115,7 +113,7 @@ public class ItemInventoryAlyzer extends ItemInventory implements IErrorSource { // Analyze if necessary if (individual != null && !individual.isAnalyzed()) { - final boolean requiresEnergy = ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.APICULTURE)); + final boolean requiresEnergy = ModuleHelper.isEnabled(ForestryModuleUids.APICULTURE); if (requiresEnergy) { // Requires energy if (!isAlyzingFuel(getStackInSlot(SLOT_ENERGY))) { @@ -172,4 +170,14 @@ public class ItemInventoryAlyzer extends ItemInventory implements IErrorSource { public boolean hasSpecimen() { return !getSpecimen().isEmpty(); } + + @Override + protected void onWriteNBT(NBTTagCompound nbt) { + ItemStack energy = getStackInSlot(ItemInventoryAlyzer.SLOT_ENERGY); + int amount = 0; + if(!energy.isEmpty()){ + amount = energy.getCount(); + } + nbt.setInteger("Charges", amount); + } } diff --git a/src/main/java/forestry/core/items/ItemAlyzer.java b/src/main/java/forestry/core/items/ItemAlyzer.java index 425154821..a59326352 100644 --- a/src/main/java/forestry/core/items/ItemAlyzer.java +++ b/src/main/java/forestry/core/items/ItemAlyzer.java @@ -10,16 +10,26 @@ ******************************************************************************/ package forestry.core.items; +import javax.annotation.Nullable; +import java.util.List; + +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.client.util.ITooltipFlag; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.text.TextFormatting; +import net.minecraft.world.World; + +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + import forestry.api.core.Tabs; import forestry.core.gui.ContainerAlyzer; import forestry.core.gui.GuiAlyzer; import forestry.core.inventory.ItemInventoryAlyzer; -import net.minecraft.client.gui.inventory.GuiContainer; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.item.ItemStack; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; +import forestry.core.utils.Translator; public class ItemAlyzer extends ItemWithGui { public ItemAlyzer() { @@ -41,4 +51,15 @@ public class ItemAlyzer extends ItemWithGui { public Container getContainer(EntityPlayer player, ItemStack heldItem, int data) { return new ContainerAlyzer(new ItemInventoryAlyzer(player, heldItem), player); } + + @Override + public void addInformation(ItemStack stack, @Nullable World world, List tooltip, ITooltipFlag advanced) { + super.addInformation(stack, world, tooltip, advanced); + int charges = 0; + NBTTagCompound compound = stack.getTagCompound(); + if(compound != null){ + charges = compound.getInteger("Charges"); + } + tooltip.add(TextFormatting.GOLD + Translator.translateToLocalFormatted(stack.getUnlocalizedName() + ".charges", charges)); + } } diff --git a/src/main/java/forestry/core/tiles/TileAnalyzer.java b/src/main/java/forestry/core/tiles/TileAnalyzer.java index 9d3ee8c45..494008843 100644 --- a/src/main/java/forestry/core/tiles/TileAnalyzer.java +++ b/src/main/java/forestry/core/tiles/TileAnalyzer.java @@ -21,7 +21,6 @@ import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; -import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.fluids.FluidStack; @@ -31,7 +30,6 @@ import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import forestry.api.arboriculture.TreeManager; -import forestry.api.core.ForestryAPI; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IIndividual; import forestry.core.config.Config; @@ -51,6 +49,7 @@ import forestry.core.utils.GeneticsUtil; import forestry.core.utils.InventoryUtil; import forestry.core.utils.NetworkUtil; import forestry.modules.ForestryModuleUids; +import forestry.modules.ModuleHelper; public class TileAnalyzer extends TilePowered implements ISidedInventory, ILiquidTankTile, IItemStackDisplay { private static final int TIME_TO_ANALYZE = 125; @@ -217,7 +216,7 @@ public class TileAnalyzer extends TilePowered implements ISidedInventory, ILiqui return; } - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.ARBORICULTURE)) && !TreeManager.treeRoot.isMember(inputStack)) { + if (ModuleHelper.isEnabled(ForestryModuleUids.ARBORICULTURE) && !TreeManager.treeRoot.isMember(inputStack)) { inputStack = GeneticsUtil.convertToGeneticEquivalent(inputStack); } diff --git a/src/main/java/forestry/core/utils/GuiElementUtil.java b/src/main/java/forestry/core/utils/GuiElementUtil.java new file mode 100644 index 000000000..fe3c64496 --- /dev/null +++ b/src/main/java/forestry/core/utils/GuiElementUtil.java @@ -0,0 +1,34 @@ +package forestry.core.utils; + +import net.minecraft.client.renderer.GlStateManager; + +import forestry.api.gui.GuiElementAlignment; +import forestry.api.gui.IGuiElement; + +public class GuiElementUtil { + private GuiElementUtil() { + } + + public static void preRender(IGuiElement element, GuiElementAlignment align){ + IGuiElement parent = element.getParent(); + int xPos = element.getX(); + int yPos = element.getY(); + if(parent != null){ + if(parent.getWidth() > element.getWidth()){ + xPos += (parent.getWidth() - element.getWidth()) * align.getXOffset(); + } + if (parent.getHeight() > element.getHeight()) { + yPos += (parent.getHeight() - element.getHeight()) * align.getYOffset(); + } + } + GlStateManager.pushMatrix(); + GlStateManager.translate(xPos, yPos, 0.0F); + GlStateManager.color(1.0F, 1.0F, 1.0F); + + } + + public static void posRender(IGuiElement element){ + GlStateManager.popMatrix(); + } + +} diff --git a/src/main/java/forestry/core/utils/InventoryUtil.java b/src/main/java/forestry/core/utils/InventoryUtil.java index 057f1c8a0..94b223b47 100644 --- a/src/main/java/forestry/core/utils/InventoryUtil.java +++ b/src/main/java/forestry/core/utils/InventoryUtil.java @@ -20,7 +20,6 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.EnumFacing; import net.minecraft.util.NonNullList; -import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -29,12 +28,12 @@ import net.minecraftforge.items.IItemHandler; import net.minecraftforge.fml.common.Optional; -import forestry.api.core.ForestryAPI; import forestry.core.circuits.ISocketable; import forestry.core.inventory.ItemHandlerInventoryManipulator; import forestry.core.inventory.StandardStackFilters; import forestry.core.tiles.AdjacentTileCache; import forestry.modules.ForestryModuleUids; +import forestry.modules.ModuleHelper; import forestry.plugins.ForestryCompatPlugins; public abstract class InventoryUtil { @@ -79,7 +78,7 @@ public abstract class InventoryUtil { } public static boolean moveOneItemToPipe(IItemHandler source, AdjacentTileCache tileCache, EnumFacing[] directions) { - if (ForestryAPI.enabledModules.contains(new ResourceLocation(ForestryCompatPlugins.ID, ForestryModuleUids.BUILDCRAFT_TRANSPORT))) { + if (ModuleHelper.isModuleEnabled(ForestryCompatPlugins.ID, ForestryModuleUids.BUILDCRAFT_TRANSPORT)) { return internal_moveOneItemToPipe(source, tileCache, directions); } diff --git a/src/main/java/forestry/core/utils/ItemTooltipUtil.java b/src/main/java/forestry/core/utils/ItemTooltipUtil.java index ea19a20a3..43414e2dd 100755 --- a/src/main/java/forestry/core/utils/ItemTooltipUtil.java +++ b/src/main/java/forestry/core/utils/ItemTooltipUtil.java @@ -1,10 +1,12 @@ package forestry.core.utils; import javax.annotation.Nullable; +import java.util.Collections; import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.client.util.ITooltipFlag; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.text.TextFormatting; import net.minecraft.world.World; @@ -14,7 +16,7 @@ import net.minecraftforge.fml.relauncher.SideOnly; public class ItemTooltipUtil { @SideOnly(Side.CLIENT) - public static void addInformation(ItemStack stack, @Nullable World world, List tooltip, ITooltipFlag advanced) { + public static void addInformation(ItemStack stack, @Nullable World world, List tooltip, ITooltipFlag flag) { String unlocalizedName = stack.getUnlocalizedName(); String tooltipKey = unlocalizedName + ".tooltip"; if (Translator.canTranslateToLocal(tooltipKey)) { @@ -29,4 +31,27 @@ public class ItemTooltipUtil { public static void addShiftInformation(ItemStack stack, World world, List tooltip, ITooltipFlag flag) { tooltip.add(TextFormatting.ITALIC .toString() + '<' + Translator.translateToLocal("for.gui.tooltip.tmi") + '>'); } + + @SideOnly(Side.CLIENT) + public static List getInformation(ItemStack stack){ + Minecraft minecraft = Minecraft.getMinecraft(); + boolean advancedTooltips = minecraft.gameSettings.advancedItemTooltips; + return getInformation(stack, minecraft.player, advancedTooltips ? ITooltipFlag.TooltipFlags.ADVANCED : ITooltipFlag.TooltipFlags.NORMAL); + } + + @SideOnly(Side.CLIENT) + public static List getInformation(ItemStack stack, EntityPlayer player, ITooltipFlag flag){ + if (stack.isEmpty()) { + return Collections.emptyList(); + } + List tooltip = stack.getTooltip(player, flag); + for (int i = 0; i < tooltip.size(); ++i) { + if (i == 0) { + tooltip.set(i, stack.getRarity().rarityColor + tooltip.get(i)); + } else { + tooltip.set(i, TextFormatting.GRAY + tooltip.get(i)); + } + } + return tooltip; + } } diff --git a/src/main/java/forestry/core/utils/JsonUtil.java b/src/main/java/forestry/core/utils/JsonUtil.java new file mode 100644 index 000000000..eb5762c3f --- /dev/null +++ b/src/main/java/forestry/core/utils/JsonUtil.java @@ -0,0 +1,35 @@ +package forestry.core.utils; + +import com.google.gson.JsonObject; +import com.google.gson.JsonSyntaxException; + +import javax.annotation.Nullable; + +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; + +import net.minecraftforge.common.util.JsonUtils; + +public class JsonUtil { + private JsonUtil() { + } + + public static ItemStack deserializeItemStack(JsonObject object){ + return deserializeItemStack(object, null); + } + + public static ItemStack deserializeItemStack(JsonObject object, @Nullable ItemStack fallback) { + if (!object.has("item")) { + if(fallback == null) { + throw new JsonSyntaxException("Unsupported icon type, currently only items are supported (add 'item' key)"); + }else{ + return fallback; + } + } + Item item = net.minecraft.util.JsonUtils.getItem(object, "item"); + int meta = net.minecraft.util.JsonUtils.getInt(object, "data", 0); + ItemStack stack = new ItemStack(item, 1, meta); + stack.setTagCompound(JsonUtils.readNBT(object, "nbt")); + return stack; + } +} diff --git a/src/main/java/forestry/core/utils/ResourceUtil.java b/src/main/java/forestry/core/utils/ResourceUtil.java new file mode 100644 index 000000000..efaea9d54 --- /dev/null +++ b/src/main/java/forestry/core/utils/ResourceUtil.java @@ -0,0 +1,39 @@ +package forestry.core.utils; + +import javax.annotation.Nullable; +import java.io.IOException; +import java.util.Collections; +import java.util.List; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.resources.IResource; +import net.minecraft.client.resources.IResourceManager; +import net.minecraft.util.ResourceLocation; + +public class ResourceUtil { + private ResourceUtil() { + } + + @Nullable + public static IResource getResource(ResourceLocation location) { + try { + IResourceManager resourceManager = Minecraft.getMinecraft().getResourceManager(); + return resourceManager.getResource(location); + } catch (IOException e) { + return null; + } + } + + public static List getResources(ResourceLocation location) { + try { + IResourceManager resourceManager = Minecraft.getMinecraft().getResourceManager(); + return resourceManager.getAllResources(location); + } catch (IOException e) { + return Collections.emptyList(); + } + } + + public static boolean resourceExists(ResourceLocation location) { + return getResource(location) != null; + } +} diff --git a/src/main/java/forestry/database/DatabaseHelper.java b/src/main/java/forestry/database/DatabaseHelper.java index a317e61be..bc3d60741 100644 --- a/src/main/java/forestry/database/DatabaseHelper.java +++ b/src/main/java/forestry/database/DatabaseHelper.java @@ -67,26 +67,13 @@ public class DatabaseHelper { break; } } - - /*if(pattern.matcher(name.toLowerCase()).find() || item.isEmpty()) { - sorted.add(databaseItem); - continue; - } - - List lines = item.getTooltip(Minecraft.getMinecraft().player, ITooltipFlag.TooltipFlags.NORMAL); - for(String tooltip : lines) { - if(pattern.matcher(tooltip).find()) { - sorted.add(databaseItem); - break; - } - }*/ } sorted.sort(SORT_BY_NAME); } //TODO: Add more filter options - public static List> getFilters(Pattern pattern, String searchText){ + private static List> getFilters(Pattern pattern, String searchText){ List> filters = new LinkedList<>(); filters.add(new DatabaseFilterName(pattern)); filters.add(new DatabaseFilterToolTip(pattern)); diff --git a/src/main/java/forestry/database/DatabaseItem.java b/src/main/java/forestry/database/DatabaseItem.java index 50ce804ae..5190f5077 100644 --- a/src/main/java/forestry/database/DatabaseItem.java +++ b/src/main/java/forestry/database/DatabaseItem.java @@ -16,6 +16,7 @@ public class DatabaseItem { if(!(obj instanceof DatabaseItem)){ return false; } - return ((DatabaseItem) obj).invIndex == invIndex && ((DatabaseItem) obj).itemStack.isEmpty() == itemStack.isEmpty(); + DatabaseItem other = (DatabaseItem) obj; + return other.invIndex == invIndex && other.itemStack.isEmpty() == itemStack.isEmpty(); } } diff --git a/src/main/java/forestry/database/DatabaseManager.java b/src/main/java/forestry/database/DatabaseManager.java deleted file mode 100644 index 2f4299378..000000000 --- a/src/main/java/forestry/database/DatabaseManager.java +++ /dev/null @@ -1,143 +0,0 @@ -package forestry.database; - -import javax.annotation.Nullable; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.item.ItemStack; - -import forestry.database.gui.GuiDatabase; -import forestry.database.tiles.TileDatabase; - -public class DatabaseManager { - - private final ArrayList sorted = new ArrayList<>(); - private final TileDatabase tile; - public final GuiDatabase gui; - private boolean markedForSorting; - /** - * the index of the selected item in {@link #sorted} - */ - private int selectedSlot; - @Nullable - private DatabaseItem selected; - - public DatabaseManager(TileDatabase tile, GuiDatabase gui) { - this.tile = tile; - this.gui = gui; - } - - public boolean canAdd(){ - return selectedSlot + 1 < getSize(); - } - - public boolean canSubtract(){ - int selectedSlot = this.selectedSlot -1; - return selectedSlot < getSize() && selectedSlot >= 0; - } - - /** - * @return the count of all valid item in {@link #sorted} - */ - public int getSize(){ - return sorted.size() - 1;//subtract one because the last entry is the empty item - } - - public int getRealSize(){ - return sorted.size(); - } - - public void setSelectedSlot(int selectedSlot) { - int oldSelected = this.selectedSlot; - this.selectedSlot = selectedSlot; - if(selectedSlot < 0){ - selected = null; - }else { - this.selected = sorted.get(selectedSlot); - } - gui.onUpdateSelectedSlot(oldSelected != selectedSlot && selected != null); - } - - public int getSelectedSlot() { - return selectedSlot; - } - - @Nullable - public DatabaseItem getSelected() { - return selected; - } - - public ItemStack getSelectedItemStack() { - if(selected == null){ - return ItemStack.EMPTY; - } - return selected.itemStack; - } - - /** - * Check if the selected slot is contained in {@link #sorted} if not set {@link #selectedSlot} to the index of the first valid item (0). - */ - public void updateSelected(){ - int index = sorted.indexOf(selected); - if(index >= 0) { - setSelectedSlot(sorted.indexOf(selected)); - return; - } - if(sorted.isEmpty()){ - setSelectedSlot(-1); - return; - } - int size = getSize(); - if(size <= 0){ - setSelectedSlot(-1); - return; - } - if(size > selectedSlot && index != -1){ - return; - } - setSelectedSlot(0); - } - - public void markForSorting(){ - markedForSorting = true; - } - - public void update(String searchText){ - if(markedForSorting){ - markedForSorting = false; - sortItems(searchText); - } - } - - public void sortItems(String searchText){ - sorted.clear(); - List items = new ArrayList<>(); - boolean firstEmpty = false; - for(int invIndex = 0;invIndex < tile.getSizeInventory();invIndex++){ - ItemStack stack = tile.getStackInSlot(invIndex).copy(); - if(!stack.isEmpty()) { - items.add(new DatabaseItem(stack, invIndex)); - continue; - } - if(!firstEmpty){ - firstEmpty = true; - items.add(new DatabaseItem(stack, invIndex)); - } - } - DatabaseHelper.update(searchText, items, sorted); - updateSelected(); - gui.onSortItems(sorted); - } - - @Nullable - public DatabaseItem getItem(int index){ - if(sorted.isEmpty() || sorted.size() <= index || index < 0){ - return null; - } - return sorted.get(index); - } - - public ArrayList getSorted() { - return sorted; - } -} diff --git a/src/main/java/forestry/database/DatabaseScreenLogic.java b/src/main/java/forestry/database/DatabaseScreenLogic.java deleted file mode 100644 index 494896d8e..000000000 --- a/src/main/java/forestry/database/DatabaseScreenLogic.java +++ /dev/null @@ -1,116 +0,0 @@ -package forestry.database; - -import javax.annotation.Nullable; - -import net.minecraft.item.ItemStack; - -import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.IDatabaseTab; -import forestry.api.genetics.ISpeciesPlugin; -import forestry.api.genetics.IIndividual; -import forestry.api.genetics.ISpeciesRoot; - - -public class DatabaseScreenLogic { - @Nullable - public ISpeciesRoot speciesRoot; - @Nullable - public ISpeciesPlugin databasePlugin; - @Nullable - public IIndividual individual; - public ItemStack itemStack = ItemStack.EMPTY; - @Nullable - public IDatabaseTab selectedTab; - public IDatabaseTab[] tabs = new IDatabaseTab[4]; - - public ScreenState onTabChange(IDatabaseTab selectedTab){ - //Check if a individual is selected and analyzed - if(individual == null){ - return ScreenState.NO_INDIVIDUAL; - }else if(!individual.isAnalyzed()){ - return ScreenState.NOT_ANALYZED; - } - - if(this.selectedTab == selectedTab){ - return ScreenState.SUCCESS; - } - - this.selectedTab = selectedTab; - return ScreenState.SUCCESS; - } - - public ScreenState onItemChange(ItemStack itemStack){ - ISpeciesRoot speciesRoot = AlleleManager.alleleRegistry.getSpeciesRoot(itemStack); - - // No individual, abort - if (speciesRoot == null) { - return ScreenState.NO_INDIVIDUAL; - } - IIndividual individual = speciesRoot.getMember(itemStack); - - //Check if a individual is selected and analyzed - if(individual == null){ - this.individual = null; - this.itemStack = ItemStack.EMPTY; - return ScreenState.NO_INDIVIDUAL; - }else if(!individual.isAnalyzed()){ - this.individual = null; - this.itemStack = ItemStack.EMPTY; - return ScreenState.NOT_ANALYZED; - } - this.individual = individual; - this.itemStack = itemStack; - if(speciesRoot != this.speciesRoot){ - IDatabaseTab[] tabs = getTabs(speciesRoot); - if(tabs == null){ - this.tabs = new IDatabaseTab[4]; - return ScreenState.NO_PLUGIN; - } - this.tabs = tabs; - //Select the first tab - onTabChange(tabs[0]); - }else{ - //Update the gui - onTabChange(selectedTab); - } - this.speciesRoot = speciesRoot; - return ScreenState.SUCCESS; - } - - private IDatabaseTab[] getTabs(ISpeciesRoot speciesRoot){ - ISpeciesPlugin databasePlugin = speciesRoot.getSpeciesPlugin(); - if(databasePlugin == null){ - //no plugin ofr this species - return null; - } - this.databasePlugin = databasePlugin; - IDatabaseTab[] tabs = new IDatabaseTab[4]; - IDatabaseTab speciesTab = databasePlugin.getSpeciesTab(true); - if(speciesTab == null){ - //the plugin does not support the database - return null; - } - IDatabaseTab productsTab = databasePlugin.getProductsTab(); - IDatabaseTab mutationTab = databasePlugin.getMutationTab(); - if(productsTab == null){ - productsTab = DatabaseTab.PRODUCTS; - } - if(mutationTab == null){ - mutationTab = DatabaseTab.MUTATIONS; - } - tabs[0] = speciesTab; - tabs[1] = databasePlugin.getSpeciesTab(false); - tabs[2] = productsTab; - tabs[3] = mutationTab; - return tabs; - } - - public enum ScreenState{ - NO_INDIVIDUAL, - //The individual is not analyzed - NOT_ANALYZED, - //The ISpeciesRoot has no IGeneticDevicePlugin for this individual - NO_PLUGIN, - SUCCESS; - } -} diff --git a/src/main/java/forestry/database/DatabaseTab.java b/src/main/java/forestry/database/DatabaseTab.java deleted file mode 100644 index e77c7f5eb..000000000 --- a/src/main/java/forestry/database/DatabaseTab.java +++ /dev/null @@ -1,126 +0,0 @@ -package forestry.database; - -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -import net.minecraft.client.Minecraft; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.util.text.TextFormatting; -import net.minecraft.util.text.translation.I18n; - -import forestry.api.apiculture.IBee; -import forestry.api.arboriculture.ITree; -import forestry.api.core.GuiElementAlignment; -import forestry.api.core.IGuiElementHelper; -import forestry.api.core.IGuiElementLayoutHelper; -import forestry.api.genetics.EnumDatabaseTab; -import forestry.api.genetics.IAlleleSpecies; -import forestry.api.genetics.IBreedingTracker; -import forestry.api.genetics.IDatabaseTab; -import forestry.api.genetics.IGenome; -import forestry.api.genetics.IIndividual; -import forestry.api.genetics.IMutation; -import forestry.api.genetics.ISpeciesRoot; -import forestry.core.gui.elements.GuiElementItemStack; -import forestry.core.utils.Translator; - -public enum DatabaseTab implements IDatabaseTab { - PRODUCTS { - @Override - public void createElements(IGuiElementHelper layoutHelper, IIndividual individual, ItemStack itemStack) { - IGuiElementLayoutHelper groupHelper = layoutHelper.layoutHelper((x, y) -> layoutHelper.factory().createHorizontal(x + 4, y, 18).setDistance(2), 90, 0); - Collection products = getProducts(individual); - if(!products.isEmpty()) { - layoutHelper.addText(Translator.translateToLocal("for.gui.beealyzer.produce"), GuiElementAlignment.CENTER); - products.forEach(product -> groupHelper.add(new GuiElementItemStack(0, 0, product))); - groupHelper.finish(); - } - - Collection specialties = getSpecialties(individual); - if(specialties.isEmpty()){ - return; - } - - layoutHelper.addText(Translator.translateToLocal("for.gui.beealyzer.specialty"), GuiElementAlignment.CENTER); - specialties.forEach(specialty -> groupHelper.add(new GuiElementItemStack(0, 0, specialty))); - groupHelper.finish(); - } - - public Collection getSpecialties(IIndividual individual){ - if(individual instanceof IBee){ - IBee bee = (IBee) individual; - return bee.getSpecialtyList(); - }else if(individual instanceof ITree){ - ITree tree = (ITree) individual; - return tree.getSpecialties().keySet(); - } - return Collections.emptyList(); - } - - public Collection getProducts(IIndividual individual){ - if(individual instanceof IBee){ - IBee bee = (IBee) individual; - return bee.getProduceList(); - }else if(individual instanceof ITree){ - ITree tree = (ITree) individual; - return tree.getProducts().keySet(); - } - return Collections.emptyList(); - } - - @Override - public EnumDatabaseTab getTab() { - return EnumDatabaseTab.PRODUCTS; - } - - }, - MUTATIONS { - @Override - public void createElements(IGuiElementHelper layoutHelper, IIndividual individual, ItemStack itemStack) { - IGenome genome = individual.getGenome(); - ISpeciesRoot speciesRoot = genome.getSpeciesRoot(); - IAlleleSpecies species = genome.getPrimary(); - - EntityPlayer player = Minecraft.getMinecraft().player; - IBreedingTracker breedingTracker = speciesRoot.getBreedingTracker(player.world, player.getGameProfile()); - - IGuiElementLayoutHelper groupHelper = layoutHelper.layoutHelper((x, y) -> layoutHelper.factory().createHorizontal(x + 1, y, 16), 100, 0); - Collection mutations = getValidMutations(speciesRoot.getCombinations(species)); - if(!mutations.isEmpty()) { - layoutHelper.addText(TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.database.mutations.further"), GuiElementAlignment.CENTER); - mutations.forEach(mutation -> groupHelper.add(layoutHelper.factory().createMutation(0, 0, 50, 16, mutation, species, breedingTracker))); - groupHelper.finish(); - } - mutations = getValidMutations(speciesRoot.getResultantMutations(species)); - if(mutations.isEmpty()){ - return; - } - layoutHelper.addText(TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.database.mutations.resultant"), GuiElementAlignment.CENTER); - mutations.forEach(mutation -> groupHelper.add(layoutHelper.factory().createMutationResultant(0, 0, 50, 16, mutation, breedingTracker))); - groupHelper.finish(); - } - - public Collection getValidMutations(List mutations){ - Iterator iterator = mutations.iterator(); - while(iterator.hasNext()){ - IMutation mutation = iterator.next(); - if(mutation.isSecret()){ - iterator.remove(); - } - } - return mutations; - } - - @Override - public EnumDatabaseTab getTab() { - return EnumDatabaseTab.MUTATIONS; - } - }; - - public String getTooltip(IIndividual individual){ - return I18n.translateToLocal("for.gui.database.tab." + getTab().toString().toLowerCase() + ".name"); - } -} diff --git a/src/main/java/forestry/database/ModuleDatabase.java b/src/main/java/forestry/database/ModuleDatabase.java index 3a86f466b..309207944 100644 --- a/src/main/java/forestry/database/ModuleDatabase.java +++ b/src/main/java/forestry/database/ModuleDatabase.java @@ -17,12 +17,13 @@ import forestry.core.items.ItemFruit; import forestry.core.items.ItemRegistryCore; import forestry.core.network.IPacketRegistry; import forestry.core.recipes.RecipeUtil; +import forestry.core.utils.OreDictUtil; import forestry.database.blocks.BlockRegistryDatabase; import forestry.database.network.PacketRegistryDatabase; import forestry.lepidopterology.ModuleLepidopterology; import forestry.modules.BlankForestryModule; import forestry.modules.ForestryModuleUids; -import forestry.modules.ModuleManager; +import forestry.modules.ModuleHelper; @ForestryModule(containerID = Constants.MOD_ID, moduleID = ForestryModuleUids.DATABASE, name = "Database", author = "Nedelosk", url = Constants.URL, unlocalizedDescription = "for.module.database.description") public class ModuleDatabase extends BlankForestryModule { @@ -50,25 +51,25 @@ public class ModuleDatabase extends BlankForestryModule { public void registerRecipes() { List possibleChests = new LinkedList<>(); List possibleSpecial = new LinkedList<>(); - if (ModuleManager.getInstance().isModuleEnabled(Constants.MOD_ID, ForestryModuleUids.APICULTURE)) { + if (ModuleHelper.isEnabled(ForestryModuleUids.APICULTURE)) { possibleChests.add(new ItemStack(ModuleApiculture.getBlocks().beeChest)); possibleSpecial.add(new ItemStack(ModuleApiculture.getItems().royalJelly)); } - if (ModuleManager.getInstance().isModuleEnabled(Constants.MOD_ID, ForestryModuleUids.ARBORICULTURE)) { + if (ModuleHelper.isEnabled(ForestryModuleUids.ARBORICULTURE)) { possibleChests.add(new ItemStack(ModuleArboriculture.getBlocks().treeChest)); possibleSpecial.add(ItemFruit.EnumFruit.PLUM.getStack()); } - if (ModuleManager.getInstance().isModuleEnabled(Constants.MOD_ID, ForestryModuleUids.LEPIDOPTEROLOGY)) { + if (ModuleHelper.isEnabled(ForestryModuleUids.LEPIDOPTEROLOGY)) { possibleChests.add(new ItemStack(ModuleLepidopterology.getBlocks().butterflyChest)); } if (possibleChests.size() == 1) { - addRecipe(possibleSpecial, "chestWood", possibleChests.get(0)); + addRecipe(possibleSpecial, OreDictUtil.CHEST_WOOD, possibleChests.get(0)); } if (possibleSpecial.isEmpty()) { - possibleSpecial.add("chestWood"); + possibleSpecial.add(OreDictUtil.CHEST_WOOD); } if (possibleChests.isEmpty()) { - addRecipe(possibleSpecial, "chestWood", "chestWood"); + addRecipe(possibleSpecial, OreDictUtil.CHEST_WOOD, OreDictUtil.CHEST_WOOD); } else { for (int firstChest = 0; firstChest < possibleChests.size(); firstChest++) { for (int secondChest = 0; secondChest < possibleChests.size(); secondChest++) { diff --git a/src/main/java/forestry/database/gui/ContainerDatabase.java b/src/main/java/forestry/database/gui/ContainerDatabase.java index de8b49004..71e9064da 100644 --- a/src/main/java/forestry/database/gui/ContainerDatabase.java +++ b/src/main/java/forestry/database/gui/ContainerDatabase.java @@ -1,43 +1,29 @@ package forestry.database.gui; -import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.IContainerListener; -import net.minecraft.inventory.Slot; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.wrapper.InvWrapper; +import forestry.core.gui.ContainerAnalyzerProvider; import forestry.core.gui.ContainerForestry; -import forestry.core.gui.ContainerTile; -import forestry.core.gui.IGuiSelectable; import forestry.core.gui.slots.SlotFilteredInventory; import forestry.database.tiles.TileDatabase; -public class ContainerDatabase extends ContainerTile implements IGuiSelectable { - - public static final int SELECT_ID = 0; +public class ContainerDatabase extends ContainerAnalyzerProvider { public ContainerDatabase(TileDatabase tileForestry, InventoryPlayer playerInventory) { - super(tileForestry, playerInventory, 18, 120); + super(tileForestry, playerInventory, 29, 120); addInventory(this, tileForestry); } - public static void addInventory(ContainerForestry container, TileDatabase inventory) { + private static void addInventory(ContainerForestry container, TileDatabase inventory) { //Only to sync the items with the client for (int i = 0; i < inventory.getSizeInventory(); i++) { container.addSlotToContainer(new SlotFilteredInventory(inventory, i, -10000, -10000)); } - - container.addSlotToContainer(new Slot(inventory.analyzerInventory, 0, 184, 120)); - } - - @Override - public void handleSelectionRequest(EntityPlayerMP player, int primary, int secondary) { - if(primary == SELECT_ID){ - tile.analyzeSpecimen(secondary); - } } public void sendContainerToListeners(){ diff --git a/src/main/java/forestry/database/gui/GuiDatabase.java b/src/main/java/forestry/database/gui/GuiDatabase.java index 1d624f049..cea613c9c 100644 --- a/src/main/java/forestry/database/gui/GuiDatabase.java +++ b/src/main/java/forestry/database/gui/GuiDatabase.java @@ -3,6 +3,7 @@ package forestry.database.gui; import javax.annotation.Nullable; import java.io.IOException; import java.util.ArrayList; +import java.util.Iterator; import java.util.List; import net.minecraft.client.gui.GuiButton; @@ -11,222 +12,130 @@ import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import forestry.core.config.Constants; +import forestry.core.gui.ContainerForestry; import forestry.core.gui.Drawable; -import forestry.core.gui.GuiForestry; +import forestry.core.gui.GuiAnalyzerProvider; import forestry.core.gui.slots.SlotFilteredInventory; import forestry.core.gui.widgets.IScrollable; import forestry.core.gui.widgets.WidgetScrollBar; -import forestry.core.inventory.watchers.ISlotChangeWatcher; -import forestry.core.network.packets.PacketGuiSelectRequest; -import forestry.core.render.ColourProperties; -import forestry.core.utils.NetworkUtil; -import forestry.core.utils.Translator; import forestry.database.DatabaseHelper; import forestry.database.DatabaseItem; -import forestry.database.DatabaseManager; import forestry.database.gui.buttons.DatabaseButton; import forestry.database.gui.buttons.GuiDatabaseButton; -import forestry.database.gui.widgets.WidgetDatabaseScreen; -import forestry.database.gui.widgets.WidgetDatabaseSelectedItem; import forestry.database.gui.widgets.WidgetDatabaseSlot; -import forestry.database.gui.widgets.WidgetDatabaseTabs; import forestry.database.tiles.TileDatabase; -import org.lwjgl.input.Keyboard; -public class GuiDatabase extends GuiForestry implements ISlotChangeWatcher, IScrollable { - - private static final int SLOTS = 24; - - public final TileDatabase database; +public class GuiDatabase extends GuiAnalyzerProvider implements IScrollable { + /* Attributes - Constants */ + private static ResourceLocation CREATIVE_TABS = new ResourceLocation(Constants.TEXTURE_PATH_GUI + "/container/creative_inventory/tabs.png"); + private static Drawable SCROLLBAR_SLIDER = new Drawable(CREATIVE_TABS, 232, 0, 12, 15); + /* Attributes - Final */ + public final TileDatabase tile; private final ArrayList slots; - private final DatabaseManager manager; - + private final ArrayList sorted = new ArrayList<>(); + /* Attributes - Gui Elements */ + @Nullable private GuiTextField searchField; - private GuiDatabaseButton lockButton; - private GuiDatabaseButton upButton; - private GuiDatabaseButton downButton; - private WidgetDatabaseScreen databaseScreen; private WidgetScrollBar scrollBar; + /* Attributes - State */ + private boolean markedForSorting; + @Nullable + private DatabaseItem selectedItem; - public GuiDatabase(TileDatabase database, EntityPlayer player) { - super(Constants.TEXTURE_PATH_GUI + "/database_inventory.png", new ContainerDatabase(database, player.inventory)); - this.database = database; + /* Constructors */ + public GuiDatabase(TileDatabase tile, EntityPlayer player) { + super(Constants.TEXTURE_PATH_GUI + "/database_inventory.png", new ContainerDatabase(tile, player.inventory), tile, 7, 140, 20, true, tile.getInternalInventory().getSizeInventory(), 0); + this.tile = tile; slots = new ArrayList<>(); xSize = 218; ySize = 202; - manager = new DatabaseManager(database, this); - - for(Slot slot : container.inventorySlots){ - if(slot instanceof SlotFilteredInventory){ + //Start at index 36, because all slots before 36 are player inventory slots + Iterator slotIterator = container.inventorySlots.listIterator(ContainerForestry.PLAYER_INV_SLOTS); + while (slotIterator.hasNext()) { + Slot slot = slotIterator.next(); + if (slot instanceof SlotFilteredInventory) { SlotFilteredInventory slotDatabase = (SlotFilteredInventory) slot; slotDatabase.setChangeWatcher(this); } } - for(int i = 0;i < SLOTS;i++){ + for (int i = 0; i < 24; i++) { WidgetDatabaseSlot slot = new WidgetDatabaseSlot(widgetManager); slots.add(slot); widgetManager.add(slot); } - int screenX = - 140; - WidgetScrollBar scrollBar = new WidgetScrollBar(widgetManager, screenX + 106, 10, new Drawable(WidgetDatabaseScreen.TEXTURE, 202, 0, 3, 156), false, new Drawable(WidgetDatabaseScreen.TEXTURE, 205, 0, 3, 5)); - widgetManager.add(databaseScreen = new WidgetDatabaseScreen(widgetManager, screenX, 0, scrollBar)); - widgetManager.add(scrollBar); - widgetManager.add(new WidgetDatabaseTabs(widgetManager, screenX, 177, databaseScreen)); - widgetManager.add(this.scrollBar = new WidgetScrollBar(widgetManager, 196, 19, 12, 90 , new Drawable(new ResourceLocation(Constants.TEXTURE_PATH_GUI + "/container/creative_inventory/tabs.png"), 232, 0, 12, 15))); - this.scrollBar.setParameters(this, 0, database.getSizeInventory() / 4 - 6, 1); - widgetManager.add(new WidgetDatabaseSelectedItem(widgetManager, 184, 158, manager)); + widgetManager.add(this.scrollBar = new WidgetScrollBar(widgetManager, 196, 19, 12, 90, SCROLLBAR_SLIDER)); + this.scrollBar.setParameters(this, 0, tile.getSizeInventory() / 4 - 6, 1); + analyzer.init(); + analyzer.setSelectedSlot(-1); } - @Override - public void drawScreen(int mouseX, int mouseY, float partialTicks) { - String searchText = searchField != null ? searchField.getText() : ""; - manager.update(searchText); - super.drawScreen(mouseX, mouseY, partialTicks); + + /* Methods */ + @Nullable + public DatabaseItem getSelectedItem() { + return selectedItem; } - @Override - protected void drawGuiContainerBackgroundLayer(float f, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(f, mouseX, mouseY); - - String name = Translator.translateToLocal(database.getUnlocalizedTitle()); - textLayout.line = 6; - textLayout.drawLine(name, 8, ColourProperties.INSTANCE.get("gui.title")); - - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - GlStateManager.disableLighting(); - this.searchField.drawTextBox(); + /** + * @return the count of all valid item in {@link #sorted} + */ + public int getSize() { + return sorted.size() - 1;//subtract one because the last entry is the empty item } - @Override - protected void drawBackground() { - bindTexture(textureFile); - - drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize); + public int getRealSize() { + return sorted.size(); } - @Override - protected void keyTyped(char typedChar, int keyCode) throws IOException { - if (this.searchField.textboxKeyTyped(typedChar, keyCode)) { - scrollBar.setValue(0); - manager.markForSorting(); - } else if((keyCode == Keyboard.KEY_DOWN || keyCode == Keyboard.KEY_RIGHT) && downButton.enabled) { - downButton.onPressed(); - } else if((keyCode == Keyboard.KEY_UP || keyCode == Keyboard.KEY_LEFT) && upButton.enabled) { - upButton.onPressed(); - } else { - super.keyTyped(typedChar, keyCode); + public ItemStack getSelectedItemStack() { + if (selectedItem == null) { + return ItemStack.EMPTY; } + return selectedItem.itemStack; } - @Override - protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { - Slot slot = getSlotAtPosition(mouseX, mouseY); - if(slot != null && slot.getSlotIndex() == -1){ - return; + public void markForSorting() { + markedForSorting = true; + } + + private void updateItems(String searchText) { + if (markedForSorting) { + sorted.clear(); + List items = new ArrayList<>(); + boolean firstEmpty = false; + for (int invIndex = 0; invIndex < tile.getSizeInventory(); invIndex++) { + ItemStack stack = tile.getStackInSlot(invIndex).copy(); + if (!stack.isEmpty()) { + items.add(new DatabaseItem(stack, invIndex)); + continue; + } + if (!firstEmpty) { + firstEmpty = true; + items.add(new DatabaseItem(stack, invIndex)); + } + } + DatabaseHelper.update(searchText, items, sorted); + analyzer.updateSelected(); + updateViewedItems(); + + markedForSorting = false; } - super.mouseClicked(mouseX, mouseY, mouseButton); - searchField.mouseClicked(mouseX, mouseY, mouseButton); } @Nullable - public DatabaseItem getItem(int index){ - return manager.getItem(index); - } - - @Nullable - public DatabaseItem getSelectedItem(){ - return manager.getSelected(); - } - - public DatabaseManager getManager() { - return manager; - } - - public void onSortItems(List sorted) { - updateViewedItems(sorted); - } - - public void onChangeLockState(boolean locked) { - lockButton.setValue(locked); - } - - @Override - public void initGui() { - super.initGui(); - - this.guiLeft = 140 + (this.width - this.xSize - 125) / 2; - - this.searchField = new GuiTextField(0, this.fontRenderer, this.guiLeft + 101, this.guiTop + 6, 80, this.fontRenderer.FONT_HEIGHT); - this.searchField.setMaxStringLength(50); - this.searchField.setEnableBackgroundDrawing(false); - this.searchField.setTextColor(16777215); - - //Left buttons - this.buttonList.add(new GuiDatabaseButton(0, guiLeft - 18, guiTop, DatabaseHelper.ascending, manager, DatabaseButton.SORT_DIRECTION_BUTTON)); - //Selection buttons - this.buttonList.add(upButton = new GuiDatabaseButton(1, guiLeft + 184, guiTop + 144, "", manager, DatabaseButton.SELECTED_UP)); - this.buttonList.add(downButton = new GuiDatabaseButton(2, guiLeft + 184, guiTop + 178, "", manager, DatabaseButton.SELECTED_DOWN)); - - updateViewedItems(); - } - - public void onUpdateSelectedSlot(boolean changed){ - upButton.enabled = manager.canSubtract(); - downButton.enabled = manager.canAdd(); - if(changed){ - int index = getSelectedItem().invIndex; - database.selectedSlot = manager.getSelectedSlot(); - NetworkUtil.sendToServer(new PacketGuiSelectRequest(ContainerDatabase.SELECT_ID, index)); - //databaseScreen.onChangeTabOrIndividual(); - databaseScreen.onItemChange(manager.getSelectedItemStack()); + public DatabaseItem getItem(int index) { + if (sorted.isEmpty() || sorted.size() <= index || index < 0) { + return null; } + return sorted.get(index); } - @Override - protected void actionPerformed(GuiButton button) throws IOException { - if(button instanceof GuiDatabaseButton){ - GuiDatabaseButton databaseButton = (GuiDatabaseButton) button; - databaseButton.onPressed(); - } - } - - @Override - protected void addLedgers() { - } - - @Override - public void onScroll(int value) { - updateViewedItems(); - } - - @Override - public boolean isFocused(int mouseX, int mouseY) { - return isPointInRegion(0, 0, xSize, ySize, mouseX + guiLeft, mouseY + guiTop); - } - - @Override - protected boolean hasClickedOutside(int mouseX, int mouseY, int guiLeft, int guiTop) { - boolean isInsideScreen = databaseScreen.isMouseOver(mouseX - guiLeft, mouseY - guiTop); - return super.hasClickedOutside(mouseX, mouseY, guiLeft, guiTop) && !isInsideScreen; - } - - @Override - public void onSlotChanged(IInventory inventory, int slot) { - if(manager.getSelected() != null && slot == manager.getSelected().invIndex){ - databaseScreen.onItemChange(manager.getSelectedItemStack()); - } - manager.markForSorting(); - } - - public void updateViewedItems(){ - updateViewedItems(manager.getSorted()); - } - - public void updateViewedItems(List sorted) { + private void updateViewedItems() { int currentRow = scrollBar.getValue(); if (currentRow < 0) { currentRow = 0; @@ -235,20 +144,20 @@ public class GuiDatabase extends GuiForestry implements ISlot int slotStart = currentRow * 4; //The inventory index of the last slot. int slotEnd = (currentRow + 6) * 4; - if(slotEnd > database.getSizeInventory()){ - slotEnd = database.getSizeInventory(); + if (slotEnd > tile.getSizeInventory()) { + slotEnd = tile.getSizeInventory(); } //The row of the first slot - byte startRow = (byte)(currentRow % 2); + byte startRow = (byte) (currentRow % 2); //The index of the empty slot in the list. int emptySlot = sorted.size() - 1; - for(int invIndex = 0;invIndex < database.getSizeInventory();invIndex++){ - if(invIndex >= slotStart && invIndex < slotEnd) { + for (int invIndex = 0; invIndex < tile.getSizeInventory(); invIndex++) { + if (invIndex >= slotStart && invIndex < slotEnd) { int x = invIndex % 4; int y = invIndex / 4 - currentRow; int yOffset; int xOffset; - if(startRow == 0) { + if (startRow == 0) { yOffset = 25; xOffset = 17; if (y % 2 == 1) { @@ -269,19 +178,157 @@ public class GuiDatabase extends GuiForestry implements ISlot int yPos = yOffset + y / 2 * 25; //If the index is above the count of the valid items in the list, set the index to the same value like the index of the empty slot. int index = invIndex; - if(sorted.size() <= index || sorted.isEmpty()){ + if (sorted.size() <= index || sorted.isEmpty()) { index = emptySlot; } WidgetDatabaseSlot slot = slots.get(invIndex - slotStart); slot.update(xPos, yPos, index, index != emptySlot); } } - //Create screen elements - if(!sorted.isEmpty() && databaseScreen.size() == 0) { - databaseScreen.onItemChange(manager.getSelectedItemStack()); - if(database.selectedSlot != -1) { - manager.setSelectedSlot(database.selectedSlot); - } + } + + /* Methods - Implement GuiScreen */ + @Override + public void initGui() { + super.initGui(); + + this.searchField = new GuiTextField(0, this.fontRenderer, this.guiLeft + 101, this.guiTop + 6, 80, this.fontRenderer.FONT_HEIGHT); + this.searchField.setMaxStringLength(50); + this.searchField.setEnableBackgroundDrawing(false); + this.searchField.setTextColor(16777215); + + addButton(new GuiDatabaseButton<>(0, guiLeft - 18, guiTop, DatabaseHelper.ascending, this, DatabaseButton.SORT_DIRECTION_BUTTON)); + + updateViewedItems(); + } + + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + String searchText = searchField != null ? searchField.getText() : ""; + updateItems(searchText); + super.drawScreen(mouseX, mouseY, partialTicks); + } + + @Override + protected void keyTyped(char typedChar, int keyCode) throws IOException { + if (searchField != null && this.searchField.textboxKeyTyped(typedChar, keyCode)) { + scrollBar.setValue(0); + markForSorting(); + } else { + super.keyTyped(typedChar, keyCode); } } + + @Override + protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { + Slot slot = getSlotAtPosition(mouseX, mouseY); + if (slot != null && slot.getSlotIndex() == -1) { + return; + } + super.mouseClicked(mouseX, mouseY, mouseButton); + if (searchField != null) { + searchField.mouseClicked(mouseX, mouseY, mouseButton); + } + } + + @Override + protected void actionPerformed(GuiButton button) throws IOException { + super.actionPerformed(button); + if (button instanceof GuiDatabaseButton) { + GuiDatabaseButton databaseButton = (GuiDatabaseButton) button; + databaseButton.onPressed(); + } + } + + /* Methods - Implement GuiContainer */ + @Override + protected void drawGuiContainerBackgroundLayer(float f, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(f, mouseX, mouseY); + + if (searchField != null) { + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + GlStateManager.disableLighting(); + this.searchField.drawTextBox(); + } + } + + /* Methods - Implement GuiForestry */ + @Override + protected void drawBackground() { + bindTexture(textureFile); + + drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize); + } + + @Override + protected void addLedgers() { + } + + /* Methods - Implement GuiForestryTitled */ + + @Override + protected boolean centeredTitle() { + return false; + } + + /* Methods - Implement IGeneticAnalyzerProvider */ + @Override + protected void drawSelectedSlot(int selectedSlot) { + //Currently not used + } + + @Override + public ItemStack getSpecimen(int index) { + DatabaseItem item = getSelectedItem(); + if (item == null) { + return ItemStack.EMPTY; + } + return item.itemStack; + } + + @Override + public boolean onUpdateSelected() { + int index = selectedItem == null ? -1 : sorted.indexOf(selectedItem); + if (index >= 0) { + analyzer.setSelectedSlot(index); + return true; + } + return false; + } + + @Override + public void onSelection(int index, boolean changed) { + if (index < 0) { + selectedItem = null; + } else { + this.selectedItem = sorted != null && index >= sorted.size() ? null : sorted.get(index); + } + } + + @Override + public int getSelectedSlot(int index) { + DatabaseItem item = getItem(index); + if (item == null) { + return -1; + } + return 1 + item.invIndex; + } + + /* Methods - Implement IScrollable */ + @Override + public void onScroll(int value) { + updateViewedItems(); + } + + @Override + public boolean isFocused(int mouseX, int mouseY) { + return isPointInRegion(0, 0, xSize, ySize, mouseX + guiLeft, mouseY + guiTop); + } + + /* Methods - Implement ISlotChangeWatcher */ + @Override + public void onSlotChanged(IInventory inventory, int slot) { + super.onSlotChanged(inventory, slot); + markForSorting(); + } } diff --git a/src/main/java/forestry/database/gui/buttons/DatabaseButton.java b/src/main/java/forestry/database/gui/buttons/DatabaseButton.java index 51912c7c4..0ac8e3808 100644 --- a/src/main/java/forestry/database/gui/buttons/DatabaseButton.java +++ b/src/main/java/forestry/database/gui/buttons/DatabaseButton.java @@ -20,30 +20,7 @@ public enum DatabaseButton { public void onPressed(GuiDatabaseButton button) { //Client side only button button.setValue(DatabaseHelper.ascending =!DatabaseHelper.ascending); - button.manager.markForSorting(); - } - }, - SELECTED_UP{ - - @Override - public void onPressed(GuiDatabaseButton button) { - button.manager.setSelectedSlot(button.manager.getSelectedSlot() - 1); - } - - @Override - public IButtonTextureSet getDefaultTexture() { - return StandardButtonTextureSets.UP_BUTTON; - } - }, - SELECTED_DOWN{ - @Override - public void onPressed(GuiDatabaseButton button) { - button.manager.setSelectedSlot(button.manager.getSelectedSlot() + 1); - } - - @Override - public IButtonTextureSet getDefaultTexture() { - return StandardButtonTextureSets.DOWN_BUTTON; + button.gui.markForSorting(); } }; diff --git a/src/main/java/forestry/database/gui/buttons/GuiDatabaseButton.java b/src/main/java/forestry/database/gui/buttons/GuiDatabaseButton.java index 6b1dc93ee..4e8f41cea 100644 --- a/src/main/java/forestry/database/gui/buttons/GuiDatabaseButton.java +++ b/src/main/java/forestry/database/gui/buttons/GuiDatabaseButton.java @@ -1,18 +1,18 @@ package forestry.database.gui.buttons; import forestry.core.gui.buttons.GuiBetterButton; -import forestry.database.DatabaseManager; +import forestry.database.gui.GuiDatabase; public class GuiDatabaseButton extends GuiBetterButton { public final DatabaseButton type; - public final DatabaseManager manager; + public final GuiDatabase gui; public V value; - public GuiDatabaseButton(int id, int x, int y, V value, DatabaseManager manager, DatabaseButton type) { + public GuiDatabaseButton(int id, int x, int y, V value, GuiDatabase gui, DatabaseButton type) { super(id, x, y, type.getDefaultTexture()); this.type = type; - this.manager = manager; + this.gui = gui; setValue(value); } diff --git a/src/main/java/forestry/database/gui/widgets/WidgetDatabaseScreen.java b/src/main/java/forestry/database/gui/widgets/WidgetDatabaseScreen.java deleted file mode 100644 index a5d19ce88..000000000 --- a/src/main/java/forestry/database/gui/widgets/WidgetDatabaseScreen.java +++ /dev/null @@ -1,132 +0,0 @@ -package forestry.database.gui.widgets; - -import java.util.List; -import java.util.Locale; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.renderer.texture.TextureManager; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; - -import forestry.api.genetics.EnumDatabaseTab; -import forestry.api.genetics.IDatabaseTab; -import forestry.core.config.Constants; -import forestry.core.gui.elements.GuiElementHelper; -import forestry.core.gui.elements.GuiElementScrollable; -import forestry.core.gui.widgets.WidgetElementProvider; -import forestry.core.gui.widgets.WidgetManager; -import forestry.core.gui.widgets.WidgetScrollBar; -import forestry.core.utils.SoundUtil; -import forestry.core.utils.Translator; -import forestry.database.DatabaseScreenLogic; - -public class WidgetDatabaseScreen extends WidgetElementProvider { - public static final ResourceLocation TEXTURE = new ResourceLocation(Constants.MOD_ID, Constants.TEXTURE_PATH_GUI + "/database_mutation_screen.png"); - - private WidgetDatabaseTabs tabs; - public WidgetScrollBar scrollBar; - public GuiElementHelper layoutHelper; - public DatabaseScreenLogic logic; - public DatabaseScreenLogic.ScreenState state; - - public WidgetDatabaseScreen(WidgetManager manager, int xPos, int yPos, WidgetScrollBar scrollBar) { - super(manager, xPos, yPos, 118, 177, new GuiElementScrollable(0, 0, 102, 157)); - this.scrollable.setXOffset(8); - this.scrollable.setYOffset(12); - this.scrollBar = scrollBar; - this.logic = new DatabaseScreenLogic(); - this.state = DatabaseScreenLogic.ScreenState.NO_INDIVIDUAL; - } - - public void setTabs(WidgetDatabaseTabs tabs){ - this.tabs = tabs; - } - - public int onTabChange(EnumDatabaseTab tab){ - state = logic.onTabChange(logic.tabs[tab.ordinal()]); - update(); - if(state == DatabaseScreenLogic.ScreenState.SUCCESS){ - SoundUtil.playButtonClick(); - return logic.selectedTab.getTab().ordinal(); - } - return -1; - } - - public void onItemChange(ItemStack itemStack){ - state = logic.onItemChange(itemStack); - update(); - if(state == DatabaseScreenLogic.ScreenState.SUCCESS){ - tabs.selectedTab = logic.selectedTab.getTab().ordinal(); - }else { - tabs.selectedTab = -1; - } - } - - public ItemStack getItemStack(EnumDatabaseTab tab){ - if(state == DatabaseScreenLogic.ScreenState.SUCCESS){ - return logic.databasePlugin.getTabDatabaseIconItem(tab); - } - return new ItemStack(Items.PAPER); - } - - public String getTooltip(EnumDatabaseTab tab){ - if(state == DatabaseScreenLogic.ScreenState.SUCCESS){ - String tooltip = logic.tabs[tab.ordinal()].getTooltip(logic.individual); - if(tooltip != null) { - return tooltip; - } - } - return Translator.translateToLocal("for.gui.database.tab." + tab.toString().toLowerCase(Locale.ENGLISH) + ".name"); - } - - private void update(){ - //reset list and layout helper - scrollable.clear(); - scrollBar.setVisible(false); - scrollable.updateVisibleElements(0); - layoutHelper = new GuiElementHelper(scrollable); - if(state == DatabaseScreenLogic.ScreenState.SUCCESS){ - IDatabaseTab selectedTab = logic.selectedTab; - selectedTab.createElements(layoutHelper, logic.individual, logic.itemStack); - int invisibleElements = scrollable.getInvisibleElementCount(); - if (invisibleElements > 0) { - scrollBar.setParameters(this, 0, invisibleElements, 1); - scrollBar.setVisible(true); - //scrollBar.setValue(0); - }else{ - scrollBar.setValue(0); - } - scrollable.updateVisibleElements(scrollBar.getValue()); - }else{ - GuiElementHelper layoutHelper = new GuiElementHelper(scrollable); - FontRenderer fontRenderer = manager.gui.getFontRenderer(); - String key ="for.gui.portablealyzer.help"; - if(state == DatabaseScreenLogic.ScreenState.NO_PLUGIN){ - key = "for.gui.database.support"; - } - List lines = fontRenderer.listFormattedStringToWidth(Translator.translateToLocal(key), width - 10); - for(String text : lines) { - layoutHelper.addText(2, text, -1); - } - scrollable.updateVisibleElements(0); - } - } - - @Override - public void draw(int startX, int startY) { - tabs.drawTabs(startX, startY); - TextureManager textureManager = Minecraft.getMinecraft().getTextureManager(); - textureManager.bindTexture(TEXTURE); - manager.gui.drawTexturedModalRect(startX + xPos, startY + yPos, 0, 0, width, height); - - //Draw the selected tab after the background so it is drawn over it - tabs.drawSelectedTab(startX, startY); - super.draw(startX, startY); - } - - public int size(){ - return scrollable.getSize(); - } -} diff --git a/src/main/java/forestry/database/gui/widgets/WidgetDatabaseSelectedItem.java b/src/main/java/forestry/database/gui/widgets/WidgetDatabaseSelectedItem.java deleted file mode 100644 index b03ab4445..000000000 --- a/src/main/java/forestry/database/gui/widgets/WidgetDatabaseSelectedItem.java +++ /dev/null @@ -1,21 +0,0 @@ -package forestry.database.gui.widgets; - -import net.minecraft.item.ItemStack; - -import forestry.core.gui.widgets.ItemStackWidgetBase; -import forestry.core.gui.widgets.WidgetManager; -import forestry.database.DatabaseManager; - -public class WidgetDatabaseSelectedItem extends ItemStackWidgetBase { - private final DatabaseManager manager; - - public WidgetDatabaseSelectedItem(WidgetManager widgetManager, int xPos, int yPos, DatabaseManager manager) { - super(widgetManager, xPos, yPos); - this.manager = manager; - } - - @Override - protected ItemStack getItemStack() { - return manager.getSelectedItemStack(); - } -} diff --git a/src/main/java/forestry/database/gui/widgets/WidgetDatabaseSlot.java b/src/main/java/forestry/database/gui/widgets/WidgetDatabaseSlot.java index 4bac45d52..f1b836e5f 100644 --- a/src/main/java/forestry/database/gui/widgets/WidgetDatabaseSlot.java +++ b/src/main/java/forestry/database/gui/widgets/WidgetDatabaseSlot.java @@ -8,8 +8,6 @@ import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.renderer.texture.TextureMap; -import net.minecraft.client.util.ITooltipFlag; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; @@ -19,6 +17,7 @@ import forestry.core.gui.GuiUtil; import forestry.core.gui.tooltips.ToolTip; import forestry.core.gui.widgets.Widget; import forestry.core.gui.widgets.WidgetManager; +import forestry.core.utils.ItemTooltipUtil; import forestry.core.utils.NetworkUtil; import forestry.database.DatabaseItem; import forestry.database.gui.GuiDatabase; @@ -108,7 +107,7 @@ public class WidgetDatabaseSlot extends Widget { } if(GuiScreen.isCtrlKeyDown() && mouseButton == 0){ - gui.getManager().setSelectedSlot(databaseIndex); + gui.analyzer.setSelectedSlot(databaseIndex); return; } @@ -147,12 +146,10 @@ public class WidgetDatabaseSlot extends Widget { @Nullable @Override public ToolTip getToolTip(int mouseX, int mouseY) { - Minecraft minecraft = Minecraft.getMinecraft(); - EntityPlayer player = minecraft.player; ItemStack itemStack = getItemStack(); ToolTip tip = new ToolTip(); if (!itemStack.isEmpty()) { - tip.add(itemStack.getTooltip(player, minecraft.gameSettings.advancedItemTooltips ? ITooltipFlag.TooltipFlags.ADVANCED : ITooltipFlag.TooltipFlags.NORMAL)); + tip.add(ItemTooltipUtil.getInformation(itemStack)); } return tip; } @@ -161,7 +158,9 @@ public class WidgetDatabaseSlot extends Widget { if(!isEmpty){ return false; } - return ((GuiDatabase)manager.gui).getItem(databaseIndex) == ((GuiDatabase)manager.gui).getSelectedItem(); + DatabaseItem slotItem = ((GuiDatabase)manager.gui).getItem(databaseIndex); + DatabaseItem selectedItem = ((GuiDatabase)manager.gui).getSelectedItem(); + return slotItem != null && slotItem.equals(selectedItem); } public ItemStack getItemStack(){ diff --git a/src/main/java/forestry/database/gui/widgets/WidgetDatabaseTabs.java b/src/main/java/forestry/database/gui/widgets/WidgetDatabaseTabs.java deleted file mode 100644 index fd0aa04c6..000000000 --- a/src/main/java/forestry/database/gui/widgets/WidgetDatabaseTabs.java +++ /dev/null @@ -1,132 +0,0 @@ -package forestry.database.gui.widgets; - -import javax.annotation.Nullable; - -import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.util.ResourceLocation; - -import forestry.api.genetics.EnumDatabaseTab; -import forestry.core.gui.Drawable; -import forestry.core.gui.GuiForestry; -import forestry.core.gui.GuiUtil; -import forestry.core.gui.tooltips.ToolTip; -import forestry.core.gui.widgets.Widget; -import forestry.core.gui.widgets.WidgetManager; - -public class WidgetDatabaseTabs extends Widget { - private static final ResourceLocation CREATIVE_TEXTURE = new ResourceLocation("textures/gui/container/creative_inventory/tabs.png"); - private static final EnumDatabaseTab[] TABS = EnumDatabaseTab.values(); - - private static final Drawable GUI_TAB = new Drawable(CREATIVE_TEXTURE, 0, 64, 28, 28); - private static final Drawable GUI_TAB_ACTIVE_LEFT = new Drawable(CREATIVE_TEXTURE, 0, 96, 28, 32); - private static final Drawable GUI_TAB_ACTIVE_CENTER = new Drawable(CREATIVE_TEXTURE, 28, 96, 28, 32); - private static final Drawable GUI_TAB_ACTIVE_RIGHT = new Drawable(CREATIVE_TEXTURE, 140, 96, 28, 32); - - private final WidgetDatabaseScreen parent; - //The space between the tabs - public int spacing = 2; - //The selected tab - public int selectedTab; - - public WidgetDatabaseTabs(WidgetManager manager, int xPos, int yPos, WidgetDatabaseScreen parent) { - super(manager, xPos, yPos); - this.width = 28; - this.height = 28; - this.parent = parent; - this.parent.setTabs(this); - this.selectedTab = 0; - } - - @Override - public void draw(int startX, int startY) { - //Drawn in the screen widget - } - - public void drawTabs(int startX, int startY) { - for(int tabIndex = 0;tabIndex < TABS.length;tabIndex++) { - if(tabIndex == selectedTab){ - continue; - } - EnumDatabaseTab tab = TABS[tabIndex]; - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - Drawable tabTexture = GUI_TAB; - int xPos = this.xPos + tabIndex * (GUI_TAB.width + spacing); - tabTexture.draw(xPos, yPos - 4); - GuiUtil.drawItemStack(manager.gui, parent.getItemStack(tab), startX + xPos + 6, startY + yPos + 2); - } - } - - public void drawSelectedTab(int startX, int startY){ - //Check if a tab is selected - if(selectedTab < 0){ - return; - } - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - EnumDatabaseTab tab = TABS[selectedTab]; - int textureIndex = selectedTab == 0 ? 0 : selectedTab == TABS.length - 1 ? 2 : 1; - Drawable tabTexture; - if (textureIndex == 0) { - tabTexture = GUI_TAB_ACTIVE_LEFT; - } else if (textureIndex == 2) { - tabTexture = GUI_TAB_ACTIVE_RIGHT; - } else { - tabTexture = GUI_TAB_ACTIVE_CENTER; - } - int xPos = this.xPos + selectedTab * (GUI_TAB.width + spacing); - tabTexture.draw(xPos, yPos - 4); - GuiUtil.drawItemStack(manager.gui, parent.getItemStack(tab), startX + xPos + 6, startY + yPos + 2); - } - - @Override - public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { - GuiForestry gui = manager.gui; - //set the mouse position relative to the gui - mouseX-=gui.getGuiLeft(); - mouseY-=gui.getGuiTop(); - int mouseOverTab = getMouseOverTab(mouseX, mouseY); - if(mouseOverTab < 0){ - return; - } - if(selectedTab != mouseOverTab) { - selectedTab = parent.onTabChange(TABS[mouseOverTab]); - } - } - - @Override - public boolean isMouseOver(int mouseX, int mouseY) { - int mouseOverTab = getMouseOverTab(mouseX, mouseY); - return mouseOverTab >= 0; - } - - @Nullable - public int getMouseOverTab(int mouseX, int mouseY){ - //set the mouse position relative to the widget - mouseX-=xPos; - mouseY-=yPos; - if(mouseY < 0 || mouseY > height){ - return -1; - } - int x = 0; - for(int tabIndex = 0;tabIndex < TABS.length;tabIndex++){ - if(mouseX < x || mouseX > x + GUI_TAB.width){ - x+= spacing + GUI_TAB.width; - continue; - } - return tabIndex; - } - return -1; - } - - @Nullable - @Override - public ToolTip getToolTip(int mouseX, int mouseY) { - int mouseOverTab = getMouseOverTab(mouseX, mouseY); - if(mouseOverTab < 0){ - return null; - } - EnumDatabaseTab tab = TABS[mouseOverTab]; - ToolTip toolTip = new ToolTip(); - toolTip.add(parent.getTooltip(tab)); - return toolTip; - } -} diff --git a/src/main/java/forestry/database/inventory/InventoryDatabaseAnalyzer.java b/src/main/java/forestry/database/inventory/InventoryDatabaseAnalyzer.java index 696dfc28f..972a21224 100644 --- a/src/main/java/forestry/database/inventory/InventoryDatabaseAnalyzer.java +++ b/src/main/java/forestry/database/inventory/InventoryDatabaseAnalyzer.java @@ -12,15 +12,13 @@ package forestry.database.inventory; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; -import forestry.api.core.ForestryAPI; import forestry.apiculture.ModuleApiculture; import forestry.apiculture.items.ItemRegistryApiculture; -import forestry.core.config.Constants; import forestry.core.inventory.InventoryAdapterTile; import forestry.database.tiles.TileDatabase; import forestry.modules.ForestryModuleUids; +import forestry.modules.ModuleHelper; public class InventoryDatabaseAnalyzer extends InventoryAdapterTile { public static final int SLOT_ENERGY = 0; @@ -34,7 +32,7 @@ public class InventoryDatabaseAnalyzer extends InventoryAdapterTile T getCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { if (super.hasCapability(capability, facing)) { diff --git a/src/main/java/forestry/factory/ModuleFactory.java b/src/main/java/forestry/factory/ModuleFactory.java index a5c2e25b6..ec46673e8 100644 --- a/src/main/java/forestry/factory/ModuleFactory.java +++ b/src/main/java/forestry/factory/ModuleFactory.java @@ -21,7 +21,6 @@ import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; -import net.minecraft.util.ResourceLocation; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; @@ -74,6 +73,7 @@ import forestry.factory.recipes.SqueezerRecipeManager; import forestry.factory.recipes.StillRecipeManager; import forestry.modules.BlankForestryModule; import forestry.modules.ForestryModuleUids; +import forestry.modules.ModuleHelper; import forestry.storage.ModuleCrates; @ForestryModule(containerID = Constants.MOD_ID, moduleID = ForestryModuleUids.FACTORY, name = "Factory", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.module.factory.description", lootTable = "factory") @@ -338,7 +338,7 @@ public class ModuleFactory extends BlankForestryModule { String[] dyes = {"dyeBlack", "dyeRed", "dyeGreen", "dyeBrown", "dyeBlue", "dyePurple", "dyeCyan", "dyeLightGray", "dyeGray", "dyePink", "dyeLime", "dyeYellow", "dyeLightBlue", "dyeMagenta", "dyeOrange", "dyeWhite"}; - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.APICULTURE))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.APICULTURE)) { ItemRegistryApiculture beeItems = ModuleApiculture.getItems(); FluidStack liquidGlass = Fluids.GLASS.getFluid(Fluid.BUCKET_VOLUME); @@ -483,7 +483,7 @@ public class ModuleFactory extends BlankForestryModule { // RAIN SUBSTRATES - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.APICULTURE))) { + if (ModuleHelper.isEnabled(Constants.MOD_ID, ForestryModuleUids.APICULTURE)) { ItemRegistryApiculture beeItems = ModuleApiculture.getItems(); RecipeManagers.carpenterManager.addRecipe(5, new FluidStack(FluidRegistry.WATER, 1000), ItemStack.EMPTY, coreItems.iodineCharge.getItemStack(), "Z#Z", @@ -539,7 +539,7 @@ public class ModuleFactory extends BlankForestryModule { RecipeManagers.carpenterManager.addRecipe(ItemStack.EMPTY, ingotBronze, "#", '#', coreItems.brokenBronzeShovel); // Crating and uncrating - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.CRATE))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.CRATE)) { ModuleCrates.createCrateRecipes(); } ICircuitLayout layout = ChipsetManager.circuitRegistry.getLayout("forestry.machine.upgrade"); diff --git a/src/main/java/forestry/factory/recipes/CarpenterRecipeManager.java b/src/main/java/forestry/factory/recipes/CarpenterRecipeManager.java index a3306e8f8..20b17db90 100644 --- a/src/main/java/forestry/factory/recipes/CarpenterRecipeManager.java +++ b/src/main/java/forestry/factory/recipes/CarpenterRecipeManager.java @@ -11,9 +11,11 @@ package forestry.factory.recipes; import javax.annotation.Nullable; +import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; +import java.util.stream.Collectors; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; @@ -111,6 +113,17 @@ public class CarpenterRecipeManager implements ICarpenterManager { return removed; } + public static Collection getRecipes(ItemStack itemStack){ + if (itemStack.isEmpty()) { + return Collections.emptyList(); + } + + return recipes.stream().filter(recipe -> { + ItemStack output = recipe.getCraftingGridRecipe().getOutput(); + return ItemStackUtil.isIdenticalItem(itemStack, output); + }).collect(Collectors.toList()); + } + public static Set getRecipeFluids() { if (recipeFluids.isEmpty()) { for (ICarpenterRecipe recipe : recipes) { diff --git a/src/main/java/forestry/factory/recipes/FabricatorRecipeManager.java b/src/main/java/forestry/factory/recipes/FabricatorRecipeManager.java index 8959c2cb5..4546067a4 100755 --- a/src/main/java/forestry/factory/recipes/FabricatorRecipeManager.java +++ b/src/main/java/forestry/factory/recipes/FabricatorRecipeManager.java @@ -11,9 +11,11 @@ package forestry.factory.recipes; import javax.annotation.Nullable; +import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; +import java.util.stream.Collectors; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; @@ -82,4 +84,15 @@ public class FabricatorRecipeManager implements IFabricatorManager { public Set recipes() { return Collections.unmodifiableSet(recipes); } + + public static Collection getRecipes(ItemStack itemStack){ + if (itemStack.isEmpty()) { + return Collections.emptyList(); + } + + return recipes.stream().filter(recipe -> { + ItemStack output = recipe.getRecipeOutput(); + return ItemStackUtil.isIdenticalItem(itemStack, output); + }).collect(Collectors.toList()); + } } diff --git a/src/main/java/forestry/factory/recipes/jei/FactoryJeiPlugin.java b/src/main/java/forestry/factory/recipes/jei/FactoryJeiPlugin.java index 38b71736a..109161c0c 100644 --- a/src/main/java/forestry/factory/recipes/jei/FactoryJeiPlugin.java +++ b/src/main/java/forestry/factory/recipes/jei/FactoryJeiPlugin.java @@ -7,13 +7,10 @@ import java.awt.Rectangle; import java.util.List; import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.core.ForestryAPI; -import forestry.core.config.Constants; import forestry.core.gui.GuiForestry; import forestry.core.recipes.jei.ForestryRecipeCategoryUid; import forestry.core.utils.JeiUtil; @@ -48,6 +45,7 @@ import forestry.factory.recipes.jei.squeezer.SqueezerRecipeMaker; import forestry.factory.recipes.jei.still.StillRecipeCategory; import forestry.factory.recipes.jei.still.StillRecipeMaker; import forestry.modules.ForestryModuleUids; +import forestry.modules.ModuleHelper; import mezz.jei.api.IGuiHelper; import mezz.jei.api.IJeiHelpers; import mezz.jei.api.IModPlugin; @@ -65,7 +63,7 @@ public class FactoryJeiPlugin implements IModPlugin { @Override public void registerCategories(IRecipeCategoryRegistration registry) { - if (!ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FACTORY))){ + if (!ModuleHelper.isEnabled(ForestryModuleUids.FACTORY)){ return; } @@ -89,7 +87,7 @@ public class FactoryJeiPlugin implements IModPlugin { public void register(IModRegistry registry) { registry.addAdvancedGuiHandlers(new ForestryAdvancedGuiHandler()); - if(!ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FACTORY))){ + if(!ModuleHelper.isEnabled(ForestryModuleUids.FACTORY)){ return; } jeiHelpers = registry.getJeiHelpers(); diff --git a/src/main/java/forestry/farming/ModuleFarming.java b/src/main/java/forestry/farming/ModuleFarming.java index 747ca343f..683232207 100644 --- a/src/main/java/forestry/farming/ModuleFarming.java +++ b/src/main/java/forestry/farming/ModuleFarming.java @@ -26,7 +26,6 @@ import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.event.TextureStitchEvent; import net.minecraftforge.common.MinecraftForge; @@ -90,6 +89,7 @@ import forestry.farming.tiles.TileFarmValve; import forestry.farming.triggers.FarmingTriggers; import forestry.modules.BlankForestryModule; import forestry.modules.ForestryModuleUids; +import forestry.modules.ModuleHelper; @ForestryModule(containerID = Constants.MOD_ID, moduleID = ForestryModuleUids.FARMING, name = "Farming", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.module.farming.description") public class ModuleFarming extends BlankForestryModule { @@ -130,7 +130,7 @@ public class ModuleFarming extends BlankForestryModule { IFarmRegistry registry = ForestryAPI.farmRegistry; registry.registerFarmables("farmArboreal", new FarmableVanillaSapling()); - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.ARBORICULTURE))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.ARBORICULTURE)) { registry.registerFarmables("farmArboreal", new FarmableGE()); } diff --git a/src/main/java/forestry/farming/compat/FarmingJeiPlugin.java b/src/main/java/forestry/farming/compat/FarmingJeiPlugin.java index 5aeff973d..407ef8c10 100644 --- a/src/main/java/forestry/farming/compat/FarmingJeiPlugin.java +++ b/src/main/java/forestry/farming/compat/FarmingJeiPlugin.java @@ -2,14 +2,12 @@ package forestry.farming.compat; import net.minecraft.item.Item; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.ResourceLocation; -import forestry.api.core.ForestryAPI; -import forestry.core.config.Constants; import forestry.farming.ModuleFarming; import forestry.farming.blocks.BlockRegistryFarming; import forestry.farming.models.EnumFarmBlockTexture; import forestry.modules.ForestryModuleUids; +import forestry.modules.ModuleHelper; import mezz.jei.api.IModPlugin; import mezz.jei.api.ISubtypeRegistry; @@ -19,7 +17,7 @@ import mezz.jei.api.JEIPlugin; public class FarmingJeiPlugin implements IModPlugin { @Override public void registerItemSubtypes(ISubtypeRegistry subtypeRegistry) { - if (!ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FARMING))) { + if (!ModuleHelper.isEnabled(ForestryModuleUids.FARMING)) { return; } diff --git a/src/main/java/forestry/greenhouse/ModuleGreenhouse.java b/src/main/java/forestry/greenhouse/ModuleGreenhouse.java index 5e9c018de..2b591718b 100644 --- a/src/main/java/forestry/greenhouse/ModuleGreenhouse.java +++ b/src/main/java/forestry/greenhouse/ModuleGreenhouse.java @@ -18,7 +18,6 @@ import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; import net.minecraft.item.EnumDyeColor; import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.MinecraftForge; @@ -30,7 +29,6 @@ import forestry.api.circuits.CircuitSocketType; import forestry.api.circuits.ICircuitLayout; import forestry.api.climate.ClimateType; import forestry.api.core.CamouflageManager; -import forestry.api.core.ForestryAPI; import forestry.api.core.Tabs; import forestry.api.modules.ForestryModule; import forestry.core.CreativeTabForestry; @@ -74,6 +72,7 @@ import forestry.greenhouse.tiles.TileHumidifier; import forestry.greenhouse.tiles.TileHygroregulator; import forestry.modules.BlankForestryModule; import forestry.modules.ForestryModuleUids; +import forestry.modules.ModuleHelper; @ForestryModule(containerID = Constants.MOD_ID, moduleID = ForestryModuleUids.GREENHOUSE, name = "Greenhouse", author = "Nedelosk", url = Constants.URL, unlocalizedDescription = "for.module.greenhouse.description") public class ModuleGreenhouse extends BlankForestryModule { @@ -98,7 +97,7 @@ public class ModuleGreenhouse extends BlankForestryModule { } public static CreativeTabs getGreenhouseTab() { - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FARMING))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.FARMING)) { return Tabs.tabAgriculture; } return CreativeTabForestry.tabForestry; diff --git a/src/main/java/forestry/greenhouse/gui/widgets/WidgetCamouflageSlot.java b/src/main/java/forestry/greenhouse/gui/widgets/WidgetCamouflageSlot.java index 97e81110d..7076fff9b 100755 --- a/src/main/java/forestry/greenhouse/gui/widgets/WidgetCamouflageSlot.java +++ b/src/main/java/forestry/greenhouse/gui/widgets/WidgetCamouflageSlot.java @@ -16,7 +16,6 @@ import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.renderer.texture.TextureMap; -import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.text.TextFormatting; @@ -32,6 +31,7 @@ import forestry.core.gui.GuiUtil; import forestry.core.gui.tooltips.ToolTip; import forestry.core.gui.widgets.Widget; import forestry.core.gui.widgets.WidgetManager; +import forestry.core.utils.ItemTooltipUtil; import forestry.core.utils.Translator; public class WidgetCamouflageSlot extends Widget { @@ -49,10 +49,10 @@ public class WidgetCamouflageSlot extends Widget { ItemStack camouflageBlock = camouflageHandler.getCamouflageBlock(); if (camouflageBlock.isEmpty()) { - toolTip.add(TextFormatting.ITALIC.toString() + Translator.translateToLocal("for.gui.empty")); + toolTip.add(Translator.translateToLocal("for.gui.empty"), TextFormatting.ITALIC); } else { Minecraft minecraft = Minecraft.getMinecraft(); - toolTip.add(TextFormatting.ITALIC.toString() + camouflageBlock.getTooltip(minecraft.player, minecraft.gameSettings.advancedItemTooltips ? ITooltipFlag.TooltipFlags.ADVANCED : ITooltipFlag.TooltipFlags.NORMAL)); + toolTip.add(ItemTooltipUtil.getInformation(camouflageBlock)); } } }; diff --git a/src/main/java/forestry/lepidopterology/ModuleLepidopterology.java b/src/main/java/forestry/lepidopterology/ModuleLepidopterology.java index b894e4969..04851384e 100644 --- a/src/main/java/forestry/lepidopterology/ModuleLepidopterology.java +++ b/src/main/java/forestry/lepidopterology/ModuleLepidopterology.java @@ -79,7 +79,7 @@ import forestry.lepidopterology.tiles.TileCocoon; import forestry.lepidopterology.worldgen.CocoonDecorator; import forestry.modules.BlankForestryModule; import forestry.modules.ForestryModuleUids; -import forestry.modules.ModuleManager; +import forestry.modules.ModuleHelper; @ForestryModule(containerID = Constants.MOD_ID, moduleID = ForestryModuleUids.LEPIDOPTEROLOGY, name = "Lepidopterology", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.module.lepidopterology.description") public class ModuleLepidopterology extends BlankForestryModule { @@ -141,7 +141,7 @@ public class ModuleLepidopterology extends BlankForestryModule { proxy.preInitializeRendering(); - if(ModuleManager.getInstance().isModuleEnabled(Constants.MOD_ID, ForestryModuleUids.SORTING)){ + if(ModuleHelper.isEnabled(ForestryModuleUids.SORTING)){ LepidopterologyFilterRule.init(); LepidopterologyFilterRuleType.init(); } @@ -171,7 +171,7 @@ public class ModuleLepidopterology extends BlankForestryModule { ButterflyDefinition.initButterflies(); ButterflyAlleles.createLoot(); - MinecraftForge.EVENT_BUS.post(new AlleleSpeciesRegisterEvent(ButterflyManager.butterflyRoot, IAlleleButterflySpecies.class)); + MinecraftForge.EVENT_BUS.post(new AlleleSpeciesRegisterEvent<>(ButterflyManager.butterflyRoot, IAlleleButterflySpecies.class)); blocks.butterflyChest.init(); diff --git a/src/main/java/forestry/lepidopterology/genetics/ButterflyDatabaseTab.java b/src/main/java/forestry/lepidopterology/genetics/ButterflyDatabaseTab.java index 690a235e5..ac02855d2 100644 --- a/src/main/java/forestry/lepidopterology/genetics/ButterflyDatabaseTab.java +++ b/src/main/java/forestry/lepidopterology/genetics/ButterflyDatabaseTab.java @@ -6,14 +6,14 @@ import net.minecraft.util.text.TextFormatting; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.core.GuiElementAlignment; -import forestry.api.core.IGuiElementHelper; import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.EnumDatabaseTab; import forestry.api.genetics.IAlleleInteger; import forestry.api.genetics.IAlleleTolerance; import forestry.api.genetics.IDatabaseTab; +import forestry.api.gui.GuiElementAlignment; +import forestry.api.gui.IElementGenetic; import forestry.api.lepidopterology.EnumButterflyChromosome; +import forestry.api.lepidopterology.EnumFlutterType; import forestry.api.lepidopterology.IAlleleButterflySpecies; import forestry.api.lepidopterology.IButterfly; import forestry.core.genetics.GenericRatings; @@ -23,45 +23,41 @@ import forestry.core.utils.Translator; @SideOnly(Side.CLIENT) public class ButterflyDatabaseTab implements IDatabaseTab { - private final EnumDatabaseTab tab; + private final boolean active; - ButterflyDatabaseTab(EnumDatabaseTab tab) { - this.tab = tab; + ButterflyDatabaseTab(boolean active) { + this.active = active; } @Override - public void createElements(IGuiElementHelper elementHelper, IButterfly butterfly, ItemStack itemStack) { - boolean active = tab == EnumDatabaseTab.ACTIVE_SPECIES; + public void createElements(IElementGenetic container, IButterfly butterfly, ItemStack itemStack) { IAlleleButterflySpecies primarySpecies = butterfly.getGenome().getPrimary(); - elementHelper.addText(Translator.translateToLocal("for.gui.database.tab." + tab.name().toLowerCase() + ".name"), GuiElementAlignment.CENTER, 0xcfb53b); + container.text(Translator.translateToLocal("for.gui.database.tab." + (active ? "active" : "inactive") + "_species.name"), GuiElementAlignment.TOP_CENTER, 0xcfb53b); - elementHelper.addAllele(Translator.translateToLocal("for.gui.species"), butterfly, EnumButterflyChromosome.SPECIES, active); + container.addAlleleRow(Translator.translateToLocal("for.gui.species"), butterfly, EnumButterflyChromosome.SPECIES, active); - elementHelper.addAllele(Translator.translateToLocal("for.gui.size"), butterfly, EnumButterflyChromosome.SIZE, active); + container.addAlleleRow(Translator.translateToLocal("for.gui.size"), butterfly, EnumButterflyChromosome.SIZE, active); - elementHelper.addAllele(Translator.translateToLocal("for.gui.lifespan"), butterfly, EnumButterflyChromosome.LIFESPAN, active); + container.addAlleleRow(Translator.translateToLocal("for.gui.lifespan"), butterfly, EnumButterflyChromosome.LIFESPAN, active); - elementHelper.addAllele(Translator.translateToLocal("for.gui.speed"), butterfly,EnumButterflyChromosome.SPEED, active); + container.addAlleleRow(Translator.translateToLocal("for.gui.speed"), butterfly,EnumButterflyChromosome.SPEED, active); - elementHelper.addAllele(Translator.translateToLocal("for.gui.metabolism"), (IAlleleInteger a)-> GenericRatings.rateMetabolism(a.getValue()), butterfly, EnumButterflyChromosome.METABOLISM, active); + container.addAlleleRow(Translator.translateToLocal("for.gui.metabolism"), (IAlleleInteger a)-> GenericRatings.rateMetabolism(a.getValue()), butterfly, EnumButterflyChromosome.METABOLISM, active); IAlleleInteger fertility = (IAlleleInteger) (active ? butterfly.getGenome().getActiveAllele(EnumButterflyChromosome.FERTILITY) : butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.FERTILITY)); - elementHelper.addText(TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.fertility"), GuiElementAlignment.CENTER); - elementHelper.addFertilityInfo(fertility, 0, 8); + container.addFertilityInfo(Translator.translateToLocal("for.gui.fertility"), fertility, 8); - elementHelper.addAllele(Translator.translateToLocal("for.gui.flowers"), butterfly, EnumButterflyChromosome.FLOWER_PROVIDER, active); - elementHelper.addAllele(Translator.translateToLocal("for.gui.effect"), butterfly, EnumButterflyChromosome.EFFECT, active); + container.addAlleleRow(Translator.translateToLocal("for.gui.flowers"), butterfly, EnumButterflyChromosome.FLOWER_PROVIDER, active); + container.addAlleleRow(Translator.translateToLocal("for.gui.effect"), butterfly, EnumButterflyChromosome.EFFECT, active); IAlleleTolerance tempTolerance = (IAlleleTolerance) (active ? butterfly.getGenome().getActiveAllele(EnumButterflyChromosome.TEMPERATURE_TOLERANCE) : butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.TEMPERATURE_TOLERANCE)); - elementHelper.addText(TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.climate"), GuiElementAlignment.CENTER); - elementHelper.addToleranceInfo(tempTolerance, primarySpecies, AlleleManager.climateHelper.toDisplay(primarySpecies.getTemperature())); + container.addToleranceInfo(Translator.translateToLocal("for.gui.climate"), tempTolerance, primarySpecies, AlleleManager.climateHelper.toDisplay(primarySpecies.getTemperature())); IAlleleTolerance humidTolerance = (IAlleleTolerance) (active ? butterfly.getGenome().getActiveAllele(EnumButterflyChromosome.HUMIDITY_TOLERANCE) : butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.HUMIDITY_TOLERANCE)); - elementHelper.addText(TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.humidity"), GuiElementAlignment.CENTER); - elementHelper.addToleranceInfo(humidTolerance, primarySpecies, AlleleManager.climateHelper.toDisplay(primarySpecies.getHumidity())); + container.addToleranceInfo(Translator.translateToLocal("for.gui.humidity"), humidTolerance, primarySpecies, AlleleManager.climateHelper.toDisplay(primarySpecies.getHumidity())); String yes = Translator.translateToLocal("for.yes"); String no = Translator.translateToLocal("for.no"); @@ -83,21 +79,20 @@ public class ButterflyDatabaseTab implements IDatabaseTab { } } - elementHelper.addText(TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.diurnal"), GuiElementAlignment.CENTER); - elementHelper.addText(diurnal, GuiElementAlignment.CENTER, elementHelper.factory().getColorCoding(false)); + container.text(TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.diurnal"), GuiElementAlignment.TOP_CENTER); + container.addRow(Translator.translateToLocal("for.gui.diurnal"), diurnal, false); - elementHelper.addText(TextFormatting.UNDERLINE + Translator.translateToLocal("for.gui.nocturnal"), GuiElementAlignment.CENTER); - elementHelper.addText(nocturnal, GuiElementAlignment.CENTER, elementHelper.factory().getColorCoding(false)); + container.addRow(Translator.translateToLocal("for.gui.nocturnal"), nocturnal, false); String flyer = StringUtil.readableBoolean(active ? butterfly.getGenome().getTolerantFlyer() : ((AlleleBoolean) butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.TOLERANT_FLYER)).getValue(), yes, no); - elementHelper.addAllele(Translator.translateToLocal("for.gui.flyer"), (a) -> flyer, butterfly, EnumButterflyChromosome.TOLERANT_FLYER, active); + container.addAlleleRow(Translator.translateToLocal("for.gui.flyer"), (a) -> flyer, butterfly, EnumButterflyChromosome.TOLERANT_FLYER, active); String fireresist = StringUtil.readableBoolean(active ? butterfly.getGenome().getFireResist() : ((AlleleBoolean) butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.FIRE_RESIST)).getValue(), yes, no); - elementHelper.addAllele(Translator.translateToLocal("for.gui.fireresist"), (a) -> fireresist, butterfly, EnumButterflyChromosome.FIRE_RESIST, active); + container.addAlleleRow(Translator.translateToLocal("for.gui.fireresist"), (a) -> fireresist, butterfly, EnumButterflyChromosome.FIRE_RESIST, active); } @Override - public EnumDatabaseTab getTab() { - return tab; + public ItemStack getIconStack() { + return ButterflyDefinition.BlueWing.getMemberStack(active ? EnumFlutterType.BUTTERFLY : EnumFlutterType.CATERPILLAR); } } diff --git a/src/main/java/forestry/lepidopterology/genetics/ButterflyPlugin.java b/src/main/java/forestry/lepidopterology/genetics/ButterflyPlugin.java index 4183b8d43..0f598bdda 100644 --- a/src/main/java/forestry/lepidopterology/genetics/ButterflyPlugin.java +++ b/src/main/java/forestry/lepidopterology/genetics/ButterflyPlugin.java @@ -1,6 +1,5 @@ package forestry.lepidopterology.genetics; -import javax.annotation.Nullable; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -11,25 +10,25 @@ import net.minecraft.util.NonNullList; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.genetics.EnumDatabaseTab; -import forestry.api.genetics.IDatabaseTab; -import forestry.api.genetics.ISpeciesPlugin; import forestry.api.lepidopterology.EnumFlutterType; import forestry.api.lepidopterology.IAlleleButterflySpecies; import forestry.api.lepidopterology.IButterfly; import forestry.core.config.Config; +import forestry.core.genetics.analyzer.DatabasePlugin; +import forestry.core.genetics.analyzer.MutationsTab; import forestry.lepidopterology.ModuleLepidopterology; @SideOnly(Side.CLIENT) -public class ButterflyPlugin implements ISpeciesPlugin { +public class ButterflyPlugin extends DatabasePlugin { public static final ButterflyPlugin INSTANCE = new ButterflyPlugin(); - private static final ButterflyDatabaseTab ACTIVE = new ButterflyDatabaseTab(EnumDatabaseTab.ACTIVE_SPECIES); - private static final ButterflyDatabaseTab INACTIVE = new ButterflyDatabaseTab(EnumDatabaseTab.INACTIVE_SPECIES); - private static final ButterflyProductsTab PRODUCTS = new ButterflyProductsTab(); protected final Map iconStacks = new HashMap<>(); private ButterflyPlugin() { + super(new ButterflyDatabaseTab(true), + new ButterflyDatabaseTab(false), + new ButterflyProductsTab(), + new MutationsTab(()->ButterflyDefinition.Glasswing.getMemberStack(EnumFlutterType.COCOON))); NonNullList butterflyList = NonNullList.create(); ModuleLepidopterology.getItems().butterflyGE.addCreativeItems(butterflyList, false); for (ItemStack butterflyStack : butterflyList) { @@ -47,31 +46,4 @@ public class ButterflyPlugin implements ISpeciesPlugin { public List getHints() { return Config.hints.get("flutterlyzer"); } - - @Override - public IDatabaseTab getSpeciesTab(boolean active) { - if(active){ - return ACTIVE; - } - return INACTIVE; - } - - @Nullable - @Override - public IDatabaseTab getProductsTab() { - return PRODUCTS; - } - - @Override - public ItemStack getTabDatabaseIconItem(EnumDatabaseTab tab) { - switch (tab){ - case ACTIVE_SPECIES: - return ButterflyDefinition.BlueWing.getMemberStack(EnumFlutterType.BUTTERFLY); - case PRODUCTS: - return ButterflyDefinition.Aurora.getMemberStack(EnumFlutterType.SERUM); - case MUTATIONS: - return ButterflyDefinition.Glasswing.getMemberStack(EnumFlutterType.COCOON); - } - return ButterflyDefinition.GlassyTiger.getMemberStack(EnumFlutterType.CATERPILLAR); - } } diff --git a/src/main/java/forestry/lepidopterology/genetics/ButterflyProductsTab.java b/src/main/java/forestry/lepidopterology/genetics/ButterflyProductsTab.java index c7beb263e..fc8619669 100644 --- a/src/main/java/forestry/lepidopterology/genetics/ButterflyProductsTab.java +++ b/src/main/java/forestry/lepidopterology/genetics/ButterflyProductsTab.java @@ -7,13 +7,14 @@ import net.minecraft.item.ItemStack; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.core.GuiElementAlignment; -import forestry.api.core.IGuiElementHelper; -import forestry.api.core.IGuiElementLayoutHelper; -import forestry.api.genetics.EnumDatabaseTab; import forestry.api.genetics.IDatabaseTab; +import forestry.api.gui.GuiElementAlignment; +import forestry.api.gui.IElementGenetic; +import forestry.api.gui.IElementLayoutHelper; +import forestry.api.lepidopterology.EnumFlutterType; import forestry.api.lepidopterology.IButterfly; -import forestry.core.gui.elements.GuiElementItemStack; +import forestry.core.gui.elements.GuiElementFactory; +import forestry.core.gui.elements.ItemElement; import forestry.core.utils.Translator; @SideOnly(Side.CLIENT) @@ -22,32 +23,32 @@ public class ButterflyProductsTab implements IDatabaseTab { } @Override - public void createElements(IGuiElementHelper layoutHelper, IButterfly individual, ItemStack itemStack) { - IGuiElementLayoutHelper groupHelper = layoutHelper.layoutHelper((x, y) -> layoutHelper.factory().createHorizontal(x + 4, y, 18).setDistance(2), 90, 0); + public void createElements(IElementGenetic container, IButterfly individual, ItemStack itemStack) { + IElementLayoutHelper groupHelper = container.layoutHelper((x, y) -> GuiElementFactory.INSTANCE.createHorizontal(x + 4, y, 18).setDistance(2), 90, 0); Collection butterflyLoot = individual.getGenome().getPrimary().getButterflyLoot().keySet(); if(!butterflyLoot.isEmpty()) { - layoutHelper.addText(Translator.translateToLocal("for.gui.loot.butterfly"), GuiElementAlignment.CENTER); - butterflyLoot.forEach(stack -> groupHelper.add(new GuiElementItemStack(0, 0, stack))); + container.text(Translator.translateToLocal("for.gui.loot.butterfly"), GuiElementAlignment.TOP_CENTER); + butterflyLoot.forEach(stack -> groupHelper.add(new ItemElement(0, 0, stack))); groupHelper.finish(); } Collection caterpillarLoot = individual.getGenome().getPrimary().getCaterpillarLoot().keySet(); if(!caterpillarLoot.isEmpty()){ - layoutHelper.addText(Translator.translateToLocal("for.gui.loot.caterpillar"), GuiElementAlignment.CENTER); - caterpillarLoot.forEach(stack -> groupHelper.add(new GuiElementItemStack(0, 0, stack))); + container.text(Translator.translateToLocal("for.gui.loot.caterpillar"), GuiElementAlignment.TOP_CENTER); + caterpillarLoot.forEach(stack -> groupHelper.add(new ItemElement(0, 0, stack))); groupHelper.finish(); } Collection cocoonLoot = individual.getGenome().getCocoon().getCocoonLoot().keySet(); if(!cocoonLoot.isEmpty()){ - layoutHelper.addText(Translator.translateToLocal("for.gui.loot.cocoon"), GuiElementAlignment.CENTER); - cocoonLoot.forEach(stack -> groupHelper.add(new GuiElementItemStack(0, 0, stack))); + container.text(Translator.translateToLocal("for.gui.loot.cocoon"), GuiElementAlignment.TOP_CENTER); + cocoonLoot.forEach(stack -> groupHelper.add(new ItemElement(0, 0, stack))); groupHelper.finish(); } } @Override - public EnumDatabaseTab getTab() { - return EnumDatabaseTab.PRODUCTS; + public ItemStack getIconStack() { + return ButterflyDefinition.Aurora.getMemberStack(EnumFlutterType.SERUM); } } diff --git a/src/main/java/forestry/lepidopterology/genetics/ButterflyRoot.java b/src/main/java/forestry/lepidopterology/genetics/ButterflyRoot.java index 8ed1671bd..733427d4f 100644 --- a/src/main/java/forestry/lepidopterology/genetics/ButterflyRoot.java +++ b/src/main/java/forestry/lepidopterology/genetics/ButterflyRoot.java @@ -35,9 +35,9 @@ import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAllele; import forestry.api.genetics.IAlyzerPlugin; import forestry.api.genetics.IChromosomeType; +import forestry.api.genetics.IDatabasePlugin; import forestry.api.genetics.IIndividual; import forestry.api.genetics.IMutation; -import forestry.api.genetics.ISpeciesPlugin; import forestry.api.genetics.ISpeciesType; import forestry.api.lepidopterology.ButterflyManager; import forestry.api.lepidopterology.EnumButterflyChromosome; @@ -129,6 +129,11 @@ public class ButterflyRoot extends SpeciesRoot implements IButterflyRoot { return EnumFlutterType.BUTTERFLY; } + @Override + public ISpeciesType[] getTypes() { + return EnumFlutterType.values(); + } + @Override public boolean isMember(ItemStack stack, ISpeciesType type) { return getType(stack) == type; @@ -370,7 +375,7 @@ public class ButterflyRoot extends SpeciesRoot implements IButterflyRoot { @Override @SideOnly(Side.CLIENT) - public ISpeciesPlugin getSpeciesPlugin() { + public IDatabasePlugin getSpeciesPlugin() { return ButterflyPlugin.INSTANCE; } } diff --git a/src/main/java/forestry/mail/ModuleMail.java b/src/main/java/forestry/mail/ModuleMail.java index 2d51e9c27..27b4f7803 100644 --- a/src/main/java/forestry/mail/ModuleMail.java +++ b/src/main/java/forestry/mail/ModuleMail.java @@ -16,14 +16,12 @@ import javax.annotation.Nullable; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import forestry.api.circuits.ICircuit; -import forestry.api.core.ForestryAPI; import forestry.api.mail.EnumAddressee; import forestry.api.mail.PostManager; import forestry.api.modules.ForestryModule; @@ -49,6 +47,7 @@ import forestry.mail.items.ItemRegistryMail; import forestry.mail.network.PacketRegistryMail; import forestry.modules.BlankForestryModule; import forestry.modules.ForestryModuleUids; +import forestry.modules.ModuleHelper; @ForestryModule(containerID = Constants.MOD_ID, moduleID = ForestryModuleUids.MAIL, name = "Mail", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.module.mail.description") public class ModuleMail extends BlankForestryModule { @@ -117,7 +116,7 @@ public class ModuleMail extends BlankForestryModule { ItemStack stampGlue; ItemStack letterGlue; - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.APICULTURE))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.APICULTURE)) { ItemRegistryApiculture beeItems = ModuleApiculture.getItems(); stampGlue = beeItems.honeyDrop.getItemStack(); letterGlue = beeItems.propolis.getWildcard(); @@ -136,7 +135,7 @@ public class ModuleMail extends BlankForestryModule { ItemStack stamps = items.stamps.get(stampDefinition, 9); - RecipeUtil.addRecipe("stamps", stamps, + RecipeUtil.addRecipe("stamps_" + stampDefinition.getUid(), stamps, "XXX", "###", "ZZZ", diff --git a/src/main/java/forestry/mail/gui/GuiLetter.java b/src/main/java/forestry/mail/gui/GuiLetter.java index cd3d9cc65..80c2dd246 100755 --- a/src/main/java/forestry/mail/gui/GuiLetter.java +++ b/src/main/java/forestry/mail/gui/GuiLetter.java @@ -22,8 +22,6 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import org.lwjgl.input.Keyboard; - import forestry.api.mail.EnumAddressee; import forestry.api.mail.IMailAddress; import forestry.core.config.Constants; @@ -38,6 +36,8 @@ import forestry.core.utils.Translator; import forestry.mail.inventory.ItemInventoryLetter; import forestry.mail.network.packets.PacketLetterInfoRequest; +import org.lwjgl.input.Keyboard; + public class GuiLetter extends GuiForestry { private final ItemInventoryLetter itemInventory; private final boolean isProcessedLetter; @@ -119,11 +119,11 @@ public class GuiLetter extends GuiForestry { } @Override - protected void mouseClicked(int par1, int par2, int mouseButton) throws IOException { - super.mouseClicked(par1, par2, mouseButton); + protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { + super.mouseClicked(mouseX, mouseY, mouseButton); - this.address.mouseClicked(par1, par2, mouseButton); - this.text.mouseClicked(par1, par2, mouseButton); + this.address.mouseClicked(mouseX, mouseY, mouseButton); + this.text.mouseClicked(mouseX, mouseY, mouseButton); } diff --git a/src/main/java/forestry/mail/gui/GuiTradeName.java b/src/main/java/forestry/mail/gui/GuiTradeName.java index bdf91560d..fd1d1fff5 100755 --- a/src/main/java/forestry/mail/gui/GuiTradeName.java +++ b/src/main/java/forestry/mail/gui/GuiTradeName.java @@ -16,8 +16,6 @@ import org.apache.commons.lang3.StringUtils; import net.minecraft.client.gui.GuiTextField; -import org.lwjgl.input.Keyboard; - import forestry.core.config.Constants; import forestry.core.gui.GuiForestry; import forestry.core.render.ColourProperties; @@ -26,6 +24,8 @@ import forestry.core.utils.Translator; import forestry.mail.network.packets.PacketTraderAddressRequest; import forestry.mail.tiles.TileTrader; +import org.lwjgl.input.Keyboard; + public class GuiTradeName extends GuiForestry { private final TileTrader tile; private GuiTextField addressNameField; @@ -65,9 +65,9 @@ public class GuiTradeName extends GuiForestry { } @Override - protected void mouseClicked(int par1, int par2, int mouseButton) throws IOException { - super.mouseClicked(par1, par2, mouseButton); - addressNameField.mouseClicked(par1, par2, mouseButton); + protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { + super.mouseClicked(mouseX, mouseY, mouseButton); + addressNameField.mouseClicked(mouseX, mouseY, mouseButton); } @Override diff --git a/src/main/java/forestry/modules/ForestryModuleUids.java b/src/main/java/forestry/modules/ForestryModuleUids.java index b926d0a2b..0570f1583 100644 --- a/src/main/java/forestry/modules/ForestryModuleUids.java +++ b/src/main/java/forestry/modules/ForestryModuleUids.java @@ -19,7 +19,9 @@ public class ForestryModuleUids { public static final String BACKPACKS = "backpacks"; public static final String DATABASE = "database"; public static final String SORTING = "sorting"; + public static final String BOOK = "book"; public static final String CULTIVATION = "cultivation"; + public static final String RESEARCH = "research"; //Mod Plugins public static final String BIOMES_O_PLENTY = "biomes.o.plenty"; diff --git a/src/main/java/forestry/modules/InternalModuleHandler.java b/src/main/java/forestry/modules/InternalModuleHandler.java index cfe56768b..569a0ca40 100644 --- a/src/main/java/forestry/modules/InternalModuleHandler.java +++ b/src/main/java/forestry/modules/InternalModuleHandler.java @@ -163,6 +163,14 @@ public class InternalModuleHandler { } } + public void runBookInit() { + for (IForestryModule module : modules) { + Log.debug("Book Entry Registration Start: {}", module); + //odule.registerBookEntries(ForesterBook.INSTANCE); + Log.debug("Book Entry Registration Complete: {}", module); + } + } + public void processIMCMessages(ImmutableList messages) { for (FMLInterModComms.IMCMessage message : messages) { for (BlankForestryModule module : modules) { diff --git a/src/main/java/forestry/modules/ModuleHelper.java b/src/main/java/forestry/modules/ModuleHelper.java new file mode 100644 index 000000000..117c9f2b2 --- /dev/null +++ b/src/main/java/forestry/modules/ModuleHelper.java @@ -0,0 +1,24 @@ +package forestry.modules; + +import java.util.stream.Stream; + +import forestry.core.config.Constants; + +public final class ModuleHelper { + + private ModuleHelper() { + } + + public static boolean isEnabled(String moduleID) { + return isModuleEnabled(Constants.MOD_ID, moduleID); + } + + public static boolean isEnabled(String... moduleIDs) { + return Stream.of(moduleIDs).allMatch(ModuleHelper::isEnabled); + } + + public static boolean isModuleEnabled(String containerID, String moduleID){ + ModuleManager manager = ModuleManager.getInstance(); + return manager.isModuleEnabled(containerID, moduleID); + } +} diff --git a/src/main/java/forestry/plugins/PluginActuallyAdditions.java b/src/main/java/forestry/plugins/PluginActuallyAdditions.java index e570a976f..faac25616 100644 --- a/src/main/java/forestry/plugins/PluginActuallyAdditions.java +++ b/src/main/java/forestry/plugins/PluginActuallyAdditions.java @@ -7,7 +7,6 @@ import net.minecraft.block.Block; import net.minecraft.block.BlockCrops; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; @@ -15,10 +14,10 @@ import net.minecraftforge.fluids.FluidStack; import forestry.api.core.ForestryAPI; import forestry.api.modules.ForestryModule; import forestry.api.recipes.RecipeManagers; -import forestry.core.config.Constants; import forestry.core.fluids.Fluids; import forestry.farming.logic.farmables.FarmableAgingCrop; import forestry.modules.ForestryModuleUids; +import forestry.modules.ModuleHelper; @SuppressWarnings("unused") @ForestryModule(containerID = ForestryCompatPlugins.ID, moduleID = ForestryModuleUids.ACT_ADD, name = "Actually Additions", author = "Ellpeck", url = "http://ellpeck.de/actadd", unlocalizedDescription = "for.module.actuallyadditions.description") @@ -38,7 +37,7 @@ public class PluginActuallyAdditions extends CompatPlugin { Item coffeeSeed = getItem("item_coffee_seed"); //add farm seed planting - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FARMING))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.FARMING)) { registerSeedPlant(canolaSeed, "block_canola"); registerSeedPlant(flaxSeed, "block_flax"); registerSeedPlant(riceSeed, "block_rice"); diff --git a/src/main/java/forestry/plugins/PluginBiomesOPlenty.java b/src/main/java/forestry/plugins/PluginBiomesOPlenty.java index 3b392cd15..1461498fd 100644 --- a/src/main/java/forestry/plugins/PluginBiomesOPlenty.java +++ b/src/main/java/forestry/plugins/PluginBiomesOPlenty.java @@ -18,7 +18,6 @@ import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; import net.minecraftforge.oredict.OreDictionary; @@ -34,6 +33,7 @@ import forestry.core.fluids.Fluids; import forestry.core.recipes.RecipeUtil; import forestry.core.utils.ItemStackUtil; import forestry.modules.ForestryModuleUids; +import forestry.modules.ModuleHelper; @SuppressWarnings("unused") @ForestryModule(containerID = ForestryCompatPlugins.ID, moduleID = ForestryModuleUids.BIOMES_O_PLENTY, name = "BiomesOPlenty", author = "Nirek", url = Constants.URL, unlocalizedDescription = "for.module.biomesoplenty.description") @@ -56,10 +56,10 @@ public class PluginBiomesOPlenty extends CompatPlugin { colorizedSaplings = getBlock("colorizedSaplings"); food = getItem("food"); - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.APICULTURE))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.APICULTURE)) { addFlowers(); } - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FARMING))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.FARMING)) { addFarmCrops(); } } @@ -67,7 +67,7 @@ public class PluginBiomesOPlenty extends CompatPlugin { @Override public void registerRecipes() { amount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FACTORY))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.FACTORY)) { addFermenterRecipes(); addSqueezerRecipes(); } @@ -97,13 +97,13 @@ public class PluginBiomesOPlenty extends CompatPlugin { // } Block boPTurnip = getBlock("turnip"); - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FARMING)) && boPTurnip != null) { + if (ModuleHelper.isEnabled(ForestryModuleUids.FARMING) && boPTurnip != null) { Item boPTurnipSeeds = getItem("turnipSeeds"); ItemStack boPTurnipSeedStack = new ItemStack(boPTurnipSeeds, 1, 0); if (!boPTurnipSeedStack.isEmpty()) { //TODO BoP for 1.9: Add farmable saplings // Farmables.farmables.get("farmVegetables").add(new FarmableHandPlanted(boPTurnipSeedStack, boPTurnip, 7)); - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FACTORY))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.FACTORY)) { RecipeManagers.squeezerManager.addRecipe(10, boPTurnipSeedStack, Fluids.SEED_OIL.getFluid(amount)); } } diff --git a/src/main/java/forestry/plugins/PluginHarvestCraft.java b/src/main/java/forestry/plugins/PluginHarvestCraft.java index 42fad245d..25d2cf9d1 100644 --- a/src/main/java/forestry/plugins/PluginHarvestCraft.java +++ b/src/main/java/forestry/plugins/PluginHarvestCraft.java @@ -16,7 +16,6 @@ import net.minecraft.block.Block; import net.minecraft.block.properties.PropertyInteger; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; import forestry.api.core.ForestryAPI; import forestry.api.farming.IFarmRegistry; @@ -32,7 +31,7 @@ import forestry.core.items.ItemRegistryCore; import forestry.core.recipes.RecipeUtil; import forestry.farming.logic.farmables.FarmableAgingCrop; import forestry.modules.ForestryModuleUids; -import forestry.modules.ModuleManager; +import forestry.modules.ModuleHelper; @SuppressWarnings("unused") @ForestryModule(containerID = ForestryCompatPlugins.ID, moduleID = ForestryModuleUids.HARVESTCRAFT, name = "HarvestCraft", author = "Nirek", url = Constants.URL, unlocalizedDescription = "for.module.harvestcraft.description") @@ -44,7 +43,7 @@ public class PluginHarvestCraft extends CompatPlugin { @Override public void registerRecipes() { - + boolean farmingModuleEnabled = ModuleHelper.isEnabled(ForestryModuleUids.FARMING); ImmutableList berries = ImmutableList.of( "cranberry", "blackberry", @@ -199,7 +198,7 @@ public class PluginHarvestCraft extends CompatPlugin { if (berrySeed != null) { RecipeManagers.squeezerManager.addRecipe(10, berrySeed, Fluids.SEED_OIL.getFluid(seedamount)); } - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FARMING)) && berrySeed != null && berryBlock != null) { + if (farmingModuleEnabled && berrySeed != null && berryBlock != null) { farmRegistry.registerFarmables("farmCrops", new FarmableAgingCrop(berrySeed, berryBlock, plantAGE, 3, 0)); } plants.add(berryName); @@ -216,7 +215,7 @@ public class PluginHarvestCraft extends CompatPlugin { if (fruitSeed != null) { RecipeManagers.squeezerManager.addRecipe(10, fruitSeed, Fluids.SEED_OIL.getFluid(seedamount)); } - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FARMING)) && fruitSeed != null && fruitBlock != null) { + if (farmingModuleEnabled && fruitSeed != null && fruitBlock != null) { farmRegistry.registerFarmables("farmCrops", new FarmableAgingCrop(fruitSeed, fruitBlock, plantAGE, 3, 0)); } plants.add(fruitName); @@ -234,7 +233,7 @@ public class PluginHarvestCraft extends CompatPlugin { if (vegetableSeed != null) { RecipeManagers.squeezerManager.addRecipe(10, vegetableSeed, Fluids.SEED_OIL.getFluid(seedamount)); } - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FARMING)) && vegetableSeed != null && vegetableBlock != null) { + if (farmingModuleEnabled && vegetableSeed != null && vegetableBlock != null) { farmRegistry.registerFarmables("farmCrops", new FarmableAgingCrop(vegetableSeed, vegetableBlock, plantAGE, 3, 0)); } plants.add(vegetableName); @@ -253,7 +252,7 @@ public class PluginHarvestCraft extends CompatPlugin { RecipeManagers.squeezerManager.addRecipe(10, grainSeed, Fluids.SEED_OIL.getFluid(seedamount)); RecipeManagers.moistenerManager.addRecipe(grainSeed, new ItemStack(Blocks.MYCELIUM), 5000); } - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FARMING)) && grainSeed != null && grainBlock != null) { + if (farmingModuleEnabled && grainSeed != null && grainBlock != null) { farmRegistry.registerFarmables("farmCrops", new FarmableAgingCrop(grainSeed, grainBlock, plantAGE, 3, 0)); } plants.add(grainName); @@ -262,7 +261,7 @@ public class PluginHarvestCraft extends CompatPlugin { for (String treeFruitName : treeFruits) { ItemStack treeFruit = getItemStack(treeFruitName + "item"); Block treeFruitBlock = getBlock("pam" + treeFruitName); - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FARMING)) && treeFruitBlock != null) { + if (farmingModuleEnabled && treeFruitBlock != null) { farmRegistry.registerFarmables("farmOrchard", new FarmableAgingCrop(ItemStack.EMPTY, treeFruitBlock, fruitAGE, 2, 0)); } if (treeFruit != null) { @@ -273,7 +272,7 @@ public class PluginHarvestCraft extends CompatPlugin { for (String treeName : trees) { Block fruitBlock = getBlock("pam" + treeName); - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FARMING)) && fruitBlock != null) { + if (farmingModuleEnabled && fruitBlock != null) { farmRegistry.registerFarmables("farmOrchard", new FarmableAgingCrop(ItemStack.EMPTY, fruitBlock, fruitAGE, 2, 0)); } plants.add(treeName); @@ -281,7 +280,7 @@ public class PluginHarvestCraft extends CompatPlugin { for (String treeName : treesSpecial) { Block fruitBlock = getBlock("pam" + treeName); - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FARMING)) && fruitBlock != null) { + if (farmingModuleEnabled && fruitBlock != null) { farmRegistry.registerFarmables("farmOrchard", new FarmableAgingCrop(ItemStack.EMPTY, fruitBlock, fruitAGE, 2, 0)); } } @@ -299,7 +298,7 @@ public class PluginHarvestCraft extends CompatPlugin { if (genericCropSeed != null) { RecipeManagers.squeezerManager.addRecipe(10, genericCropSeed, Fluids.SEED_OIL.getFluid(seedamount)); } - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FARMING)) && genericCropSeed != null && genericCropBlock != null) { + if (farmingModuleEnabled && genericCropSeed != null && genericCropBlock != null) { farmRegistry.registerFarmables("farmCrops", new FarmableAgingCrop(genericCropSeed, genericCropBlock, plantAGE, 3, 0)); } plants.add(cropName); @@ -310,7 +309,7 @@ public class PluginHarvestCraft extends CompatPlugin { if (mustardCropSeed != null) { RecipeManagers.squeezerManager.addRecipe(10, mustardCropSeed, Fluids.SEED_OIL.getFluid(seedamount)); } - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FARMING)) && mustardCropSeed != null && mustardCropBlock != null) { + if (farmingModuleEnabled && mustardCropSeed != null && mustardCropBlock != null) { farmRegistry.registerFarmables("farmCrops", new FarmableAgingCrop(mustardCropSeed, mustardCropBlock, plantAGE, 3, 0)); } if (mustardFruit != null) { @@ -331,7 +330,7 @@ public class PluginHarvestCraft extends CompatPlugin { if (cropnutSeed != null) { RecipeManagers.squeezerManager.addRecipe(10, cropnutSeed, Fluids.SEED_OIL.getFluid(seedamount)); } - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FARMING)) && cropnutSeed != null && cropnutBlock != null) { + if (farmingModuleEnabled && cropnutSeed != null && cropnutBlock != null) { farmRegistry.registerFarmables("farmCrops", new FarmableAgingCrop(cropnutSeed, cropnutBlock, plantAGE, 3, 0)); } if (cropnut != null) { @@ -342,7 +341,7 @@ public class PluginHarvestCraft extends CompatPlugin { for (String nutName : nuts) { ItemStack nut = getItemStack(nutName + "item"); Block nutBlock = getBlock("pam" + nutName); - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FARMING)) && nutBlock != null) { + if (farmingModuleEnabled && nutBlock != null) { farmRegistry.registerFarmables("farmOrchard", new FarmableAgingCrop(ItemStack.EMPTY, nutBlock, fruitAGE, 2, 0)); } if (nut != null) { @@ -350,7 +349,7 @@ public class PluginHarvestCraft extends CompatPlugin { } } - if(ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.APICULTURE))) { + if(ModuleHelper.isEnabled(ForestryModuleUids.APICULTURE)) { ItemStack hcHoneyItem = getItemStack("honeyitem"); if (hcHoneyItem != null) { RecipeManagers.squeezerManager.addRecipe(10, hcHoneyItem, Fluids.FOR_HONEY.getFluid(Constants.FLUID_PER_HONEY_DROP)); diff --git a/src/main/java/forestry/plugins/PluginIC2.java b/src/main/java/forestry/plugins/PluginIC2.java index 19873a07c..4e7dd05ec 100644 --- a/src/main/java/forestry/plugins/PluginIC2.java +++ b/src/main/java/forestry/plugins/PluginIC2.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.plugins; +import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import javax.annotation.Nonnull; @@ -65,6 +66,8 @@ import forestry.farming.logic.FarmLogicRubber; import forestry.farming.logic.farmables.FarmableBasicIC2Crop; import forestry.modules.BlankForestryModule; import forestry.modules.ForestryModuleUids; +import forestry.modules.ModuleHelper; + import ic2.api.item.IC2Items; import ic2.api.recipe.Recipes; @@ -85,7 +88,17 @@ public class PluginIC2 extends BlankForestryModule { public static ItemStack fertilizer; @Nullable - public BlockRegistryIC2 blocks; + public static BlockRegistryIC2 blocks; + + public static BlockRegistryIC2 getBlocks() { + Preconditions.checkState(blocks != null); + return blocks; + } + + @Override + public void registerItemsAndBlocks() { + blocks = new BlockRegistryIC2(); + } @Override public boolean isAvailable() { @@ -257,7 +270,7 @@ public class PluginIC2 extends BlankForestryModule { } - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.ENERGY))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.ENERGY)) { Fluid biogas = FluidRegistry.getFluid("ic2biogas"); if (biogas != null) { int burnDuration = Math.round(Constants.ENGINE_CYCLE_DURATION_BIOMASS * ForestryAPI.activeMode.getFloatSetting("fuel.biomass.biogas")); @@ -283,7 +296,7 @@ public class PluginIC2 extends BlankForestryModule { ChipsetManager.solderManager.addRecipe(layout, coreItems.tubes.get(EnumElectronTube.BRONZE, 1), Circuits.energyElectricBoost2); ChipsetManager.solderManager.addRecipe(layout, coreItems.tubes.get(EnumElectronTube.IRON, 1), Circuits.energyElectricEfficiency1); - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FARMING))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.FARMING)) { if (resin != null && rubberWood != null) { ICircuitLayout layoutManual = ChipsetManager.circuitRegistry.getLayout("forestry.farms.manual"); ChipsetManager.solderManager.addRecipe(layoutManual, coreItems.tubes.get(EnumElectronTube.RUBBER, 1), Circuits.farmRubberManual); @@ -313,9 +326,4 @@ public class PluginIC2 extends BlankForestryModule { 'V', Blocks.PISTON); } } - - @Override - public void registerItemsAndBlocks() { - blocks = new BlockRegistryIC2(); - } } diff --git a/src/main/java/forestry/plugins/PluginMysticalAgriculture.java b/src/main/java/forestry/plugins/PluginMysticalAgriculture.java index ad0d781ba..d5c633827 100644 --- a/src/main/java/forestry/plugins/PluginMysticalAgriculture.java +++ b/src/main/java/forestry/plugins/PluginMysticalAgriculture.java @@ -5,7 +5,6 @@ import com.google.common.collect.ImmutableList; import net.minecraft.block.Block; import net.minecraft.block.BlockCrops; import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; import forestry.api.core.ForestryAPI; import forestry.api.farming.IFarmRegistry; @@ -15,6 +14,7 @@ import forestry.core.config.Constants; import forestry.core.fluids.Fluids; import forestry.farming.logic.farmables.FarmableAgingCrop; import forestry.modules.ForestryModuleUids; +import forestry.modules.ModuleHelper; @SuppressWarnings("unused") @ForestryModule(containerID = ForestryCompatPlugins.ID, moduleID = ForestryModuleUids.MAGICAL_AGRICULTURE, name = "Mystical Agriculture", author = "Nedelosk", url = Constants.URL, unlocalizedDescription = "for.module.mysticalagriculture.description") @@ -27,7 +27,7 @@ public class PluginMysticalAgriculture extends CompatPlugin { @Override public void registerRecipes() { - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FARMING))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.FARMING)) { ImmutableList crops = ImmutableList.of( "stone", "dirt", diff --git a/src/main/java/forestry/plugins/PluginNatura.java b/src/main/java/forestry/plugins/PluginNatura.java index 988e79f3a..c8eabe43b 100644 --- a/src/main/java/forestry/plugins/PluginNatura.java +++ b/src/main/java/forestry/plugins/PluginNatura.java @@ -56,6 +56,7 @@ import forestry.farming.logic.farmables.FarmableSapling; import forestry.farming.logic.farmables.FarmableVanillaMushroom; import forestry.modules.BlankForestryModule; import forestry.modules.ForestryModuleUids; +import forestry.modules.ModuleHelper; @SuppressWarnings("unused") @ForestryModule(containerID = ForestryCompatPlugins.ID, moduleID = ForestryModuleUids.NATURA, name = "Natura", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.module.natura.description") @@ -274,7 +275,7 @@ public class PluginNatura extends BlankForestryModule { RecipeManagers.moistenerManager.addRecipe(seed, new ItemStack(Blocks.MYCELIUM), 5000); } - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FARMING))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.FARMING)) { cropBlocks.forEach(itemStack -> { Block block = ItemStackUtil.getBlock(itemStack); ItemStack seedItem; diff --git a/src/main/java/forestry/sorting/ModuleSorting.java b/src/main/java/forestry/sorting/ModuleSorting.java index c36bd3a16..d5e3d408c 100644 --- a/src/main/java/forestry/sorting/ModuleSorting.java +++ b/src/main/java/forestry/sorting/ModuleSorting.java @@ -22,7 +22,7 @@ import forestry.core.utils.OreDictUtil; import forestry.lepidopterology.ModuleLepidopterology; import forestry.modules.BlankForestryModule; import forestry.modules.ForestryModuleUids; -import forestry.modules.ModuleManager; +import forestry.modules.ModuleHelper; import forestry.sorting.blocks.BlockRegistrySorting; import forestry.sorting.network.PacketRegistrySorting; import forestry.sorting.tiles.TileGeneticFilter; @@ -68,7 +68,7 @@ public class ModuleSorting extends BlankForestryModule { @Override public void registerRecipes() { - if(ModuleManager.getInstance().isModuleEnabled(Constants.MOD_ID, ForestryModuleUids.APICULTURE)) { + if(ModuleHelper.isEnabled(ForestryModuleUids.APICULTURE)) { RecipeUtil.addRecipe("genetic_filter_api", new ItemStack(getBlocks().filter, 2), "WDW", "PGP", @@ -79,7 +79,7 @@ public class ModuleSorting extends BlankForestryModule { 'B', OreDictUtil.GEAR_BRONZE, 'P', ModuleApiculture.getItems().propolis); } - if(ModuleManager.getInstance().isModuleEnabled(Constants.MOD_ID, ForestryModuleUids.ARBORICULTURE)) { + if(ModuleHelper.isEnabled(ForestryModuleUids.ARBORICULTURE)) { RecipeUtil.addRecipe("genetic_filter_arb", new ItemStack(getBlocks().filter, 2), "WDW", "FGF", @@ -90,7 +90,7 @@ public class ModuleSorting extends BlankForestryModule { 'B', OreDictUtil.GEAR_BRONZE, 'F', OreDictUtil.FRUIT_FORESTRY); } - if(ModuleManager.getInstance().isModuleEnabled(Constants.MOD_ID, ForestryModuleUids.LEPIDOPTEROLOGY)) { + if(ModuleHelper.isEnabled(ForestryModuleUids.LEPIDOPTEROLOGY)) { RecipeUtil.addRecipe("genetic_filter_lep", new ItemStack(getBlocks().filter, 2), "WDW", "FGF", diff --git a/src/main/java/forestry/storage/ModuleBackpacks.java b/src/main/java/forestry/storage/ModuleBackpacks.java index 1db1adaf5..5eddf4a77 100644 --- a/src/main/java/forestry/storage/ModuleBackpacks.java +++ b/src/main/java/forestry/storage/ModuleBackpacks.java @@ -28,7 +28,6 @@ import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.Property; @@ -40,7 +39,6 @@ import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.fml.common.event.FMLInterModComms.IMCMessage; import forestry.Forestry; -import forestry.api.core.ForestryAPI; import forestry.api.modules.ForestryModule; import forestry.api.recipes.RecipeManagers; import forestry.api.storage.BackpackManager; @@ -65,6 +63,7 @@ import forestry.lepidopterology.ModuleLepidopterology; import forestry.lepidopterology.blocks.BlockRegistryLepidopterology; import forestry.modules.BlankForestryModule; import forestry.modules.ForestryModuleUids; +import forestry.modules.ModuleHelper; import forestry.storage.items.ItemRegistryBackpacks; @ForestryModule(moduleID = ForestryModuleUids.BACKPACKS, containerID = Constants.MOD_ID, name = "Backpack", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.module.backpacks.description", lootTable = "storage") @@ -103,13 +102,13 @@ public class ModuleBackpacks extends BlankForestryModule { BackpackDefinition definition; - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.APICULTURE))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.APICULTURE)) { Predicate filter = BackpackManager.backpackInterface.createNaturalistBackpackFilter("rootBees"); definition = new BackpackDefinition(new Color(0xc4923d), Color.WHITE, filter); BackpackManager.backpackInterface.registerBackpackDefinition("apiarist", definition); } - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.LEPIDOPTEROLOGY))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.LEPIDOPTEROLOGY)) { Predicate filter = BackpackManager.backpackInterface.createNaturalistBackpackFilter("rootButterflies"); definition = new BackpackDefinition(new Color(0x995b31), Color.WHITE, filter); BackpackManager.backpackInterface.registerBackpackDefinition("lepidopterist", definition); @@ -374,7 +373,7 @@ public class ModuleBackpacks extends BlankForestryModule { new ItemStack(Items.SPRUCE_DOOR) ))); - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.APICULTURE))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.APICULTURE)) { BlockRegistryApiculture beeBlocks = ModuleApiculture.getBlocks(); backpackAcceptedItemDefaults.get(BackpackManager.BUILDER_UID).addAll(getItemStrings(Arrays.asList( new ItemStack(beeBlocks.candle, 1, OreDictionary.WILDCARD_VALUE), @@ -557,12 +556,12 @@ public class ModuleBackpacks extends BlankForestryModule { @Override public void registerRecipes() { ItemRegistryBackpacks items = getItems(); - if (items.apiaristBackpack != null && ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.APICULTURE))) { + if (items.apiaristBackpack != null && ModuleHelper.isEnabled(ForestryModuleUids.APICULTURE)) { BlockRegistryApiculture beeBlocks = ModuleApiculture.getBlocks(); addBackpackRecipe("bee", items.apiaristBackpack, "stickWood", beeBlocks.beeChest); } - if (items.lepidopteristBackpack != null && ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.LEPIDOPTEROLOGY))) { + if (items.lepidopteristBackpack != null && ModuleHelper.isEnabled(ForestryModuleUids.LEPIDOPTEROLOGY)) { BlockRegistryLepidopterology butterflyBlocks = ModuleLepidopterology.getBlocks(); ItemStack chest = new ItemStack(butterflyBlocks.butterflyChest); addBackpackRecipe("butterfly", items.lepidopteristBackpack, "stickWood", chest); @@ -576,7 +575,7 @@ public class ModuleBackpacks extends BlankForestryModule { addBackpackRecipe("building", items.builderBackpack, Items.CLAY_BALL); // / CARPENTER - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FACTORY))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.FACTORY)) { // / BACKPACKS WOVEN addT2BackpackRecipe(items.minerBackpack, items.minerBackpackT2); addT2BackpackRecipe(items.diggerBackpack, items.diggerBackpackT2); diff --git a/src/main/java/forestry/storage/ModuleCrates.java b/src/main/java/forestry/storage/ModuleCrates.java index a7b80233f..5b755a5f2 100644 --- a/src/main/java/forestry/storage/ModuleCrates.java +++ b/src/main/java/forestry/storage/ModuleCrates.java @@ -22,13 +22,13 @@ import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.core.ForestryAPI; import forestry.api.modules.ForestryModule; import forestry.api.recipes.RecipeManagers; import forestry.api.storage.StorageManager; import forestry.core.config.Constants; import forestry.modules.BlankForestryModule; import forestry.modules.ForestryModuleUids; +import forestry.modules.ModuleHelper; import forestry.storage.items.ItemCrated; import forestry.storage.items.ItemRegistryCrates; import forestry.storage.models.ModelCrate; @@ -77,7 +77,7 @@ public class ModuleCrates extends BlankForestryModule { ItemRegistryCrates items = getItems(); // / CARPENTER - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.FACTORY))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.FACTORY)) { // / CRATES RecipeManagers.carpenterManager.addRecipe(20, new FluidStack(FluidRegistry.WATER, Fluid.BUCKET_VOLUME), ItemStack.EMPTY, items.crate.getItemStack(24), " # ", "# #", " # ", '#', "logWood"); diff --git a/src/main/java/forestry/storage/items/ItemRegistryBackpacks.java b/src/main/java/forestry/storage/items/ItemRegistryBackpacks.java index d2555223a..141569ee1 100644 --- a/src/main/java/forestry/storage/items/ItemRegistryBackpacks.java +++ b/src/main/java/forestry/storage/items/ItemRegistryBackpacks.java @@ -13,18 +13,16 @@ package forestry.storage.items; import javax.annotation.Nullable; import net.minecraft.item.Item; -import net.minecraft.util.ResourceLocation; import forestry.api.apiculture.BeeManager; -import forestry.api.core.ForestryAPI; import forestry.api.core.Tabs; import forestry.api.lepidopterology.ButterflyManager; import forestry.api.storage.BackpackManager; import forestry.api.storage.EnumBackpackType; import forestry.api.storage.IBackpackInterface; -import forestry.core.config.Constants; import forestry.core.items.ItemRegistry; import forestry.modules.ForestryModuleUids; +import forestry.modules.ModuleHelper; public class ItemRegistryBackpacks extends ItemRegistry { @Nullable @@ -49,14 +47,14 @@ public class ItemRegistryBackpacks extends ItemRegistry { // BACKPACKS IBackpackInterface backpackInterface = BackpackManager.backpackInterface; - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.APICULTURE))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.APICULTURE)) { apiaristBackpack = registerItem(backpackInterface.createNaturalistBackpack("apiarist", BeeManager.beeRoot), "apiarist_bag"); apiaristBackpack.setCreativeTab(Tabs.tabApiculture); } else { apiaristBackpack = null; } - if (ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.LEPIDOPTEROLOGY))) { + if (ModuleHelper.isEnabled(ForestryModuleUids.LEPIDOPTEROLOGY)) { lepidopteristBackpack = registerItem(backpackInterface.createNaturalistBackpack("lepidopterist", ButterflyManager.butterflyRoot), "lepidopterist_bag"); lepidopteristBackpack.setCreativeTab(Tabs.tabLepidopterology); } else { diff --git a/src/main/java/forestry/worktable/compat/WorktableJeiPlugin.java b/src/main/java/forestry/worktable/compat/WorktableJeiPlugin.java index 0aa862254..9481d5170 100644 --- a/src/main/java/forestry/worktable/compat/WorktableJeiPlugin.java +++ b/src/main/java/forestry/worktable/compat/WorktableJeiPlugin.java @@ -3,15 +3,13 @@ package forestry.worktable.compat; import com.google.common.base.Preconditions; import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.core.ForestryAPI; -import forestry.core.config.Constants; import forestry.core.utils.JeiUtil; import forestry.modules.ForestryModuleUids; +import forestry.modules.ModuleHelper; import forestry.worktable.ModuleWorktable; import forestry.worktable.blocks.BlockRegistryWorktable; @@ -27,7 +25,7 @@ public class WorktableJeiPlugin implements IModPlugin { @Override public void register(IModRegistry registry) { - if (!ForestryAPI.enabledModules.contains(new ResourceLocation(Constants.MOD_ID, ForestryModuleUids.WORKTABLE))) { + if(!ModuleHelper.isEnabled(ForestryModuleUids.WORKTABLE)){ return; } BlockRegistryWorktable blocks = ModuleWorktable.getBlocks(); diff --git a/src/main/resources/assets/forestry/models/item/book_forester.json b/src/main/resources/assets/forestry/models/item/book_forester.json new file mode 100644 index 000000000..4b121d9d4 --- /dev/null +++ b/src/main/resources/assets/forestry/models/item/book_forester.json @@ -0,0 +1,6 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "forestry:items/book_forester" + } +} diff --git a/src/main/resources/assets/forestry/textures/gui/almanac/almanac.png b/src/main/resources/assets/forestry/textures/gui/almanac/almanac.png new file mode 100644 index 000000000..6e82a2d9e Binary files /dev/null and b/src/main/resources/assets/forestry/textures/gui/almanac/almanac.png differ diff --git a/src/main/resources/assets/forestry/textures/gui/almanac/crafting.png b/src/main/resources/assets/forestry/textures/gui/almanac/crafting.png new file mode 100644 index 000000000..44d9dfe54 Binary files /dev/null and b/src/main/resources/assets/forestry/textures/gui/almanac/crafting.png differ diff --git a/src/main/resources/assets/forestry/textures/gui/almanac/fam_layouts/3x3.png b/src/main/resources/assets/forestry/textures/gui/almanac/fam_layouts/3x3.png new file mode 100644 index 000000000..09889a00c Binary files /dev/null and b/src/main/resources/assets/forestry/textures/gui/almanac/fam_layouts/3x3.png differ diff --git a/src/main/resources/assets/forestry/textures/gui/almanac/fam_layouts/3x4.png b/src/main/resources/assets/forestry/textures/gui/almanac/fam_layouts/3x4.png new file mode 100644 index 000000000..d737ec0a2 Binary files /dev/null and b/src/main/resources/assets/forestry/textures/gui/almanac/fam_layouts/3x4.png differ diff --git a/src/main/resources/assets/forestry/textures/gui/almanac/fam_layouts/3x5.png b/src/main/resources/assets/forestry/textures/gui/almanac/fam_layouts/3x5.png new file mode 100644 index 000000000..5cf519142 Binary files /dev/null and b/src/main/resources/assets/forestry/textures/gui/almanac/fam_layouts/3x5.png differ diff --git a/src/main/resources/assets/forestry/textures/gui/almanac/fam_layouts/4x4.png b/src/main/resources/assets/forestry/textures/gui/almanac/fam_layouts/4x4.png new file mode 100644 index 000000000..35c9e521a Binary files /dev/null and b/src/main/resources/assets/forestry/textures/gui/almanac/fam_layouts/4x4.png differ diff --git a/src/main/resources/assets/forestry/textures/gui/almanac/fam_layouts/5x5.png b/src/main/resources/assets/forestry/textures/gui/almanac/fam_layouts/5x5.png new file mode 100644 index 000000000..6fe9e275a Binary files /dev/null and b/src/main/resources/assets/forestry/textures/gui/almanac/fam_layouts/5x5.png differ diff --git a/src/main/resources/assets/forestry/textures/gui/almanac/guis/multi_farm.png b/src/main/resources/assets/forestry/textures/gui/almanac/guis/multi_farm.png new file mode 100644 index 000000000..4e7f207a6 Binary files /dev/null and b/src/main/resources/assets/forestry/textures/gui/almanac/guis/multi_farm.png differ diff --git a/src/main/resources/assets/forestry/textures/gui/almanac/logo.png b/src/main/resources/assets/forestry/textures/gui/almanac/logo.png new file mode 100644 index 000000000..a9933e37f Binary files /dev/null and b/src/main/resources/assets/forestry/textures/gui/almanac/logo.png differ diff --git a/src/main/resources/assets/forestry/textures/gui/almanac/scraps/alveary.png b/src/main/resources/assets/forestry/textures/gui/almanac/scraps/alveary.png new file mode 100644 index 000000000..dd07df826 Binary files /dev/null and b/src/main/resources/assets/forestry/textures/gui/almanac/scraps/alveary.png differ diff --git a/src/main/resources/assets/forestry/textures/gui/almanac/scraps/apiary_gui.png b/src/main/resources/assets/forestry/textures/gui/almanac/scraps/apiary_gui.png new file mode 100644 index 000000000..039ca852b Binary files /dev/null and b/src/main/resources/assets/forestry/textures/gui/almanac/scraps/apiary_gui.png differ diff --git a/src/main/resources/assets/forestry/textures/gui/almanac/scraps/hive.png b/src/main/resources/assets/forestry/textures/gui/almanac/scraps/hive.png new file mode 100644 index 000000000..951fee519 Binary files /dev/null and b/src/main/resources/assets/forestry/textures/gui/almanac/scraps/hive.png differ diff --git a/src/main/resources/assets/forestry/textures/gui/analyzer_screen.png b/src/main/resources/assets/forestry/textures/gui/analyzer_screen.png new file mode 100644 index 000000000..33a2fd439 Binary files /dev/null and b/src/main/resources/assets/forestry/textures/gui/analyzer_screen.png differ diff --git a/src/main/resources/assets/forestry/textures/gui/database_inventory.png b/src/main/resources/assets/forestry/textures/gui/database_inventory.png index 9bff83c5f..0bfe653ab 100644 Binary files a/src/main/resources/assets/forestry/textures/gui/database_inventory.png and b/src/main/resources/assets/forestry/textures/gui/database_inventory.png differ diff --git a/src/main/resources/assets/forestry/textures/items/book_forester.png b/src/main/resources/assets/forestry/textures/items/book_forester.png new file mode 100644 index 000000000..5b910a8fa Binary files /dev/null and b/src/main/resources/assets/forestry/textures/items/book_forester.png differ