Compare commits

...
Author SHA1 Message Date
Martin Robertz cea80c9748 Merge remote-tracking branch 'slprime/fix_shift_scroll' into dev 2025-10-29 07:55:55 +01:00
Martin Robertz 690b469d05 Merge remote-tracking branch 'slprime/fix_guirecipe_height' into dev 2025-10-29 07:55:46 +01:00
Martin Robertz 30d91dd9c6 Merge remote-tracking branch 'slprime/remove_permutations_from_output' into dev 2025-10-29 07:55:27 +01:00
Martin Robertz d143266c49 Merge remote-tracking branch 'slprime/recipe_with_count' into dev 2025-10-29 07:55:14 +01:00
Martin Robertz f4f7e94b0c Merge remote-tracking branch 'slprime/normalize_recipe' into dev 2025-10-29 07:55:05 +01:00
Martin Robertz 1e1d2f1076 update 2025-10-29 07:54:19 +01:00
slprime 2201b3264e split PR 2025-10-29 08:47:56 +02:00
slprime 1e5b2a5ce6 Fixed shift+scroll of ingredients in the recipe GUI 2025-10-29 08:45:31 +02:00
slprime b6380c4a74 split PR 2025-10-29 08:39:57 +02:00
slprime e2206db0f1 Сalculate the height of the container before scrolling to the recipe 2025-10-29 08:38:19 +02:00
slprimeandWilhelm Schuster 7cb94fb22a Clear rawText before formatting (#780)
Co-authored-by: Wilhelm Schuster <[email protected]>
2025-10-25 15:20:28 +02:00
Martin Robertz 87aa4f9ed5 update 2025-10-25 14:18:58 +02:00
DarkShadow44andMartin Robertz 9760fd3eaf Fix another race condition, affecting IndustrialGrafter (#779)
Co-authored-by: Martin Robertz <[email protected]>
2025-10-25 14:11:49 +02:00
Martin Robertz 3da26983e2 Merge branch 'master' into normalize_recipe 2025-10-25 13:16:55 +02:00
slprime 13d9b9b835 Remove Permutations from Output 2025-10-25 01:25:23 +03:00
slprime 9f50932990 supply 2025-10-24 12:31:18 +03:00
slprime 518aad6d37 Add Recipe With Count Option 2025-10-24 12:18:04 +03:00
slprime 1054871982 Add Scroll to Recipe Catalysts (#770) 2025-10-21 12:28:14 +00:00
Martin Robertz f725f1e96c Merge branch 'master' into normalize_recipe 2025-10-21 14:24:50 +02:00
slprime d90a667f68 Fix Bookmarks Chain Tooltip Height (#773) 2025-10-19 21:33:46 +03:00
slprime 69e6df5848 Fix Button Texture (#771) 2025-10-19 19:56:23 +02:00
slprime 47871942b8 Create normalizeRecipeQueryStack 2025-10-19 20:42:07 +03:00
slprime 25fa7ce44e Add defaultbookmarkcontainers.cfg (#769) 2025-10-19 16:07:45 +03:00
slprime e3cd7b860d Fix recipe result count (#767) 2025-10-18 11:07:39 +00:00
slprime 2a3aabc073 Add recipe index to recipe handler height (#768) 2025-10-18 13:03:08 +02:00
slprimeandMartin Robertz 76db43c835 Optimize permutations (#761)
Co-authored-by: Martin Robertz <[email protected]>
2025-10-17 22:23:10 +03:00
slprimeandMartin Robertz 40e53eea7a Fixing HUD flickering (#762)
Co-authored-by: Martin Robertz <[email protected]>
2025-10-17 21:36:30 +03:00
Martin Robertz 6c4d16d6b9 update 2025-10-17 12:50:52 +02:00
RealSilverMoon 4a2abe9fd7 Add a function to copy item name and meta (#758) 2025-10-17 10:54:47 +03:00
sisyphussy d47417302e Fix recipe tooltip lighting (#757) 2025-10-14 17:09:02 +03:00
e13401ded8 Optimize Bookmark Chains with Containers (#751)
Co-authored-by: Martin Robertz <[email protected]>
Co-authored-by: sisyphussy <[email protected]>
2025-10-13 11:01:58 +00:00
sisyphussy 7ada842ef3 Fix tooltip item lighting (#755) 2025-10-13 00:29:09 +03:00
slprimeandMartin Robertz fe0c5d4e50 Create Recipe Widget; Recipe GUI: Infinity Scroll; Recipe GUI: Max Height Settings (#701)
Co-authored-by: Martin Robertz <[email protected]>
2025-10-12 18:39:21 +02:00
slprime 2ea9ae1eb9 Show Handler Icon in Bookmarks (#747) 2025-10-09 21:22:37 +02:00
slprime f7f0596fda Show Items Loading Message (#745) 2025-10-08 16:58:23 +02:00
sbwaz d5e919a9cd [Extended+] Fix the prefixed sequence parsing. (#741) 2025-10-04 13:19:00 +02:00
sisyphussyandMartin Robertz a0ed5da699 Speedup rendering (#740)
Co-authored-by: Martin Robertz <[email protected]>
2025-10-02 12:53:18 +02:00
Martin Robertz 99fb5a656e update 2025-10-02 12:13:08 +02:00
DarkShadow44 4b663222b1 Force tag compounds to be initialized so doesn't happen concurrently later (#730) 2025-10-02 07:15:28 +02:00
Martin Robertz 3e5d0088bc update 2025-10-01 17:21:16 +02:00
948be399d2 allow the steam furnace multiblock to show up in NEI under furnaces (#702)
Co-authored-by: Martin Robertz <[email protected]>
Co-authored-by: EnderProyects <[email protected]>
2025-09-28 13:39:45 +02:00
DarkShadow44 5f6091924d Add more logging for fuel crash (#736) 2025-09-28 01:02:47 +03:00
Dredonkey c5bd1f897a Fix pressing '2' when hovering crafting output not putting the crafted item(s) in the hotbar (#733) 2025-09-27 10:17:40 +00:00
Julia 61d4b6ab62 Revert "Replace lambda with method reference" (#735) 2025-09-27 03:09:17 -07:00
Julia 791d05d5f5 Support Inline Comments After # (#734) 2025-09-26 18:11:47 -07:00
Mike_be 66001275c4 Remove UXV and MAX biolab from NEI recipe catalysts (#732) 2025-09-26 21:40:03 +02:00
slprime db6b83c906 Try fix Fuels (#729) 2025-09-24 13:17:34 +02:00
slprime 58ef6c85e0 Fix NBT Copy (#728) 2025-09-22 20:28:05 -07:00
Martin Robertz ab0aeef872 update 2025-09-21 21:38:41 +02:00
slprime 23b7c69e2f Fix None hotkeys for java8 (#726) 2025-09-21 19:44:20 +02:00
slprime bb89384493 Fix Bookmarks Shadow Items (#724) 2025-09-18 19:07:51 +02:00
slprime e96e4dfdde Create Item Untranslator (#719) 2025-09-17 12:42:35 +00:00
slprime 0a6a6771d8 Fixed Favorite Recipes in bookmarks for ingredients (#720) 2025-09-15 19:21:52 +02:00
sbwaz c96199a727 [Extended+] Filter permutations on the left. Fail on recipe expression, when not searching a recipe. (#716) 2025-09-13 11:18:29 +02:00
azod ab4ea2cfa1 feat(moboverlay): add chat message (on/off) (#715) 2025-09-11 03:45:06 -03:00
Mike_be b679883d02 Remove old entries which resulted in ghost catalysts (#714) 2025-09-08 20:11:32 +02:00
Worive 0048ef80d0 Fix(MobSpawnOverlay): avoid IOB from checking light value from block outside of world (#711) 2025-09-07 11:03:21 +00:00
slprime 84576aa7a2 Fix Permutation Filter (#712) 2025-09-06 22:32:14 +02:00
109 changed files with 5783 additions and 2567 deletions

No files matched your search

+1 -1
View File
@@ -2,7 +2,7 @@
dependencies {
api('com.github.GTNewHorizons:CodeChickenCore:1.4.7:dev')
implementation('com.github.GTNewHorizons:GTNHLib:0.6.39:dev')
implementation('com.github.GTNewHorizons:GTNHLib:0.7.3:dev')
shadowImplementation('org.apache.commons:commons-csv:1.10.0')
+3 -1
View File
@@ -96,7 +96,9 @@ usesMixinDebug = false
# Specify the location of your implementation of IMixinConfigPlugin. Leave it empty otherwise.
mixinPlugin =
# Specify the package that contains all of your Mixins. You may only place Mixins in this package or the build will fail!
# Specify the package that contains all of your Mixins. The package must exist or
# the build will fail. If you have a package property defined in your mixins.<modid>.json,
# it must match with this or the build will fail.
mixinsPackage =
# Specify the core mod entry class if you use a core mod. This class must implement IFMLLoadingPlugin!
+1 -1
View File
@@ -17,7 +17,7 @@ pluginManagement {
}
plugins {
id 'com.gtnewhorizons.gtnhsettingsconvention' version '1.0.42'
id 'com.gtnewhorizons.gtnhsettingsconvention' version '1.0.47'
}
+6 -4
View File
@@ -18,20 +18,22 @@ public SearchExpressionLexer(CharStream input, SearchTokenParser searchParser) {
// Lexer rules
REGEX_LEFT : 'r'? '/' -> pushMode(REGEX) ;
QUOTE_LEFT : '"' -> pushMode(QUOTED) ;
DASH : '-' ;
RECIPE_INGREDIENTS : '<&' | '<' ;
RECIPE_RESULT : '>&' | '>' ;
RECIPE_OTHERS : '^&' | '^' ;
PREFIX : CLEAN_SYMBOL {searchParser.hasRedefinedPrefix(getText().charAt(0))}? ;
OR : '|' ;
LEFT_BRACKET : '{' ;
RIGHT_BRACKET : '}' ;
PLAIN_TEXT : (CLEAN_SYMBOL | ESCAPED_SYMBOL)+ {!searchParser.hasRedefinedPrefix(getText().charAt(0))}? ;
NEWLINE_OR_TAB : [\t\r\n] -> skip ;
SPACE : ' ' ;
ESCAPED_SYMBOL : '\\' . ;
fragment ESCAPED_SYMBOL : '\\' . ;
fragment CLEAN_SYMBOL : ~[-<>^{}|/\\ "] ;
PREFIX : CLEAN_SYMBOL {searchParser.hasRedefinedPrefix(getText().charAt(0))}? ;
CLEAN_SYMBOL : ~[-<>^{}|/\\ "] ;
mode REGEX;
+4 -1
View File
@@ -56,7 +56,7 @@ prefixedExpression
token[Character prefix]
: regex[prefix]
| quoted[prefix]
| PLAIN_TEXT
| plainText
;
regex[Character prefix]
@@ -67,4 +67,7 @@ quoted[Character prefix]
: QUOTE_LEFT QUOTED_CONTENT QUOTE_RIGHT?
;
plainText
: (CLEAN_SYMBOL | ESCAPED_SYMBOL)+
;
@@ -6,12 +6,11 @@ import net.minecraft.item.ItemStack;
import org.lwjgl.opengl.GL11;
import codechicken.nei.ItemsGrid.ItemsGridSlot;
import codechicken.nei.api.ShortcutInputHandler;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.guihook.IContainerTooltipHandler;
import codechicken.nei.recipe.GuiCraftingRecipe;
import codechicken.nei.recipe.GuiRecipe;
import codechicken.nei.recipe.GuiUsageRecipe;
public abstract class AbstractSubpanel<T extends ItemsGrid<? extends ItemsGridSlot, ? extends ItemsGrid.MouseContext>>
extends Widget implements IContainerTooltipHandler {
@@ -122,13 +121,7 @@ public abstract class AbstractSubpanel<T extends ItemsGrid<? extends ItemsGridSl
if (NEIController.manager.window instanceof GuiRecipe || NEIClientUtils.shiftKey()
|| !NEIClientConfig.canCheatItem(hoverSlot.getItemStack())) {
if (button == 0) {
GuiCraftingRecipe.openRecipeGui("item", hoverSlot.getItemStack().copy());
} else if (button == 1) {
GuiUsageRecipe.openRecipeGui("item", hoverSlot.getItemStack().copy());
}
ShortcutInputHandler.handleMouseClick(hoverSlot.getItemStack().copy());
} else {
NEIClientUtils.cheatItem(getDraggedStackWithQuantity(hoverSlot.getItemStack()), button, -1);
}
@@ -29,6 +29,7 @@ import codechicken.nei.api.IBookmarkContainerHandler;
import codechicken.nei.bookmark.BookmarkGrid;
import codechicken.nei.bookmark.BookmarkGroup;
import codechicken.nei.bookmark.BookmarkItem;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.bookmark.BookmarkStorage;
import codechicken.nei.bookmark.BookmarksGridSlot;
import codechicken.nei.bookmark.GroupingItem;
@@ -184,23 +185,26 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
final boolean existsRecipe = recipeId != null
&& this.grid.existsRecipe(recipeId, BookmarkGrid.DEFAULT_GROUP_ID);
final NBTTagCompound nbTag = StackInfo.itemStackToNBT(itemStack);
long factor = nbTag.getInteger("Count");
long count = nbTag.getInteger("Count");
long factor = existsRecipe ? Math.max(count, 1) : 1;
if (existsRecipe) {
for (int i = 0; i < this.grid.size(); i++) {
if (this.grid.getBookmarkItem(i).equalsRecipe(recipeId, groupId)) {
final long multiplier = this.grid.getBookmarkItem(i).getMultiplier();
factor *= multiplier;
count *= this.grid.getBookmarkItem(i).getMultiplier();
break;
}
}
} else {
factor = nbTag.hasKey("gtFluidName") ? Math.min(144, nbTag.getInteger("Count")) : 1;
}
this.grid.addItem(BookmarkItem.of(groupId, itemStack, factor, recipeId, false), true);
this.grid.addItem(
BookmarkItem.of(
groupId,
StackInfo.withAmount(itemStack, count),
factor,
recipeId,
existsRecipe ? BookmarkItemType.RESULT : BookmarkItemType.ITEM),
true);
return true;
}
@@ -242,7 +246,8 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
if (stack != null && uniqueRecipe.add(recipeId)) {
this.grid.addItem(
BookmarkItem.of(groupId, stack, StackInfo.getAmount(stack), recipeId, false),
BookmarkItem
.of(groupId, stack, StackInfo.getAmount(stack), recipeId, BookmarkItemType.ITEM),
true);
uniqueStack.add(stack);
}
@@ -302,7 +307,7 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
}
final int groupId = slot.getGroupId();
final RecipeId recipeId = slot.getRecipeId();
final RecipeId recipeId = slot.getType() == BookmarkItemType.ITEM ? null : slot.getRecipeId();
final BookmarkGroup group = slot.getGroup();
if (group.crafting != null && group.collapsed) {
@@ -366,7 +371,7 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
public RecipeId getRecipeId(int itemIndex) {
BookmarkItem meta = this.grid.getCalculatedItem(itemIndex);
return meta.isIngredient ? null : meta.recipeId;
return meta.type == BookmarkItemType.INGREDIENT ? null : meta.recipeId;
}
public boolean existsRecipe(RecipeId recipeId, int groupId) {
@@ -695,7 +700,7 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
}
@Override
public List<String> handleTooltip(GuiContainer gui, int mousex, int mousey, List<String> currenttip) {
public List<String> handleTooltip(int mousex, int mousey, List<String> currenttip) {
if (this.grid.getPerPage() == 0 || this.grid.isEmpty()) {
return new ArrayList<>();
@@ -722,7 +727,7 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
this.recipeChainTooltipLineHandler = null;
}
return super.handleTooltip(gui, mousex, mousey, currenttip);
return super.handleTooltip(mousex, mousey, currenttip);
}
@Override
@@ -748,7 +753,7 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
}
@Override
public Map<String, String> handleHotkeys(GuiContainer gui, int mousex, int mousey, Map<String, String> hotkeys) {
public Map<String, String> handleHotkeys(int mousex, int mousey, Map<String, String> hotkeys) {
final int overRowIndex = this.grid.getHoveredRowIndex(true);
final BookmarksGridSlot slot = getSlotMouseOver(mousex, mousey);
@@ -781,7 +786,7 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
NEIClientConfig.getKeyName("gui.remove_recipe"),
NEIClientUtils.translate("bookmark.group.remove_recipe"));
if (BookmarkContainerInfo.getBookmarkContainerHandler(gui) != null) {
if (BookmarkContainerInfo.getBookmarkContainerHandler(NEIClientUtils.getGuiContainer()) != null) {
hotkeys.put(
NEIClientConfig.getKeyName("gui.bookmark_pull_items"),
NEIClientUtils.translate("bookmark.group.pull_items"));
@@ -878,7 +883,7 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
}
}
return hotkeys;
return super.handleHotkeys(mousex, mousey, hotkeys);
}
private List<String> recipeChainTooltip(int groupId, List<String> currenttip) {
@@ -915,13 +920,13 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
}
@Override
public List<String> handleItemTooltip(GuiContainer gui, ItemStack itemstack, int mousex, int mousey,
List<String> currenttip) {
public List<String> handleItemTooltip(ItemStack itemstack, int mousex, int mousey, List<String> currenttip) {
final BookmarksGridSlot slot = this.grid.getSlotMouseOver(mousex, mousey);
if (slot != null) {
if (slot.isIngredient() && slot.getRecipeId() != null && slot.getBookmarkItem().permutations.size() > 1) {
if (slot.getType() == BookmarkItemType.INGREDIENT && slot.getRecipeId() != null
&& slot.getBookmarkItem().permutations.size() > 1) {
RecipeId recipeId = slot.getRecipeId();
if (recipeId == null) {
@@ -1019,7 +1024,8 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
if (NEIClientUtils.altKey()) {
multiplier = NEIClientConfig.showItemQuantityWidget() ? NEIClientConfig.getItemQuantity() : 0;
if (multiplier == 0) {
multiplier = slot.getItemStack().getMaxStackSize();
multiplier = StackInfo.itemStackToNBT(slot.getItemStack()).hasKey("gtFluidName") ? 144
: slot.getItemStack().getMaxStackSize();
}
}
@@ -1252,7 +1258,7 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
@Deprecated
public BookmarkRecipeId getBookmarkRecipeId(int itemIndex) {
BookmarkItem item = this.grid.getCalculatedItem(itemIndex);
return item == null || item.isIngredient || item.recipeId == null ? null
return item == null || item.type == BookmarkItemType.INGREDIENT || item.recipeId == null ? null
: new BookmarkRecipeId(item.recipeId.getHandleName(), item.recipeId.getIngredients());
}
@@ -1,10 +1,13 @@
package codechicken.nei;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
@@ -21,10 +24,13 @@ import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiErrorScreen;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiSelectWorld;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.client.resources.IResource;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import net.minecraftforge.client.event.GuiOpenEvent;
import net.minecraftforge.client.event.RenderWorldLastEvent;
@@ -148,6 +154,7 @@ public class ClientHandler {
loadHiddenHandlers();
loadEnableAutoFocus();
loadGuiCraftablesBlacklist();
loadDefaultBookmarkContainers();
ItemInfo.preInit();
StackInfo.loadGuidFilters();
}
@@ -165,11 +172,34 @@ public class ClientHandler {
}, callback);
}
public static void loadSettingsFile(String resource, BiConsumer<File, FileWriter> createDefault,
public static boolean loadSettingsResource(String resource, Consumer<Stream<String>> callback) {
final ResourceLocation location = new ResourceLocation("nei", resource);
try {
final IResource res = Minecraft.getMinecraft().getResourceManager().getResource(location);
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(res.getInputStream(), StandardCharsets.UTF_8))) {
NEIClientConfig.logger.info("Loading '{}' from jar {}", resource, location);
callback.accept(
IOUtils.readLines(reader).stream()
.map(line -> line.contains("#") ? line.substring(0, line.indexOf('#')) : line)
.map(String::trim).filter(line -> !line.isEmpty()));
return true;
}
} catch (Exception io) {
NEIClientConfig.logger.error("Failed to load '{}' file {}", resource, location);
}
return false;
}
public static boolean loadSettingsFile(String resource, BiConsumer<File, FileWriter> createDefault,
Consumer<Stream<String>> callback) {
File file = new File(NEIClientConfig.configDir, resource);
if (!file.exists()) {
if (!file.exists() && createDefault != null) {
try (FileWriter writer = new FileWriter(file)) {
NEIClientConfig.logger.info("Creating default '{}' {}", resource, file);
createDefault.accept(file, writer);
@@ -178,13 +208,20 @@ public class ClientHandler {
}
}
try (FileReader reader = new FileReader(file)) {
NEIClientConfig.logger.info("Loading '{}' file {}", resource, file);
callback.accept(
IOUtils.readLines(reader).stream().filter(line -> !line.startsWith("#") && !line.trim().isEmpty()));
} catch (IOException e) {
NEIClientConfig.logger.error("Failed to load '{}' file {}", resource, file, e);
if (file.exists()) {
try (FileReader reader = new FileReader(file)) {
NEIClientConfig.logger.info("Loading '{}' file {}", resource, file);
callback.accept(
IOUtils.readLines(reader).stream()
.map(line -> line.contains("#") ? line.substring(0, line.indexOf('#')) : line)
.map(String::trim).filter(line -> !line.isEmpty()));
return true;
} catch (IOException e) {
NEIClientConfig.logger.error("Failed to load '{}' file {}", resource, file, e);
}
}
return false;
}
public static void loadSerialHandlers() {
@@ -218,6 +255,20 @@ public class ClientHandler {
lines -> ItemCraftablesPanel.guiBlacklist = lines.collect(Collectors.toList()));
}
public static void loadDefaultBookmarkContainers() {
loadSettingsFile("defaultbookmarkcontainers.cfg", lines -> {
for (String clazz : lines.collect(Collectors.toList())) {
try {
API.registerBookmarkContainerHandler(
(Class<? extends GuiContainer>) Class.forName(clazz),
new DefaultBookmarkContainerHandler());
} catch (Exception e) {
NEIClientConfig.logger.error("Failed to load class '{}' for defaultbookmarkcontainers.cfg", clazz);
}
}
});
}
public static void loadHiddenItems() {
loadSettingsFile("hiddenitems.cfg", lines -> lines.forEach(API::hideItem));
}
@@ -117,12 +117,14 @@ public class FavoriteRecipes {
final RecipeId recipeId = RecipeId.of(jsonObject.getAsJsonObject("recipeId"));
final ItemStack stack = StackInfo.loadFromNBT(itemStackNBT);
if (stack != null) {
final String fluidKey = getFluidKey(stack);
if (recipeId == null || stack == null) {
continue;
}
if (fluidKey != null) {
fluids.put(fluidKey, recipeId);
}
final String fluidKey = getFluidKey(stack);
if (fluidKey != null) {
fluids.put(fluidKey, recipeId);
}
items.put(itemStackNBT, recipeId);
@@ -132,8 +134,8 @@ public class FavoriteRecipes {
}
}
} catch (IllegalArgumentException | JsonSyntaxException | IllegalStateException e) {
NEIClientConfig.logger.error("Failed to load favorite from json string:\n{}", itemStr);
} catch (Exception e) {
NEIClientConfig.logger.error("Failed to load favorite from json string: {}", itemStr);
}
}
@@ -61,6 +61,11 @@ public class FormattedTextField extends GuiTextField {
super.setFocused(focus);
}
@Override
public void setText(String rawText) {
super.setText(EnumChatFormatting.getTextWithoutFormattingCodes(rawText));
}
@Override
public void setSelectionPos(int p_146199_1_) {
String text = this.getText();
@@ -42,13 +42,11 @@ public class HUDRenderer implements IKeyStateTracker {
&& mc.objectMouseOver != null
&& mc.objectMouseOver.typeOfHit == MovingObjectType.BLOCK) {
World world = mc.theWorld;
ItemStack[] items = ItemInfo.getIdentifierItems(world, mc.thePlayer, mc.objectMouseOver)
.toArray(new ItemStack[0]);
final List<ItemStack> items = ItemInfo.getIdentifierItems(world, mc.thePlayer, mc.objectMouseOver);
if (items.length == 0) return;
ItemStack stack = StackInfo.getItemStackWithMinimumDamage(items);
if (items.isEmpty()) return;
final ItemStack stack = StackInfo.getItemStackWithMinimumDamage(items.toArray(new ItemStack[0]));
renderOverlay(stack, ItemInfo.getText(stack, world, mc.thePlayer, mc.objectMouseOver), getPositioning());
}
}
@@ -27,8 +27,8 @@ public class HeldItemHandler implements IContainerInputHandler, IContainerToolti
protected boolean contains(int mousex, int mousey) {
return NEIClientUtils.getHeldItem() != null && !ItemPanels.bookmarkPanel.inEditingState()
&& !AutoCraftingManager.processing()
&& (ItemPanels.bookmarkPanel.contains(mousex, mousey) || ItemPanels.itemPanel.contains(mousex, mousey)
|| ItemPanels.itemPanel.historyPanel.contains(mousex, mousey));
&& (ItemPanels.bookmarkPanel.contains(mousex, mousey)
|| ItemPanels.itemPanel.containsWithSubpanels(mousex, mousey));
}
@Override
@@ -7,14 +7,27 @@ import net.minecraft.item.ItemStack;
import codechicken.nei.ItemsGrid.ItemsGridSlot;
import codechicken.nei.ItemsGrid.MouseContext;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.recipe.StackInfo;
public class ItemHistoryPanel extends AbstractSubpanel<ItemsGrid<ItemsGridSlot, MouseContext>> {
public class ItemHistoryPanel extends AbstractSubpanel<ItemsGrid<ItemHistoryPanel.HistoryGridSlot, MouseContext>> {
public static class HistoryGridSlot extends ItemsGridSlot {
public HistoryGridSlot(int slotIndex, int itemIndex, ItemStack item) {
super(slotIndex, itemIndex, item);
}
@Override
public RecipeId getRecipeId() {
return FavoriteRecipes.getFavorite(this.item);
}
}
public ItemHistoryPanel() {
this.grid = new ItemsGrid<>() {
protected List<ItemsGridSlot> gridMask;
protected List<HistoryGridSlot> gridMask;
@Override
protected void onGridChanged() {
@@ -23,12 +36,12 @@ public class ItemHistoryPanel extends AbstractSubpanel<ItemsGrid<ItemsGridSlot,
}
@Override
public List<ItemsGridSlot> getMask() {
public List<HistoryGridSlot> getMask() {
if (this.gridMask == null) {
this.gridMask = new ArrayList<>();
for (int slotIndex = 0; slotIndex < Math.min(size(), this.rows * this.columns); slotIndex++) {
this.gridMask.add(new ItemsGridSlot(slotIndex, slotIndex, getItem(slotIndex)));
this.gridMask.add(new HistoryGridSlot(slotIndex, slotIndex, getItem(slotIndex)));
}
}
@@ -37,7 +50,7 @@ public class ItemHistoryPanel extends AbstractSubpanel<ItemsGrid<ItemsGridSlot,
@Override
protected MouseContext getMouseContext(int mousex, int mousey) {
final ItemsGridSlot hovered = getSlotMouseOver(mousex, mousey);
final HistoryGridSlot hovered = getSlotMouseOver(mousex, mousey);
if (hovered != null) {
return new MouseContext(
@@ -16,10 +16,12 @@ import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import net.minecraft.client.Minecraft;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.IIcon;
import net.minecraftforge.fluids.IFluidContainerItem;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
@@ -30,6 +32,8 @@ import codechicken.nei.api.ItemFilter.ItemFilterProvider;
import codechicken.nei.api.ItemInfo;
import codechicken.nei.recipe.InformationHandler;
import codechicken.nei.search.TooltipFilter;
import codechicken.nei.util.ItemUntranslator;
import cpw.mods.fml.common.FMLLog;
public class ItemList {
@@ -101,6 +105,12 @@ public class ItemList {
return true;
}
displayName = ItemUntranslator.getInstance().getItemStackDisplayName(item);
if (!displayName.isEmpty() && this.pattern.matcher(displayName).find()) {
return true;
}
if (item.hasDisplayName()) {
displayName = EnumChatFormatting
.getTextWithoutFormattingCodes(item.getItem().getItemStackDisplayName(item));
@@ -290,6 +300,64 @@ public class ItemList {
.collect(Collectors.toList());
}
private void runChecked(ItemStack stack, Runnable action, String reason) {
int hashOld = 0;
if (stack.hasTagCompound()) {
hashOld = stack.stackTagCompound.hashCode();
}
action.run();
if (stack.hasTagCompound() && hashOld != stack.stackTagCompound.hashCode()) {
FMLLog.warning(
"NEI: Forced tag update with reason (" + reason
+ ") for "
+ stack
+ "("
+ stack.getItem()
+ ")");
}
}
private void forceTagCompoundInitialization(ItemStack stack) {
Item item = stack.getItem();
if (item == null) {
return;
}
if (item instanceof IFluidContainerItem) {
IFluidContainerItem fluidItem = (IFluidContainerItem) item;
runChecked(stack, () -> fluidItem.getFluid(stack), "getFluid");
}
runChecked(stack, () -> item.isDamaged(stack), "isDamaged");
runChecked(stack, () -> item.getDamage(stack), "getDamage");
runChecked(stack, () -> item.showDurabilityBar(stack), "showDurabilityBar");
runChecked(stack, () -> item.getAttributeModifiers(stack), "getAttributeModifiers");
runChecked(stack, () -> item.getDurabilityForDisplay(stack), "getDurabilityForDisplay");
runChecked(stack, () -> item.getItemStackLimit(stack), "getItemStackLimit");
runChecked(stack, () -> item.getToolClasses(stack), "getToolClasses");
runChecked(stack, () -> item.getUnlocalizedNameInefficiently(stack), "getUnlocalizedNameInefficiently");
runChecked(stack, () -> item.hasEffect(stack), "hasEffect");
runChecked(stack, () -> item.getDigSpeed(stack, Blocks.stone, 0), "getDigSpeed");
/*
* unused... for now runChecked(stack, () -> GameRegistry.getFuelValue(stack), "getFuelValue");
* runChecked(stack, () -> item.getUnlocalizedName(stack), "getUnlocalizedName"); runChecked(stack, () ->
* item.doesContainerItemLeaveCraftingGrid(stack), "doesContainerItemLeaveCraftingGrid"); runChecked(stack,
* () -> item.getItemUseAction(stack), "getItemUseAction"); runChecked(stack, () ->
* item.getMaxItemUseDuration(stack), "getMaxItemUseDuration"); runChecked(stack, () ->
* item.getPotionEffect(stack), "getPotionEffect"); runChecked(stack, () -> item.isPotionIngredient(stack),
* "isPotionIngredient"); runChecked(stack, () -> item.getRarity(stack), "getRarity"); runChecked(stack, ()
* -> item.hasCustomEntity(stack), "hasCustomEntity"); runChecked(stack, () ->
* item.getSmeltingExperience(stack), "getSmeltingExperience"); runChecked(stack, () ->
* item.getMaxDamage(stack), "getMaxDamage"); runChecked(stack, () -> item.getDamage(stack), "getDamage");
* runChecked(stack, stack::isItemDamaged, "isItemDamaged"); runChecked(stack, () -> item.hasEffect(stack,
* 0), "hasEffect"); runChecked(stack, () -> item.getItemEnchantability(stack), "getItemEnchantability");
* runChecked(stack, () -> item.isBeaconPayment(stack), "isBeaconPayment"); runChecked(stack, () ->
* item.getDamage(stack), "getDamage"); runChecked(stack, () -> item.getDamage(stack), "getDamage");
* runChecked(stack, () -> item.getDamage(stack), "getDamage");
*/
}
// Generate itemlist, permutations, orders, collapsibleitems, and informationhandler stacks
@Override
@SuppressWarnings("unchecked")
@@ -329,6 +397,8 @@ public class ItemList {
items.add(stack);
}
forceTagCompoundInitialization(stack);
CollapsibleItems.putItem(stack);
TooltipFilter.getSearchTooltip(stack);
InformationHandler.populateStacks(stack);
+9 -5
View File
@@ -222,8 +222,7 @@ public class ItemPanel extends PanelWidget<ItemsPanelGrid> {
}
@Override
public List<String> handleItemTooltip(GuiContainer gui, ItemStack itemstack, int mousex, int mousey,
List<String> currenttip) {
public List<String> handleItemTooltip(ItemStack itemstack, int mousex, int mousey, List<String> currenttip) {
if (!this.grid.forceExpand && !currenttip.isEmpty()) {
final ItemsPanelGridSlot hoverSlot = this.grid.getSlotMouseOver(mousex, mousey);
@@ -237,7 +236,7 @@ public class ItemPanel extends PanelWidget<ItemsPanelGrid> {
}
}
return super.handleItemTooltip(gui, itemstack, mousex, mousey, currenttip);
return super.handleItemTooltip(itemstack, mousex, mousey, currenttip);
}
@Override
@@ -258,7 +257,7 @@ public class ItemPanel extends PanelWidget<ItemsPanelGrid> {
}
@Override
public Map<String, String> handleHotkeys(GuiContainer gui, int mousex, int mousey, Map<String, String> hotkeys) {
public Map<String, String> handleHotkeys(int mousex, int mousey, Map<String, String> hotkeys) {
final ItemsPanelGridSlot hoverSlot = this.grid.getSlotMouseOver(mousex, mousey);
if (!this.grid.forceExpand && hoverSlot != null && hoverSlot.groupIndex >= 0 && hoverSlot.groupSize > 1) {
@@ -269,7 +268,12 @@ public class ItemPanel extends PanelWidget<ItemsPanelGrid> {
NEIClientUtils.translate(message, hoverSlot.groupSize));
}
return hotkeys;
return super.handleHotkeys(mousex, mousey, hotkeys);
}
public boolean containsWithSubpanels(int px, int py) {
return contains(px, py) || NEIClientConfig.showHistoryPanelWidget() && this.historyPanel.contains(px, py)
|| NEIClientConfig.showCraftablesPanelWidget() && this.craftablesPanel.contains(px, py);
}
}
+1 -1
View File
@@ -58,7 +58,7 @@ public class ItemZoom extends Widget implements IContainerInputHandler {
GL11.glPopMatrix();
GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_LIGHTING_BIT);
GuiContainerManager.enable2DRender();
if (NEIClientConfig.getBooleanSetting("inventory.itemzoom.showName")) {
+1 -15
View File
@@ -52,7 +52,7 @@ public abstract class ItemsGrid<T extends ItemsGrid.ItemsGridSlot, M extends Ite
}
public void captureScreen(Runnable callback, int mode) {
GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_LIGHTING_BIT);
resetFramebuffer();
this.framebuffer.bindFramebuffer(false);
@@ -281,8 +281,6 @@ public abstract class ItemsGrid<T extends ItemsGrid.ItemsGridSlot, M extends Ite
protected boolean[] invalidSlotMap;
protected Label messageLabel = new Label(getMessageOnEmpty(), true);
protected ScreenCapture screenCapture = null;
public ArrayList<ItemStack> getItems() {
@@ -360,9 +358,6 @@ public abstract class ItemsGrid<T extends ItemsGrid.ItemsGridSlot, M extends Ite
rows = height / SLOT_SIZE;
paddingLeft = (width % SLOT_SIZE) / 2;
messageLabel.x = marginLeft + width / 2;
messageLabel.y = marginTop + height / 2;
}
public void shiftPage(int shift) {
@@ -566,12 +561,6 @@ public abstract class ItemsGrid<T extends ItemsGrid.ItemsGridSlot, M extends Ite
afterDrawItems(mousex, mousey, mouseContext);
}
public void setVisible() {
if (getItems().isEmpty() && getMessageOnEmpty() != null) {
LayoutManager.addWidget(messageLabel);
}
}
public boolean contains(int px, int py) {
final Rectangle4i rect = new Rectangle4i(
marginLeft + paddingLeft,
@@ -586,7 +575,4 @@ public abstract class ItemsGrid<T extends ItemsGrid.ItemsGridSlot, M extends Ite
return !isInvalidSlot(columns * getRowIndex(py) + getColumnIndex(px));
}
public String getMessageOnEmpty() {
return null;
}
}
@@ -11,6 +11,7 @@ import java.util.Set;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.item.ItemStack;
import codechicken.lib.gui.GuiDraw;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.ItemsGrid.ItemsGridSlot;
import codechicken.nei.guihook.GuiContainerManager;
@@ -237,9 +238,18 @@ public class ItemsPanelGrid extends ItemsGrid<ItemsPanelGrid.ItemsPanelGridSlot,
Math.min((int) (color.getAlpha() + (255f / 5) * 2), 255));
}
@Override
public String getMessageOnEmpty() {
return ItemList.loadFinished ? null : NEIClientUtils.translate("itempanel.loading");
public void draw(int mousex, int mousey) {
if (ItemList.loadFinished) {
super.draw(mousex, mousey);
} else {
GuiDraw.drawStringC(
NEIClientUtils
.cropText(GuiDraw.fontRenderer, NEIClientUtils.translate("itempanel.loading"), width - 10),
marginLeft + width / 2,
marginTop + height / 2,
0xffffff,
true);
}
}
}
@@ -70,8 +70,8 @@ public class ItemsTooltipLineHandler implements ITooltipLineHandler {
}
public void setActiveStack(ItemStack activeStack) {
final ItemStack realStack = items.stream().filter(stack -> StackInfo.equalItemAndNBT(stack, activeStack, true))
.findFirst().orElse(null);
final ItemStack realStack = items.stream()
.filter(stack -> NEIClientUtils.areStacksSameTypeWithNBT(stack, activeStack)).findFirst().orElse(null);
this.activeStackIndex = items.indexOf(realStack);
}
@@ -100,13 +100,15 @@ public class ItemsTooltipLineHandler implements ITooltipLineHandler {
fontRenderer.drawStringWithShadow(this.labelColor + this.label + ":", x, y, 0);
GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
GL11.glPushMatrix();
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_LIGHTING_BIT);
RenderHelper.enableGUIStandardItemLighting();
GL11.glScaled(1, 1, 3);
GL11.glTranslatef(x, y + fontRenderer.FONT_HEIGHT + 2, 0);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
final int xTranslation = x;
final int yTranslation = y + fontRenderer.FONT_HEIGHT + 2;
final int zTranslation = GuiContainerManager.TOOLTIP_Z_OFFSET;
GL11.glTranslatef(xTranslation, yTranslation, zTranslation);
int indexShift = 0;
@@ -142,7 +144,7 @@ public class ItemsTooltipLineHandler implements ITooltipLineHandler {
});
}
GL11.glPopMatrix();
GL11.glTranslatef(-xTranslation, -yTranslation, -zTranslation);
GL11.glPopAttrib();
}
@@ -31,7 +31,7 @@ public class KeyManager {
public static void tickKeyStates() {
for (Entry<String, KeyState> entry : keyStates.entrySet()) {
final int keyCode = NEIKeyboardUtils.unhash(NEIClientConfig.getKeyBinding(entry.getKey()));
final boolean down = keyCode < Keyboard.KEYBOARD_SIZE ? Keyboard.isKeyDown(keyCode) : null;
final boolean down = keyCode > 0 && keyCode < Keyboard.KEYBOARD_SIZE && Keyboard.isKeyDown(keyCode);
final KeyState state = entry.getValue();
if (down) {
@@ -66,6 +66,7 @@ import codechicken.nei.guihook.IContainerInputHandler;
import codechicken.nei.guihook.IContainerObjectHandler;
import codechicken.nei.guihook.IContainerTooltipHandler;
import codechicken.nei.recipe.AutoCraftingManager;
import codechicken.nei.recipe.DebugHandlerWidget;
import codechicken.nei.recipe.GuiRecipeTab;
import codechicken.nei.recipe.RecipeCatalysts;
@@ -91,6 +92,7 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
public static SubsetWidget dropDown;
public static SearchField searchField;
public static ItemZoom itemZoom;
public static DebugHandlerWidget recipeHandlerWidget;
public static ButtonCycled options;
public static ButtonCycled bookmarksButton;
@@ -291,19 +293,6 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
}
}
@Override
public void postRenderTooltips(GuiContainer gui, int mousex, int mousey, List<String> tooltip) {
if (!isHidden() && isEnabled() && GuiContainerManager.shouldShowTooltip(gui)) {
final Widget focused = getWidgetUnderMouse(mousex, mousey);
if (focused != null) {
focused.postDrawTooltips(mousex, mousey, tooltip);
}
}
}
@Override
public List<String> handleTooltip(GuiContainer gui, int mousex, int mousey, List<String> currenttip) {
@@ -354,6 +343,10 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
if (!isHidden() && isEnabled() && GuiContainerManager.shouldShowTooltip(gui)) {
final Widget focused = getWidgetUnderMouse(mousex, mousey);
if (focused != null) {
currenttip = focused.handleItemTooltip(itemstack, mousex, mousey, currenttip);
}
if (focused instanceof IContainerTooltipHandler tip) {
currenttip = tip.handleItemTooltip(gui, itemstack, mousex, mousey, currenttip);
}
@@ -368,9 +361,14 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
if (!isHidden() && isEnabled() && GuiContainerManager.shouldShowTooltip(gui)) {
final Widget focused = getWidgetUnderMouse(mousex, mousey);
if (focused instanceof IContainerTooltipHandler tip) {
hotkeys = tip.handleHotkeys(gui, mousex, mousey, hotkeys);
if (focused != null) {
hotkeys = focused.handleHotkeys(mousex, mousey, hotkeys);
if (focused instanceof IContainerTooltipHandler tip) {
hotkeys = tip.handleHotkeys(gui, mousex, mousey, hotkeys);
}
}
}
return hotkeys;
@@ -408,6 +406,8 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
itemZoom = new ItemZoom();
recipeHandlerWidget = new DebugHandlerWidget();
dropDown = new SubsetWidget();
searchField = new SearchField("search");
API.addItemFilter(searchField);
@@ -783,9 +783,11 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
addWidget(itemZoom);
if (visiblity.showSubsetDropdown) {
// Bookmarks or Subset/dropdown
addWidget(dropDown);
}
addWidget(recipeHandlerWidget);
recipeHandlerWidget.setVisible();
}
public static LayoutStyle getLayoutStyle(int id) {
@@ -905,6 +907,9 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
final int ty2 = ty + 20 - h2 - te;
final int tx2 = 200 - w2 - te;
final boolean is2DTexture = GL11.glGetBoolean(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_TEXTURE_2D);
changeTexture("textures/gui/widgets.png");
drawTexturedModalRect(x, y, tx1, ty1, w1, h1); // top left
drawTexturedModalRect(x, y2, tx1, ty2, w1, h2); // bottom left
@@ -917,6 +922,8 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
drawTexturedModalRect(x2, y, tx2, ty1, w2, h1); // top right
drawTexturedModalRect(x2, y2, tx2, ty2, w2, h2); // bottom right
if (!is2DTexture) GL11.glDisable(GL11.GL_TEXTURE_2D);
}
public static void drawItemPresenceOverlay(int slotX, int slotY, boolean isPresent, boolean slotHighlight) {
@@ -56,11 +56,13 @@ import codechicken.nei.config.OptionToggleButtonBoubs;
import codechicken.nei.config.OptionUtilities;
import codechicken.nei.config.preset.GuiPresetList;
import codechicken.nei.event.NEIConfigsLoadedEvent;
import codechicken.nei.recipe.DebugHandlerWidget;
import codechicken.nei.recipe.GuiRecipeTab;
import codechicken.nei.recipe.IRecipeHandler;
import codechicken.nei.recipe.InformationHandler;
import codechicken.nei.recipe.RecipeCatalysts;
import codechicken.nei.recipe.RecipeInfo;
import codechicken.nei.util.ItemUntranslator;
import codechicken.nei.util.NEIKeyboardUtils;
import codechicken.obfuscator.ObfuscationRun;
@@ -146,6 +148,8 @@ public class NEIClientConfig {
tag.getTag("inventory.widgetsenabled").getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.widgetsenabled"));
tag.getTag("findFuelsParallel").getBooleanValue(true);
tag.getTag("inventory.autocrafting").getBooleanValue(true);
tag.getTag("inventory.dynamicFontSize").getBooleanValue(true);
tag.getTag("inventory.hidden").getBooleanValue(false);
@@ -206,6 +210,10 @@ public class NEIClientConfig {
0,
OptionIntegerField.UNSIGNED_INT_MAX));
tag.getTag("inventory.bookmarks.showRecipeHandlerIcon").setComment("Show Recipe Handler Icon")
.getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.bookmarks.showRecipeHandlerIcon", true));
tag.getTag("inventory.bookmarks.recipeChainDir").getIntValue(1);
API.addOption(new OptionCycled("inventory.bookmarks.recipeChainDir", 2, true));
@@ -217,17 +225,17 @@ public class NEIClientConfig {
.getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.bookmarks.bookmarkItemsWithRecipe", true));
tag.getTag("inventory.bookmarks.bookmarkRecipeWithCount").setComment("Bookmark recipe with count")
.getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.bookmarks.bookmarkRecipeWithCount", true));
tag.getTag("inventory.guirecipe.jeiStyleTabs").setComment("Enable/disable JEI Style Tabs")
.getBooleanValue(true);
API.addOption(new OptionToggleButtonBoubs("inventory.guirecipe.jeiStyleTabs", true));
tag.getTag("inventory.guirecipe.jeiStyleRecipeCatalyst").setComment("Enable/disable JEI Style Recipe Catalysts")
.getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.guirecipe.jeiStyleRecipeCatalyst", true));
tag.getTag("inventory.guirecipe.jeiStyleCycledIngredients").setComment("JEI styled cycled ingredients")
.getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.guirecipe.jeiStyleCycledIngredients", true));
tag.getTag("inventory.guirecipe.jeiStyleRecipeCatalyst")
.setComment("JEI Style Recipe Catalysts (0 - none, 1 - grid, 2 - scroll)").getIntValue(1);
API.addOption(new OptionCycled("inventory.guirecipe.jeiStyleRecipeCatalyst", 3, true));
tag.getTag("inventory.guirecipe.cycledIngredientsTooltip").setComment("Show cycled ingredients tooltip")
.getBooleanValue(true);
@@ -245,6 +253,13 @@ public class NEIClientConfig {
.getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.guirecipe.slotHighlightPresent", true));
tag.getTag("inventory.guirecipe.infiniteScroll").setComment("Use Infinite Scroll for Handlers")
.getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.guirecipe.infiniteScroll", true));
tag.getTag("inventory.guirecipe.maxHeight").setComment("Recipe GUI Max Height").getIntValue(370);
API.addOption(new OptionIntegerField("inventory.guirecipe.maxHeight", 166, 4000));
tag.getTag("inventory.guirecipe.shiftOverlayRecipe")
.setComment("Require holding shift to move items when overlaying recipe").getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.guirecipe.shiftOverlayRecipe", true));
@@ -252,6 +267,10 @@ public class NEIClientConfig {
tag.getTag("inventory.guirecipe.profile").getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.guirecipe.profile", true));
tag.getTag("inventory.guirecipe.handlerInfo").setComment("ADVANCED: Handler Info Widget")
.getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.guirecipe.handlerInfo", true));
tag.getTag("inventory.subsets.enabled").setComment("Enable/disable Subsets Dropdown").getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.subsets.enabled", true));
@@ -424,6 +443,24 @@ public class NEIClientConfig {
tag.getTag("inventory.autocrafting").setComment("Autocrafting").getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.autocrafting", true));
tag.getTag("inventory.itemUntranslator").setComment("Item Untranslator").getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.itemUntranslator", true) {
@Override
public boolean onClick(int button) {
super.onClick(button);
if (enableItemUntranslator()) {
ItemUntranslator.getInstance().load();
} else {
ItemUntranslator.getInstance().unload();
}
return true;
}
});
tag.getTag("tools.handler_load_from_config").setComment("ADVANCED: Load handlers from config")
.getBooleanValue(false);
API.addOption(new OptionToggleButton("tools.handler_load_from_config", true) {
@@ -801,6 +838,7 @@ public class NEIClientConfig {
API.addKeyBind("world.creative", 0);
API.addHashBind("gui.copy_name", Keyboard.KEY_C + NEIClientUtils.CTRL_HASH);
API.addHashBind("gui.copy_oredict", Keyboard.KEY_D + NEIClientUtils.CTRL_HASH);
API.addHashBind("gui.copy_id", Keyboard.KEY_X + NEIClientUtils.CTRL_HASH);
API.addHashBind("gui.chat_link_item", Keyboard.KEY_L + NEIClientUtils.CTRL_HASH);
}
@@ -861,6 +899,10 @@ public class NEIClientConfig {
}
public static void unloadWorld() {
if (world == null) {
return;
}
if (ItemPanels.bookmarkPanel != null) {
ItemPanels.bookmarkPanel.save();
}
@@ -871,6 +913,8 @@ public class NEIClientConfig {
if (world != null) {
world.saveNBT();
NEIClientConfig.worldPath = null;
world = null;
}
}
@@ -968,6 +1012,7 @@ public class NEIClientConfig {
pluginNEIConfigLoaded = true;
MinecraftForge.EVENT_BUS.post(new NEIConfigsLoadedEvent());
DebugHandlerWidget.loadHandlerInfoPatch();
ItemList.loadItems.restart();
}
}.start();
@@ -1064,8 +1109,8 @@ public class NEIClientConfig {
return getBooleanSetting("inventory.guirecipe.slotHighlightPresent");
}
public static boolean areJEIStyleRecipeCatalystsVisible() {
return getBooleanSetting("inventory.guirecipe.jeiStyleRecipeCatalyst");
public static int getJEIStyleRecipeCatalysts() {
return getIntSetting("inventory.guirecipe.jeiStyleRecipeCatalyst");
}
public static boolean useCreativeTabStyle() {
@@ -1084,10 +1129,6 @@ public class NEIClientConfig {
return getBooleanSetting("inventory.optimize_gui_overlap_computation");
}
public static boolean useJEIStyledCycledIngredients() {
return getBooleanSetting("inventory.guirecipe.jeiStyleCycledIngredients");
}
public static boolean showCycledIngredientsTooltip() {
return getBooleanSetting("inventory.guirecipe.cycledIngredientsTooltip");
}
@@ -1208,6 +1249,10 @@ public class NEIClientConfig {
return getBooleanSetting("inventory.collapsibleItems.enabled");
}
public static boolean enableItemUntranslator() {
return getBooleanSetting("inventory.itemUntranslator");
}
public static boolean getMagnetMode() {
return enabledActions.contains("magnet");
}
@@ -528,7 +528,9 @@ public class NEIClientUtils extends NEIServerUtils {
}
public static void drawRect(double left, double top, double width, double height, Color color) {
Tessellator tessellator = Tessellator.instance;
final boolean is2DTexture = GL11.glGetBoolean(GL11.GL_TEXTURE_2D);
final boolean isBlend = GL11.glGetBoolean(GL11.GL_BLEND);
final Tessellator tessellator = Tessellator.instance;
GL11.glEnable(GL11.GL_BLEND);
GL11.glDisable(GL11.GL_TEXTURE_2D);
@@ -540,8 +542,9 @@ public class NEIClientUtils extends NEIServerUtils {
tessellator.addVertex(left + width, top, 0.0D);
tessellator.addVertex(left, top, 0.0D);
tessellator.draw();
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glDisable(GL11.GL_BLEND);
GL11.glColor4f(1, 1, 1, 1);
if (is2DTexture) GL11.glEnable(GL11.GL_TEXTURE_2D);
if (!isBlend) GL11.glDisable(GL11.GL_BLEND);
}
public static void drawNEIOverlayText(String text, Rectangle4i rect, float scale, int color, boolean shadow,
@@ -21,6 +21,7 @@ import codechicken.nei.api.INEIGuiHandler;
import codechicken.nei.api.ItemInfo;
import codechicken.nei.commands.CommandBookmarkAdd;
import codechicken.nei.commands.CommandRecipeId;
import codechicken.nei.commands.CommandUntranslator;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.guihook.IContainerInputHandler;
import codechicken.nei.guihook.IContainerSlotClickHandler;
@@ -68,6 +69,7 @@ public class NEIController implements IContainerSlotClickHandler, IContainerInpu
public static void registerClientCommands() {
ClientCommandHandler.instance.registerCommand(new CommandBookmarkAdd());
ClientCommandHandler.instance.registerCommand(new CommandRecipeId());
ClientCommandHandler.instance.registerCommand(new CommandUntranslator());
}
public static void updateUnlimitedItems(InventoryPlayer inventory) {
@@ -136,7 +138,7 @@ public class NEIController implements IContainerSlotClickHandler, IContainerInpu
return true;
}
if (button == 1 && slot instanceof SlotCrafting) // right click
if (button == 1 && modifier != 2 && slot instanceof SlotCrafting) // right click
{
for (int i1 = 0; i1 < 64; i1++) // click this slot 64 times
manager.handleSlotClick(slot.slotNumber, button, 0);
+3 -12
View File
@@ -11,14 +11,12 @@ import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.ItemsGrid.ItemsGridSlot;
import codechicken.nei.api.GuiInfo;
import codechicken.nei.api.INEIGuiHandler;
import codechicken.nei.api.ShortcutInputHandler;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.guihook.IContainerTooltipHandler;
import codechicken.nei.recipe.GuiCraftingRecipe;
import codechicken.nei.recipe.GuiRecipe;
import codechicken.nei.recipe.GuiUsageRecipe;
public abstract class PanelWidget<T extends ItemsGrid<? extends ItemsGridSlot, ? extends ItemsGrid.MouseContext>>
extends Widget implements IContainerTooltipHandler {
extends Widget {
protected static final int PADDING = 2;
@@ -147,7 +145,6 @@ public abstract class PanelWidget<T extends ItemsGrid<? extends ItemsGridSlot, ?
LayoutManager.addWidget(pagePrev);
LayoutManager.addWidget(pageNext);
LayoutManager.addWidget(pageLabel);
this.grid.setVisible();
}
}
@@ -285,13 +282,7 @@ public abstract class PanelWidget<T extends ItemsGrid<? extends ItemsGridSlot, ?
if (NEIController.manager.window instanceof GuiRecipe || NEIClientUtils.shiftKey()
|| !NEIClientConfig.canCheatItem(hoverSlot.getItemStack())) {
if (button == 0) {
GuiCraftingRecipe.openRecipeGui("item", hoverSlot.getItemStack().copy());
} else if (button == 1) {
GuiUsageRecipe.openRecipeGui("item", hoverSlot.getItemStack().copy());
}
ShortcutInputHandler.handleMouseClick(hoverSlot.getItemStack());
} else {
NEIClientUtils.cheatItem(getDraggedStackWithQuantity(hoverSlot.getItemStack()), button, -1);
}
@@ -114,16 +114,25 @@ public class PositionedStack {
return filteredItems.isEmpty() ? items : filteredItems;
}
public boolean setPermutationToRender(ItemStack ingredient) {
public int getPermutationIndex(ItemStack stack) {
for (int index = 0; index < this.items.length; index++) {
if (NEIServerUtils.areStacksSameTypeCraftingWithNBT(this.items[index], ingredient)) {
setPermutationToRender(index);
return true;
if (NEIServerUtils.areStacksSameTypeCraftingWithNBT(items[index], stack)) {
return index;
}
}
return false;
return -1;
}
public boolean setPermutationToRender(ItemStack ingredient) {
final int stackIndex = getPermutationIndex(ingredient);
if (stackIndex >= 0) {
setPermutationToRender(stackIndex);
}
return stackIndex >= 0;
}
public void setPermutationToRender(int index) {
@@ -136,6 +145,10 @@ public class PositionedStack {
}
}
public boolean contains(int mx, int my) {
return this.relx <= mx && this.rely <= my && this.relx + 16 >= mx && this.rely + 16 >= my;
}
public boolean contains(ItemStack ingredient) {
for (ItemStack item : items) if (NEIServerUtils.areStacksSameTypeCrafting(item, ingredient)) return true;
@@ -23,6 +23,7 @@ public abstract class RecipeSearchField extends TextField implements ItemFilterP
final GuiSearchField field = new GuiSearchField();
field.setMaxStringLength(maxSearchLength);
field.setCursorPositionZero();
field.setSkipRecipeTokens(true);
((SearchTextFormatter) field.getFormatter()).setContextToken("<>");
this.field = field;
}
@@ -93,6 +93,7 @@ public class SearchField extends TextField implements ItemFilterProvider {
public static class GuiSearchField extends FormattedTextField implements ItemFilterProvider, IRecipeFilterProvider {
protected final SearchTokenParser searchParser;
protected boolean skipRecipeTokens = false;
public GuiSearchField() {
this(SearchField.searchParser);
@@ -106,6 +107,10 @@ public class SearchField extends TextField implements ItemFilterProvider {
setPlaceholder(NEIClientUtils.translate("inventory.search.placeholder"));
}
public void setSkipRecipeTokens(boolean skipRecipeTokens) {
this.skipRecipeTokens = skipRecipeTokens;
}
@Override
public ItemFilter getFilter() {
return getFilter(getText());
@@ -117,7 +122,7 @@ public class SearchField extends TextField implements ItemFilterProvider {
}
public ItemFilter getFilter(String filterText) {
return this.searchParser.getFilter(filterText);
return this.searchParser.getFilter(filterText, this.skipRecipeTokens);
}
public IRecipeFilter getRecipeFilter(String filterText) {
@@ -29,7 +29,7 @@ public class SearchTextFormatter implements TextFormatter {
text = SearchTokenParser.SPACE_PATTERN.matcher(text).replaceAll("\\\\ ");
}
final SearchExpressionFormatVisitor visitor = new SearchExpressionFormatVisitor(searchParser);
return SearchExpressionUtils.visitSearchExpression(text, visitor);
return SearchExpressionUtils.visitRecipeSearchExpression(text, visitor);
} else {
final StringBuilder formattedText = new StringBuilder();
@@ -42,7 +42,9 @@ public class SearchTextFormatter implements TextFormatter {
if (!contextPart[0].isEmpty()) {
formattedText.append(
SearchExpressionUtils.HIGHLIGHTS.RECIPE + contextPart[0] + EnumChatFormatting.RESET);
SearchExpressionUtils.HIGHLIGHTS.RECIPE + contextPart[0].substring(0, 1)
+ EnumChatFormatting.RESET);
contextPart[1] = contextPart[0].substring(1) + contextPart[1];
}
if (contextPart[1].isEmpty()) {
@@ -122,10 +122,8 @@ public class SearchTokenParser {
Language currentLanguage = Minecraft.getMinecraft().getLanguageManager().getCurrentLanguage();
if (!currentLanguage.getLanguageCode().equals(providersCache.languageCode)) {
providersCache.providers = new ArrayList<>();
providersCache.languageCode = currentLanguage.getLanguageCode();
Map<Character, ISearchParserProvider> providers = new HashMap<>();
final List<ISearchParserProvider> providersList = new ArrayList<>();
final Map<Character, ISearchParserProvider> providers = new HashMap<>();
for (int index = this.searchProviders.size() - 1; index >= 0; index--) {
ISearchParserProvider provider = this.searchProviders.get(index);
@@ -134,12 +132,14 @@ public class SearchTokenParser {
if (provider.getSearchMode() == SearchMode.PREFIX && !providers.containsKey(provider.getPrefix())) {
providers.put(provider.getPrefix(), provider);
} else if (provider.getSearchMode() == SearchMode.ALWAYS) {
providersCache.providers.add(provider);
providersList.add(provider);
}
}
}
providersCache.providers.addAll(providers.values());
providersList.addAll(providers.values());
providersCache.languageCode = currentLanguage.getLanguageCode();
providersCache.providers = providersList;
}
return providersCache.providers;
@@ -173,7 +173,11 @@ public class SearchTokenParser {
}
public synchronized ItemFilter getFilter(String filterText) {
filterText = EnumChatFormatting.getTextWithoutFormattingCodes(filterText).toLowerCase();
return getFilter(filterText, false);
}
public synchronized ItemFilter getFilter(String rawText, boolean skipRecipeTokens) {
final String filterText = EnumChatFormatting.getTextWithoutFormattingCodes(rawText).toLowerCase();
if (filterText == null || filterText.isEmpty()) {
return new EverythingItemFilter();
@@ -182,10 +186,10 @@ public class SearchTokenParser {
final int patternMode = NEIClientConfig.getIntSetting("inventory.search.patternMode");
if (patternMode != 3) {
return this.filtersCache.computeIfAbsent(filterText, text -> {
return this.filtersCache.computeIfAbsent(skipRecipeTokens + ":" + filterText, _t -> {
final List<ItemFilter> searchTokens = new ArrayList<>();
for (String[] subQuery : splitByDelimiters(text, "|", false)) {
for (String[] subQuery : splitByDelimiters(filterText, "|", false)) {
if (subQuery[1].isEmpty()) {
continue;
@@ -193,11 +197,22 @@ public class SearchTokenParser {
final List<ItemFilter> tokens = new ArrayList<>();
for (SearchToken token : splitSearchText(subQuery[1])) {
final ItemFilter result = token.getFilter(this);
for (String[] contextQuery : splitByDelimiters(subQuery[1], skipRecipeTokens ? "<>" : "", false)) {
if (result != null) {
tokens.add(result);
if (contextQuery[1].isEmpty() || contextQuery[0].startsWith(">")) {
continue;
}
if (!contextQuery[0].isEmpty()) {
contextQuery[0] = contextQuery[0].substring(1);
}
for (SearchToken token : splitSearchText(contextQuery[0] + contextQuery[1])) {
final ItemFilter result = token.getFilter(this);
if (result != null) {
tokens.add(result);
}
}
}
@@ -223,9 +238,13 @@ public class SearchTokenParser {
if (spaceMode == 1) {
text = SearchTokenParser.SPACE_PATTERN.matcher(text).replaceAll("\\\\ ");
}
return new IsRegisteredItemFilter(
SearchExpressionUtils.visitSearchExpression(text, new ItemFilterVisitor(this)));
if (skipRecipeTokens) {
return new IsRegisteredItemFilter(
SearchExpressionUtils.visitRecipeSearchExpression(text, new ItemFilterVisitor(this)));
} else {
return new IsRegisteredItemFilter(
SearchExpressionUtils.visitSearchExpression(text, new ItemFilterVisitor(this)));
}
});
}
@@ -305,7 +324,7 @@ public class SearchTokenParser {
text = SearchTokenParser.SPACE_PATTERN.matcher(text).replaceAll("\\\\ ");
}
return SearchExpressionUtils.visitSearchExpression(text, new RecipeFilterVisitor(this));
return SearchExpressionUtils.visitRecipeSearchExpression(text, new RecipeFilterVisitor(this));
});
}
@@ -18,7 +18,6 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
@@ -40,7 +39,6 @@ import codechicken.nei.api.API;
import codechicken.nei.api.ItemFilter;
import codechicken.nei.api.ItemFilter.ItemFilterProvider;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.guihook.IContainerTooltipHandler;
import codechicken.nei.recipe.GuiCraftingRecipe;
import codechicken.nei.recipe.GuiRecipeTab;
import codechicken.nei.recipe.ICraftingHandler;
@@ -49,7 +47,7 @@ import codechicken.nei.recipe.StackInfo;
import codechicken.nei.util.NBTJson;
import codechicken.nei.util.NEIMouseUtils;
public class SubsetWidget extends Button implements ItemFilterProvider, IContainerTooltipHandler {
public class SubsetWidget extends Button implements ItemFilterProvider {
protected static final int SLOT_HEIGHT = 18;
protected static final int MARGIN = 2;
@@ -788,7 +786,7 @@ public class SubsetWidget extends Button implements ItemFilterProvider, IContain
root.resize(screen, parent, dropRight);
GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_LIGHTING_BIT);
GuiContainerManager.enable2DRender();
GuiContainerManager.drawItems.zLevel += 100;
@@ -939,7 +937,7 @@ public class SubsetWidget extends Button implements ItemFilterProvider, IContain
}
@Override
public Map<String, String> handleHotkeys(GuiContainer gui, int mousex, int mousey, Map<String, String> hotkeys) {
public Map<String, String> handleHotkeys(int mousex, int mousey, Map<String, String> hotkeys) {
if (SubsetWidget.hoverStack != null) {
+14 -2
View File
@@ -1,6 +1,7 @@
package codechicken.nei;
import java.util.List;
import java.util.Map;
import net.minecraft.item.ItemStack;
@@ -14,8 +15,6 @@ public abstract class Widget {
public void postDraw(int mx, int my) {}
public void postDrawTooltips(int mx, int my, List<String> tooltip) {}
public boolean handleClick(int mx, int my, int button) {
return true;
}
@@ -38,6 +37,10 @@ public abstract class Widget {
return false;
}
public Map<String, String> handleHotkeys(int mousex, int mousey, Map<String, String> hotkeys) {
return hotkeys;
}
public void update() {}
public Rectangle4i bounds() {
@@ -58,6 +61,14 @@ public abstract class Widget {
return tooltip;
}
public List<String> handleItemTooltip(ItemStack itemstack, int mousex, int mousey, List<String> tooltip) {
return tooltip;
}
public boolean isFocused() {
return false;
}
public void loseFocus() {}
public void gainFocus() {}
@@ -67,4 +78,5 @@ public abstract class Widget {
public int z;
public int w;
public int h;
}
@@ -0,0 +1,254 @@
package codechicken.nei;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import net.minecraft.item.ItemStack;
import codechicken.lib.gui.GuiDraw;
import codechicken.lib.vec.Rectangle4i;
public class WidgetContainer extends Widget {
protected final List<Widget> widgets = new ArrayList<>();
protected boolean isFocused = false;
public void addWidget(Widget widget) {
this.widgets.add(widget);
}
public void setWidgets(List<Widget> widgets) {
final boolean isFocused = this.isFocused;
clear();
loseFocus();
for (Widget widget : widgets) {
addWidget(widget);
}
this.isFocused = isFocused;
}
public void clear() {
this.widgets.clear();
this.isFocused = false;
}
public List<Widget> getWidgets() {
return Collections.unmodifiableList(this.widgets);
}
public boolean removeIf(Predicate<Widget> filter) {
return this.widgets.removeIf(filter);
}
@Override
public void draw(int mousex, int mousey) {
drawWidgets(mousex, mousey);
}
protected void drawWidgets(int mousex, int mousey) {
final Rectangle4i bounds = bounds();
for (Widget widget : this.widgets) {
if (widget.bounds().intersects(bounds)) {
widget.draw(mousex, mousey);
}
}
}
@Override
public void update() {
for (Widget widget : this.widgets) {
widget.update();
}
Collections.sort(this.widgets, Comparator.comparingInt((Widget widget) -> widget.z));
}
public Widget getWidgetUnderMouse(int mousex, int mousey) {
if (!bounds().contains(mousex, mousey)) {
return null;
}
for (int index = this.widgets.size() - 1; index >= 0; index--) {
final Widget widget = this.widgets.get(index);
if (widget.contains(mousex, mousey)) {
return widget;
}
}
return null;
}
@Override
public boolean onMouseWheel(int scroll, int mousex, int mousey) {
final Widget widget = getWidgetUnderMouse(mousex, mousey);
return widget != null && widget.onMouseWheel(scroll, mousex, mousey);
}
@Override
public boolean handleClick(int mousex, int mousey, int button) {
if (contains(mousex, mousey)) {
gainFocus();
}
final Widget widget = getWidgetUnderMouse(mousex, mousey);
return widget != null && widget.handleClick(mousex, mousey, button);
}
@Override
public boolean handleClickExt(int mousex, int mousey, int button) {
loseFocus();
for (int index = this.widgets.size() - 1; index >= 0; index--) {
final Widget widget = this.widgets.get(index);
if (!widget.contains(mousex, mousey) && widget.handleClickExt(mousex, mousey, button)) {
return true;
}
}
return false;
}
@Override
public void mouseDragged(int mousex, int mousey, int button, long heldTime) {
for (int index = this.widgets.size() - 1; index >= 0; index--) {
final Widget widget = this.widgets.get(index);
widget.mouseDragged(mousex, mousey, button, heldTime);
}
}
@Override
public void mouseUp(int mousex, int mousey, int button) {
for (int index = this.widgets.size() - 1; index >= 0; index--) {
final Widget widget = this.widgets.get(index);
widget.mouseUp(mousex, mousey, button);
}
}
@Override
public boolean handleKeyPress(int keyCode, char keyChar) {
for (int index = this.widgets.size() - 1; index >= 0; index--) {
final Widget widget = this.widgets.get(index);
if (widget.handleKeyPress(keyCode, keyChar)) {
return true;
}
}
return false;
}
@Override
public void lastKeyTyped(int keyID, char keyChar) {
for (int index = this.widgets.size() - 1; index >= 0; index--) {
final Widget widget = this.widgets.get(index);
widget.lastKeyTyped(keyID, keyChar);
}
}
@Override
public boolean isFocused() {
return this.isFocused;
}
@Override
public void loseFocus() {
for (int index = this.widgets.size() - 1; index >= 0; index--) {
final Widget widget = this.widgets.get(index);
if (widget.isFocused()) {
widget.loseFocus();
}
}
this.isFocused = false;
}
@Override
public void gainFocus() {
final Point mouse = GuiDraw.getMousePosition();
final Widget widget = getWidgetUnderMouse(mouse.x, mouse.y);
if (widget != null) {
if (!widget.isFocused()) {
loseFocus();
widget.gainFocus();
}
} else {
loseFocus();
}
this.isFocused = true;
}
@Override
public ItemStack getStackMouseOver(int mousex, int mousey) {
final Widget widget = getWidgetUnderMouse(mousex, mousey);
if (widget != null) {
return widget.getStackMouseOver(mousex, mousey);
}
return null;
}
@Override
public void postDraw(int mousex, int mousey) {
for (Widget widget : this.widgets) {
widget.postDraw(mousex, mousey);
}
}
@Override
public void onGuiClick(int mousex, int mousey) {
for (int index = this.widgets.size() - 1; index >= 0; index--) {
final Widget widget = this.widgets.get(index);
widget.onGuiClick(mousex, mousey);
}
}
@Override
public List<String> handleTooltip(int mousex, int mousey, List<String> tooltip) {
final Widget widget = getWidgetUnderMouse(mousex, mousey);
if (widget != null) {
return widget.handleTooltip(mousex, mousey, tooltip);
}
return tooltip;
}
@Override
public Map<String, String> handleHotkeys(int mousex, int mousey, Map<String, String> hotkeys) {
final Widget widget = getWidgetUnderMouse(mousex, mousey);
if (widget != null) {
return widget.handleHotkeys(mousex, mousey, hotkeys);
}
return hotkeys;
}
}
@@ -38,7 +38,11 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
public void tickKeyStates() {
if (Minecraft.getMinecraft().currentScreen != null) return;
if (KeyManager.keyStates.get("world.moboverlay").down) mobOverlay = (mobOverlay + 1) % 2;
if (KeyManager.keyStates.get("world.moboverlay").down) {
mobOverlay = (mobOverlay + 1) % 2;
NEIClientUtils
.printChatMessage(new ChatComponentText(NEIClientUtils.translate("chat.moboverlay." + mobOverlay)));
}
if (KeyManager.keyStates.get("world.chunkoverlay").down) {
chunkOverlay = (chunkOverlay + 1) % (NEIModContainer.isGT5Loaded() ? 4 : 3);
// 0-2 (or 3 with gt)
@@ -73,9 +77,11 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
}
World world = entity.worldObj;
int worldHeight = world.getHeight();
int x1 = (int) entity.posX;
int z1 = (int) entity.posZ;
int y1 = (int) MathHelper.clip(entity.posY, 16, world.getHeight() - 16);
int y1 = (int) MathHelper.clip(entity.posY, 16, worldHeight - 16);
for (int i = 0; i <= 32; i++) {
int x = x1 - 16 + i;
@@ -94,6 +100,12 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
for (int k = 0; k <= 32; k++) {
int y = y1 - 16 + k;
if (y >= worldHeight) {
mobSpawnCache[bufIndex + k] = -1;
continue;
}
if (y > maxHeight) {
mobSpawnCache[bufIndex + k] = -1;
break;
@@ -177,6 +189,10 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
private static final AxisAlignedBB aabb = AxisAlignedBB.getBoundingBox(0, 0, 0, 0, 0, 0);
private static byte getSpawnMode(Chunk chunk, int x, int y, int z) {
if (y >= chunk.worldObj.getHeight()) {
return 0;
}
if (chunk.getSavedLightValue(EnumSkyBlock.Block, x & 15, y, z & 15) >= 8
|| !SpawnerAnimals.canCreatureTypeSpawnAtLocation(EnumCreatureType.monster, chunk.worldObj, x, y, z)) {
return 0;
@@ -24,7 +24,7 @@ public class DefaultOverlayRenderer implements IRecipeOverlayRenderer {
@Override
public void renderOverlay(GuiContainerManager gui, Slot slot) {
GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_LIGHTING_BIT);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(770, 1);
@@ -16,7 +16,6 @@ import codechicken.nei.NEIDummySlotHandler;
import codechicken.nei.NEIPotionGuiHandler;
import codechicken.nei.recipe.CheatItemHandler;
import codechicken.nei.recipe.FillFluidContainerHandler;
import codechicken.nei.recipe.GuiRecipeCatalyst;
import codechicken.nei.recipe.SearchInputDropHandler;
public class GuiInfo {
@@ -31,7 +30,6 @@ public class GuiInfo {
API.registerNEIGuiHandler(new NEICreativeGuiHandler());
API.registerNEIGuiHandler(new NEIChestGuiHandler());
API.registerNEIGuiHandler(new NEIDummySlotHandler());
API.registerNEIGuiHandler(new GuiRecipeCatalyst(null));
API.registerNEIGuiHandler(new SearchInputDropHandler());
API.registerNEIGuiHandler(new FillFluidContainerHandler());
API.registerNEIGuiHandler(new CheatItemHandler());
@@ -18,6 +18,10 @@ public interface IStackStringifyHandler {
return null;
}
default ItemStack normalizeRecipeQueryStack(ItemStack stack) {
return null;
}
default void pauseItemDamageSound(boolean pause) {}
}
+24 -11
View File
@@ -65,6 +65,7 @@ import codechicken.nei.search.IdentifierFilter;
import codechicken.nei.search.ModNameFilter;
import codechicken.nei.search.OreDictionaryFilter;
import codechicken.nei.search.TooltipFilter;
import codechicken.nei.util.ItemUntranslator;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.registry.GameRegistry;
@@ -137,6 +138,10 @@ public class ItemInfo {
addSearchProviders();
RecipeItemInputHandler.load();
PresetsList.load();
if (NEIClientConfig.enableItemUntranslator()) {
ItemUntranslator.getInstance().load();
}
}
private static void addSearchProviders() {
@@ -416,30 +421,38 @@ public class ItemInfo {
Block mouseoverBlock = world.getBlock(x, y, z);
ArrayList<ItemStack> items = new ArrayList<>();
ArrayList<IHighlightHandler> handlers = new ArrayList<>();
if (highlightIdentifiers.containsKey(null)) handlers.addAll(highlightIdentifiers.get(null));
if (highlightIdentifiers.containsKey(mouseoverBlock)) handlers.addAll(highlightIdentifiers.get(mouseoverBlock));
for (IHighlightHandler ident : handlers) {
ItemStack item = ident.identifyHighlight(world, player, hit);
final ItemStack item = ident.identifyHighlight(world, player, hit);
if (item != null) items.add(item);
}
if (items.size() > 0) return items;
if (!items.isEmpty()) return items;
ItemStack pick = mouseoverBlock.getPickBlock(hit, world, x, y, z, player);
if (pick != null) items.add(pick);
try {
final ItemStack pick = mouseoverBlock.getPickBlock(hit, world, x, y, z, player);
if (pick != null) items.add(pick);
} catch (Exception ignored) {}
if (!items.isEmpty()) return items;
if (mouseoverBlock instanceof IShearable shearable) {
if (shearable.isShearable(new ItemStack(Items.shears), world, x, y, z)) {
items.addAll(shearable.onSheared(new ItemStack(Items.shears), world, x, y, z, 0));
}
}
if (!items.isEmpty()) return items;
try {
items.addAll(mouseoverBlock.getDrops(world, x, y, z, world.getBlockMetadata(x, y, z), 0));
} catch (Exception ignored) {}
if (mouseoverBlock instanceof IShearable) {
IShearable shearable = (IShearable) mouseoverBlock;
if (shearable.isShearable(new ItemStack(Items.shears), world, x, y, z))
items.addAll(shearable.onSheared(new ItemStack(Items.shears), world, x, y, z, 0));
}
if (items.size() == 0) items.add(0, new ItemStack(mouseoverBlock, 1, world.getBlockMetadata(x, y, z)));
if (items.isEmpty()) items.add(new ItemStack(mouseoverBlock, 1, world.getBlockMetadata(x, y, z)));
return items;
}
@@ -27,6 +27,7 @@ import codechicken.nei.SearchField;
import codechicken.nei.bookmark.BookmarkGrid;
import codechicken.nei.bookmark.BookmarkGroup;
import codechicken.nei.bookmark.BookmarkItem;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.bookmark.BookmarksGridSlot;
import codechicken.nei.recipe.AutoCraftingManager;
import codechicken.nei.recipe.GuiCraftingRecipe;
@@ -42,6 +43,31 @@ import codechicken.nei.util.NEIMouseUtils;
public abstract class ShortcutInputHandler {
private static class HotkeysCache {
public int mousex;
public int mousey;
public ItemStack stack;
public int groupId;
public Map<String, String> hotkeys = new HashMap<>();
public boolean matches(int mousex, int mousey, ItemStack stack, int groupId) {
return Math.abs(this.mousex - mousex) < 16 && Math.abs(this.mousey - mousey) < 16
&& (this.stack == null ? stack == null && this.groupId == groupId
: stack != null && NEIClientUtils.areStacksSameTypeWithNBT(stack, this.stack));
}
public void update(int mousex, int mousey, ItemStack stack, int groupId, Map<String, String> hotkeys) {
this.mousex = mousex;
this.mousey = mousey;
this.stack = stack != null ? stack.copy() : null;
this.groupId = groupId;
this.hotkeys = hotkeys;
}
}
private static HotkeysCache hotkeysCache = new HotkeysCache();
public static boolean handleKeyEvent(ItemStack stackover) {
if (!NEIClientConfig.isLoaded()) {
@@ -98,6 +124,9 @@ public abstract class ShortcutInputHandler {
if (NEIClientConfig.isKeyHashDown("gui.copy_name")) {
return copyItemStackName(stackover);
}
if (NEIClientConfig.isKeyHashDown("gui.copy_id")) {
return copyItemStackID(stackover);
}
if (NEIClientConfig.isKeyHashDown("gui.copy_oredict")) {
return copyItemStackOreDictionary(stackover);
@@ -145,9 +174,9 @@ public abstract class ShortcutInputHandler {
final int button = Mouse.getEventButton();
if (button == 0) {
return GuiCraftingRecipe.openRecipeGui("item", stackover);
return GuiCraftingRecipe.openRecipeGui("item", stackover.copy());
} else if (button == 1) {
return GuiUsageRecipe.openRecipeGui("item", stackover);
return GuiUsageRecipe.openRecipeGui("item", stackover.copy());
}
}
@@ -159,6 +188,14 @@ public abstract class ShortcutInputHandler {
return true;
}
private static boolean copyItemStackID(ItemStack stackover) {
if (stackover == null || stackover.getItem() == null) return false;
GuiScreen.setClipboardString(
stackover.getItem().delegate.name()
+ (stackover.getItemDamage() != 0 ? "/" + stackover.getItemDamage() : ""));
return true;
}
private static boolean sendItemStackChatLink(ItemStack stackover) {
if (stackover == null) return false;
@@ -197,7 +234,7 @@ public abstract class ShortcutInputHandler {
if (recipe != null) {
math = RecipeChainMath.of(recipe, 1);
}
} else if (slot.getRecipeId() != null && !slot.isIngredient()) {
} else if (slot.getRecipeId() != null && slot.getType() == BookmarkItemType.RESULT) {
if (slot.getGroup().crafting == null) {
final Recipe recipe = Recipe.of(slot.getRecipeId());
@@ -276,11 +313,14 @@ public abstract class ShortcutInputHandler {
private static boolean saveRecipeInBookmark(ItemStack stackover, boolean saveIngredients, boolean saveStackSize) {
final Point mousePos = GuiDraw.getMousePosition();
// If no slot was removed from the bookmark panel on click:
if (!ItemPanels.bookmarkPanel.removeSlot(mousePos.x, mousePos.y, saveIngredients)) {
final Recipe recipe = getFocusedRecipe(stackover, mousePos.x, mousePos.y, saveIngredients);
// --- Case 1: saving a recipe (with ingredients) ---
if (recipe != null && saveIngredients) {
// If the recipe is not already bookmarked, add it
if (!ItemPanels.bookmarkPanel.removeRecipe(recipe.getRecipeId(), BookmarkGrid.DEFAULT_GROUP_ID)) {
final Recipe singleRecipe = Recipe.of(
Arrays.asList(recipe.getResult(stackover)),
@@ -288,27 +328,38 @@ public abstract class ShortcutInputHandler {
recipe.getIngredients());
singleRecipe.setCustomRecipeId(recipe.getRecipeId());
ItemPanels.bookmarkPanel
.addRecipe(singleRecipe, saveStackSize ? 1 : 0, BookmarkGrid.DEFAULT_GROUP_ID);
ItemPanels.bookmarkPanel.addRecipe(
singleRecipe,
// Determine if stack size should be saved
saveStackSize
|| NEIClientConfig.getBooleanSetting("inventory.bookmarks.bookmarkRecipeWithCount")
? 1
: 0,
BookmarkGrid.DEFAULT_GROUP_ID);
}
// --- Case 2: saving an item only ---
} else {
final RecipeId recipeId = recipe != null ? recipe.getRecipeId() : null;
// Determine if the item is associated with a recipe and should be saved with it
final boolean existsRecipe = recipeId != null
&& ItemPanels.bookmarkPanel.existsRecipe(recipeId, BookmarkGrid.DEFAULT_GROUP_ID)
|| NEIClientConfig.getBooleanSetting("inventory.bookmarks.bookmarkItemsWithRecipe");
// If the item was not removed from the bookmarks, add it
if (!ItemPanels.bookmarkPanel
.removeItem(stackover, existsRecipe ? recipeId : null, BookmarkGrid.DEFAULT_GROUP_ID)) {
// Determine whether to preserve the item count
saveStackSize = saveStackSize || saveIngredients
|| ItemPanels.bookmarkPanel.existsRecipe(recipeId, BookmarkGrid.DEFAULT_GROUP_ID);
if (!saveStackSize) {
stackover = StackInfo.withAmount(stackover, 0);
} else if (ItemPanels.itemPanel.contains(mousePos.x, mousePos.y)
|| ItemPanels.itemPanel.historyPanel.contains(mousePos.x, mousePos.y)) {
stackover = ItemQuantityField.prepareStackWithQuantity(stackover, 0);
}
} else if (ItemPanels.itemPanel.containsWithSubpanels(mousePos.x, mousePos.y)) {
stackover = ItemQuantityField.prepareStackWithQuantity(stackover, 0);
}
ItemPanels.bookmarkPanel
.addItem(stackover, existsRecipe ? recipeId : null, BookmarkGrid.DEFAULT_GROUP_ID);
@@ -380,8 +431,14 @@ public abstract class ShortcutInputHandler {
return ItemPanels.bookmarkPanel.pullBookmarkItems(math, shift);
}
public static Map<String, String> handleHotkeys(GuiContainer gui, int mousex, int mousey, ItemStack stack) {
public static Map<String, String> handleHotkeys(int mousex, int mousey, ItemStack stack) {
final int groupId = ItemPanels.bookmarkPanel.getHoveredGroupId(true);
if (hotkeysCache.matches(mousex, mousey, stack, groupId)) {
return hotkeysCache.hotkeys;
}
final GuiContainer gui = NEIClientUtils.getGuiContainer();
final Map<String, String> hotkeys = new HashMap<>();
if (groupId != -1) {
@@ -408,9 +465,13 @@ public abstract class ShortcutInputHandler {
NEIClientConfig.getKeyName("gui.craft_items", NEIClientUtils.SHIFT_HASH),
NEIClientUtils.translate("bookmark.group.craft_all"));
}
hotkeysCache.update(mousex, mousey, stack, groupId, hotkeys);
return hotkeys;
}
if (stack == null) {
hotkeysCache.update(mousex, mousey, stack, groupId, hotkeys);
return hotkeys;
}
@@ -424,7 +485,7 @@ public abstract class ShortcutInputHandler {
hotkeys.put(
NEIClientConfig.getKeyName("gui.bookmark", NEIClientUtils.SHIFT_HASH),
NEIClientUtils.translate("bookmark.group.remove_recipe"));
} else if (slot.getRecipeId() == null) {
} else if (slot.getRecipeId() == null || slot.getType() == BookmarkItemType.ITEM) {
hotkeys.put(
NEIClientConfig.getKeyName("gui.bookmark"),
NEIClientUtils.translate("bookmark.remove_item"));
@@ -439,7 +500,7 @@ public abstract class ShortcutInputHandler {
NEIClientConfig.getKeyName("gui.bookmark", NEIClientUtils.SHIFT_HASH),
NEIClientUtils.translate("bookmark.remove_recipe"));
if (slot.isIngredient()) {
if (slot.getType() == BookmarkItemType.INGREDIENT) {
hotkeys.put(
NEIClientConfig.getKeyName("gui.bookmark"),
NEIClientUtils.translate("bookmark.remove_item"));
@@ -452,7 +513,8 @@ public abstract class ShortcutInputHandler {
if (ItemPanels.bookmarkPanel.getGrid().createChainItems(groupId).values().stream()
.noneMatch(
m -> !m.isIngredient && !m.equals(item) && item.equalsRecipe(m))) {
m -> m.type == BookmarkItemType.RESULT && !m.equals(item)
&& item.equalsRecipe(m))) {
hotkeys.put(
NEIClientConfig.getKeyName("gui.bookmark"),
NEIClientUtils.translate("bookmark.remove_recipe"));
@@ -511,6 +573,7 @@ public abstract class ShortcutInputHandler {
hotkeys.put(NEIClientConfig.getKeyName("gui.copy_name"), NEIClientUtils.translate("itempanel.copy_name"));
hotkeys.put(NEIClientConfig.getKeyName("gui.copy_oredict"), NEIClientUtils.translate("itempanel.copy_oredict"));
hotkeys.put(NEIClientConfig.getKeyName("gui.copy_id"), NEIClientUtils.translate("itempanel.copy_id"));
hotkeys.put(
NEIClientConfig.getKeyName("gui.chat_link_item"),
NEIClientUtils.translate("itempanel.chat_link_item"));
@@ -570,6 +633,8 @@ public abstract class ShortcutInputHandler {
}
hotkeysCache.update(mousex, mousey, stack, groupId, hotkeys);
return hotkeys;
}
@@ -599,7 +664,7 @@ public abstract class ShortcutInputHandler {
BookmarksGridSlot slot) {
if (slot != null) {
return slot.isIngredient() ? null : slot.getRecipeId();
return slot.getType() == BookmarkItemType.INGREDIENT ? null : slot.getRecipeId();
}
ItemsGridSlot itemSlot = ItemPanels.itemPanel.getSlotMouseOver(mousex, mousey);
@@ -30,6 +30,7 @@ import codechicken.nei.ItemsGrid.MouseContext;
import codechicken.nei.LayoutManager;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.recipe.Recipe;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.recipe.StackInfo;
@@ -367,19 +368,26 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
}
for (BookmarkItem item : this.bookmarkItems) {
if (item.groupId == groupId && item.recipeId != null) {
if (item.recipeId == null && item.type != BookmarkItemType.ITEM) {
item.type = BookmarkItemType.ITEM;
} else if (item.groupId == groupId && item.recipeId != null && item.type != BookmarkItemType.ITEM) {
recipeState.put(
item.recipeId,
recipeState.getOrDefault(item.recipeId, 0) | (item.isIngredient ? 1 : 2));
recipeState.getOrDefault(item.recipeId, 0)
| (item.type == BookmarkItemType.INGREDIENT ? 1 : 2));
}
}
for (BookmarkItem item : this.bookmarkItems) {
if (item.groupId == groupId && item.isIngredient
&& (item.recipeId == null || recipeState.getOrDefault(item.recipeId, 1) == 1)) {
if (item.groupId == groupId && item.type != BookmarkItemType.ITEM
&& recipeState.getOrDefault(item.recipeId, 0) != 3) {
if (item.type == BookmarkItemType.INGREDIENT) {
item.recipeId = null;
}
recipeState.remove(item.recipeId);
item.isIngredient = false;
item.recipeId = null;
item.type = BookmarkItemType.ITEM;
}
}
@@ -405,7 +413,8 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
for (int index = itemIndex; index < size; index++) {
if (item.equalsRecipe(this.bookmarkItems.get(index))) {
sortingRank.put(index, this.bookmarkItems.get(index).isIngredient ? 1 : -1);
sortingRank
.put(index, this.bookmarkItems.get(index).type == BookmarkItemType.INGREDIENT ? 1 : -1);
items.add(index);
}
}
@@ -632,6 +641,7 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
if (group.crafting == null) {
for (BookmarkItem item : chainItems) {
item.type = BookmarkItemType.ITEM;
item.recipeId = null;
}
}
@@ -820,7 +830,7 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
for (int itemIndex = 0; itemIndex < this.bookmarkItems.size(); itemIndex++) {
final BookmarkItem item = this.bookmarkItems.get(itemIndex);
if (item.groupId == groupId && item.isIngredient == ingredient
if (item.groupId == groupId && ingredient == (item.type == BookmarkItemType.INGREDIENT)
&& (recipeId == item.recipeId || recipeId != null && recipeId.equals(item.recipeId))
&& StackInfo.equalItemAndNBT(stackA, item.itemStack, true)) {
return itemIndex;
@@ -876,7 +886,12 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
for (ItemStack stack : ItemStackAmount.of(results).values()) {
long factor = StackInfo.getAmount(stack);
this.addItem(
BookmarkItem.of(groupId, StackInfo.withAmount(stack, factor * multiplier), factor, recipeId, false),
BookmarkItem.of(
groupId,
StackInfo.withAmount(stack, factor * multiplier),
factor,
recipeId,
BookmarkItemType.RESULT),
true);
}
@@ -888,7 +903,7 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
StackInfo.withAmount(stack, factor * multiplier),
factor,
recipeId,
true,
BookmarkItemType.INGREDIENT,
BookmarkItem.generatePermutations(stack, recipe)),
true);
}
@@ -901,12 +916,12 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
return;
}
if (!removeFullRecipe && item.recipeId != null && !item.isIngredient) {
if (!removeFullRecipe && item.recipeId != null && item.type == BookmarkItemType.RESULT) {
removeFullRecipe = this.bookmarkItems.stream()
.noneMatch(m -> !m.isIngredient && !m.equals(item) && item.equalsRecipe(m));
.noneMatch(m -> m.type == BookmarkItemType.RESULT && !m.equals(item) && item.equalsRecipe(m));
}
if (item.recipeId != null && removeFullRecipe) {
if (item.recipeId != null && item.type != BookmarkItemType.ITEM && removeFullRecipe) {
removeRecipe(item.recipeId, item.groupId);
} else if (itemIndex >= 0) {
this.bookmarkItems.remove(itemIndex);
@@ -925,7 +940,8 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
}
public boolean existsRecipe(RecipeId recipeId, int groupId) {
return this.bookmarkItems.stream().anyMatch(item -> item.equalsRecipe(recipeId, groupId));
return this.bookmarkItems.stream()
.anyMatch(item -> item.type != BookmarkItemType.ITEM && item.equalsRecipe(recipeId, groupId));
}
public RecipeId getRecipeId(int itemIndex) {
@@ -1028,8 +1044,14 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
}
if (bookmarkItem != null && (group.crafting != null && group.viewMode == BookmarkViewMode.DEFAULT
|| group.viewMode == BookmarkViewMode.TODO_LIST && !sortableItem.bookmarkItem.isIngredient)) {
while (sortIndex > 0 && bookmarkItem.equalsRecipe(getCalculatedItem(sortedIndexes.get(sortIndex - 1)))) {
|| group.viewMode == BookmarkViewMode.TODO_LIST
&& sortableItem.bookmarkItem.type == BookmarkItemType.RESULT)) {
BookmarkItem prevBookmarkItem = sortIndex > 1 ? getCalculatedItem(sortedIndexes.get(sortIndex - 1)) : null;
while (sortIndex > 0 && prevBookmarkItem != null
&& prevBookmarkItem.type != BookmarkItemType.ITEM
&& bookmarkItem.equalsRecipe(prevBookmarkItem)) {
prevBookmarkItem = sortIndex > 1 ? getCalculatedItem(sortedIndexes.get(sortIndex - 1)) : null;
sortIndex--;
}
@@ -1058,7 +1080,7 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
if (nextSortIndex < sortedIndexes.size()) {
final int nextItemIndex = sortedIndexes.get(nextSortIndex);
if (group.viewMode == BookmarkViewMode.TODO_LIST && !target.isIngredient
if (group.viewMode == BookmarkViewMode.TODO_LIST && target.type == BookmarkItemType.RESULT
&& target.equalsRecipe(getCalculatedItem(nextItemIndex))) {
return -1;
}
@@ -1149,7 +1171,7 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
if (group.collapsed) {
shiftGroupAmount(targetItem.groupId, shift);
} else if (targetItem.recipeId != null) {
} else if (targetItem.recipeId != null && targetItem.type != BookmarkItemType.ITEM) {
final RecipeId recipeId = this.gridGenerator.itemToRecipe
.getOrDefault(targetItemIndex, targetItem.recipeId);
final boolean recipeInMiddle = group.crafting != null && group.crafting.recipeInMiddle.contains(recipeId);
@@ -11,6 +11,7 @@ import java.util.stream.Collectors;
import codechicken.nei.BookmarkPanel.BookmarkViewMode;
import codechicken.nei.ItemSorter;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.bookmark.RecipeChainDetails.BookmarkChainItem;
import codechicken.nei.bookmark.RecipeChainDetails.CalculatedType;
import codechicken.nei.recipe.Recipe.RecipeId;
@@ -117,7 +118,7 @@ public class BookmarkGridGenerator {
this.itemToSlot.put(collapsedItemIndex, absoluteSlotIndex);
this.caclulatedItems.put(collapsedItemIndex, getItem(group, collapsedItemIndex));
if (!(shadows = getShadows(group, item.recipeId)).isEmpty()) {
if (item.recipeId != null && !(shadows = getShadows(group, item.recipeId)).isEmpty()) {
borderGrid.put(absoluteSlotIndex, "recipe:" + shadows.get(0));
}
}
@@ -165,7 +166,7 @@ public class BookmarkGridGenerator {
break;
}
if (!bookmarkItem.isIngredient
if (bookmarkItem.type != BookmarkItemType.INGREDIENT
&& (group.crafting == null || group.crafting.calculatedItems.containsKey(itemIndex))) {
results.add(itemIndex);
}
@@ -193,7 +194,7 @@ public class BookmarkGridGenerator {
bookmarkItem.itemStack,
1,
bookmarkItem.recipeId,
isIngredient,
isIngredient ? BookmarkItemType.INGREDIENT : BookmarkItemType.RESULT,
Collections.emptyMap());
if ((absoluteSlotIndex = nextSlotIndex(
@@ -238,17 +239,21 @@ public class BookmarkGridGenerator {
return index;
} else if (isFirstColumn && (meta.recipeId == null || previousMeta == null
|| previousMeta.groupId != meta.groupId
|| meta.type == BookmarkItemType.ITEM
|| !meta.recipeId.equals(previousMeta.recipeId)
|| index + 1 < maxIndex && this.grid.isInvalidSlot((index + 1) % maxIndex))) {
// In first column must be an item without recipe, a recipe result, or an ingredient
// if the second column is occupied
return index;
} else
if (!isFirstColumn && meta.recipeId != null && meta.recipeId.equals(previousMeta.recipeId)) {
return index;
} else {
index++;
}
if (!isFirstColumn && meta.type != BookmarkItemType.ITEM
&& previousMeta.type != BookmarkItemType.ITEM
&& meta.recipeId != null
&& meta.recipeId.equals(previousMeta.recipeId)) {
return index;
} else {
index++;
}
}
@@ -17,6 +17,21 @@ import codechicken.nei.recipe.StackInfo;
public class BookmarkItem {
public enum BookmarkItemType {
INGREDIENT,
RESULT,
ITEM;
public static BookmarkItemType fromInt(int type) {
return type == 0 ? ITEM : type == 1 ? RESULT : INGREDIENT;
}
public int toInt() {
return this == ITEM ? 0 : this == RESULT ? 1 : 2;
}
}
private static Map<ItemStack, String> fuzzyPermutations = new HashMap<>();
public int groupId;
@@ -28,10 +43,10 @@ public class BookmarkItem {
public long factor;
public RecipeId recipeId;
public boolean isIngredient = false;
public BookmarkItemType type = BookmarkItemType.ITEM;
protected BookmarkItem(int groupId, long amount, int fluidCellAmount, ItemStack itemStack,
Map<String, ItemStack> permutations, long factor, RecipeId recipeId, boolean isIngredient) {
Map<String, ItemStack> permutations, long factor, RecipeId recipeId, BookmarkItemType type) {
this.groupId = groupId;
this.amount = amount;
@@ -41,10 +56,10 @@ public class BookmarkItem {
this.factor = factor;
this.recipeId = recipeId;
this.isIngredient = isIngredient;
this.type = type == null ? BookmarkItemType.ITEM : type;
}
public static BookmarkItem of(int groupId, ItemStack stack, long factor, RecipeId recipeId, boolean isIngredient,
public static BookmarkItem of(int groupId, ItemStack stack, long factor, RecipeId recipeId, BookmarkItemType type,
Map<String, ItemStack> permutations) {
final FluidStack fluidStack = StackInfo.getFluid(stack);
int fluidCellAmount = 1;
@@ -65,18 +80,29 @@ public class BookmarkItem {
permutations,
factor * fluidCellAmount,
recipeId,
isIngredient);
type);
}
public static BookmarkItem of(int groupId, ItemStack stack, long factor, RecipeId recipeId, boolean isIngredient) {
return of(groupId, stack, factor, recipeId, isIngredient, generatePermutations(stack, recipeId, isIngredient));
public static BookmarkItem of(int groupId, ItemStack stack, long factor, RecipeId recipeId, BookmarkItemType type) {
return of(
groupId,
stack,
factor,
recipeId,
type,
generatePermutations(stack, recipeId, type == BookmarkItemType.INGREDIENT));
}
public static BookmarkItem of(int groupId, ItemStack stack) {
final NBTTagCompound nbTag = StackInfo.itemStackToNBT(stack);
final long factor = nbTag.hasKey("gtFluidName") ? Math.min(144, nbTag.getInteger("Count")) : 1;
return BookmarkItem
.of(groupId, stack, factor, null, false, Collections.singletonMap(getItemGUID(stack), stack));
return BookmarkItem.of(
groupId,
stack,
factor,
null,
BookmarkItemType.ITEM,
Collections.singletonMap(getItemGUID(stack), stack));
}
public BookmarkItem copyWithAmount(long amount) {
@@ -88,7 +114,7 @@ public class BookmarkItem {
this.permutations,
this.factor,
this.recipeId,
this.isIngredient);
this.type);
}
public BookmarkItem copy() {
@@ -186,14 +212,14 @@ public class BookmarkItem {
@Override
public int hashCode() {
return Objects.hash(this.groupId, this.fluidCellAmount, this.isIngredient, this.recipeId);
return Objects.hash(this.groupId, this.fluidCellAmount, this.type.toInt(), this.recipeId);
}
@Override
public boolean equals(Object object) {
if (object instanceof BookmarkItem item) {
return this.groupId == item.groupId && this.isIngredient == item.isIngredient
return this.groupId == item.groupId && this.type == item.type
&& this.fluidCellAmount == item.fluidCellAmount
&& StackInfo.equalItemAndNBT(this.itemStack, item.itemStack, true)
&& (this.recipeId == item.recipeId || this.recipeId != null && this.recipeId.equals(item.recipeId));
@@ -25,6 +25,7 @@ import com.google.gson.JsonSyntaxException;
import codechicken.nei.BookmarkPanel.BookmarkViewMode;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.recipe.StackInfo;
import codechicken.nei.util.NBTJson;
@@ -239,7 +240,15 @@ public class BookmarkStorage {
int groupId = jsonObject.has("groupId") ? jsonObject.get("groupId").getAsInt()
: BookmarkGrid.DEFAULT_GROUP_ID;
int factor = jsonObject.has("factor") ? Math.abs(jsonObject.get("factor").getAsInt()) : (isFluid ? 144 : 1);
boolean isIngredient = jsonObject.has("ingredient") && jsonObject.get("ingredient").getAsBoolean();
BookmarkItemType type = jsonObject.has("type") ? BookmarkItemType.fromInt(jsonObject.get("type").getAsInt())
: null;
if (type == null) {
// old format
type = jsonObject.has("ingredient") && jsonObject.get("ingredient").getAsBoolean()
? BookmarkItemType.INGREDIENT
: BookmarkItemType.RESULT;
}
if (jsonObject.get("recipeId") instanceof JsonObject recipeJson) {
recipeId = RecipeId.of(recipeJson);
@@ -249,7 +258,7 @@ public class BookmarkStorage {
groupId = BookmarkGrid.DEFAULT_GROUP_ID;
}
grid.addItem(BookmarkItem.of(groupId, itemStack, factor, recipeId, isIngredient), false);
grid.addItem(BookmarkItem.of(groupId, itemStack, factor, recipeId, type), false);
}
return itemStack != null;
@@ -266,7 +275,8 @@ public class BookmarkStorage {
final Map<String, RecipeId> recipes = new HashMap<>();
for (BookmarkItem item : grid.bookmarkItems) {
if (item.recipeId != null && !item.isIngredient && item.recipeId.getResult() == null) {
if (item.recipeId != null && item.type != BookmarkItemType.INGREDIENT
&& item.recipeId.getResult() == null) {
final JsonObject recipeJson = item.recipeId.toJsonObject();
final String recipeGUID = item.groupId + ":" + NBTJson.toJson(recipeJson);
@@ -284,8 +294,10 @@ public class BookmarkStorage {
if (recipes.containsKey(recipeGUID)) {
item.recipeId = recipes.get(recipeGUID).copy();
item.permutations = BookmarkItem
.generatePermutations(item.itemStack, item.recipeId, item.isIngredient);
item.permutations = BookmarkItem.generatePermutations(
item.itemStack,
item.recipeId,
item.type == BookmarkItemType.INGREDIENT);
} else {
item.recipeId = null;
}
@@ -338,7 +350,7 @@ public class BookmarkStorage {
row.add("item", NBTJson.toJsonObject(StackInfo.itemStackToNBT(item.getItemStack())));
row.add("factor", new JsonPrimitive(item.getFactor()));
row.add("ingredient", new JsonPrimitive(item.isIngredient));
row.add("type", new JsonPrimitive(item.type.toInt()));
if (item.groupId != BookmarkGrid.DEFAULT_GROUP_ID) {
row.add("groupId", new JsonPrimitive(item.groupId));
@@ -4,6 +4,8 @@ import java.awt.Color;
import net.minecraft.item.ItemStack;
import org.lwjgl.opengl.GL11;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.BookmarkPanel.BookmarkViewMode;
import codechicken.nei.ItemPanels;
@@ -13,7 +15,11 @@ import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.NEIClientUtils.Alignment;
import codechicken.nei.bookmark.BookmarkGrid.BookmarkMouseContext;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.bookmark.RecipeChainDetails.CalculatedType;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.recipe.GuiRecipeTab;
import codechicken.nei.recipe.HandlerInfo;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.recipe.StackInfo;
import codechicken.nei.util.ReadableNumberConverter;
@@ -51,6 +57,7 @@ public class BookmarksGridSlot extends ItemsGridSlot {
protected final CalculatedType calculatedType;
protected final CalculatedType realType;
protected final BookmarkItem bookmarkItem;
protected HandlerInfo handlerInfo = null;
protected final boolean isOutputRecipe;
protected final boolean isFirstOutput;
@@ -83,7 +90,7 @@ public class BookmarksGridSlot extends ItemsGridSlot {
this.realType = this.group.crafting.calculatedItems.get(this.itemIndex).calculatedType
== CalculatedType.INGREDIENT ? CalculatedType.INGREDIENT : CalculatedType.RESULT;
} else {
this.realType = this.bookmarkItem.isIngredient
this.realType = this.bookmarkItem.type == BookmarkItemType.INGREDIENT
|| this.group.crafting != null && this.bookmarkItem.recipeId == null ? CalculatedType.INGREDIENT
: CalculatedType.RESULT;
}
@@ -91,9 +98,10 @@ public class BookmarksGridSlot extends ItemsGridSlot {
final BookmarkGrid grid = ItemPanels.bookmarkPanel.getGrid();
final BookmarkItem prevItem = grid.getCalculatedItem(
grid.gridGenerator.slotToItem.getOrDefault(grid.gridGenerator.itemToSlot.get(this.itemIndex) - 1, -1));
this.isFirstOutput = this.itemIndex >= 0 && !this.bookmarkItem.isIngredient
this.isFirstOutput = this.itemIndex >= 0 && this.bookmarkItem.type == BookmarkItemType.RESULT
&& ((this.slotIndex % grid.getColumns()) == 0 || group.viewMode == BookmarkViewMode.DEFAULT)
&& (prevItem == null || prevItem.isIngredient || !this.bookmarkItem.equalsRecipe(prevItem));
&& (prevItem == null || prevItem.type == BookmarkItemType.INGREDIENT
|| !this.bookmarkItem.equalsRecipe(prevItem));
this.rowIndex = this.slotIndex / grid.getColumns();
}
@@ -110,8 +118,8 @@ public class BookmarksGridSlot extends ItemsGridSlot {
return this.bookmarkItem.recipeId;
}
public boolean isIngredient() {
return this.bookmarkItem.isIngredient;
public BookmarkItemType getType() {
return this.bookmarkItem.type;
}
public BookmarkGroup getGroup() {
@@ -145,11 +153,17 @@ public class BookmarksGridSlot extends ItemsGridSlot {
return false;
}
if (this.group.crafting != null) {
if (this.slotIndex == mouseContext.slotIndex || this.group.crafting != null) {
return true;
}
return this.bookmarkItem.equalsRecipe(mouseContext.recipeId, mouseContext.groupId);
if (this.bookmarkItem.type == BookmarkItemType.ITEM && this.group.viewMode == BookmarkViewMode.TODO_LIST
&& mouseContext.rowIndex == this.rowIndex) {
return true;
}
return this.bookmarkItem.type != BookmarkItemType.ITEM
&& this.bookmarkItem.equalsRecipe(mouseContext.recipeId, mouseContext.groupId);
}
protected boolean showRealItem(BookmarkMouseContext mouseContext) {
@@ -167,7 +181,8 @@ public class BookmarksGridSlot extends ItemsGridSlot {
return true;
}
if (this.bookmarkItem.equalsRecipe(mouseContext.recipeId, mouseContext.groupId)) {
if (this.bookmarkItem.type != BookmarkItemType.ITEM
&& this.bookmarkItem.equalsRecipe(mouseContext.recipeId, mouseContext.groupId)) {
return true;
}
@@ -175,6 +190,13 @@ public class BookmarksGridSlot extends ItemsGridSlot {
&& mouseContext.recipeId.equals(this.group.crafting.itemToRecipe.get(this.itemIndex));
}
protected HandlerInfo getHandlerInfo() {
if (this.bookmarkItem.recipeId != null && this.handlerInfo == null) {
this.handlerInfo = GuiRecipeTab.getHandlerInfo(this.bookmarkItem.recipeId.getHandleName(), null);
}
return this.handlerInfo;
}
@Override
public void drawItem(Rectangle4i rect) {
super.drawItem(this.emptyItemStack, rect);
@@ -199,7 +221,7 @@ public class BookmarksGridSlot extends ItemsGridSlot {
}
if (!this.bookmarkItem.isIngredient && this.bookmarkItem.recipeId != null
if (this.bookmarkItem.type != BookmarkItemType.INGREDIENT && this.bookmarkItem.recipeId != null
&& calculatedType == null
&& showMarker
&& (mouseContext == null || mouseContext.slotIndex != this.slotIndex)) {
@@ -246,7 +268,7 @@ public class BookmarksGridSlot extends ItemsGridSlot {
drawStackSize(rect, shownItemType);
if (this.bookmarkItem.isIngredient || this.bookmarkItem.recipeId == null) {
if (this.bookmarkItem.type == BookmarkItemType.INGREDIENT || this.bookmarkItem.recipeId == null) {
return;
}
@@ -255,27 +277,65 @@ public class BookmarksGridSlot extends ItemsGridSlot {
drawMarker(
rect,
"x" + ReadableNumberConverter.INSTANCE.toWideReadableForm(this.realMultiplier),
0xFFFFFF);
0xFFFFFF,
Alignment.TopLeft);
} else if (shownItemType == ShownItemType.SHIFT) {
drawMarker(rect, "x" + ReadableNumberConverter.INSTANCE.toWideReadableForm(getMultiplier()), 0xFFFFFF);
drawMarker(
rect,
"x" + ReadableNumberConverter.INSTANCE.toWideReadableForm(getMultiplier()),
0xFFFFFF,
Alignment.TopLeft);
} else if (this.isOutputRecipe || this.realMultiplier > 1) {
drawMarker(
rect,
"x" + ReadableNumberConverter.INSTANCE.toWideReadableForm(this.realMultiplier),
NEIClientConfig.getSetting("inventory.bookmarks.recipeMarkerColor").getHexValue());
} else if (NEIClientConfig.showRecipeMarkerMode() == 1) {
drawMarker(
rect,
"R",
NEIClientConfig.getSetting("inventory.bookmarks.recipeMarkerColor").getHexValue());
NEIClientConfig.getSetting("inventory.bookmarks.recipeMarkerColor").getHexValue(),
Alignment.TopLeft);
}
} else if (NEIClientConfig.showRecipeMarkerMode() == 1) {
drawMarker(rect, "R", NEIClientConfig.getSetting("inventory.bookmarks.recipeMarkerColor").getHexValue());
}
if (this.isFirstOutput || NEIClientConfig.showRecipeMarkerMode() == 1) {
drawRecipeMarker(rect);
}
}
protected void drawMarker(Rectangle4i rect, String text, int color) {
protected void drawRecipeMarker(Rectangle4i rect) {
if (NEIClientConfig.getBooleanSetting("inventory.bookmarks.showRecipeHandlerIcon")
&& getHandlerInfo() != null) {
drawHandlerIcon(rect);
} else if (NEIClientConfig.showRecipeMarkerMode() == 1) {
drawMarker(
rect,
"R",
NEIClientConfig.getSetting("inventory.bookmarks.recipeMarkerColor").getHexValue(),
Alignment.TopRight);
}
}
protected void drawHandlerIcon(Rectangle4i rect) {
float panelFactor = 1;
if (rect.w != DEFAULT_SLOT_SIZE) {
panelFactor = (rect.w - 2) / (DEFAULT_SLOT_SIZE - 2);
}
panelFactor *= 0.4f;
float x = rect.x + 2 + 16 - 16 * panelFactor;
GL11.glTranslatef(x, rect.y, 0);
GL11.glScaled(panelFactor, panelFactor, 1.5f);
if (this.handlerInfo.getImage() != null) {
this.handlerInfo.getImage().draw(0, 0);
} else {
GuiContainerManager.drawItem(0, 0, this.handlerInfo.getItemStack(), true, "");
}
GL11.glScaled(1f / panelFactor, 1f / panelFactor, 1f / 1.5f);
GL11.glTranslatef(-1 * x, -1 * rect.y, 0);
}
protected void drawMarker(Rectangle4i rect, String text, int color, Alignment alignment) {
final float panelFactor = (rect.w - 2) / (DEFAULT_SLOT_SIZE - 2);
NEIClientUtils.drawNEIOverlayText(
text,
@@ -283,7 +343,7 @@ public class BookmarksGridSlot extends ItemsGridSlot {
panelFactor,
color,
true,
Alignment.TopLeft);
alignment);
}
protected void drawStackSize(Rectangle4i rect, ShownItemType shownItemType) {
@@ -7,6 +7,7 @@ import java.util.Map;
import java.util.Set;
import codechicken.nei.BookmarkPanel.BookmarkViewMode;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.recipe.Recipe.RecipeId;
public class GroupingItem {
@@ -124,7 +125,7 @@ public class GroupingItem {
final BookmarkItem item = this.grid.getCalculatedItem(itemIndex);
if (item.recipeId != null) {
if (item.recipeId != null && item.type != BookmarkItemType.ITEM) {
final List<Integer> sortedItems = this.grid.getSortedItems();
final BookmarkGroup group = this.grid.getGroup(item.groupId);
final boolean isCollapsedGroup = group.collapsed
@@ -139,7 +140,8 @@ public class GroupingItem {
for (Integer rItemIndex : sortedItems) {
final BookmarkItem rItem = this.grid.getCalculatedItem(rItemIndex);
if (rItem.groupId == item.groupId && (isCollapsedGroup || recipeRelations.contains(rItem.recipeId))) {
if (rItem.groupId == item.groupId && (isCollapsedGroup
|| rItem.type != BookmarkItemType.ITEM && recipeRelations.contains(rItem.recipeId))) {
return this.grid.getAbsoluteSlotIndex(rItemIndex) / this.grid.getColumns();
}
}
@@ -160,7 +162,7 @@ public class GroupingItem {
final BookmarkItem item = this.grid.getCalculatedItem(itemIndex);
if (item.recipeId != null) {
if (item.recipeId != null && item.type != BookmarkItemType.ITEM) {
final List<Integer> sortedItems = this.grid.getSortedItems();
final BookmarkGroup group = this.grid.getGroup(item.groupId);
final boolean isCollapsedGroup = group.collapsed
@@ -176,7 +178,8 @@ public class GroupingItem {
final int rItemIndex = sortedItems.get(index);
final BookmarkItem rItem = this.grid.getCalculatedItem(rItemIndex);
if (rItem.groupId == item.groupId && (isCollapsedGroup || recipeRelations.contains(rItem.recipeId))) {
if (rItem.groupId == item.groupId && (isCollapsedGroup
|| rItem.type != BookmarkItemType.ITEM && recipeRelations.contains(rItem.recipeId))) {
return this.grid.getAbsoluteSlotIndex(rItemIndex) / this.grid.getColumns();
}
}
@@ -12,6 +12,7 @@ import java.util.stream.Collectors;
import net.minecraft.item.ItemStack;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.recipe.StackInfo;
import codechicken.nei.recipe.chain.RecipeChainMath;
@@ -69,7 +70,7 @@ public class RecipeChainDetails {
item,
item.amount,
item.amount,
item.isIngredient ? CalculatedType.INGREDIENT : CalculatedType.RESULT);
item.type == BookmarkItemType.INGREDIENT ? CalculatedType.INGREDIENT : CalculatedType.RESULT);
}
public ItemStack getItemStack(long amount) {
@@ -217,11 +218,12 @@ public class RecipeChainDetails {
for (BookmarkChainItem value : items) {
int itemIndex = sortingChainItems.get(value.getItem());
if (value.getItem().isIngredient || !recipeId.equals(value.getItem().recipeId)) {
if (value.getItem().type == BookmarkItemType.INGREDIENT || !recipeId.equals(value.getItem().recipeId)) {
itemIndex *= -1;
}
if (!value.getItem().isIngredient && !math.outputRecipes.containsKey(value.getItem().recipeId)) {
if (value.getItem().type == BookmarkItemType.RESULT
&& !math.outputRecipes.containsKey(value.getItem().recipeId)) {
value.calculatedType = CalculatedType.REMAINDER;
}
@@ -251,7 +253,7 @@ public class RecipeChainDetails {
for (BookmarkChainItem value : items) {
int itemIndex = sortingChainItems.get(value.getItem());
if (value.getItem().isIngredient || !recipeId.equals(value.getItem().recipeId)) {
if (value.getItem().type == BookmarkItemType.INGREDIENT || !recipeId.equals(value.getItem().recipeId)) {
itemIndex *= -1;
}
@@ -9,6 +9,7 @@ import java.util.Map;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.BookmarkPanel.BookmarkViewMode;
import codechicken.nei.ItemsGrid;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.bookmark.RecipeChainDetails.BookmarkChainItem;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.recipe.Recipe.RecipeId;
@@ -30,10 +31,10 @@ public class SortableItem {
this.grid = grid;
this.bookmarkItem = bookmarkItem.copy();
this.moveRecipe = bookmarkItem.recipeId != null && !bookmarkItem.isIngredient
this.moveRecipe = bookmarkItem.recipeId != null && bookmarkItem.type == BookmarkItemType.RESULT
&& (group.viewMode == BookmarkViewMode.TODO_LIST || group.crafting != null);
this.crossGroup = !group.collapsed && group.viewMode == BookmarkViewMode.TODO_LIST
&& !this.bookmarkItem.isIngredient;
&& bookmarkItem.type != BookmarkItemType.INGREDIENT;
this.isCollapsedRecipe = group.crafting != null && group.crafting.itemToRecipe.values().stream()
.anyMatch(recipeId -> this.bookmarkItem.equalsRecipe(recipeId, this.bookmarkItem.groupId));
@@ -0,0 +1,78 @@
package codechicken.nei.commands;
import java.io.File;
import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommandSender;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.ChatStyle;
import net.minecraft.util.EnumChatFormatting;
import codechicken.nei.ItemList;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.util.ItemUntranslator;
public class CommandUntranslator extends CommandBase {
@Override
public String getCommandName() {
return "untranslator";
}
@Override
public String getCommandUsage(ICommandSender sender) {
return "/untranslator dump OR /untranslator clear";
}
@Override
public int getRequiredPermissionLevel() {
return 0;
}
@Override
public void processCommand(ICommandSender sender, String[] args) {
final String command = args.length == 0 ? null : args[0];
if ("dump".equals(command)) {
if (ItemList.items.isEmpty()) {
sendChatErrorMessage(sender, "nei.chat.untranslator.dump.error");
return;
} else {
sendChatInfoMessage(sender, "nei.chat.untranslator.dump.start");
ItemUntranslator.getInstance().generateUntranslatedNames();
sendChatInfoMessage(sender, "nei.chat.untranslator.dump.finish");
if (NEIClientConfig.enableItemUntranslator()) {
ItemUntranslator.getInstance().load();
}
}
} else if ("clear".equals(command)) {
final File file = new File(NEIClientConfig.configDir, "untranslator.cfg");
if (file.exists() && file.delete()) {
sendChatInfoMessage(sender, "nei.chat.untranslator.clear");
if (NEIClientConfig.enableItemUntranslator()) {
ItemUntranslator.getInstance().load();
}
} else {
sendChatErrorMessage(sender, "nei.chat.untranslator.clear.error");
}
} else {
sendChatErrorMessage(sender, getCommandUsage(sender));
}
}
private static void sendChatInfoMessage(ICommandSender sender, String translationKey, Object... args) {
sender.addChatMessage(
new ChatComponentTranslation(translationKey, args)
.setChatStyle(new ChatStyle().setColor(EnumChatFormatting.AQUA)));
}
private static void sendChatErrorMessage(ICommandSender sender, String translationKey, Object... args) {
sender.addChatMessage(
new ChatComponentTranslation(translationKey, args)
.setChatStyle(new ChatStyle().setColor(EnumChatFormatting.RED)));
}
}
@@ -98,6 +98,7 @@ public class IMCHandler {
}
// true if not set to false
info.setUseCustomScroll(tag.hasKey("useCustomScroll") && tag.getBoolean("useCustomScroll"));
info.setShowFavoritesButton(!tag.hasKey("showFavoritesButton") || tag.getBoolean("showFavoritesButton"));
info.setShowOverlayButton(!tag.hasKey("showOverlayButton") || tag.getBoolean("showOverlayButton"));
@@ -47,7 +47,7 @@ public class OptionUtilities extends OptionStringSet {
LayoutManager.drawIcon(x + 4, 4, new Image(132, 12, 12, 12));
x += 24;
GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_LIGHTING_BIT);
RenderHelper.enableGUIStandardItemLighting();
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
ItemStack sword = new ItemStack(Items.diamond_sword);
@@ -4,6 +4,8 @@ import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import codechicken.nei.Image;
public class DrawableResource extends Image {
@@ -43,15 +45,160 @@ public class DrawableResource extends Image {
}
public void draw(int xOffset, int yOffset, int maskTop, int maskBottom, int maskLeft, int maskRight) {
Minecraft.getMinecraft().getTextureManager().bindTexture(this.resourceLocation);
final int x = xOffset + this.paddingLeft + maskLeft;
final int y = yOffset + this.paddingTop + maskTop;
final int textureX = this.x + maskLeft;
final int textureY = this.y + maskTop;
final boolean is2DTexture = GL11.glGetBoolean(GL11.GL_TEXTURE_2D);
final int width = this.width - maskRight - maskLeft;
final int height = this.height - maskBottom - maskTop;
// drawModalRectWithCustomSizedTexture
Gui.func_146110_a(x, y, textureX, textureY, width, height, textureWidth, textureHeight);
GL11.glEnable(GL11.GL_TEXTURE_2D);
Minecraft.getMinecraft().getTextureManager().bindTexture(this.resourceLocation);
drawModalRectWithCustomSizedTexture(xOffset + maskLeft, yOffset + maskTop, maskLeft, maskTop, width, height);
if (!is2DTexture) GL11.glDisable(GL11.GL_TEXTURE_2D);
}
public void draw(int xOffset, int yOffset, int width, int height, int sliceLeft, int sliceRight, int sliceTop,
int sliceBottom) {
final int textureWidth = getWidth();
final int textureHeight = getHeight();
final int middleWidth = textureWidth - sliceLeft - sliceRight;
final int middleHeight = textureHeight - sliceTop - sliceBottom;
final int tileWidth = width - sliceLeft - sliceRight;
final int tileHeight = height - sliceTop - sliceBottom;
if (middleWidth > 0 && middleHeight > 0 && tileWidth > 0 && tileHeight > 0) {
final boolean is2DTexture = GL11.glGetBoolean(GL11.GL_TEXTURE_2D);
final int tileWidthCount = tileWidth / middleWidth;
final int remainderWidth = tileWidth - (tileWidthCount * middleWidth);
final int tileHeightCount = tileHeight / middleHeight;
final int remainderHeight = tileHeight - (tileHeightCount * middleHeight);
GL11.glEnable(GL11.GL_TEXTURE_2D);
Minecraft.getMinecraft().getTextureManager().bindTexture(this.resourceLocation);
// middle parts
for (int tileW = 0; tileW <= tileWidthCount; tileW++) {
final int tileWidthSize = (tileW == tileWidthCount) ? remainderWidth : middleWidth;
final int x = xOffset + sliceLeft + tileW * middleWidth;
for (int tileH = 0; tileH <= tileHeightCount; tileH++) {
final int tileHeightSize = (tileH == tileHeightCount) ? remainderHeight : middleHeight;
drawModalRectWithCustomSizedTexture(
x,
yOffset + sliceTop + tileH * middleHeight,
sliceLeft,
sliceTop,
tileWidthSize,
tileHeightSize);
}
}
// border top
if (sliceTop > 0) {
for (int tileW = 0; tileW <= tileWidthCount; tileW++) {
final int tileWidthSize = (tileW == tileWidthCount) ? remainderWidth : middleWidth;
drawModalRectWithCustomSizedTexture(
xOffset + sliceLeft + tileW * middleWidth,
yOffset,
sliceLeft,
0,
tileWidthSize,
sliceTop);
}
}
// border bottom
if (sliceBottom > 0) {
for (int tileW = 0; tileW <= tileWidthCount; tileW++) {
final int tileWidthSize = (tileW == tileWidthCount) ? remainderWidth : middleWidth;
drawModalRectWithCustomSizedTexture(
xOffset + sliceLeft + tileW * middleWidth,
yOffset + sliceTop + tileHeight,
sliceLeft,
sliceTop + middleHeight,
tileWidthSize,
sliceBottom);
}
}
// border left
if (sliceLeft > 0) {
for (int tileH = 0; tileH <= tileHeightCount; tileH++) {
final int tileHeightSize = (tileH == tileHeightCount) ? remainderHeight : middleHeight;
drawModalRectWithCustomSizedTexture(
xOffset,
yOffset + sliceTop + tileH * middleHeight,
0,
sliceTop,
sliceLeft,
tileHeightSize);
}
}
// border right
if (sliceRight > 0) {
for (int tileH = 0; tileH <= tileHeightCount; tileH++) {
final int tileHeightSize = (tileH == tileHeightCount) ? remainderHeight : middleHeight;
drawModalRectWithCustomSizedTexture(
xOffset + sliceLeft + tileWidth,
yOffset + sliceTop + tileH * middleHeight,
sliceLeft + middleWidth,
sliceTop,
sliceRight,
tileHeightSize);
}
}
// angle left-top
if (sliceLeft > 0 && sliceTop > 0) {
drawModalRectWithCustomSizedTexture(xOffset, yOffset, 0, 0, sliceLeft, sliceTop);
}
// angle right-top
if (sliceRight > 0 && sliceTop > 0) {
drawModalRectWithCustomSizedTexture(
xOffset + sliceLeft + tileWidth,
yOffset,
sliceLeft + middleWidth,
0,
sliceRight,
sliceTop);
}
// angle left-bottom
if (sliceLeft > 0 && sliceBottom > 0) {
drawModalRectWithCustomSizedTexture(
xOffset,
yOffset + sliceTop + tileHeight,
0,
sliceTop + middleHeight,
sliceLeft,
sliceBottom);
}
// angle right-bottom
if (sliceRight > 0 && sliceBottom > 0) {
drawModalRectWithCustomSizedTexture(
xOffset + sliceLeft + tileWidth,
yOffset + sliceTop + tileHeight,
sliceLeft + middleWidth,
sliceTop + middleHeight,
sliceRight,
sliceBottom);
}
if (!is2DTexture) GL11.glDisable(GL11.GL_TEXTURE_2D);
}
}
private void drawModalRectWithCustomSizedTexture(int xOffset, int yOffset, int u, int v, int width, int height) {
Gui.func_146110_a(
xOffset + this.paddingLeft,
yOffset + this.paddingTop,
this.x + u,
this.y + v,
width,
height,
this.textureWidth,
this.textureHeight);
}
}
@@ -1,93 +0,0 @@
package codechicken.nei.drawable;
import net.minecraft.client.gui.GuiScreen;
import org.lwjgl.opengl.GL11;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
/*
* Taken from Mantle 1.12-1.3.3.49 under the MIT License 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.
*/
@SideOnly(Side.CLIENT)
public class GuiElementDuex {
// this is totally completely ugly but it's a simple solution that doesn't clutter everything too much >_>
public static int defaultTexW = 256;
public static int defaultTexH = 256;
public final int x;
public final int y;
public final int w;
public final int h;
public int texW;
public int texH;
public GuiElementDuex(int x, int y, int w, int h, int texW, int texH) {
this(x, y, w, h);
setTextureSize(texW, texH);
defaultTexW = texW;
defaultTexH = texH;
}
public GuiElementDuex(int x, int y, int w, int h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
setTextureSize(defaultTexW, defaultTexH);
}
public GuiElementDuex setTextureSize(int w, int h) {
texW = w;
texH = h;
return this;
}
public GuiElementDuex shift(int xd, int yd) {
return new GuiElementDuex(this.x + xd, this.y + yd, this.w, this.h, this.texW, this.texH);
}
/**
* Draws the element at the given x/y coordinates
*
* @param xPos X-Coordinate on the screen
* @param yPos Y-Coordinate on the screen
*/
public int draw(int xPos, int yPos) {
// drawModalRectWithCustomSizedTexture
GL11.glColor4f(1, 1, 1, 1);
GuiScreen.func_146110_a(xPos, yPos, x, y, w, h, texW, texH);
return w;
}
public static class Builder {
public int w;
public int h;
public Builder(int w, int h) {
this.w = w;
this.h = h;
}
public GuiElementDuex get(int x, int y, int w, int h) {
return new GuiElementDuex(x, y, w, h, this.w, this.h);
}
}
}
@@ -1,91 +0,0 @@
package codechicken.nei.drawable;
import net.minecraft.client.gui.GuiScreen;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
/*
* Taken from Mantle 1.12-1.3.3.49 under the MIT License 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.
*/
@SideOnly(Side.CLIENT)
public class GuiElementScalable extends GuiElementDuex {
public GuiElementScalable(int x, int y, int w, int h, int texW, int texH) {
super(x, y, w, h, texW, texH);
}
public GuiElementScalable(int x, int y, int w, int h) {
super(x, y, w, h);
}
public int drawScaledX(int xPos, int yPos, int width) {
for (int i = 0; i < width / w; i++) {
draw(xPos + i * w, yPos);
}
// remainder that doesn't fit total width
int remainder = width % w;
if (remainder > 0) {
GuiScreen.func_146110_a(xPos + width - remainder, yPos, x, y, remainder, h, texW, texH);
}
return width;
}
public int drawScaledY(int xPos, int yPos, int height) {
for (int i = 0; i < height / h; i++) {
draw(xPos, yPos + i * h);
}
// remainder that doesn't fit total width
int remainder = height % h;
if (remainder > 0) {
// drawModalRectWithCustomSizedTexture
GuiScreen.func_146110_a(xPos, yPos + height - remainder, x, y, w, remainder, texW, texH);
}
return w;
}
public int drawScaled(int xPos, int yPos, int width, int height) {
// we draw full height row-wise
int full = height / this.h;
for (int i = 0; i < full; i++) {
drawScaledX(xPos, yPos + i * this.h, width);
}
yPos += full * this.h;
// and the remainder is drawn manually
int yRest = height % this.h;
// the same as drawScaledX but with the remaining height
for (int i = 0; i < width / w; i++) {
drawScaledY(xPos + i * w, yPos, yRest);
}
// remainder that doesn't fit total width
int remainder = width % w;
if (remainder > 0) {
// drawModalRectWithCustomSizedTexture
GuiScreen.func_146110_a(xPos + width - remainder, yPos, x, y, remainder, yRest, texW, texH);
}
return width;
}
@Override
public GuiElementScalable shift(int xd, int yd) {
GuiElementScalable element = new GuiElementScalable(this.x + xd, this.y + yd, this.w, this.h);
element.setTextureSize(texW, texH);
return element;
}
}
@@ -49,6 +49,7 @@ import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.NEIModContainer;
import codechicken.nei.recipe.StackInfo;
import codechicken.nei.util.ItemUntranslator;
import codechicken.nei.util.ReadableNumberConverter;
import codechicken.nei.util.RenderTooltipEventHelper;
@@ -60,6 +61,10 @@ public class GuiContainerManager {
public void onResourceManagerReload(IResourceManager p_110549_1_) {
renderingErrorItems.clear();
ItemList.loadItems.restart();
if (NEIClientConfig.enableItemUntranslator()) {
ItemUntranslator.getInstance().load();
}
}
}
@@ -77,6 +82,9 @@ public class GuiContainerManager {
public static final LinkedList<IContainerSlotClickHandler> slotClickHandlers = new HideousLinkedList<>(
new CopyOnWriteArrayList<>());
// Any item rendered with this z offset should render it on top of every other gui element
public static final int TOOLTIP_Z_OFFSET = 400;
static {
addSlotClickHandler(new DefaultSlotClickHandler());
}
@@ -399,7 +407,7 @@ public class GuiContainerManager {
public static void enableMatrixStackLogging() {
if (!contextEnabled) {
GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_LIGHTING_BIT);
modelviewDepth = GL11.glGetInteger(GL11.GL_MODELVIEW_STACK_DEPTH);
contextEnabled = true;
}
@@ -590,8 +598,6 @@ public class GuiContainerManager {
}
}
if (!tooltip.isEmpty()) tooltip.set(0, tooltip.get(0) + GuiDraw.TOOLTIP_LINESPACE); // add space after 'title'
if (showTooltip && NEIClientConfig.getBooleanSetting("inventory.showHotkeys")) {
List<String> hotkeystips = collectHotkeyTips(mousex, mousey);
@@ -605,6 +611,19 @@ public class GuiContainerManager {
}
}
if (showTooltip && stack != null && !tooltip.isEmpty()) {
final String secondDisplayName = ItemUntranslator.getInstance().getItemStackDisplayName(stack);
if (!secondDisplayName.isEmpty()) {
tooltip.add(1, EnumChatFormatting.DARK_GRAY + secondDisplayName + GuiDraw.TOOLTIP_LINESPACE);
} else {
tooltip.set(0, tooltip.get(0) + GuiDraw.TOOLTIP_LINESPACE);
}
} else if (!tooltip.isEmpty()) {
tooltip.set(0, tooltip.get(0) + GuiDraw.TOOLTIP_LINESPACE);
}
if (NEIModContainer.isGTNHLibLoaded() && !tooltip.isEmpty()) {
if (RenderTooltipEventHelper.post(stack, this.window, mousex, mousey, font)) {
return;
@@ -632,9 +651,6 @@ public class GuiContainerManager {
drawPagedTooltip(font, mousex + 12, mousey - 12, tooltip);
}
for (IContainerDrawHandler drawHandler : drawHandlers) {
drawHandler.postRenderTooltips(window, mousex, mousey, tooltip);
}
}
private List<String> collectHotkeyTips(int mousex, int mousey) {
@@ -1,7 +1,5 @@
package codechicken.nei.guihook;
import java.util.List;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.inventory.Slot;
@@ -9,14 +7,14 @@ public interface IContainerDrawHandler {
/**
* Initialize your objects and the gui for drawing.
*
*
* @param gui An instance of the currentscreen
*/
public void onPreDraw(GuiContainer gui);
/**
* Draw your objects. Called after all normal gui rendering has been performed.
*
*
* @param gui An instance of the currentscreen
* @param mousex The x position of the mouse in pixels from left
* @param mousey The y position of the mouse in pixels from top
@@ -25,27 +23,16 @@ public interface IContainerDrawHandler {
/**
* Use this to draw things that should always be on top, for example objects being held by the mouse.
*
*
* @param gui An instance of the currentscreen
* @param mousex The x position of the mouse in pixels from left
* @param mousey The y position of the mouse in pixels from top
*/
public void postRenderObjects(GuiContainer gui, int mousex, int mousey);
/**
* Use this to draw things that should be drawn just after vanilla slot tooltips, on top of buttons and other
* usually always-on-top widgets.
*
* @param gui An instance of the currentscreen
* @param mousex The x position of the mouse in pixels from left
* @param mousey The y position of the mouse in pixels from top
* @param tooltip The contents of the tooltip that has previously been drawn
*/
default void postRenderTooltips(GuiContainer gui, int mousex, int mousey, List<String> tooltip) {}
/**
* Render something over a slot before the item in the slot.
*
*
* @param gui An instance of the currentscreen
* @param slot The slot being rendered.
*/
@@ -53,7 +40,7 @@ public interface IContainerDrawHandler {
/**
* Render something over a slot after the item in the slot.
*
*
* @param gui An instance of the currentscreen
* @param slot The slot being rendered.
*/
@@ -11,7 +11,7 @@ import codechicken.nei.NEIClientUtils;
public class AcceptsFollowingTooltipLineHandler extends ItemsTooltipLineHandler {
protected static final int DEFAULT_MAX_ROWS = 5;
protected static final int DEFAULT_MAX_ROWS = 4;
public Object tooltipGUID;
@@ -2,122 +2,29 @@ package codechicken.nei.recipe;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import codechicken.nei.PositionedStack;
import codechicken.nei.api.ShortcutInputHandler;
public class ContainerRecipe extends Container {
private class RecipeInventory implements IInventory {
private ItemStack activeStack = null;
@Override
public boolean isUseableByPlayer(EntityPlayer entityplayer) {
return true;
}
@Override
public int getSizeInventory() {
return inventorySlots.size();
}
@Override
public ItemStack getStackInSlot(int i) {
if (i < 0 || i > inventoryItemStacks.size()) return null;
return (ItemStack) inventoryItemStacks.get(i);
}
@Override
public ItemStack decrStackSize(int i, int j) {
return null;
}
@Override
public void setInventorySlotContents(int slot, ItemStack itemstack) {
if (slot < 0 || slot >= inventoryItemStacks.size()) return;
inventoryItemStacks.set(slot, itemstack);
}
@Override
public String getInventoryName() {
return null;
}
@Override
public int getInventoryStackLimit() {
return 1;
}
@Override
public void markDirty() {}
@Override
public void openInventory() {}
@Override
public void closeInventory() {}
@Override
public ItemStack getStackInSlotOnClosing(int var1) {
return null;
}
@Override
public boolean isItemValidForSlot(int i, ItemStack itemstack) {
return false;
}
@Override
public boolean hasCustomInventoryName() {
return false;
}
}
private final RecipeInventory recipeInventory = new RecipeInventory();
public void clearInventory() {
inventoryItemStacks.clear();
inventorySlots.clear();
}
public ItemStack slotClick(int slot, int button, boolean flag, EntityPlayer entityplayer) {
if (slot < 0) return null;
ItemStack stack = recipeInventory.getStackInSlot(slot);
if (stack != null) {
if (button == 0) {
GuiCraftingRecipe.openRecipeGui("item", stack);
} else if (button == 1) {
GuiUsageRecipe.openRecipeGui("item", stack);
}
}
@Override
public ItemStack slotClick(int slotId, int clickedButton, int mode, EntityPlayer player) {
ShortcutInputHandler.handleMouseClick(this.activeStack);
return null;
}
public void addSlot(PositionedStack stack, int recipex, int recipey) {
int slot = inventorySlots.size();
addSlotToContainer(new Slot(recipeInventory, slot, recipex + stack.relx, recipey + stack.rely) {
@Override
public boolean isItemValid(ItemStack par1ItemStack) {
return false;
}
});
recipeInventory.setInventorySlotContents(slot, stack.item);
}
public Slot getSlotWithStack(PositionedStack stack, int recipex, int recipey) {
for (Object inventorySlot : inventorySlots) {
Slot slot = (Slot) inventorySlot;
if (slot.xDisplayPosition == (stack.relx + recipex) && slot.yDisplayPosition == (stack.rely + recipey))
return slot;
}
return null;
public void setActiveStack(ItemStack activeStack) {
this.inventorySlots.clear();
this.inventoryItemStacks.clear();
this.activeStack = activeStack;
}
@Override
public boolean canInteractWith(EntityPlayer entityplayer) {
return true;
}
@@ -131,4 +38,9 @@ public class ContainerRecipe extends Container {
public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int par2) {
return null; // no shift clicking (scrolling...)
}
@Deprecated
public Slot getSlotWithStack(PositionedStack stack, int recipex, int recipey) {
return null;
}
}
@@ -0,0 +1,646 @@
package codechicken.nei.recipe;
import java.awt.Point;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.stream.Collectors;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.inventory.GuiContainer;
import org.apache.commons.io.IOUtils;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
import codechicken.lib.gui.GuiDraw;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.Button;
import codechicken.nei.ClientHandler;
import codechicken.nei.FormattedTextField;
import codechicken.nei.LayoutManager;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.TextField;
import codechicken.nei.Widget;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.guihook.IContainerInputHandler;
import codechicken.nei.recipe.TemplateRecipeHandler.RecipeTransferRect;
public class DebugHandlerWidget extends Widget implements IContainerInputHandler {
private static abstract class IntegerField extends TextField {
protected int defaultValue = 0;
public IntegerField(String ident, int defaultValue) {
super(ident);
this.defaultValue = defaultValue;
this.h = LINE_HEIGHT;
this.z = 2;
((FormattedTextField) field).setPlaceholder(Integer.toString(this.defaultValue));
}
@Override
protected void initInternalTextField() {
field = new FormattedTextField(Minecraft.getMinecraft().fontRenderer, 0, 0, 0, 0) {
@Override
public String getText() {
String text = super.getText();
return !isFocused() && this.placeholder.equals(text) ? "" : text;
}
@Override
protected boolean beforeWrite(String text) {
if (text == null || text.isEmpty()) return true;
try {
return Integer.parseInt(text) >= 0;
} catch (NumberFormatException e) {
return false;
}
}
@Override
public boolean textboxKeyTyped(char keyChar, int keyID) {
if (!isFocused()) return false;
if (super.textboxKeyTyped(keyChar, keyID)) {
return true;
} else if (keyID == Keyboard.KEY_DOWN) {
setText(Integer.toString(getInteger() - 1));
return true;
} else if (keyID == Keyboard.KEY_UP) {
setText(Integer.toString(getInteger() + 1));
return true;
}
return false;
}
};
field.setMaxStringLength(maxSearchLength);
field.setCursorPositionZero();
}
protected int getInteger() {
try {
return Integer.parseInt(text());
} catch (NumberFormatException nfe) {
return this.defaultValue;
}
}
@Override
public boolean onMouseWheel(int i, int mx, int my) {
if (!contains(mx, my)) return false;
setText(Integer.toString(getInteger() + i));
return true;
}
}
private final int[] COLORS = new int[] { 0x2200FF00, 0x22FF0000, 0x220000FF, 0x2200FFFF, 0x22FF00FF, 0x22FFFF00 };
private IRecipeHandler handler;
private HandlerInfo handlerInfo;
private static final int WINDOW_WIDTH = 176;
private static final int LINE_HEIGHT = 16;
private static final int INLINE_PADDING = 6;
private static final int LABEL_WIDTH = 50;
private IntegerField order;
private IntegerField yShift;
private IntegerField handlerHeight;
private IntegerField handlerWidth;
private IntegerField maxRecipesPerPage;
private Button useCustomScroll;
private Point dragPoint = null;
public boolean showWidget = false;
private static final int BORDER_PADDING = 6;
private final DrawableResource BG_TEXTURE = new DrawableBuilder("nei:textures/gui/recipebg.png", 0, 0, 176, 166)
.build();
public DebugHandlerWidget() {
GuiContainerManager.addInputHandler(this);
this.order = new IntegerField("order", 0) {
@Override
public void onTextChange(String oldText) {
if (NEIClientConfig.handlerOrdering.get(handler.getOverlayIdentifier()) != null) {
if (getInteger() != NEIClientConfig.handlerOrdering.get(handler.getOverlayIdentifier())) {
updatePatch(5, getInteger(), this.defaultValue);
}
} else if (NEIClientConfig.handlerOrdering.get(handler.getHandlerId()) != null) {
if (getInteger() != NEIClientConfig.handlerOrdering.get(handler.getHandlerId())) {
updatePatch(5, getInteger(), this.defaultValue);
}
}
}
};
this.yShift = new IntegerField("yShift", 0) {
@Override
public void onTextChange(String oldText) {
if (getInteger() != handlerInfo.getYShift()) {
handlerInfo.setYShift(getInteger());
updatePatch(1, getInteger(), this.defaultValue);
}
}
};
this.maxRecipesPerPage = new IntegerField("maxRecipesPerPage", HandlerInfo.DEFAULT_MAX_PER_PAGE) {
@Override
public void onTextChange(String oldText) {
if (getInteger() != handlerInfo.getMaxRecipesPerPage()) {
handlerInfo.setHandlerDimensions(handlerInfo.getHeight(), handlerInfo.getWidth(), getInteger());
updatePatch(4, getInteger(), this.defaultValue);
}
}
};
this.handlerHeight = new IntegerField("handlerHeight", HandlerInfo.DEFAULT_HEIGHT) {
@Override
public void draw(int mx, int my) {
this.field.setEnabled(handler.getRecipeHeight(0) <= 0);
super.draw(mx, my);
}
@Override
public void onTextChange(String oldText) {
if (getInteger() != handlerInfo.getHeight()) {
handlerInfo.setHandlerDimensions(
getInteger(),
handlerInfo.getWidth(),
handlerInfo.getMaxRecipesPerPage());
updatePatch(2, getInteger(), this.defaultValue);
}
}
};
this.handlerWidth = new IntegerField("handlerWidth", HandlerInfo.DEFAULT_WIDTH) {
@Override
public void onTextChange(String oldText) {
if (getInteger() != handlerInfo.getWidth()) {
handlerInfo.setHandlerDimensions(
handlerInfo.getHeight(),
getInteger(),
handlerInfo.getMaxRecipesPerPage());
updatePatch(3, getInteger(), this.defaultValue);
}
}
};
this.useCustomScroll = new Button() {
{
this.h = LINE_HEIGHT;
this.z = 2;
}
public String getRenderLabel() {
return handlerInfo.getUseCustomScroll() ? "On" : "Off";
}
@Override
public boolean onButtonPress(boolean rightclick) {
handlerInfo.setUseCustomScroll(!handlerInfo.getUseCustomScroll());
updatePatch(6, handlerInfo.getUseCustomScroll() ? 1 : 0, 0);
return true;
}
};
this.w = WINDOW_WIDTH;
this.h = 10 + 13 * LINE_HEIGHT;
this.x = 10;
this.y = 50;
this.z = 1;
}
private void updatePatch(int key, int value, int defaultValue) {
final String handlerKey = getHandlerID(handler);
if (!patches.containsKey(handlerKey)) {
patches.put(handlerKey, new String[] { handlerKey, null, null, null, null, null, null });
}
if (value == defaultValue) {
patches.get(handlerKey)[key] = null;
} else {
patches.get(handlerKey)[key] = String.valueOf(value);
}
saveHandlerInfoPatch();
if (NEIClientUtils.getGuiContainer() instanceof GuiRecipe<?>recipe) {
recipe.forceRefreshPage();
}
}
private void drawKeyLabel(String keyLabel, int topShift) {
GuiDraw.drawString(
NEIClientUtils.cropText(GuiDraw.fontRenderer, keyLabel, LABEL_WIDTH),
this.x + INLINE_PADDING,
topShift,
0x66555555,
false);
GuiDraw.drawString(":", this.x + INLINE_PADDING + LABEL_WIDTH, topShift, 0x66555555, false);
}
private void drawDetail(String keyLabel, String valueLabel, int topShift, int spaceWidth) {
drawKeyLabel(keyLabel, topShift);
GuiDraw.drawString(
NEIClientUtils.cropText(
GuiDraw.fontRenderer,
valueLabel,
this.w - INLINE_PADDING * 2 - LABEL_WIDTH - spaceWidth),
this.x + INLINE_PADDING + LABEL_WIDTH + spaceWidth,
topShift,
0xffffff);
}
private void drawControl(String keyLabel, Widget field, int topShift, int spaceWidth) {
drawKeyLabel(keyLabel, topShift);
field.x = this.x + INLINE_PADDING + LABEL_WIDTH + spaceWidth;
field.y = topShift - 4;
field.w = this.w - INLINE_PADDING * 2 - LABEL_WIDTH - spaceWidth;
}
@Override
public void draw(int mx, int my) {
if (this.handler != null) {
final int spaceWidth = GuiDraw.fontRenderer.getStringWidth(": ");
int topShift = this.y + BORDER_PADDING + 12 + 6;
GL11.glColor4f(1F, 1F, 1F, 1F);
GL11.glScaled(1, 1, 2f);
GL11.glDisable(GL11.GL_DEPTH_TEST);
BG_TEXTURE.draw(
this.x,
this.y,
this.w,
this.h,
BORDER_PADDING,
BORDER_PADDING,
BORDER_PADDING,
BORDER_PADDING);
GuiDraw.drawRect(
this.x + INLINE_PADDING,
this.y + BORDER_PADDING,
this.w - INLINE_PADDING * 2,
12,
0x30000000);
GuiDraw.drawStringC("Debug Recipe Handler", this.x + this.w / 2, this.y + BORDER_PADDING + 2, 0xffffff);
for (Map.Entry<String, String> entry : getDetailsInfo().entrySet()) {
drawDetail(entry.getKey(), entry.getValue(), topShift, spaceWidth);
topShift += LINE_HEIGHT;
}
drawControl("Order", this.order, topShift, spaceWidth);
topShift += LINE_HEIGHT;
drawControl("yShift", this.yShift, topShift, spaceWidth);
topShift += LINE_HEIGHT;
drawControl("Per Page", this.maxRecipesPerPage, topShift, spaceWidth);
topShift += LINE_HEIGHT;
drawControl("Height", this.handlerHeight, topShift, spaceWidth);
topShift += LINE_HEIGHT;
drawControl("Width", this.handlerWidth, topShift, spaceWidth);
topShift += LINE_HEIGHT;
drawControl("Use Custom Scroll", this.useCustomScroll, topShift, spaceWidth);
topShift += LINE_HEIGHT;
GL11.glScaled(1, 1, 1 / 2f);
}
}
private Map<String, String> getDetailsInfo() {
final Map<String, String> lines = new LinkedHashMap<>();
final boolean isHeightHackApplied = NEIClientConfig.heightHackHandlerRegex.stream()
.map(pattern -> pattern.matcher(this.handler.getHandlerId())).anyMatch(Matcher::matches);
lines.put("Name", this.handler.getRecipeName());
lines.put("ID", this.handler.getOverlayIdentifier());
lines.put("Key", this.handler.getHandlerId());
lines.put("H.Hack", String.valueOf(isHeightHackApplied));
lines.put("Mod Name", this.handlerInfo.getModName());
lines.put("Mod ID", this.handlerInfo.getModId());
return lines;
}
public void setVisible() {
if (showWidget && this.handler != null) {
LayoutManager.addWidget(this.order);
LayoutManager.addWidget(this.yShift);
LayoutManager.addWidget(this.handlerHeight);
LayoutManager.addWidget(this.handlerWidth);
LayoutManager.addWidget(this.maxRecipesPerPage);
LayoutManager.addWidget(this.useCustomScroll);
}
}
@Override
public void update() {
final GuiContainer gui = NEIClientUtils.getGuiContainer();
if (showWidget && gui instanceof GuiRecipe recipe) {
if (this.handler != recipe.getHandler()) {
this.handler = recipe.getHandler();
this.handlerInfo = GuiRecipeTab.getHandlerInfo(handler);
this.order.setText(String.valueOf(NEIClientConfig.getHandlerOrder(this.handler)));
this.yShift.setText(String.valueOf(this.handlerInfo.getYShift()));
this.handlerHeight.setText(String.valueOf(this.handlerInfo.getHeight()));
this.handlerWidth.setText(String.valueOf(this.handlerInfo.getWidth()));
this.maxRecipesPerPage.setText(String.valueOf(this.handlerInfo.getMaxRecipesPerPage()));
}
} else {
this.handler = null;
this.handlerInfo = null;
showWidget = false;
}
}
@Override
public List<String> handleTooltip(int mx, int my, List<String> tooltip) {
if (this.handler != null) {
final int spaceWidth = GuiDraw.fontRenderer.getStringWidth(": ");
final int leftShift = this.x + INLINE_PADDING;
if (mx >= leftShift && mx < this.x + WINDOW_WIDTH - INLINE_PADDING) {
int topShift = this.y + BORDER_PADDING + 12 + 6;
for (Map.Entry<String, String> entry : getDetailsInfo().entrySet()) {
if (my >= topShift && my < topShift + LINE_HEIGHT) {
if (mx < leftShift + LABEL_WIDTH + spaceWidth) {
tooltip.add(String.valueOf(entry.getKey()));
} else {
tooltip.add(String.valueOf(entry.getValue()));
}
break;
}
topShift += LINE_HEIGHT;
}
}
}
return tooltip;
}
@Override
public boolean keyTyped(GuiContainer gui, char keyChar, int keyCode) {
if (NEIClientConfig.getBooleanSetting("inventory.guirecipe.handlerInfo") && showWidget
&& keyCode == Keyboard.KEY_C
&& NEIClientUtils.controlKey()) {
final int spaceWidth = GuiDraw.fontRenderer.getStringWidth(": ");
final Point mouse = GuiDraw.getMousePosition();
if (mouse.x >= this.x + INLINE_PADDING + LABEL_WIDTH + spaceWidth
&& mouse.x < this.x + WINDOW_WIDTH - INLINE_PADDING) {
int topShift = this.y + BORDER_PADDING + 12 + 6;
for (Map.Entry<String, String> entry : getDetailsInfo().entrySet()) {
if (mouse.y >= topShift && mouse.y < topShift + LINE_HEIGHT) {
GuiScreen.setClipboardString(entry.getValue());
return true;
}
topShift += LINE_HEIGHT;
}
}
}
return false;
}
@Override
public boolean mouseClicked(GuiContainer gui, int mousex, int mousey, int button) {
return false;
}
@Override
public void onKeyTyped(GuiContainer gui, char keyChar, int keyID) {}
@Override
public boolean lastKeyTyped(GuiContainer gui, char keyChar, int keyID) {
if (NEIClientConfig.getBooleanSetting("inventory.guirecipe.handlerInfo") && keyID == Keyboard.KEY_D
&& NEIClientUtils.shiftKey()) {
showWidget = !showWidget;
return true;
} else if (this.handler != null) {
return this.order.focused() || this.yShift.focused()
|| this.handlerHeight.focused()
|| this.handlerWidth.focused()
|| this.maxRecipesPerPage.focused();
}
return false;
}
@Override
public void onMouseClicked(GuiContainer gui, int mousex, int mousey, int button) {
if (this.handler != null
&& new Rectangle4i(this.x + INLINE_PADDING, this.y + BORDER_PADDING, this.w - INLINE_PADDING * 2, 12)
.contains(mousex, mousey)) {
this.dragPoint = new Point(mousex, mousey);
}
}
@Override
public boolean contains(int px, int py) {
return this.handler != null && super.contains(px, py);
}
@Override
public void onMouseUp(GuiContainer gui, int mousex, int mousey, int button) {
this.dragPoint = null;
}
@Override
public boolean mouseScrolled(GuiContainer gui, int mousex, int mousey, int scrolled) {
return false;
}
@Override
public void onMouseScrolled(GuiContainer gui, int mousex, int mousey, int scrolled) {}
@Override
public boolean handleClickExt(int mx, int my, int button) {
return false;
}
@Override
public void onMouseDragged(GuiContainer gui, int mousex, int mousey, int button, long heldTime) {
if (this.dragPoint != null) {
this.x -= this.dragPoint.x - mousex;
this.y -= this.dragPoint.y - mousey;
this.dragPoint.move(mousex, mousey);
}
}
public void drawGuiPlaceholder(NEIRecipeWidget widget) {
if (!showWidget) return;
NEIClientUtils.gl2DRenderContext(() -> {
// background
GuiDraw.drawRect(
widget.x,
widget.y,
widget.w,
widget.h,
COLORS[widget.handlerRef.recipeIndex % COLORS.length]);
// blue-line-top (grid-top)
GuiDraw.drawRect(widget.x + 14, widget.y + 5, widget.w - 38, 1, 0xff0000aa);
// blue-line-bottom {grid-bottom}
GuiDraw.drawRect(widget.x + 14, widget.y + widget.h - 7, widget.w - 38, 1, 0xff0000aa);
// blue-left (grid start)
GuiDraw.drawRect(widget.x + 24, widget.y + (widget.h - 16) / 2, 1, 16, 0xffaa00aa);
// purple (before favorite)
GuiDraw.drawRect(
widget.x + Math.min(168, widget.w) - 27,
widget.y + widget.h - 6 - GuiRecipeButton.BUTTON_HEIGHT * 2 - 4,
GuiRecipeButton.BUTTON_WIDTH,
1,
0xffaa00aa);
// green ()
GuiDraw.drawRect(
widget.x + Math.min(168, widget.w) - 35,
widget.y + widget.h - 6 - GuiRecipeButton.BUTTON_HEIGHT - 3,
20,
1,
0xff00aa00);
// purple space before bottom grid
GuiDraw.drawRect(
widget.x + 14,
widget.y + widget.h - 7 - GuiRecipeButton.BUTTON_WIDTH / 2,
38,
1,
0xffaa00aa);
if (widget.handlerRef.handler instanceof TemplateRecipeHandler handler) {
int yShift = widget.getHandlerInfo().getYShift();
for (RecipeTransferRect rect : handler.transferRects) {
GuiDraw.drawRect(
widget.x + rect.rect.x,
widget.y + yShift + rect.rect.y,
rect.rect.width,
rect.rect.height,
0x40ff0000);
}
}
});
}
private static Map<String, String[]> patches = new HashMap<>();
public static void loadHandlerInfoPatch() {
ClientHandler.loadSettingsFile("handlers.patch", lines -> {
for (String line : lines.collect(Collectors.toCollection(HashSet::new))) {
final String[] parts = line.split(",");
final String handler = parts[0];
if (GuiRecipeTab.handlerMap.containsKey(handler)) {
final HandlerInfo info = GuiRecipeTab.handlerMap.get(handler);
final int yShift = intOrDefault(parts[1], info.getYShift());
final int height = intOrDefault(parts[2], info.getHeight());
final int width = intOrDefault(parts[3], info.getWidth());
final int maxRecipesPerPage = intOrDefault(parts[4], info.getMaxRecipesPerPage());
final int order = intOrDefault(parts[5], NEIClientConfig.handlerOrdering.getOrDefault(handler, 0));
final boolean useCustomScroll = intOrDefault(parts[6], info.getUseCustomScroll() ? 1 : 0) == 1;
info.setYShift(yShift);
info.setHandlerDimensions(height, width, maxRecipesPerPage);
info.setUseCustomScroll(useCustomScroll);
NEIClientConfig.handlerOrdering.put(handler, order);
}
patches.put(handler, parts);
}
});
}
private static void saveHandlerInfoPatch() {
final List<String> lines = new ArrayList<>();
for (String[] line : patches.values()) {
lines.add(String.join(",", line));
}
final File path = new File(NEIClientConfig.configDir, "handlers.patch");
try (FileOutputStream output = new FileOutputStream(path)) {
IOUtils.writeLines(lines, "\n", output, StandardCharsets.UTF_8);
} catch (IOException e) {}
}
private static int intOrDefault(String str, int defaultValue) {
if (str == null || str.equals("")) return defaultValue;
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) {
return defaultValue;
}
}
private static String getHandlerID(IRecipeHandler handler) {
if (GuiRecipeTab.handlerMap.containsKey(handler.getHandlerId())) {
return handler.getHandlerId();
} else if (handler instanceof TemplateRecipeHandler) {
return handler.getOverlayIdentifier();
}
return null;
}
}
@@ -27,7 +27,7 @@ public class FurnaceRecipeHandler extends TemplateRecipeHandler {
}
public List<PositionedStack> getIngredients() {
return getCycledIngredients(cycleticks / 48, Collections.singletonList(ingred));
return Collections.singletonList(ingred);
}
public PositionedStack getResult() {
@@ -13,13 +13,14 @@ import net.minecraft.client.gui.GuiScreen;
import net.minecraft.item.ItemStack;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.FavoriteRecipes;
import codechicken.nei.ItemPanels;
import codechicken.nei.ItemsGrid.ItemsGridSlot;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.bookmark.BookmarksGridSlot;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.recipe.stackinfo.GTFluidStackStringifyHandler;
public class GuiCraftingRecipe extends GuiRecipe<ICraftingHandler> {
@@ -35,10 +36,13 @@ public class GuiCraftingRecipe extends GuiRecipe<ICraftingHandler> {
final Minecraft mc = NEIClientUtils.mc();
final RecipeId recipeId;
if ("item".equals(outputId)) {
for (int i = 0; i < results.length; i++) {
results[i] = normalizeItemStack((ItemStack) results[i]);
for (int i = 0; i < results.length; i++) {
if (results[i] instanceof ItemStack stack) {
results[i] = StackInfo.normalizeRecipeQueryStack(stack.copy());
}
}
if ("item".equals(outputId)) {
recipeId = getRecipeId(mc.currentScreen, (ItemStack) results[0]);
} else if ("recipeId".equals(outputId)) {
recipeId = (RecipeId) results[1];
@@ -49,7 +53,7 @@ public class GuiCraftingRecipe extends GuiRecipe<ICraftingHandler> {
final ArrayList<ICraftingHandler> handlers = getCraftingHandlers(outputId, results);
if (!handlers.isEmpty()) {
final GuiCraftingRecipe gui = new GuiCraftingRecipe(handlers, "recipeId".equals(outputId));
final GuiCraftingRecipe gui = new GuiCraftingRecipe(handlers);
if (open) {
@@ -104,13 +108,6 @@ public class GuiCraftingRecipe extends GuiRecipe<ICraftingHandler> {
return GuiRecipeTab.getHandlerInfo(handler).getHandlerName();
}
private static ItemStack normalizeItemStack(ItemStack stack) {
GTFluidStackStringifyHandler.replaceAE2FCFluidDrop = true;
stack = StackInfo.loadFromNBT(StackInfo.itemStackToNBT(stack));
GTFluidStackStringifyHandler.replaceAE2FCFluidDrop = false;
return stack;
}
public static RecipeId getRecipeId(GuiScreen gui, ItemStack stackover) {
if (gui instanceof GuiRecipe guiRecipe) {
@@ -123,10 +120,11 @@ public class GuiCraftingRecipe extends GuiRecipe<ICraftingHandler> {
final Point mouseover = GuiDraw.getMousePosition();
final BookmarksGridSlot panelSlot = ItemPanels.bookmarkPanel.getSlotMouseOver(mouseover.x, mouseover.y);
RecipeId recipeId = null;
if (panelSlot != null && !panelSlot.isIngredient()) {
recipeId = panelSlot.getRecipeId();
if (panelSlot != null) {
return panelSlot.getType() == BookmarkItemType.INGREDIENT || panelSlot.getRecipeId() == null
? FavoriteRecipes.getFavorite(stackover)
: panelSlot.getRecipeId();
}
ItemsGridSlot itemSlot = ItemPanels.itemPanel.getSlotMouseOver(mouseover.x, mouseover.y);
@@ -143,12 +141,11 @@ public class GuiCraftingRecipe extends GuiRecipe<ICraftingHandler> {
return itemSlot.getRecipeId();
}
return recipeId;
return null;
}
private GuiCraftingRecipe(ArrayList<ICraftingHandler> handlers, boolean limitToOneRecipe) {
private GuiCraftingRecipe(ArrayList<ICraftingHandler> handlers) {
super(NEIClientUtils.mc().currentScreen);
this.limitToOneRecipe = limitToOneRecipe;
this.currenthandlers = handlers;
}
@@ -9,7 +9,6 @@ import java.util.Map;
import java.util.Set;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.item.ItemStack;
import org.lwjgl.opengl.GL11;
@@ -116,7 +115,7 @@ public class GuiFavoriteButton extends GuiRecipeButton {
return Recipe.of(this.handlerRef);
}
public void lastKeyTyped(GuiRecipe<?> gui, char keyChar, int keyID) {
public void lastKeyTyped(char keyChar, int keyID) {
if (NEIClientConfig.isKeyHashDown("gui.bookmark") && NEIClientUtils.shiftKey()) {
saveRecipeInBookmark();
@@ -125,7 +124,7 @@ public class GuiFavoriteButton extends GuiRecipeButton {
}
@Override
public Map<String, String> handleHotkeys(GuiContainer gui, int mousex, int mousey, Map<String, String> hotkeys) {
public Map<String, String> handleHotkeys(int mousex, int mousey, Map<String, String> hotkeys) {
hotkeys.put(
NEIClientConfig.getKeyName("gui.bookmark", NEIClientUtils.SHIFT_HASH),
translate("recipe.favorite.bookmark_recipe"));
@@ -140,7 +139,7 @@ public class GuiFavoriteButton extends GuiRecipeButton {
}
@Override
public List<String> handleTooltip(GuiRecipe<?> gui, List<String> currenttip) {
public List<String> handleTooltip(List<String> currenttip) {
currenttip.add(translate("recipe.favorite"));
return currenttip;
@@ -161,7 +160,7 @@ public class GuiFavoriteButton extends GuiRecipeButton {
}
@Override
public boolean mouseScrolled(GuiRecipe<?> gui, int scroll) {
public boolean mouseScrolled(int scroll) {
if (this.selectedResult == null) return true;
final List<RecipeIngredient> results = new ArrayList<>(this.recipe.getResults());
@@ -106,17 +106,17 @@ public class GuiOverlayButton extends GuiRecipeButton {
}
@Override
public List<String> handleTooltip(GuiRecipe<?> gui, List<String> currenttip) {
public List<String> handleTooltip(List<String> currenttip) {
currenttip.add(NEIClientUtils.translate("recipe.overlay"));
if (!this.enabled && this.requireShiftForOverlayRecipe && this.canFillCraftingGrid) {
if (!this.enabled && requireShiftForOverlayRecipe() && canFillCraftingGrid()) {
currenttip.set(currenttip.size() - 1, currenttip.get(currenttip.size() - 1) + GuiDraw.TOOLTIP_LINESPACE);
currenttip.add(
EnumChatFormatting.RED + NEIClientUtils.translate("recipe.overlay.mismatch")
+ EnumChatFormatting.RESET);
} else if (this.missedMaterialsTooltipLineHandler != null) {
if ((!this.requireShiftForOverlayRecipe || NEIClientUtils.shiftKey()) && this.canFillCraftingGrid) {
if ((!requireShiftForOverlayRecipe() || NEIClientUtils.shiftKey()) && canFillCraftingGrid()) {
this.missedMaterialsTooltipLineHandler.setLabelColor(EnumChatFormatting.RED);
} else {
this.missedMaterialsTooltipLineHandler.setLabelColor(EnumChatFormatting.GRAY);
@@ -129,7 +129,7 @@ public class GuiOverlayButton extends GuiRecipeButton {
}
@Override
public Map<String, String> handleHotkeys(GuiContainer gui, int mousex, int mousey, Map<String, String> hotkeys) {
public Map<String, String> handleHotkeys(int mousex, int mousey, Map<String, String> hotkeys) {
if (requireShiftForOverlayRecipe()) {
@@ -174,7 +174,7 @@ public class GuiOverlayButton extends GuiRecipeButton {
protected void drawContent(Minecraft minecraft, int y, int x, boolean mouseOver) {
DrawableResource icon = ICON_OVERLAY;
if (this.hasOverlay && (!this.requireShiftForOverlayRecipe || NEIClientUtils.shiftKey())) {
if (hasOverlay() && (!requireShiftForOverlayRecipe() || NEIClientUtils.shiftKey())) {
icon = this.missedMaterialsTooltipLineHandler == null ? ICON_FILL : ICON_FILL_ERROR;
}
@@ -206,18 +206,19 @@ public class GuiOverlayButton extends GuiRecipeButton {
}
protected List<ItemOverlayState> ingredientsOverlay() {
List<PositionedStack> ingredients = this.handlerRef.handler.getIngredientStacks(this.handlerRef.recipeIndex);
final List<PositionedStack> ingredients = this.handlerRef.handler
.getIngredientStacks(this.handlerRef.recipeIndex);
if (this.itemPresenceCache.size() != ingredients.size()) {
this.itemPresenceCache.clear();
if (this.canFillCraftingGrid) {
if (canFillCraftingGrid()) {
this.itemPresenceCache.addAll(this.handlerRef.getPresenceOverlay(this.firstGui));
} else if (this.firstGui != null) {
this.itemPresenceCache.addAll(presenceOverlay(ingredients));
}
List<ItemStack> items = this.itemPresenceCache.stream().filter(state -> !state.isPresent())
final List<ItemStack> items = this.itemPresenceCache.stream().filter(state -> !state.isPresent())
.map(state -> state.getSlot().item).collect(Collectors.toList());
if (!items.isEmpty()) {
@@ -236,7 +237,7 @@ public class GuiOverlayButton extends GuiRecipeButton {
public void setRequireShiftForOverlayRecipe(boolean require) {
this.requireShiftForOverlayRecipe = require;
this.enabled = this.hasOverlay && (this.requireShiftForOverlayRecipe || this.canFillCraftingGrid);
this.enabled = hasOverlay() && (this.requireShiftForOverlayRecipe || canFillCraftingGrid());
}
public void setCanUseOverlayRenderer(boolean use) {
@@ -263,7 +264,7 @@ public class GuiOverlayButton extends GuiRecipeButton {
return Recipe.of(this.handlerRef);
}
private List<ItemOverlayState> presenceOverlay(List<PositionedStack> ingredients) {
protected List<ItemOverlayState> presenceOverlay(List<PositionedStack> ingredients) {
final List<ItemOverlayState> itemPresenceSlots = new ArrayList<>();
final List<ItemStack> invStacks = this.firstGui.inventorySlots.inventorySlots.stream()
.filter(
@@ -289,9 +290,9 @@ public class GuiOverlayButton extends GuiRecipeButton {
}
public void overlayRecipe(boolean shift) {
if (!this.hasOverlay) return;
if (!hasOverlay()) return;
if (!this.requireShiftForOverlayRecipe || shift) {
if (!requireShiftForOverlayRecipe() || shift) {
if (canFillCraftingGrid()) {
this.handlerRef.fillCraftingGrid(this.firstGui, 0);
}
@@ -302,8 +303,7 @@ public class GuiOverlayButton extends GuiRecipeButton {
}
@Override
public void lastKeyTyped(GuiRecipe<?> gui, char keyChar, int keyID) {
public void lastKeyTyped(char keyChar, int keyID) {
if (NEIClientConfig.isKeyHashDown("gui.bookmark") && NEIClientUtils.shiftKey()) {
saveRecipeInBookmark();
}
@@ -313,8 +313,11 @@ public class GuiOverlayButton extends GuiRecipeButton {
final Recipe recipe = getRecipe();
if (!ItemPanels.bookmarkPanel.removeRecipe(recipe.getRecipeId(), BookmarkGrid.DEFAULT_GROUP_ID)) {
ItemPanels.bookmarkPanel
.addRecipe(recipe, NEIClientUtils.controlKey() ? 1 : 0, BookmarkGrid.DEFAULT_GROUP_ID);
ItemPanels.bookmarkPanel.addRecipe(
recipe,
NEIClientUtils.controlKey()
|| NEIClientConfig.getBooleanSetting("inventory.bookmarks.bookmarkRecipeWithCount") ? 1 : 0,
BookmarkGrid.DEFAULT_GROUP_ID);
}
}
File diff suppressed because it is too large. Load diff
@@ -4,7 +4,6 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraftforge.client.event.GuiScreenEvent;
import codechicken.lib.vec.Rectangle4i;
@@ -16,33 +15,30 @@ public abstract class GuiRecipeButton extends GuiNEIButton {
public static class UpdateRecipeButtonsEvent extends GuiScreenEvent {
public List<GuiRecipeButton> buttonList;
public NEIRecipeWidget recipeWidget;
public UpdateRecipeButtonsEvent(GuiRecipe<?> gui, List<GuiRecipeButton> buttonList) {
public UpdateRecipeButtonsEvent(GuiRecipe<?> gui, NEIRecipeWidget recipeWidget,
List<GuiRecipeButton> buttonList) {
super(gui);
this.recipeWidget = recipeWidget;
this.buttonList = new ArrayList<>(buttonList);
}
@Cancelable
public static class Pre extends UpdateRecipeButtonsEvent {
public int xOffset;
public int yOffset;
public int height;
public HandlerInfo handlerInfo;
public Pre(GuiRecipe<?> gui, int xOffset, int yOffset, int height, HandlerInfo handlerInfo) {
super(gui, new ArrayList<>());
this.xOffset = xOffset;
this.yOffset = yOffset;
this.height = height;
public Pre(GuiRecipe<?> gui, NEIRecipeWidget recipeWidget, HandlerInfo handlerInfo) {
super(gui, recipeWidget, new ArrayList<>());
this.handlerInfo = handlerInfo;
}
}
public static class Post extends UpdateRecipeButtonsEvent {
public Post(GuiRecipe<?> gui, List<GuiRecipeButton> buttonList) {
super(gui, buttonList);
public Post(GuiRecipe<?> gui, NEIRecipeWidget recipeWidget, List<GuiRecipeButton> buttonList) {
super(gui, recipeWidget, buttonList);
}
}
}
@@ -57,15 +53,15 @@ public abstract class GuiRecipeButton extends GuiNEIButton {
this.handlerRef = point;
}
abstract List<String> handleTooltip(GuiRecipe<?> gui, List<String> currenttip);
public abstract List<String> handleTooltip(List<String> currenttip);
abstract Map<String, String> handleHotkeys(GuiContainer gui, int mousex, int mousey, Map<String, String> hotkeys);
public abstract Map<String, String> handleHotkeys(int mousex, int mousey, Map<String, String> hotkeys);
abstract void lastKeyTyped(GuiRecipe<?> gui, char keyChar, int keyID);
public abstract void lastKeyTyped(char keyChar, int keyID);
abstract void drawItemOverlay();
public abstract void drawItemOverlay();
public boolean mouseScrolled(GuiRecipe<?> gui, int scroll) {
public boolean mouseScrolled(int scroll) {
return false;
}
@@ -1,159 +1,193 @@
package codechicken.nei.recipe;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.util.ResourceLocation;
import java.util.ArrayList;
import java.util.List;
import org.lwjgl.util.Rectangle;
import org.lwjgl.opengl.GL11;
import codechicken.nei.api.INEIGuiAdapter;
import codechicken.nei.drawable.GuiElementDuex;
import codechicken.nei.drawable.GuiElementScalable;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.NEIServerUtils;
import codechicken.nei.PositionedStack;
import codechicken.nei.Widget;
import codechicken.nei.api.ShortcutInputHandler;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.scroll.ScrollBar;
import codechicken.nei.scroll.ScrollContainer;
public class GuiRecipeCatalyst extends INEIGuiAdapter {
public class GuiRecipeCatalyst extends ScrollContainer {
private GuiRecipe<?> guiRecipe;
public static final int ingredientSize = 16;
public static final int ingredientBorder = 1;
public static final int tabBorder = 5;
public static final int fullBorder = ingredientBorder + tabBorder;
protected static class ItemStackWidget extends Widget {
private static final Rectangle catalystRect = new Rectangle();
private static final Rectangle targetRect = new Rectangle();
private final PositionedStack pStack;
public GuiRecipeCatalyst(GuiRecipe<?> guiRecipe) {
this.guiRecipe = guiRecipe;
public ItemStackWidget(PositionedStack pStack) {
this.pStack = pStack;
this.x = pStack.relx;
this.y = pStack.rely;
this.w = SLOT_SIZE;
this.h = SLOT_SIZE;
}
@Override
public void draw(int mx, int my) {
GuiContainerManager.drawItem(this.x, this.y, this.pStack.item);
if (contains(mx, my)) {
NEIClientUtils.gl2DRenderContext(() -> GuiDraw.drawRect(this.x, this.y, this.w, this.h, 0x80FFFFFF));
}
}
@Override
public boolean handleClick(int mx, int my, int button) {
return ShortcutInputHandler.handleMouseClick(this.pStack.item);
}
}
public void draw() {
if (guiRecipe == null) return;
int catalystsSize = RecipeCatalysts.getRecipeCatalysts(guiRecipe.getHandler()).size();
if (catalystsSize == 0) return;
private static final int SLOT_SIZE = 16;
private static final int BORDER_PADDING = 6;
private static final DrawableResource BG_TEXTURE = new DrawableBuilder(
"nei:textures/catalyst_tab.png",
0,
0,
28,
28).setTextureSize(28, 28).build();
int availableHeight = RecipeCatalysts.getHeight();
int columnCount = RecipeCatalysts.getColumnCount(availableHeight, catalystsSize);
int rowCount = RecipeCatalysts.getRowCount(availableHeight, catalystsSize);
int width, height, xPos, yPos;
private static final DrawableResource FG_TEXTURE = new DrawableBuilder("nei:textures/slot.png", 0, 0, 18, 18)
.setTextureSize(18, 18).build();
width = (ingredientBorder * 2) + (tabBorder * 2) + (columnCount * ingredientSize);
height = (ingredientBorder * 2) + (tabBorder * 2) + (rowCount * ingredientSize);
xPos = guiRecipe.guiLeft - width + tabBorder + 1;
yPos = guiRecipe.guiTop;
drawBordered("nei:textures/catalyst_tab.png", xPos, yPos, width, height, 28, 28, 6, 6, 6, 6);
private static final ScrollBar VERTICAL_SCROLLBAR = ScrollBar.defaultVerticalBar()
.setOverflowType(ScrollBar.OverflowType.AUTO).setMarginStart(BORDER_PADDING).setMarginEnd(BORDER_PADDING)
.setPadding(-13).setScrollPlace(ScrollBar.ScrollPlace.START);
width = (ingredientBorder * 2) + (columnCount * ingredientSize);
height = (ingredientBorder * 2) + (rowCount * ingredientSize);
xPos = guiRecipe.guiLeft - width + ingredientBorder + 1;
yPos = guiRecipe.guiTop + fullBorder - ingredientBorder;
drawBordered("nei:textures/slot.png", xPos, yPos, width, height, 18, 18, 1, 1, 1, 1);
private final List<PositionedStack> items = new ArrayList<>();
private boolean showWidget = false;
private int availableHeight = 0;
public GuiRecipeCatalyst() {
setPaddingBlock(BORDER_PADDING + 1, BORDER_PADDING + 1);
}
public void setCatalysts(List<PositionedStack> items) {
this.items.clear();
this.items.addAll(items);
createWidgets();
}
public void setAvailableHeight(int height) {
if (this.availableHeight != height) {
this.availableHeight = height;
createWidgets();
}
}
public int getAvailableHeight() {
return this.availableHeight;
}
public boolean isShowWidget() {
return this.showWidget;
}
public int getColumnCount() {
if (NEIClientConfig.getJEIStyleRecipeCatalysts() == 1) {
final int maxItemsPerColumn = Math.max(0, this.availableHeight - 2 - BORDER_PADDING * 2) / SLOT_SIZE;
return maxItemsPerColumn > 0 ? NEIServerUtils.divideCeil(this.items.size(), maxItemsPerColumn) : 0;
}
return 1;
}
public int getRowCount() {
final int columnCount = getColumnCount();
return columnCount > 0 ? NEIServerUtils.divideCeil(this.items.size(), columnCount) : 0;
}
protected void createWidgets() {
final int columns = getColumnCount();
final int rows = getRowCount();
setVerticalScroll(null);
setPaddingInline(BORDER_PADDING + 1, BORDER_PADDING - 3);
this.h = rows * SLOT_SIZE + this.paddingBlockStart + this.paddingBlockEnd;
this.w = columns * SLOT_SIZE + this.paddingInlineStart + this.paddingInlineEnd;
if (NEIClientConfig.getJEIStyleRecipeCatalysts() == 2
&& rows * SLOT_SIZE + this.paddingBlockStart + this.paddingBlockEnd > this.availableHeight) {
this.h = Math.min(this.h, this.availableHeight);
this.w += VERTICAL_SCROLLBAR.getScrollbarSize();
setVerticalScroll(VERTICAL_SCROLLBAR);
setPaddingInline(BORDER_PADDING + 1 + VERTICAL_SCROLLBAR.getScrollbarSize(), this.paddingInlineEnd);
}
this.showWidget = rows * columns > 0;
if (rows == 0 || columns == 0) {
return;
}
final int visibleWidth = getVisibleWidth();
final List<Widget> widgets = new ArrayList<>();
int index = 0;
for (PositionedStack pStack : this.items) {
if (pStack.items.length > 1) {
final int stackIndex = (pStack.items.length + pStack.getPermutationIndex(pStack.item) + 1)
% pStack.items.length;
pStack.setPermutationToRender(stackIndex);
}
pStack.relx = visibleWidth - SLOT_SIZE - (index / rows) * SLOT_SIZE;
pStack.rely = (index % rows) * SLOT_SIZE;
index++;
widgets.add(new ItemStackWidget(pStack));
}
setWidgets(widgets);
}
@Override
public boolean hideItemPanelSlot(GuiContainer gui, int x, int y, int w, int h) {
if (!(gui instanceof GuiRecipe)) return false;
guiRecipe = (GuiRecipe<?>) gui;
int catalystsSize = RecipeCatalysts.getRecipeCatalysts(guiRecipe.getHandler()).size();
if (catalystsSize == 0) return false;
public void draw(int mx, int my) {
if (!this.showWidget) return;
int availableHeight = RecipeCatalysts.getHeight();
int columnCount = RecipeCatalysts.getColumnCount(availableHeight, catalystsSize);
int rowCount = RecipeCatalysts.getRowCount(availableHeight, catalystsSize);
int margin = 4;
GL11.glColor4f(1, 1, 1, 1);
BG_TEXTURE.draw(this.x, this.y, this.w, this.h, BORDER_PADDING, BORDER_PADDING, BORDER_PADDING, BORDER_PADDING);
FG_TEXTURE.draw(
this.x + this.paddingInlineStart - 1,
this.y + this.paddingBlockStart - 1,
this.w - this.paddingInlineStart - this.paddingInlineEnd + 2,
this.h - this.paddingBlockStart - this.paddingBlockEnd + 2,
1,
1,
1,
1);
int width = (ingredientBorder * 2) + (tabBorder * 2) + (columnCount * ingredientSize) + margin;
int height = (ingredientBorder * 2) + (tabBorder * 2) + (rowCount * ingredientSize) + margin;
int xOffset = guiRecipe.guiLeft - width + tabBorder;
int yOffset = guiRecipe.guiTop;
catalystRect.setBounds(xOffset, yOffset, width, height);
targetRect.setBounds(x, y, w, h);
return targetRect.intersects(catalystRect);
super.draw(mx, my);
}
private void drawBordered(String location, int xPos, int yPos, int width, int height, int texWidth, int texHeight,
int sliceLeft, int sliceRight, int sliceTop, int sliceBottom) {
Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation(location));
public PositionedStack getPositionedStackMouseOver(int mx, int my) {
final Widget widget = getWidgetUnderMouse(mx, my);
GuiElementDuex cornerTopLeft = new GuiElementDuex(0, 0, sliceLeft, sliceTop, texWidth, texHeight);
GuiElementDuex cornerTopRight = new GuiElementDuex(
texWidth - sliceRight,
0,
sliceRight,
sliceTop,
texWidth,
texHeight);
GuiElementDuex cornerBottomLeft = new GuiElementDuex(
0,
texHeight - sliceBottom,
sliceLeft,
sliceBottom,
texWidth,
texHeight);
GuiElementDuex cornerBottomRight = new GuiElementDuex(
texWidth - sliceRight,
texHeight - sliceBottom,
sliceRight,
sliceBottom,
texWidth,
texHeight);
if (widget instanceof ItemStackWidget stackWidget) {
return stackWidget.pStack;
}
GuiElementScalable borderTop = new GuiElementScalable(
sliceLeft,
0,
texWidth - sliceLeft - sliceRight,
sliceTop,
texWidth,
texHeight);
GuiElementScalable borderBottom = new GuiElementScalable(
sliceLeft,
texHeight - sliceBottom,
texWidth - sliceLeft - sliceRight,
sliceBottom,
texWidth,
texHeight);
GuiElementScalable borderLeft = new GuiElementScalable(
0,
sliceTop,
sliceLeft,
texHeight - sliceTop - sliceBottom,
texWidth,
texHeight);
GuiElementScalable borderRight = new GuiElementScalable(
texWidth - sliceRight,
sliceTop,
sliceRight,
texHeight - sliceTop - sliceBottom,
texWidth,
texHeight);
GuiElementScalable center = new GuiElementScalable(
sliceLeft,
sliceTop,
texWidth - sliceLeft - sliceRight,
texHeight - sliceTop - sliceBottom,
texWidth,
texHeight);
int midW = width - borderLeft.w - borderRight.w;
int midH = height - borderTop.h - borderBottom.h;
// top row
int x = xPos;
int y = yPos;
x += cornerTopLeft.draw(x, y);
x += borderTop.drawScaledX(x, y, midW);
cornerTopRight.draw(x, y);
// center row
x = xPos;
y += borderTop.h;
x += borderLeft.drawScaledY(x, y, midH);
x += center.drawScaled(x, y, midW, midH);
borderRight.drawScaledY(x, y, midH);
// bottom row
x = xPos;
y += midH;
x += cornerBottomLeft.draw(x, y);
x += borderBottom.drawScaledX(x, y, midW);
cornerBottomRight.draw(x, y);
return null;
}
@Deprecated
public static final int ingredientSize = 16;
@Deprecated
public static final int ingredientBorder = 1;
@Deprecated
public static final int tabBorder = 5;
@Deprecated
public static final int fullBorder = ingredientBorder + tabBorder;
}
@@ -42,10 +42,9 @@ public abstract class GuiRecipeTab extends Widget {
public static HashMap<String, HandlerInfo> handlerAdderFromIMC = new HashMap<>();
public static Set<String> handlerRemoverFromIMC = new HashSet<>();
private final GuiRecipe<?> guiRecipe;
private final IRecipeHandler handler;
private final String handlerName;
private final String handlerID;
protected final IRecipeHandler handler;
protected final String handlerName;
protected final String handlerID;
private boolean selected;
@@ -61,7 +60,7 @@ public abstract class GuiRecipeTab extends Widget {
protected abstract int getForegroundIconY();
public GuiRecipeTab(GuiRecipe<?> guiRecipe, IRecipeHandler handler, int x, int y) {
public GuiRecipeTab(IRecipeHandler handler, int x, int y) {
super();
this.x = x;
this.y = y;
@@ -69,7 +68,6 @@ public abstract class GuiRecipeTab extends Widget {
this.h = getHeight();
this.handler = handler;
this.handlerName = handler.getHandlerId();
this.guiRecipe = guiRecipe;
this.selected = false;
if (handler instanceof TemplateRecipeHandler) {
@@ -154,16 +152,10 @@ public abstract class GuiRecipeTab extends Widget {
}
}
public boolean onButtonPress(boolean rightclick) {
int newIdx = guiRecipe.currenthandlers.indexOf(handler);
if (newIdx == -1) return false;
public abstract boolean onButtonPress(boolean rightclick);
guiRecipe.setRecipePage(newIdx);
return true;
}
public void setSelected(IRecipeHandler current) {
selected = handler == current;
public void setSelected(boolean selected) {
this.selected = selected;
}
public static HandlerInfo getHandlerInfo(IRecipeHandler handler) {
@@ -273,6 +265,8 @@ public abstract class GuiRecipeTab extends Widget {
NEIClientConfig.logger.info("Error setting handler dimensions for " + handler);
}
info.setUseCustomScroll(
record.isSet("useCustomScroll") ? Boolean.parseBoolean(record.get("useCustomScroll")) : false);
handlerMap.put(handler, info);
NEIClientConfig.logger.info("Loaded " + handler);
}
@@ -3,7 +3,7 @@ package codechicken.nei.recipe;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
public class GuiRecipeTabCreative extends GuiRecipeTab {
public abstract class GuiRecipeTabCreative extends GuiRecipeTab {
public static final int TAB_WIDTH = 28;
public static final int TAB_HEIGHT = 31;
@@ -20,8 +20,8 @@ public class GuiRecipeTabCreative extends GuiRecipeTab {
28,
30).build();
public GuiRecipeTabCreative(GuiRecipe<?> guiRecipe, IRecipeHandler handler, int x, int y) {
super(guiRecipe, handler, x, y);
public GuiRecipeTabCreative(IRecipeHandler handler, int x, int y) {
super(handler, x, y);
}
@Override
@@ -3,7 +3,7 @@ package codechicken.nei.recipe;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
public class GuiRecipeTabJEI extends GuiRecipeTab {
public abstract class GuiRecipeTabJEI extends GuiRecipeTab {
public static final int TAB_WIDTH = 24;
public static final int TAB_HEIGHT = 24;
@@ -20,8 +20,8 @@ public class GuiRecipeTabJEI extends GuiRecipeTab {
24,
24).build();
public GuiRecipeTabJEI(GuiRecipe<?> guiRecipe, IRecipeHandler handler, int x, int y) {
super(guiRecipe, handler, x, y);
public GuiRecipeTabJEI(IRecipeHandler handler, int x, int y) {
super(handler, x, y);
}
@Override
@@ -1,168 +1,154 @@
package codechicken.nei.recipe;
import static codechicken.lib.gui.GuiDraw.getMousePosition;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.List;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.Button;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
public class GuiRecipeTabs {
private final GuiRecipe<?> guiRecipe;
private final List<GuiRecipeTab> tabs = new ArrayList<>();
private final List<Button> buttons = new ArrayList<>();
private final Rectangle area = new Rectangle();
private List<? extends IRecipeHandler> currenthandlers;
private int pageCount = 1;
private int pageNumber = 0;
private int categoriesPerPage = 1;
private int numHandlers = 1;
private int tabWidth;
private int tabHeight;
private int recipetype;
public GuiRecipeTabs(GuiRecipe<?> guiRecipe) {
this.guiRecipe = guiRecipe;
}
private final Button prevTab = new Button("<") {
public void initLayout() {
if (NEIClientConfig.useCreativeTabStyle()) {
tabWidth = GuiRecipeTabCreative.TAB_WIDTH;
tabHeight = GuiRecipeTabCreative.TAB_HEIGHT;
} else {
tabWidth = GuiRecipeTabJEI.TAB_WIDTH;
tabHeight = GuiRecipeTabJEI.TAB_HEIGHT;
@Override
public boolean onButtonPress(boolean rightClick) {
if (!rightClick) {
NEIClientUtils.playClickSound();
return previousPage();
} else return false;
}
int totalWidth = 0;
categoriesPerPage = 0;
numHandlers = guiRecipe.currenthandlers.size();
};
for (int i = 0; i < numHandlers; i++) {
if (totalWidth + tabWidth < (guiRecipe.xSize - 4)) {
totalWidth += tabWidth;
categoriesPerPage++;
} else {
break;
}
private final Button nextTab = new Button(">") {
@Override
public boolean onButtonPress(boolean rightclick) {
if (!rightclick) {
NEIClientUtils.playClickSound();
return nextPage();
} else return false;
}
area.width = totalWidth;
area.height = tabHeight;
area.x = guiRecipe.guiLeft + 4;
area.y = guiRecipe.guiTop - tabHeight + 3;
};
pageCount = (int) Math.ceil((float) numHandlers / categoriesPerPage);
calcPageNumber();
Rectangle navigationArea = new Rectangle(area);
navigationArea.height = 20;
navigationArea.translate(0, -(2 + navigationArea.height));
public static int getTabWidth() {
return NEIClientConfig.useCreativeTabStyle() ? GuiRecipeTabCreative.TAB_WIDTH : GuiRecipeTabJEI.TAB_WIDTH;
}
public void calcPageNumber() {
pageNumber = guiRecipe.recipetype / Math.max(categoriesPerPage, 1);
public static int getTabHeight() {
return NEIClientConfig.useCreativeTabStyle() ? GuiRecipeTabCreative.TAB_HEIGHT : GuiRecipeTabJEI.TAB_HEIGHT;
}
public void update(GuiRecipe<?> guiRecipe) {
final int tabWidth = getTabWidth();
final int tabHeight = getTabHeight();
this.recipetype = guiRecipe.recipetype;
this.currenthandlers = guiRecipe.currenthandlers;
this.numHandlers = this.currenthandlers.size();
this.categoriesPerPage = (guiRecipe.xSize - 4) / tabWidth;
this.pageNumber = this.recipetype / Math.max(this.categoriesPerPage, 1);
this.pageCount = (int) Math.ceil((float) this.numHandlers / this.categoriesPerPage);
this.area.width = this.categoriesPerPage * tabWidth;
this.area.height = tabHeight;
this.area.x = guiRecipe.guiLeft + 4;
this.area.y = guiRecipe.guiTop - tabHeight + 3;
refreshPage();
updateArrows(tabHeight);
}
public void refreshPage() {
tabs.clear();
buttons.clear();
final int startIndex = this.pageNumber * this.categoriesPerPage;
final int tabWidth = getTabWidth();
final int startIndex = pageNumber * categoriesPerPage;
for (int i = 0; i < categoriesPerPage; i++) {
this.tabs.clear();
for (int i = 0; i < this.categoriesPerPage && i + startIndex < numHandlers; i++) {
final int index = i + startIndex;
if (index >= numHandlers) break;
IRecipeHandler handler = guiRecipe.currenthandlers.get(index);
int tabX = area.x + (i * tabWidth);
final IRecipeHandler handler = this.currenthandlers.get(index);
final int tabX = this.area.x + (i * tabWidth);
if (NEIClientConfig.useCreativeTabStyle()) {
tabs.add(new GuiRecipeTabCreative(guiRecipe, handler, tabX, area.y));
tabs.add(new GuiRecipeTabCreative(handler, tabX, this.area.y) {
@Override
public boolean onButtonPress(boolean rightclick) {
setRecipePage(index);
return true;
}
});
} else {
tabs.add(new GuiRecipeTabJEI(guiRecipe, handler, tabX, area.y));
tabs.add(new GuiRecipeTabJEI(handler, tabX, this.area.y) {
@Override
public boolean onButtonPress(boolean rightclick) {
setRecipePage(index);
return true;
}
});
}
}
}
// Maybe add buttons
if (numHandlers > categoriesPerPage) {
Button prevTab = new Button("prevTab") {
private void updateArrows(int tabHeight) {
this.buttons.clear();
@Override
public boolean onButtonPress(boolean rightClick) {
if (!rightClick) {
NEIClientUtils.playClickSound();
return previousPage();
} else return false;
}
if (this.numHandlers > this.categoriesPerPage) {
this.prevTab.w = this.nextTab.w = 8;
this.prevTab.h = this.nextTab.h = tabHeight - 4;
this.prevTab.y = this.nextTab.y = this.area.y + 2;
@Override
public String getRenderLabel() {
return "<";
}
};
prevTab.w = 8;
prevTab.h = tabHeight - 4;
prevTab.x = area.x - prevTab.w + 1;
prevTab.y = area.y + 2;
buttons.add(prevTab);
this.prevTab.x = this.area.x - this.prevTab.w + 1;
this.nextTab.x = this.area.x + this.area.width - 1;
Button nextTab = new Button("nextTab") {
@Override
public boolean onButtonPress(boolean rightclick) {
if (!rightclick) {
NEIClientUtils.playClickSound();
return nextPage();
} else return false;
}
@Override
public String getRenderLabel() {
return ">";
}
};
nextTab.w = prevTab.w;
nextTab.h = prevTab.h;
nextTab.x = area.x + area.width - 1;
nextTab.y = prevTab.y;
buttons.add(nextTab);
this.buttons.add(this.prevTab);
this.buttons.add(this.nextTab);
}
}
public boolean nextPage() {
if (hasNext()) pageNumber++;
else pageNumber = 0;
protected void setRecipePage(int recipetype) {}
public boolean nextPage() {
this.pageNumber = (this.pageNumber + 1) % this.pageCount;
refreshPage();
return true;
}
public boolean hasNext() {
return pageNumber + 1 < pageCount;
}
public boolean previousPage() {
if (hasPrevious()) pageNumber--;
else pageNumber = pageCount - 1;
this.pageNumber = (this.pageCount + this.pageNumber - 1) % this.pageCount;
refreshPage();
return true;
}
public boolean hasPrevious() {
return pageNumber > 0;
}
public void draw(int mouseX, int mouseY) {
IRecipeHandler current = guiRecipe.currenthandlers.get(guiRecipe.recipetype);
for (GuiRecipeTab tab : tabs) {
tab.setSelected(current);
final int indexShift = this.pageNumber * this.categoriesPerPage;
for (int index = 0; index < this.tabs.size(); index++) {
final GuiRecipeTab tab = this.tabs.get(index);
tab.setSelected(indexShift + index == this.recipetype);
tab.draw(mouseX, mouseY);
}
for (Button button : buttons) {
for (Button button : this.buttons) {
button.draw(mouseX, mouseY);
}
}
@@ -170,12 +156,12 @@ public class GuiRecipeTabs {
public void handleTooltip(int mousex, int mousey, List<String> tooltips) {
if (!NEIClientConfig.areJEIStyleTabsVisible()) return;
for (GuiRecipeTab tab : tabs) {
for (GuiRecipeTab tab : this.tabs) {
if (tab.contains(mousex, mousey)) {
tab.addTooltips(tooltips);
}
}
for (Button button : buttons) {
for (Button button : this.buttons) {
if (button.contains(mousex, mousey)) {
button.addTooltips(tooltips);
}
@@ -185,27 +171,26 @@ public class GuiRecipeTabs {
protected boolean mouseClicked(int x, int y, int mouseButton) {
if (!NEIClientConfig.areJEIStyleTabsVisible()) return false;
for (Button button : buttons) {
for (Button button : this.buttons) {
if (button.contains(x, y)) {
return button.onButtonPress(mouseButton == 1);
}
}
for (GuiRecipeTab tab : tabs) {
for (GuiRecipeTab tab : this.tabs) {
if (tab.contains(x, y)) {
return tab.onButtonPress(mouseButton == 1);
}
}
return false;
}
protected boolean mouseScrolled(int i) {
Point mousePosition = getMousePosition();
protected boolean mouseScrolled(int scroll) {
// Switch between recipe handlers if the cursor is over the tabbar.
if (NEIClientConfig.areJEIStyleTabsVisible() && area.contains(mousePosition)) {
if (i < 0) guiRecipe.nextType();
else guiRecipe.prevType();
if (NEIClientConfig.areJEIStyleTabsVisible() && this.area.contains(GuiDraw.getMousePosition())) {
setRecipePage(this.recipetype - scroll);
return true;
}
@@ -12,7 +12,6 @@ import codechicken.nei.ItemPanels;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.recipe.stackinfo.GTFluidStackStringifyHandler;
public class GuiUsageRecipe extends GuiRecipe<IUsageHandler> {
@@ -22,9 +21,9 @@ public class GuiUsageRecipe extends GuiRecipe<IUsageHandler> {
public static boolean openRecipeGui(String inputId, Object... ingredients) {
if ("item".equals(inputId)) {
for (int i = 0; i < ingredients.length; i++) {
ingredients[i] = normalizeItemStack((ItemStack) ingredients[i]);
for (int i = 0; i < ingredients.length; i++) {
if (ingredients[i] instanceof ItemStack stack) {
ingredients[i] = StackInfo.normalizeRecipeQueryStack(stack.copy());
}
}
@@ -66,13 +65,6 @@ public class GuiUsageRecipe extends GuiRecipe<IUsageHandler> {
return recipeQuery.runWithProfiling(NEIClientUtils.translate("recipe.concurrent.usage"));
}
private static ItemStack normalizeItemStack(ItemStack stack) {
GTFluidStackStringifyHandler.replaceAE2FCFluidDrop = true;
stack = StackInfo.loadFromNBT(StackInfo.itemStackToNBT(stack));
GTFluidStackStringifyHandler.replaceAE2FCFluidDrop = false;
return stack;
}
public static void registerUsageHandler(IUsageHandler handler) {
final String handlerId = handler.getHandlerId();
@@ -99,7 +91,7 @@ public class GuiUsageRecipe extends GuiRecipe<IUsageHandler> {
private static IUsageHandler getUsageOrCatalystHandler(IUsageHandler handler, String inputId,
Object... ingredients) {
boolean skipCatalyst = NEIClientUtils.controlKey();
if (NEIClientConfig.areJEIStyleRecipeCatalystsVisible() && !skipCatalyst) {
if (NEIClientConfig.getJEIStyleRecipeCatalysts() != 0 && !skipCatalyst) {
return handler.getUsageAndCatalystHandler(inputId, ingredients);
} else {
return handler.getUsageHandler(inputId, ingredients);
@@ -21,15 +21,13 @@ public class HandlerInfo {
private boolean requiresMod;
private String excludedModId;
private String itemId;
private String nbtString;
private int yShift = 0;
private int height = DEFAULT_HEIGHT;
private int width = DEFAULT_WIDTH;
private int maxRecipesPerPage = DEFAULT_MAX_PER_PAGE;
private boolean showFavoritesButton = true;
private boolean showOverlayButton = true;
private boolean useCustomScroll = false;
private ItemStack itemStack = null;
private DrawableResource image = null;
@@ -51,13 +49,13 @@ public class HandlerInfo {
public boolean setItem(String itemId, String nbtString) {
if (hasImageOrItem()) return false;
itemStack = NEIServerUtils.getModdedItem(itemId, nbtString);
if (itemStack == null) NEIClientConfig.logger.info("Couldn't find " + modName + " - " + itemId);
else {
this.itemId = itemId;
this.nbtString = nbtString;
this.itemStack = NEIServerUtils.getModdedItem(itemId, nbtString);
if (this.itemStack == null) {
NEIClientConfig.logger.info("Couldn't find " + this.modName + " - " + itemId);
}
return (itemStack != null);
return this.itemStack != null;
}
public boolean setImage(String resourceLocation, int imageX, int imageY, int imageWidth, int imageHeight) {
@@ -68,46 +66,43 @@ public class HandlerInfo {
}
public DrawableResource getImage() {
return image;
return this.image;
}
public ItemStack getItemStack() {
return itemStack;
return this.itemStack;
}
public String getModName() {
return modName;
return this.modName;
}
public String getModId() {
return modId;
return this.modId;
}
public int getHeight() {
return height;
return this.height;
}
public int getWidth() {
return width;
return this.width;
}
public int getMaxRecipesPerPage() {
return Math.max(maxRecipesPerPage, 1);
return Math.max(this.maxRecipesPerPage, 1);
}
public int getYShift() {
return yShift;
return this.yShift;
}
public String getHandlerName() {
return handlerName;
return this.handlerName;
}
public boolean hasImageOrItem() {
if (image != null) return true;
if (itemStack != null) return true;
return false;
return this.image != null || this.itemStack != null;
}
public void setYShift(int yShift) {
@@ -130,6 +125,18 @@ public class HandlerInfo {
this.showOverlayButton = showOverlayButton;
}
public boolean getUseCustomScroll() {
return this.useCustomScroll;
}
public void setUseCustomScroll(boolean useCustomScroll) {
this.useCustomScroll = useCustomScroll;
}
public boolean expandVertically() {
return this.useCustomScroll && this.maxRecipesPerPage <= 1;
}
public static class Builder {
private final HandlerInfo info;
@@ -162,6 +169,11 @@ public class HandlerInfo {
return this;
}
public Builder setUseCustomScroll(boolean useCustomScroll) {
info.setUseCustomScroll(useCustomScroll);
return this;
}
public Builder setShiftY(int shiftY) {
info.setYShift(shiftY);
return this;
@@ -44,6 +44,10 @@ public interface IRecipeHandler {
return getRecipeName();
}
default int getRecipeHeight(int recipe) {
return 0;
}
/**
*
* @return The number of recipes that this handler contains.
@@ -126,12 +130,6 @@ public interface IRecipeHandler {
return null;
}
/**
*
* @return The number of recipes that can fit on a page in the viewer (1 or 2)
*/
int recipiesPerPage();
/**
*
* @param gui An instance of the currentscreen
@@ -178,4 +176,12 @@ public interface IRecipeHandler {
default boolean mouseScrolled(GuiRecipe<?> gui, int scroll, int recipe) {
return false;
}
/**
* @deprecated
* @return The number of recipes that can fit on a page in the viewer (1 or 2)
*/
default int recipiesPerPage() {
return 2;
}
}
@@ -99,7 +99,7 @@ public class InformationHandler extends TemplateRecipeHandler {
@Override
public List<PositionedStack> getIngredients() {
return getCycledIngredients(cycleticks / 20, Collections.singletonList(this.stack));
return Collections.singletonList(this.stack);
}
public InformationPage getPage() {
@@ -0,0 +1,544 @@
package codechicken.nei.recipe;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.function.Function;
import java.util.stream.Stream;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.FavoriteRecipes;
import codechicken.nei.LayoutManager;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.NEIServerUtils;
import codechicken.nei.PositionedStack;
import codechicken.nei.Widget;
import codechicken.nei.api.IGuiContainerOverlay;
import codechicken.nei.api.ShortcutInputHandler;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.recipe.GuiRecipeButton.UpdateRecipeButtonsEvent;
import codechicken.nei.util.NEIMouseUtils;
public class NEIRecipeWidget extends Widget {
protected AcceptsFollowingTooltipLineHandler acceptsFollowingTooltipLineHandler;
protected final WeakHashMap<PositionedStack, List<ItemStack>> permutations = new WeakHashMap<>();
protected boolean needUpdate = true;
protected int cycleticks = 0;
protected int lastcycle = 0;
protected final RecipeHandlerRef handlerRef;
protected final HandlerInfo handlerInfo;
protected boolean showAsWidget = false;
protected List<GuiRecipeButton> recipeButtons = null;
public NEIRecipeWidget(RecipeHandlerRef handlerRef) {
this.handlerRef = handlerRef;
this.handlerInfo = GuiRecipeTab.getHandlerInfo(this.handlerRef.handler);
update();
}
public void setLocation(int x, int y) {
this.x = x;
this.y = y;
}
public void update() {
this.w = Math.max(166, this.handlerInfo.getWidth());
if (this.showAsWidget || !this.handlerInfo.expandVertically()) {
final int recipeHeight = this.handlerRef.handler.getRecipeHeight(this.handlerRef.recipeIndex);
this.h = recipeHeight > 0 ? recipeHeight : this.handlerInfo.getHeight();
this.h += this.handlerInfo.getYShift();
}
if (!this.needUpdate && !NEIClientUtils.shiftKey() && (this.cycleticks++) / 20 != this.lastcycle) {
this.lastcycle = this.cycleticks / 20;
this.needUpdate = true;
}
}
public List<GuiRecipeButton> getRecipeButtons() {
if (this.recipeButtons == null) {
if (!getOutputs().isEmpty()) {
this.recipeButtons = initButtons();
} else {
this.recipeButtons = Collections.emptyList();
}
}
return Collections.unmodifiableList(this.recipeButtons);
}
protected List<GuiRecipeButton> getRecipeButtonsIfInit() {
if (this.recipeButtons == null) {
return Collections.emptyList();
}
return Collections.unmodifiableList(this.recipeButtons);
}
public RecipeHandlerRef getRecipeHandlerRef() {
return this.handlerRef;
}
public Recipe getRecipe() {
return Recipe.of(this.handlerRef);
}
public HandlerInfo getHandlerInfo() {
return this.handlerInfo;
}
public void showAsWidget(boolean show) {
this.showAsWidget = show;
}
protected List<GuiRecipeButton> initButtons() {
final GuiRecipe<?> guiRecipe = getGuiRecipe();
if (guiRecipe != null) {
final UpdateRecipeButtonsEvent.Pre preEvent = new UpdateRecipeButtonsEvent.Pre(
guiRecipe,
this,
this.handlerInfo);
if (MinecraftForge.EVENT_BUS.post(preEvent)) {
return preEvent.buttonList;
} else {
final UpdateRecipeButtonsEvent.Post postEvent = new UpdateRecipeButtonsEvent.Post(
guiRecipe,
this,
getDefatulButtons());
MinecraftForge.EVENT_BUS.post(postEvent);
return postEvent.buttonList;
}
} else {
return getDefatulButtons();
}
}
protected List<GuiRecipeButton> getDefatulButtons() {
GuiContainer guiContainer = NEIClientUtils.getGuiContainer();
final List<GuiRecipeButton> buttons = new ArrayList<>();
final boolean showFavorites = NEIClientConfig.favoritesEnabled() && handlerInfo.getShowFavoritesButton();
final boolean showOverlay = handlerInfo.getShowOverlayButton();
final int x = Math.min(168, this.w) - GuiRecipeButton.BUTTON_WIDTH;
int y = this.h - GuiRecipeButton.BUTTON_HEIGHT - 6;
if (guiContainer instanceof IGuiContainerOverlay overlay) {
guiContainer = overlay.getFirstScreen();
}
if (showOverlay) {
buttons.add(new GuiOverlayButton(guiContainer, this.handlerRef, x, y));
y -= GuiRecipeButton.BUTTON_HEIGHT + 1;
}
if (showFavorites) {
buttons.add(new GuiFavoriteButton(handlerRef, x, y));
}
return buttons;
}
@Override
public void draw(int mouseX, int mouseY) {
final int yShift = this.handlerInfo.getYShift();
if (this.needUpdate) {
this.needUpdate = false;
updatePermutations();
}
GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_LIGHTING_BIT);
GL11.glTranslatef(this.x, this.y + yShift, 0);
this.handlerRef.handler.drawBackground(this.handlerRef.recipeIndex);
RenderHelper.enableGUIStandardItemLighting();
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
GL11.glColor4f(1, 1, 1, 1);
GuiContainerManager.enableMatrixStackLogging();
for (PositionedStack pStack : getInputs()) {
GuiContainerManager.drawItem(pStack.relx, pStack.rely, pStack.item);
if (pStack.contains(mouseX - this.x, mouseY - this.y - yShift)) {
NEIClientUtils.gl2DRenderContext(() -> GuiDraw.drawRect(pStack.relx, pStack.rely, 16, 16, 0x80FFFFFF));
}
}
for (PositionedStack pStack : getCatalysts()) {
GuiContainerManager.drawItem(pStack.relx, pStack.rely, pStack.item);
if (pStack.contains(mouseX - this.x, mouseY - this.y - yShift)) {
NEIClientUtils.gl2DRenderContext(() -> GuiDraw.drawRect(pStack.relx, pStack.rely, 16, 16, 0x80FFFFFF));
}
}
for (PositionedStack pStack : getOutputs()) {
GuiContainerManager.drawItem(pStack.relx, pStack.rely, pStack.item);
if (pStack.contains(mouseX - this.x, mouseY - this.y - yShift)) {
NEIClientUtils.gl2DRenderContext(() -> GuiDraw.drawRect(pStack.relx, pStack.rely, 16, 16, 0x80FFFFFF));
}
}
GuiContainerManager.disableMatrixStackLogging();
this.handlerRef.handler.drawForeground(this.handlerRef.recipeIndex);
final GuiRecipeButton overlayButton = getRecipeButtons().stream()
.filter(
b -> this.showAsWidget ? b instanceof GuiOverlayButton
: b.contains(mouseX - this.x, mouseY - this.y - yShift))
.findAny().orElse(null);
if (overlayButton != null && overlayButton.enabled) {
NEIClientUtils.gl2DRenderContext(() -> overlayButton.drawItemOverlay());
}
GL11.glTranslatef(-this.x, -this.y - yShift, 0);
GL11.glPopAttrib();
if (!this.showAsWidget) {
final Minecraft mc = NEIClientUtils.mc();
for (GuiRecipeButton button : getRecipeButtons()) {
button.xPosition += this.x;
button.yPosition += this.y;
button.drawButton(mc, mouseX, mouseY);
button.xPosition -= this.x;
button.yPosition -= this.y;
}
}
LayoutManager.recipeHandlerWidget.drawGuiPlaceholder(this);
}
@Override
public boolean handleKeyPress(int keyID, char keyChar) {
return false;
}
@Override
public void lastKeyTyped(int keyID, char keyChar) {
final Point mouse = GuiDraw.getMousePosition();
forEachButtons(button -> {
if (button.contains(mouse.x, mouse.y)) {
button.lastKeyTyped(keyChar, keyID);
}
return null;
}, null);
}
@Override
public boolean handleClick(int mouseX, int mouseY, int button) {
if (ShortcutInputHandler.handleMouseClick(getStackMouseOver(mouseX, mouseY))) {
return true;
}
if (button == 0) {
final Minecraft mc = NEIClientUtils.mc();
if (forEachButtons(guibutton -> {
if (guibutton.mousePressed(mc, mouseX, mouseY)) {
NEIClientUtils.playClickSound();
guibutton.mouseReleased(mouseX, mouseY);
return true;
}
return null;
}, false)) {
return true;
}
}
final GuiRecipe<?> guiRecipe = getGuiRecipe();
if (guiRecipe == null) {
return false;
}
return this.handlerRef.handler.mouseClicked(guiRecipe, button, this.handlerRef.recipeIndex);
}
@Override
public List<String> handleTooltip(int mouseX, int mouseY, List<String> tooltip) {
final GuiRecipe<?> guiRecipe = getGuiRecipe();
if (guiRecipe == null) {
return tooltip;
}
final List<String> localTooltip = this.handlerRef.handler
.handleTooltip(guiRecipe, tooltip, this.handlerRef.recipeIndex);
return forEachButtons(
button -> button.contains(mouseX, mouseY) ? button.handleTooltip(localTooltip) : null,
localTooltip);
}
@Override
public List<String> handleItemTooltip(ItemStack itemstack, int mousex, int mousey, List<String> tooltip) {
final GuiRecipe<?> guiRecipe = getGuiRecipe();
if (guiRecipe == null) {
return tooltip;
}
tooltip = this.handlerRef.handler.handleItemTooltip(guiRecipe, itemstack, tooltip, this.handlerRef.recipeIndex);
if (NEIClientConfig.showCycledIngredientsTooltip() && itemstack != null) {
final int yShift = this.handlerInfo.getYShift();
PositionedStack hovered = null;
for (PositionedStack pStack : getInputs()) {
if (pStack.contains(mousex - this.x, mousey - this.y - yShift)) {
hovered = pStack;
break;
}
}
if (hovered == null) {
for (PositionedStack pStack : getCatalysts()) {
if (pStack.contains(mousex - this.x, mousey - this.y - yShift)) {
hovered = pStack;
}
}
}
if (hovered == null || hovered.items.length <= 1) {
this.acceptsFollowingTooltipLineHandler = null;
} else if (this.acceptsFollowingTooltipLineHandler == null
|| this.acceptsFollowingTooltipLineHandler.tooltipGUID != hovered) {
this.acceptsFollowingTooltipLineHandler = AcceptsFollowingTooltipLineHandler
.of(hovered, hovered.getFilteredPermutations(), hovered.item);
}
} else if (this.acceptsFollowingTooltipLineHandler != null) {
this.acceptsFollowingTooltipLineHandler = null;
}
if (this.acceptsFollowingTooltipLineHandler != null) {
tooltip.add(GuiDraw.TOOLTIP_HANDLER + GuiDraw.getTipLineId(this.acceptsFollowingTooltipLineHandler));
}
return tooltip;
}
@Override
public Map<String, String> handleHotkeys(int mouseX, int mouseY, Map<String, String> hotkeys) {
final Map<String, String> buttonHotkeys = forEachButtons(
button -> button.contains(mouseX, mouseY) ? button.handleHotkeys(mouseX, mouseY, hotkeys) : null,
hotkeys);
if (this.acceptsFollowingTooltipLineHandler != null) {
buttonHotkeys.put(
NEIClientUtils.getKeyName(
NEIClientUtils.SHIFT_HASH,
NEIMouseUtils.MOUSE_BTN_NONE + NEIMouseUtils.MOUSE_SCROLL),
NEIClientUtils.translate("recipe.accepts.scroll"));
}
return buttonHotkeys;
}
@Override
public boolean onMouseWheel(int scroll, int mx, int my) {
if (forEachButtons(button -> button.contains(mx, my) ? button.mouseScrolled(scroll) : null, false)) {
return true;
}
if (scrollPermutations(scroll, mx, my)) {
return true;
}
final GuiRecipe<?> guiRecipe = getGuiRecipe();
return guiRecipe != null
&& this.handlerRef.handler.mouseScrolled(guiRecipe, scroll, this.handlerRef.recipeIndex);
}
protected boolean scrollPermutations(int scroll, int mx, int my) {
if (!NEIClientUtils.shiftKey()) return false;
final PositionedStack overStack = getPositionedStackMouseOver(mx, my);
if (overStack != null && overStack.items.length > 1) {
final List<ItemStack> items = overStack.getFilteredPermutations();
final int stackIndex = indexOf(items, overStack.item);
final ItemStack stack = items.get((items.size() - scroll + stackIndex) % items.size());
Stream.concat(getInputs().stream(), getCatalysts().stream()).filter(pStack -> pStack.containsWithNBT(stack))
.forEach(pStack -> pStack.setPermutationToRender(stack));
if (this.acceptsFollowingTooltipLineHandler != null) {
this.acceptsFollowingTooltipLineHandler
.setActiveStack(((PositionedStack) this.acceptsFollowingTooltipLineHandler.tooltipGUID).item);
}
return true;
}
return false;
}
protected int indexOf(List<ItemStack> list, ItemStack stack) {
for (int i = 0; i < list.size(); i++) {
if (NEIServerUtils.areStacksSameTypeCraftingWithNBT(list.get(i), stack)) {
return i;
}
}
return -1;
}
protected <R> R forEachButtons(Function<GuiRecipeButton, R> callback, R defaultValue) {
for (GuiRecipeButton button : getRecipeButtonsIfInit()) {
button.xPosition += this.x;
button.yPosition += this.y;
final R result = callback.apply(button);
button.xPosition -= this.x;
button.yPosition -= this.y;
if (result != null) {
return result;
}
}
return defaultValue;
}
public boolean isFocusedRecipe(int mx, int my) {
final int yShift = this.handlerInfo.getYShift();
for (PositionedStack pStackOver : getOutputs()) {
if (pStackOver.contains(mx - this.x, my - this.y - yShift)) {
return true;
}
}
return false;
}
public PositionedStack getPositionedStackMouseOver(int mx, int my) {
final int yShift = this.handlerInfo.getYShift();
for (PositionedStack pStack : getInputs()) {
if (pStack.contains(mx - this.x, my - this.y - yShift)) {
return pStack;
}
}
for (PositionedStack pStack : getCatalysts()) {
if (pStack.contains(mx - this.x, my - this.y - yShift)) {
return pStack;
}
}
for (PositionedStack pStack : getOutputs()) {
if (pStack.contains(mx - this.x, my - this.y - yShift)) {
return pStack;
}
}
return null;
}
@Override
public ItemStack getStackMouseOver(int mx, int my) {
final PositionedStack pStack = getPositionedStackMouseOver(mx, my);
return pStack != null ? pStack.item : null;
}
protected GuiRecipe<?> getGuiRecipe() {
final GuiContainer guiContainer = NEIClientUtils.getGuiContainer();
if (guiContainer instanceof GuiRecipe<?>guiRecipe) {
return guiRecipe;
}
return null;
}
protected GuiContainer getFirstGui() {
final GuiContainer guiContainer = NEIClientUtils.getGuiContainer();
if (guiContainer instanceof GuiRecipe<?>guiRecipe) {
return guiRecipe.firstGui;
}
return guiContainer;
}
protected void updatePermutations() {
for (PositionedStack pStack : getInputs()) {
if (pStack.items.length > 1) {
final List<ItemStack> permutations = this.permutations
.computeIfAbsent(pStack, stack -> stack.getFilteredPermutations(FavoriteRecipes::contains));
pStack.setPermutationToRender(permutations.get(this.lastcycle % permutations.size()));
}
}
for (PositionedStack pStack : getCatalysts()) {
if (pStack.items.length > 1) {
final List<ItemStack> permutations = this.permutations
.computeIfAbsent(pStack, stack -> stack.getFilteredPermutations(FavoriteRecipes::contains));
pStack.setPermutationToRender(permutations.get(this.lastcycle % permutations.size()));
}
}
if (this.acceptsFollowingTooltipLineHandler != null) {
this.acceptsFollowingTooltipLineHandler
.setActiveStack(((PositionedStack) this.acceptsFollowingTooltipLineHandler.tooltipGUID).item);
}
}
protected List<PositionedStack> getInputs() {
return this.handlerRef.handler.getIngredientStacks(this.handlerRef.recipeIndex);
}
protected List<PositionedStack> getOutputs() {
final PositionedStack pStackResult = this.handlerRef.handler.getResultStack(this.handlerRef.recipeIndex);
return pStackResult != null ? Arrays.asList(pStackResult)
: this.handlerRef.handler.getOtherStacks(this.handlerRef.recipeIndex);
}
protected List<PositionedStack> getCatalysts() {
if (this.handlerRef.handler.getResultStack(this.handlerRef.recipeIndex) == null) {
return Collections.emptyList();
}
return this.handlerRef.handler.getOtherStacks(this.handlerRef.recipeIndex);
}
}
@@ -102,11 +102,6 @@ public class ProfilerRecipeHandler implements ICraftingHandler, IUsageHandler {
return null;
}
@Override
public int recipiesPerPage() {
return 1;
}
@Override
public List<String> handleTooltip(GuiRecipe<?> gui, List<String> currenttip, int recipe) {
return currenttip;
@@ -18,6 +18,7 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.NEIServerUtils;
import codechicken.nei.PositionedStack;
import codechicken.nei.api.ItemInfo;
@@ -235,11 +236,6 @@ public class Recipe {
return false;
}
if (this.result != null && anRecipeId.result != null
&& !StackInfo.equalItemAndNBT(this.result, anRecipeId.result, true)) {
return false;
}
for (int idx = 0; idx < this.ingredients.size(); idx++) {
if (!StackInfo.equalItemAndNBT(this.ingredients.get(idx), anRecipeId.ingredients.get(idx), true)) {
return false;
@@ -311,7 +307,8 @@ public class Recipe {
}
public boolean contains(ItemStack stackA) {
return getPermutations().stream().anyMatch(stackB -> StackInfo.equalItemAndNBT(stackA, stackB, true));
return getPermutations().stream()
.anyMatch(stackB -> NEIClientUtils.areStacksSameTypeWithNBT(stackB, stackA));
}
public List<ItemStack> getPermutations() {
@@ -17,6 +17,7 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import net.minecraft.item.ItemStack;
@@ -37,10 +38,8 @@ public class RecipeCatalysts {
private static final Map<String, List<ItemStack>> catalystsRemoverFromAPI = new HashMap<>();
public static final Map<String, CatalystInfoList> catalystsAdderFromIMC = new HashMap<>();
public static final Map<String, List<ItemStack>> catalystsRemoverFromIMC = new HashMap<>();
private static final Map<String, CatalystInfoList> recipeCatalystMap = new HashMap<>();
private static Map<String, List<PositionedStack>> positionedRecipeCatalystMap = new HashMap<>();
private static final Map<String, List<PositionedStack>> recipeCatalystMap = new HashMap<>();
private static final List<String> forceClassNameList = new ArrayList<>();
private static int heightCache;
public static void addRecipeCatalyst(String handlerID, CatalystInfo catalystInfo) {
if (handlerID == null || handlerID.isEmpty() || catalystInfo.getStack() == null) return;
@@ -49,6 +48,7 @@ public class RecipeCatalysts {
public static void removeRecipeCatalyst(String handlerID, ItemStack stack) {
if (handlerID == null || handlerID.isEmpty() || stack == null) return;
if (catalystsRemoverFromAPI.containsKey(handlerID)) {
catalystsRemoverFromAPI.get(handlerID).add(stack);
} else {
@@ -56,8 +56,23 @@ public class RecipeCatalysts {
}
}
public static Map<String, List<PositionedStack>> getPositionedRecipeCatalystMap() {
return positionedRecipeCatalystMap;
public static void putRecipeCatalysts(String handlerID, List<ItemStack> items) {
if (handlerID == null || handlerID.isEmpty()) return;
final CatalystInfoList catalystInfoList = new CatalystInfoList(handlerID);
int stackIndex = 0;
for (ItemStack stack : items) {
catalystInfoList.add(new CatalystInfo(stack, stackIndex++));
}
putRecipeCatalysts(handlerID, catalystInfoList);
}
public static void putRecipeCatalysts(String handlerID, CatalystInfoList catalystInfoList) {
if (handlerID == null || handlerID.isEmpty()) return;
catalystsAdderFromAPI.put(handlerID, catalystInfoList);
recipeCatalystMap.put(handlerID, convertToPositionedStackList(catalystInfoList));
}
public static List<PositionedStack> getRecipeCatalysts(IRecipeHandler handler) {
@@ -65,10 +80,7 @@ public class RecipeCatalysts {
}
public static List<PositionedStack> getRecipeCatalysts(String handlerID) {
if (!NEIClientConfig.areJEIStyleTabsVisible() || !NEIClientConfig.areJEIStyleRecipeCatalystsVisible()) {
return Collections.emptyList();
}
return positionedRecipeCatalystMap.getOrDefault(handlerID, Collections.emptyList());
return recipeCatalystMap.getOrDefault(handlerID, Collections.emptyList());
}
public static boolean containsCatalyst(IRecipeHandler handler, ItemStack candidate) {
@@ -76,63 +88,21 @@ public class RecipeCatalysts {
}
public static boolean containsCatalyst(String handlerID, ItemStack candidate) {
if (recipeCatalystMap.containsKey(handlerID)) {
return recipeCatalystMap.get(handlerID).contains(candidate);
return recipeCatalystMap.get(handlerID).stream().anyMatch(pStack -> pStack.contains(candidate));
}
return false;
}
public static void updatePosition(int availableHeight, boolean force) {
if (availableHeight == heightCache && !force) return;
Map<String, List<PositionedStack>> newMap = new HashMap<>();
for (Map.Entry<String, CatalystInfoList> entry : recipeCatalystMap.entrySet()) {
CatalystInfoList catalysts = entry.getValue();
catalysts.sort();
List<PositionedStack> newStacks = new ArrayList<>();
int rowCount = getRowCount(availableHeight, catalysts.size());
for (int index = 0; index < catalysts.size(); index++) {
ItemStack catalyst = catalysts.get(index).getStack();
int column = index / rowCount;
int row = index % rowCount;
newStacks.add(
new PositionedStack(
catalyst,
-column * GuiRecipeCatalyst.ingredientSize,
row * GuiRecipeCatalyst.ingredientSize));
}
newMap.put(entry.getKey(), newStacks);
}
positionedRecipeCatalystMap = newMap;
heightCache = availableHeight;
}
public static void updatePosition(int availableHeight) {
updatePosition(availableHeight, false);
}
public static int getHeight() {
return heightCache;
}
public static int getColumnCount(int availableHeight, int catalystsSize) {
int maxItemsPerColumn = availableHeight / GuiRecipeCatalyst.ingredientSize;
return NEIServerUtils.divideCeil(catalystsSize, maxItemsPerColumn);
}
public static int getRowCount(int availableHeight, int catalystsSize) {
int columnCount = getColumnCount(availableHeight, catalystsSize);
return NEIServerUtils.divideCeil(catalystsSize, columnCount);
}
public static void loadCatalystInfo() {
final boolean fromJar = NEIClientConfig.loadCatalystsFromJar();
final URL handlerUrl = RecipeCatalysts.class.getResource("/assets/nei/csv/catalysts.csv");
final Map<String, CatalystInfoList> calculatedCatalysts = new HashMap<>();
NEIClientConfig.logger.info("Loading catalyst info from " + (fromJar ? "JAR" : "Config"));
recipeCatalystMap.clear();
URL handlerUrl = RecipeCatalysts.class.getResource("/assets/nei/csv/catalysts.csv");
resolveAdderQueue();
resolveAdderQueue(calculatedCatalysts);
URL url;
if (fromJar) {
@@ -211,7 +181,7 @@ public class RecipeCatalysts {
// Prefer info added by API if we're using default jar config.
// If not, user config overwrites it.
addOrPut(recipeCatalystMap, handlerID, catalystInfo, !fromJar);
addOrPut(calculatedCatalysts, handlerID, catalystInfo, !fromJar);
}
} catch (Exception e) {
NEIClientConfig.logger.warn("Error parsing CSV");
@@ -219,13 +189,17 @@ public class RecipeCatalysts {
}
if (fromJar) {
resolveRemoverQueue();
resolveRemoverQueue(calculatedCatalysts);
}
recipeCatalystMap.clear();
for (Map.Entry<String, CatalystInfoList> entry : calculatedCatalysts.entrySet()) {
recipeCatalystMap.put(entry.getKey(), convertToPositionedStackList(entry.getValue()));
}
updatePosition(getHeight(), true);
}
private static void resolveAdderQueue() {
private static void resolveAdderQueue(Map<String, CatalystInfoList> recipeCatalystMap) {
for (Map.Entry<String, CatalystInfoList> entry : catalystsAdderFromAPI.entrySet()) {
String handlerID = entry.getKey();
for (CatalystInfo catalyst : entry.getValue()) {
@@ -256,7 +230,7 @@ public class RecipeCatalysts {
}
}
private static void resolveRemoverQueue() {
private static void resolveRemoverQueue(Map<String, CatalystInfoList> recipeCatalystMap) {
for (Map.Entry<String, List<ItemStack>> entry : catalystsRemoverFromAPI.entrySet()) {
String handlerID = entry.getKey();
if (recipeCatalystMap.containsKey(handlerID)) {
@@ -308,16 +282,49 @@ public class RecipeCatalysts {
}
}
private static List<PositionedStack> convertToPositionedStackList(CatalystInfoList catalystInfoList) {
catalystInfoList.sort();
return catalystInfoList.stream().filter(catalyst -> catalyst.getStack() != null)
.map(catalyst -> new PositionedStack(catalyst.getStack(), 0, 0, false)).collect(Collectors.toList());
}
@Deprecated
public static void addRecipeCatalyst(List<ItemStack> stacks, Class<? extends IRecipeHandler> handler) {}
@Deprecated
public static List<PositionedStack> getRecipeCatalysts(Class<? extends IRecipeHandler> handler) {
return Collections.emptyList();
return new ArrayList<>();
}
@Deprecated
public static boolean containsCatalyst(Class<? extends IRecipeHandler> handler, ItemStack candidate) {
return false;
}
@Deprecated
public static Map<String, List<PositionedStack>> getPositionedRecipeCatalystMap() {
return new HashMap<>();
}
@Deprecated
public static void updatePosition(int availableHeight, boolean force) {}
@Deprecated
public static void updatePosition(int availableHeight) {}
@Deprecated
public static int getHeight() {
return 1;
}
@Deprecated
public static int getColumnCount(int availableHeight, int catalystsSize) {
return 1;
}
@Deprecated
public static int getRowCount(int availableHeight, int catalystsSize) {
return 1;
}
}
@@ -62,7 +62,13 @@ public class RecipeHandlerQuery<T extends IRecipeHandler> {
private ArrayList<T> getRecipeHandlersParallel() throws InterruptedException, ExecutionException {
// Pre-find the fuels so we're not fighting over it
FuelRecipeHandler.findFuelsOnceParallel();
if (NEIClientConfig.getBooleanSetting("findFuelsParallel")) {
FuelRecipeHandler.findFuelsOnceParallel();
} else {
FuelRecipeHandler.findFuelsOnce();
}
ArrayList<T> handlers = getSerialHandlersWithRecipes();
handlers.addAll(getHandlersWithRecipes());
handlers.sort(NEIClientConfig.HANDLER_COMPARATOR);
@@ -61,6 +61,10 @@ public class RecipeHandlerRef {
return firstGui != null && firstGui.inventorySlots != null ? firstGui : null;
}
public NEIRecipeWidget getRecipeWidget() {
return new NEIRecipeWidget(this);
}
public IOverlayHandler getOverlayHandler(GuiContainer gui) {
final GuiContainer firstGui = prepareGui(gui);
@@ -14,6 +14,7 @@ import codechicken.nei.ItemPanels;
import codechicken.nei.ItemsGrid.ItemsGridSlot;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.api.ShortcutInputHandler;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.bookmark.BookmarksGridSlot;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.guihook.IContainerInputHandler;
@@ -37,23 +38,16 @@ public class RecipeItemInputHandler implements IContainerInputHandler, IContaine
@Override
public boolean mouseClicked(GuiContainer gui, int mousex, int mousey, int button) {
if (!(gui instanceof GuiRecipe) || ItemPanels.itemPanel.contains(mousex, mousey)
|| ItemPanels.bookmarkPanel.contains(mousex, mousey)
|| ItemPanels.itemPanel.historyPanel.contains(mousex, mousey))
return false;
return ShortcutInputHandler.handleMouseClick(GuiContainerManager.getStackMouseOver(gui));
return false;
}
@Override
public Map<String, String> handleHotkeys(GuiContainer gui, int mousex, int mousey, Map<String, String> hotkeys) {
if ((gui instanceof GuiRecipe) || ItemPanels.itemPanel.contains(mousex, mousey)
|| ItemPanels.bookmarkPanel.contains(mousex, mousey)
|| ItemPanels.itemPanel.historyPanel.contains(mousex, mousey)) {
if (gui instanceof GuiRecipe || ItemPanels.itemPanel.containsWithSubpanels(mousex, mousey)
|| ItemPanels.bookmarkPanel.contains(mousex, mousey)) {
hotkeys.putAll(
ShortcutInputHandler
.handleHotkeys(gui, mousex, mousey, GuiContainerManager.getStackMouseOver(gui)));
ShortcutInputHandler.handleHotkeys(mousex, mousey, GuiContainerManager.getStackMouseOver(gui)));
}
return hotkeys;
@@ -88,7 +82,7 @@ public class RecipeItemInputHandler implements IContainerInputHandler, IContaine
final BookmarksGridSlot slot = ItemPanels.bookmarkPanel.getSlotMouseOver(mousex, mousey);
if (slot != null && slot.getRecipeId() != null
&& !slot.isIngredient()
&& slot.getType() != BookmarkItemType.INGREDIENT
&& NEIClientConfig.getRecipeTooltipsMode() != 0) {
final int tooltipMode = NEIClientConfig.getRecipeTooltipsMode();
final BookmarkViewMode viewMode = slot.getGroup().viewMode;
@@ -1,23 +1,34 @@
package codechicken.nei.recipe;
import java.awt.Dimension;
import java.util.List;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import codechicken.lib.gui.GuiDraw;
import codechicken.lib.gui.GuiDraw.ITooltipLineHandler;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.scroll.GuiHelper;
public class RecipeTooltipLineHandler implements ITooltipLineHandler {
private static final int BG_PADDING = 5;
private static final DrawableResource BG_TEXTURE = new DrawableBuilder(
"nei:textures/gui/recipebg.png",
0,
0,
176,
166).build();
protected long lastUpdate = System.currentTimeMillis();
protected String recipeName = "";
protected GuiRecipe<?> gui = null;
protected RecipeHandlerRef handlerRef = null;
protected NEIRecipeWidget widget = null;
protected RecipeId recipeId = null;
protected boolean createdGui = false;
@@ -36,19 +47,22 @@ public class RecipeTooltipLineHandler implements ITooltipLineHandler {
@Override
public Dimension getSize() {
if (this.gui == null && !this.createdGui) {
this.gui = GuiCraftingRecipe.createRecipeGui("recipeId", false, this.recipeId.getResult(), this.recipeId);
if (this.widget == null && !this.createdGui) {
this.handlerRef = RecipeHandlerRef.of(this.recipeId);
this.createdGui = true;
if (this.gui != null) {
this.gui.initGui();
this.gui.guiTop = 0;
this.gui.guiLeft = 0;
if (handlerRef != null) {
this.widget = new NEIRecipeWidget(this.handlerRef);
this.widget.showAsWidget(true);
this.widget.x = BG_PADDING;
this.widget.y = BG_PADDING + 12;
this.recipeName = this.widget.getRecipeHandlerRef().handler.getRecipeName().trim();
}
}
if (this.gui != null) {
return this.gui.getWidgetSize();
if (this.widget != null) {
return new Dimension(this.widget.w + BG_PADDING * 2, this.widget.h + BG_PADDING * 2 + 12);
}
return new Dimension(0, 0);
@@ -56,41 +70,40 @@ public class RecipeTooltipLineHandler implements ITooltipLineHandler {
@Override
public void draw(int x, int y) {
if (this.gui == null) return;
if (this.widget == null) return;
if ((System.currentTimeMillis() - lastUpdate) > 50) {
lastUpdate = System.currentTimeMillis();
this.gui.onUpdate();
this.handlerRef.handler.onUpdate();
this.widget.update();
}
GL11.glPushMatrix();
GL11.glScaled(1, 1, 3);
GL11.glTranslatef(x, y, 0);
GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
RenderHelper.disableStandardItemLighting();
final Dimension size = getSize();
this.gui.drawGuiContainerBackgroundLayer(0.0f, -100, -100);
GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_LIGHTING_BIT);
final int zTranslation = GuiContainerManager.TOOLTIP_Z_OFFSET;
GL11.glTranslatef(x, y, zTranslation);
GuiContainerManager.enable2DRender();
GL11.glColor4f(1, 1, 1, 1);
BG_TEXTURE.draw(0, 0, size.width, size.height, BG_PADDING, BG_PADDING, BG_PADDING, BG_PADDING);
GL11.glEnable(GL11.GL_ALPHA_TEST);
GuiDraw.drawRect(BG_PADDING, BG_PADDING, size.width - BG_PADDING * 2, 12, 0x30000000);
GuiDraw.drawStringC(this.recipeName, this.widget.w / 2, BG_PADDING + 2, 0xffffff);
GuiHelper.useScissor(
this.widget.x,
this.widget.y,
this.widget.w,
this.widget.h,
() -> { this.widget.draw(0, 0); });
GL11.glPopAttrib();
if (this.gui.slotcontainer != null) {
GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
RenderHelper.enableGUIStandardItemLighting();
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
GL11.glDisable(GL11.GL_DEPTH_TEST);
List<Slot> slots = this.gui.slotcontainer.inventorySlots;
for (Slot slot : slots) {
if (slot != null && slot.getStack() != null) {
GuiContainerManager.drawItem(slot.xDisplayPosition, slot.yDisplayPosition, slot.getStack());
}
}
GL11.glPopAttrib();
}
this.gui.drawGuiContainerForegroundLayer(-100, -100);
GL11.glPopMatrix();
GL11.glTranslatef(-x, -y, -zTranslation);
}
}
@@ -1,6 +1,7 @@
package codechicken.nei.recipe;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.function.IntPredicate;
@@ -23,16 +24,16 @@ class SearchRecipeHandler<H extends IRecipeHandler> {
this.original = handler;
if (this.original.numRecipes() == 0) {
this.filteredRecipes = new ArrayList<>();
this.filteredRecipes = Collections.emptyList();
} else {
final Stream<Integer> items = IntStream.range(0, this.original.numRecipes()).boxed();
final IRecipeFilter filter = this.searchingAvailable() ? GuiRecipe.getRecipeListFilter() : null;
if (filter == null) {
this.filteredRecipes = items.collect(Collectors.toCollection(ArrayList::new));
this.filteredRecipes = items.collect(Collectors.toList());
} else {
this.filteredRecipes = items.filter(recipe -> mathRecipe(this.original, recipe, filter))
.collect(Collectors.toCollection(ArrayList::new));
.collect(Collectors.toList());
}
}
}
@@ -54,7 +54,7 @@ public class ShapedRecipeHandler extends TemplateRecipeHandler {
@Override
public List<PositionedStack> getIngredients() {
return getCycledIngredients(cycleticks / 20, ingredients);
return ingredients;
}
public PositionedStack getResult() {
@@ -64,7 +64,7 @@ public class ShapelessRecipeHandler extends ShapedRecipeHandler {
@Override
public List<PositionedStack> getIngredients() {
return getCycledIngredients(cycleticks / 20, ingredients);
return ingredients;
}
@Override
@@ -76,6 +76,16 @@ public class StackInfo {
return stack;
}
public static ItemStack normalizeRecipeQueryStack(ItemStack stack) {
ItemStack result = null;
for (int i = stackStringifyHandlers.size() - 1; i >= 0 && result == null; i--) {
result = stackStringifyHandlers.get(i).normalizeRecipeQueryStack(stack);
}
return result == null ? stack : result;
}
public static void pauseItemDamageSound(boolean pause) {
if (isPausedItemDamageSound != (isPausedItemDamageSound = pause)) {
for (IStackStringifyHandler handler : stackStringifyHandlers) {
@@ -9,13 +9,11 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.init.Blocks;
@@ -31,8 +29,6 @@ import org.lwjgl.opengl.GL11;
import com.google.common.base.Stopwatch;
import codechicken.lib.gui.GuiDraw;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.FavoriteRecipes;
import codechicken.nei.ItemList;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
@@ -45,6 +41,7 @@ import codechicken.nei.api.IStackPositioner;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.guihook.IContainerInputHandler;
import codechicken.nei.guihook.IContainerTooltipHandler;
import cpw.mods.fml.common.FMLLog;
/**
* A Template Recipe Handler! How about that. Because it was sooo hard, and more seriously required lots of copied code
@@ -108,10 +105,15 @@ public abstract class TemplateRecipeHandler implements ICraftingHandler, IUsageH
}
private static FurnaceRecipeHandler.FuelPair identifyFuel(final ItemStack itemStack) {
if (efuels.contains(itemStack.getItem())) return null;
final int burnTime = TileEntityFurnace.getItemBurnTime(itemStack);
if (burnTime <= 0) return null;
return new FurnaceRecipeHandler.FuelPair(itemStack.copy(), burnTime);
try {
if (efuels.contains(itemStack.getItem())) return null;
final int burnTime = TileEntityFurnace.getItemBurnTime(itemStack);
if (burnTime <= 0) return null;
return new FurnaceRecipeHandler.FuelPair(itemStack.copy(), burnTime);
} catch (Exception e) {
FMLLog.getLogger().error("NEI: Error identifying fuel for item " + itemStack.getItem());
throw e;
}
}
/**
@@ -172,43 +174,16 @@ public abstract class TemplateRecipeHandler implements ICraftingHandler, IUsageH
return null;
}
/**
* This will perform default cycling of ingredients, mulitItem capable
*
* @param cycle Current cycle step
* @param ingredients List of ItemStacks to cycle
* @return The provided list of ingredients, with their permutations cycled to a different permutation, if one
* is available
*/
@Deprecated
public List<PositionedStack> getCycledIngredients(int cycle, List<PositionedStack> ingredients) {
if (!NEIClientUtils.shiftKey() && !disableCycledIngredients) {
randomRenderPermutation(ingredients, cycle);
}
return ingredients;
}
public void randomRenderPermutation(List<PositionedStack> stacks, long cycle) {
cycle = NEIClientConfig.useJEIStyledCycledIngredients() ? cycle
: Math.abs(new Random(cycle + offset).nextInt());
for (PositionedStack pStack : stacks) {
if (pStack.items.length <= 1) continue;
final List<ItemStack> items = pStack.getFilteredPermutations(FavoriteRecipes::contains);
pStack.setPermutationToRender(items.get((int) (cycle % items.size())));
}
}
@Deprecated
public void randomRenderPermutation(List<PositionedStack> stacks, long cycle) {}
@Deprecated
public void randomRenderPermutation(PositionedStack stack, long cycle) {
cycle = NEIClientConfig.useJEIStyledCycledIngredients() ? cycle
: Math.abs(new Random(cycle + offset).nextInt());
if (stack.items.length <= 1) return;
final List<ItemStack> items = stack.getFilteredPermutations(FavoriteRecipes::contains);
stack.setPermutationToRender(items.get((int) (cycle % items.size())));
}
public void randomRenderPermutation(PositionedStack stack, long cycle) {}
public void setIngredientPermutation(Collection<PositionedStack> ingredients, ItemStack ingredient) {
for (PositionedStack stack : ingredients) {
@@ -400,8 +375,6 @@ public abstract class TemplateRecipeHandler implements ICraftingHandler, IUsageH
*/
public LinkedList<RecipeTransferRect> transferRects = new LinkedList<>();
public static boolean disableCycledIngredients = true;
public TemplateRecipeHandler() {
loadTransferRects();
RecipeTransferRectHandler.registerRectsToGuis(getRecipeTransferRectGuis(), transferRects);
@@ -635,7 +608,7 @@ public abstract class TemplateRecipeHandler implements ICraftingHandler, IUsageH
}
public void onUpdate() {
if (!NEIClientUtils.shiftKey()) cycleticks++;
cycleticks++;
}
public boolean hasOverlay(GuiContainer gui, Container container, int recipe) {
@@ -654,11 +627,6 @@ public abstract class TemplateRecipeHandler implements ICraftingHandler, IUsageH
return RecipeInfo.getOverlayHandler(gui, getOverlayIdentifier());
}
@Override
public int recipiesPerPage() {
return 2;
}
@Override
public List<String> handleTooltip(GuiRecipe<?> gui, List<String> currenttip, int recipe) {
if (GuiContainerManager.shouldShowTooltip(gui) && currenttip.isEmpty()) {
@@ -699,49 +667,9 @@ public abstract class TemplateRecipeHandler implements ICraftingHandler, IUsageH
@Override
public boolean mouseScrolled(GuiRecipe<?> gui, int scroll, int recipe) {
if (!NEIClientUtils.shiftKey()) return false;
final Point pos = GuiDraw.getMousePosition();
final Point offset = gui.getRecipePosition(recipe);
final Point relMouse = new Point(pos.x - gui.guiLeft - offset.x, pos.y - gui.guiTop - offset.y);
final PositionedStack overStack = getIngredientMouseOver(relMouse.x, relMouse.y, recipe);
if (overStack != null && overStack.items.length > 1) {
final List<ItemStack> items = overStack.getFilteredPermutations();
final int stackIndex = getPermutationIndex(overStack.item, items);
final ItemStack stack = items.get((items.size() - scroll + stackIndex) % items.size());
if (NEIClientConfig.useJEIStyledCycledIngredients()) {
Stream.concat(getIngredientStacks(recipe).stream(), getOtherStacks(recipe).stream())
.filter(pStack -> pStack.containsWithNBT(stack))
.forEach(pStack -> pStack.setPermutationToRender(stack));
} else {
overStack.setPermutationToRender(stack);
}
return true;
}
return false;
}
private int getPermutationIndex(ItemStack stack, List<ItemStack> items) {
for (int index = 0; index < items.size(); index++) {
if (NEIServerUtils.areStacksSameTypeCraftingWithNBT(items.get(index), stack)) {
return index;
}
}
return -1;
}
private PositionedStack getIngredientMouseOver(int mousex, int mousey, int recipe) {
return Stream.concat(getIngredientStacks(recipe).stream(), getOtherStacks(recipe).stream())
.filter(pStack -> new Rectangle4i(pStack.relx, pStack.rely, 18, 18).contains(mousex, mousey))
.findFirst().orElse(null);
}
private boolean transferRect(GuiRecipe<?> gui, int recipe, boolean usage) {
Point offset = gui.getRecipePosition(recipe);
return transferRect(gui, transferRects, offset.x, offset.y, usage);
@@ -16,6 +16,7 @@ import net.minecraft.nbt.NBTTagCompound;
import codechicken.nei.ItemStackAmount;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.bookmark.BookmarkItem;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.recipe.Recipe;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.recipe.Recipe.RecipeIngredient;
@@ -52,20 +53,12 @@ public class RecipeChainMath {
private final List<ItemStack> containerItemsBlacklist = new ArrayList<>();
private RecipeChainMath(List<BookmarkItem> recipeItems, Set<RecipeId> collapsedRecipes) {
final Map<RecipeId, Integer> recipeState = new HashMap<>();
final Map<RecipeId, Long> multipliers = new HashMap<>();
for (BookmarkItem item : recipeItems) {
if (item.recipeId != null) {
recipeState
.put(item.recipeId, recipeState.getOrDefault(item.recipeId, 0) | (item.isIngredient ? 1 : 2));
}
}
for (BookmarkItem item : recipeItems) {
if (recipeState.getOrDefault(item.recipeId, 0) != 3) {
if (item.recipeId == null || item.type == BookmarkItemType.ITEM) {
this.initialItems.add(item.copy());
} else if (item.isIngredient) {
} else if (item.type == BookmarkItemType.INGREDIENT) {
this.recipeIngredients.add(item.copyWithAmount(0));
} else {
this.recipeResults.add(item.copyWithAmount(0));
@@ -209,7 +202,7 @@ public class RecipeChainMath {
item.getItemStack(amount),
item.getStackSize(amount),
ROOT_RECIPE_ID,
true,
BookmarkItemType.INGREDIENT,
BookmarkItem.generatePermutations(item.itemStack, null)));
}
}
@@ -217,7 +210,7 @@ public class RecipeChainMath {
this.outputRecipes.clear();
this.outputRecipes.put(ROOT_RECIPE_ID, 1L);
this.recipeResults.removeIf(item -> ROOT_RECIPE_ID.equals(item.recipeId));
this.recipeResults.add(BookmarkItem.of(-1, ROOT_ITEM, 1, ROOT_RECIPE_ID, false));
this.recipeResults.add(BookmarkItem.of(-1, ROOT_ITEM, 1, ROOT_RECIPE_ID, BookmarkItemType.RESULT));
this.recipeIngredients.addAll(rootIngredients);
return ROOT_RECIPE_ID;
@@ -236,7 +229,7 @@ public class RecipeChainMath {
final RecipeId recipeId = recipe.getRecipeId();
final ItemStack result = recipe.getResult();
chainItems.add(BookmarkItem.of(-1, result, StackInfo.getAmount(result), recipeId, false));
chainItems.add(BookmarkItem.of(-1, result, StackInfo.getAmount(result), recipeId, BookmarkItemType.RESULT));
for (RecipeIngredient ingr : recipe.getIngredients()) {
chainItems.add(
@@ -245,7 +238,7 @@ public class RecipeChainMath {
ingr.getItemStack(),
ingr.getAmount(),
recipeId,
true,
BookmarkItemType.INGREDIENT,
BookmarkItem.generatePermutations(ingr.getItemStack(), recipe)));
}
@@ -406,14 +399,46 @@ public class RecipeChainMath {
ItemStack itemStack = prefItem.itemStack;
while (ingrAmount > 0 && shiftAmount < maxAmount) {
long multiplier = 1;
itemStack = itemStack.copy();
itemStack.stackSize = 1;
this.containerItems.add(itemStack);
ingrAmount = shiftContainerItems(itemStack, prefItem.getStackSize(ingrAmount))
* prefItem.fluidCellAmount;
shiftAmount += prefItem.fluidCellAmount;
if (ingrAmount > 0) {
long steps = prefItem.getStackSize(ingrAmount);
final ContainerItemResult result = getToolsContainerItems(itemStack, steps);
if (result.stack == null) {
multiplier = steps / (steps - result.leftSteps);
steps = steps % (steps - result.leftSteps);
} else {
steps = result.leftSteps;
}
if (result.containerItem != null) {
long stackSize = result.containerItem.stackSize * multiplier;
while (stackSize > Integer.MAX_VALUE) {
final ItemStack copy = result.containerItem.copy();
copy.stackSize = Integer.MAX_VALUE;
this.containerItems.add(copy);
stackSize -= copy.stackSize;
}
result.containerItem.stackSize = (int) stackSize;
this.containerItems.add(result.containerItem);
}
if (result.stack != null) {
this.containerItems.add(result.stack);
}
ingrAmount = steps * prefItem.fluidCellAmount;
}
shiftAmount += multiplier * prefItem.fluidCellAmount;
}
} else {
@@ -429,8 +454,9 @@ public class RecipeChainMath {
}
private long shiftContainerItems(ItemStack aStack, long steps) {
final int initialSize = this.containerItems.size();
for (int i = 0; i < this.containerItems.size() && steps > 0; i++) {
for (int i = 0; i < initialSize && steps > 0; i++) {
ItemStack bStack = this.containerItems.get(i);
if (bStack != null && NEIClientUtils.areStacksSameTypeCraftingWithNBT(aStack, bStack)) {
@@ -463,12 +489,12 @@ public class RecipeChainMath {
final NBTTagCompound toolStats = tagCompound.getCompoundTag("GT.ToolStats");
final long maxDamage = toolStats.getLong("MaxDamage");
final long damage = toolStats.getLong("Damage");
final long leftSteps = (maxDamage - damage) / damagePerContainerCraft;
final long leftSteps = (long) Math.ceil((maxDamage - damage) / (double) damagePerContainerCraft);
final long availableSteps = Math.min(steps, Math.max(1, leftSteps));
steps -= availableSteps;
if ((damage + availableSteps * damagePerContainerCraft) == maxDamage || leftSteps <= 0) {
if ((damage + availableSteps * damagePerContainerCraft) >= maxDamage || leftSteps <= 0) {
aStack = null;
} else {
toolStats.setLong("Damage", damage + availableSteps * damagePerContainerCraft);
@@ -170,13 +170,13 @@ public class RecipeChainTooltipLineHandler implements ITooltipLineHandler {
inputs.sort(
Comparator.comparing((ItemStack stack) -> StackInfo.getFluid(stack) != null)
.thenComparing(ItemSorter.instance));
.thenComparingInt(stack -> -1 * stack.stackSize).thenComparing(ItemSorter.instance));
outputs.sort(
Comparator.comparing((ItemStack stack) -> StackInfo.getFluid(stack) != null)
.thenComparing(ItemSorter.instance));
.thenComparingInt(stack -> -1 * stack.stackSize).thenComparing(ItemSorter.instance));
remainder.sort(
Comparator.comparing((ItemStack stack) -> StackInfo.getFluid(stack) != null)
.thenComparing(ItemSorter.instance));
.thenComparingInt(stack -> -1 * stack.stackSize).thenComparing(ItemSorter.instance));
this.inputs = new ItemsTooltipLineHandler(
this.lastShiftKey ? NEIClientUtils.translate("bookmark.crafting_chain.missing")
@@ -208,6 +208,8 @@ public class RecipeChainTooltipLineHandler implements ITooltipLineHandler {
this.available.setLabelColor(EnumChatFormatting.GREEN);
}
this.size.height = this.size.width = 0;
if (!this.inputs.isEmpty() || !this.outputs.isEmpty()
|| !this.remainder.isEmpty()
|| !this.available.isEmpty()) {
@@ -225,8 +227,6 @@ public class RecipeChainTooltipLineHandler implements ITooltipLineHandler {
this.size.height += this.inputs.getSize().height + this.outputs.getSize().height
+ this.remainder.getSize().height
+ this.available.getSize().height;
} else {
this.size.height = this.size.width = 0;
}
}
@@ -25,7 +25,7 @@ public class DefaultStackStringifyHandler implements IStackStringifyHandler {
nbTag.setShort("Damage", (short) stack.getItemDamage());
if (stack.hasTagCompound() && !stack.getTagCompound().hasNoTags()) {
nbTag.setTag("tag", stack.getTagCompound());
nbTag.setTag("tag", stack.getTagCompound().copy());
}
return nbTag;
@@ -19,9 +19,8 @@ public class GTFluidStackStringifyHandler implements IStackStringifyHandler {
protected static Class<?> itemFluidDisplay = null;
protected static Method getFluidDisplayStack = null;
protected static Method getFluidFromDisplayStack = null;
public static boolean replaceAE2FCFluidDrop = false;
private static Class<?> gtMetaGeneratedTool = null;
private static Field playSound = null;
protected static Class<?> gtMetaGeneratedTool = null;
protected static Field playSound = null;
static {
try {
@@ -48,7 +47,7 @@ public class GTFluidStackStringifyHandler implements IStackStringifyHandler {
public NBTTagCompound convertItemStackToNBT(ItemStack stack, boolean saveStackSize) {
if (replaceAE2FCFluidDrop || stack.getItem() != GameRegistry.findItem("ae2fc", "fluid_drop")) {
if (stack.getItem() != GameRegistry.findItem("ae2fc", "fluid_drop")) {
final FluidStack fluidStack = getFluid(stack);
if (fluidStack != null) {
@@ -69,14 +68,11 @@ public class GTFluidStackStringifyHandler implements IStackStringifyHandler {
final Fluid fluid = FluidRegistry.getFluid(fluidName);
final int amount = nbtTag.getInteger("Count");
try {
final Object obj = getFluidDisplayStack.invoke(null, new FluidStack(fluid, amount), true);
if (obj != null) {
return (ItemStack) obj;
}
} catch (Exception e) {}
if (fluid != null) {
try {
return (ItemStack) getFluidDisplayStack.invoke(null, new FluidStack(fluid, amount), true);
} catch (Exception e) {}
}
}
return null;
@@ -114,6 +110,21 @@ public class GTFluidStackStringifyHandler implements IStackStringifyHandler {
return null;
}
public ItemStack normalizeRecipeQueryStack(ItemStack stack) {
if (stack.getItem() == GameRegistry.findItem("ae2fc", "fluid_drop")) {
final FluidStack fluidStack = getFluid(stack);
if (fluidStack != null) {
try {
return (ItemStack) getFluidDisplayStack.invoke(null, fluidStack, true);
} catch (Exception e) {}
}
}
return null;
}
@Override
public void pauseItemDamageSound(boolean pause) {
if (playSound != null) {
@@ -0,0 +1,131 @@
package codechicken.nei.scroll;
import java.nio.FloatBuffer;
import java.util.Stack;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class GuiHelper {
private static final Stack<int[]> scissorFrameStack = new Stack<>();
public static void useScissor(int x, int y, int width, int height, Runnable codeBlock) {
pushScissorFrame(x, y, width, height);
try {
codeBlock.run();
} finally {
popScissorFrame();
}
}
private static int[] peekFirstScissorOrFullScreen() {
final int[] currentTopFrame = scissorFrameStack.isEmpty() ? null : scissorFrameStack.peek();
if (currentTopFrame == null) {
final Minecraft minecraft = Minecraft.getMinecraft();
return new int[] { 0, 0, minecraft.displayWidth, minecraft.displayHeight };
}
return currentTopFrame;
}
private static void pushScissorFrame(int x, int y, int width, int height) {
int[] matrix = prepareMatrix(x, y, width, height);
int[] parentScissor = peekFirstScissorOrFullScreen();
int parentX = parentScissor[0];
int parentY = parentScissor[1];
int parentWidth = parentScissor[2];
int parentHeight = parentScissor[3];
boolean pushedFrame = false;
x = matrix[0];
y = matrix[1];
width = matrix[2];
height = matrix[3];
if (x <= parentX + parentWidth && y <= parentY + parentHeight) {
int newX = Math.max(x, parentX);
int newY = Math.max(y, parentY);
int newWidth = width - (newX - x);
int newHeight = height - (newY - y);
if (newWidth > 0 && newHeight > 0) {
int maxWidth = parentWidth - (x - parentX);
int maxHeight = parentHeight - (y - parentY);
newWidth = Math.min(maxWidth, newWidth);
newHeight = Math.min(maxHeight, newHeight);
applyScissor(newX, newY, newWidth, newHeight);
// finally, push applied scissor on top of scissor stack
if (scissorFrameStack.isEmpty()) {
GL11.glEnable(GL11.GL_SCISSOR_TEST);
}
scissorFrameStack.push(new int[] { newX, newY, newWidth, newHeight });
pushedFrame = true;
}
}
if (!pushedFrame) {
if (scissorFrameStack.isEmpty()) {
GL11.glEnable(GL11.GL_SCISSOR_TEST);
}
scissorFrameStack.push(new int[] { parentX, parentY, parentWidth, parentHeight });
}
}
public static void popScissorFrame() {
scissorFrameStack.pop();
int[] parentScissor = peekFirstScissorOrFullScreen();
int parentX = parentScissor[0];
int parentY = parentScissor[1];
int parentWidth = parentScissor[2];
int parentHeight = parentScissor[3];
applyScissor(parentX, parentY, parentWidth, parentHeight);
if (scissorFrameStack.isEmpty()) {
GL11.glDisable(GL11.GL_SCISSOR_TEST);
}
}
// applies scissor with gui-space coordinates and sizes
private static void applyScissor(int x, int y, int w, int h) {
// translate upper-left to bottom-left
final Minecraft mc = Minecraft.getMinecraft();
final ScaledResolution res = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight);
final int scaleFactor = res.getScaleFactor();
final int translatedY = mc.displayHeight - (y + h) * scaleFactor;
GL11.glScissor(x * scaleFactor, translatedY, w * scaleFactor, h * scaleFactor);
}
private static int[] prepareMatrix(int x, int y, int w, int h) {
// Get the current translation component to support the Gui being drawn at any position on the screen
final FloatBuffer matBuf = BufferUtils.createFloatBuffer(16);
GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, matBuf);
final float xScale = matBuf.get(0);
final float yScale = matBuf.get(5);
final int xTranslate = (int) (matBuf.get(12) / xScale);
final int yTranslate = (int) (matBuf.get(13) / yScale);
x += xTranslate;
y += yTranslate;
x *= xScale;
y *= yScale;
w *= xScale;
h *= yScale;
return new int[] { x, y, w, h };
}
}
@@ -0,0 +1,450 @@
package codechicken.nei.scroll;
import java.awt.Color;
import org.lwjgl.opengl.GL11;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
public class ScrollBar {
/** The minimum length of the scrollbar cursor. */
private static final int MINIMUM_THUMB_SIZE = 6;
private static final Color BACKGROUND_COLOR = new Color(0x90B1D4E0);
private static final Color THUMB_COLOR = new Color(0xF0145DA0);
private static final Color THUMB_SELECTED_COLOR = new Color(0xF02E8BC0);
public enum ScrollType {
HORIZONTAL,
VERTICAL
}
public enum OverflowType {
NONE,
AUTO,
SCROLL,
OVERLAY
}
public enum ScrollPlace {
START,
END
}
private ScrollType scrollType = ScrollType.VERTICAL;
private OverflowType overflowType = OverflowType.SCROLL;
private ScrollPlace scrollPlace = ScrollPlace.END;
private float handleClickOffset = -1;
private int scrollbarSize = 6;
private int thumbPadding = 0;
private int padding = 0;
private int marginStart = 0;
private int marginEnd = 0;
private DrawableResource thumbTexture;
private int thumbSliceStart;
private int thumbSliceEnd;
private DrawableResource trackTexture;
private int trackSliceStart;
private int trackSliceEnd;
public static ScrollBar defaultScrollBar() {
return new ScrollBar();
}
public static ScrollBar defaultVerticalBar() {
return new ScrollBar().setScrollbarSize(8)
.setTrackTexture(new DrawableBuilder("nei:textures/nei_sprites.png", 28, 95, 11, 11).build(), 3, 4)
.setThumbTexture(new DrawableBuilder("nei:textures/nei_sprites.png", 21, 96, 7, 9).build(), 3, 2)
.setThumbPadding(1);
}
public static ScrollBar defaultHorizontalBar() {
return new ScrollBar().setScrollbarSize(8).setOverflowType(OverflowType.SCROLL).setScrollPlace(ScrollPlace.END)
.setTrackTexture(new DrawableBuilder("nei:textures/nei_sprites.png", 0, 97, 11, 8).build(), 3, 4)
.setThumbTexture(new DrawableBuilder("nei:textures/nei_sprites.png", 12, 97, 9, 7).build(), 3, 2)
.setThumbPadding(1);
}
public ScrollBar setScrollbarSize(int scrollbarSize) {
this.scrollbarSize = scrollbarSize;
return this;
}
public ScrollBar setThumbPadding(int thumbPadding) {
this.thumbPadding = thumbPadding;
return this;
}
public ScrollBar setPadding(int padding) {
this.padding = padding;
return this;
}
public int getPadding() {
return this.padding;
}
public ScrollBar setMarginStart(int start) {
this.marginStart = start;
return this;
}
public int getMarginStart() {
return this.marginStart;
}
public ScrollBar setMarginEnd(int end) {
this.marginEnd = end;
return this;
}
public int getMarginEnd() {
return this.marginEnd;
}
public int getScrollbarSize() {
return this.scrollbarSize;
}
public ScrollBar setThumbTexture(DrawableResource texture, int sliceStart, int sliceEnd) {
this.thumbTexture = texture;
this.thumbSliceStart = sliceStart;
this.thumbSliceEnd = sliceEnd;
return this;
}
public ScrollBar setTrackTexture(DrawableResource texture, int sliceStart, int sliceEnd) {
this.trackTexture = texture;
this.trackSliceStart = sliceStart;
this.trackSliceEnd = sliceEnd;
return this;
}
public ScrollBar setOverflowType(OverflowType overflowType) {
this.overflowType = overflowType;
return this;
}
public OverflowType getOverflowType() {
return this.overflowType;
}
public ScrollBar setScrollPlace(ScrollPlace scrollPlace) {
this.scrollPlace = scrollPlace;
return this;
}
public ScrollPlace getScrollPlace() {
return this.scrollPlace;
}
public ScrollBar setScrollType(ScrollType scrollType) {
this.scrollType = scrollType;
return this;
}
private int getActualSize(ScrollContainer container) {
if (this.scrollType == ScrollType.HORIZONTAL) {
return container.getActualWidth();
} else {
return container.getActualHeight();
}
}
public int getVisibleSize(ScrollContainer container) {
if (this.scrollType == ScrollType.HORIZONTAL) {
return container.getVisibleWidth();
} else {
return container.getVisibleHeight();
}
}
private int getMaxThumbSize(ScrollContainer container) {
return getMaxTrackSize(container) - this.thumbPadding * 2;
}
private int getMaxTrackSize(ScrollContainer container) {
if (this.scrollType == ScrollType.HORIZONTAL) {
return container.w - this.marginStart - this.marginEnd;
} else {
return container.h - this.marginStart - this.marginEnd;
}
}
private int getMinThumbSize() {
if (this.thumbTexture != null) {
return this.scrollType == ScrollType.HORIZONTAL ? this.thumbTexture.getWidth()
: this.thumbTexture.getHeight();
}
return MINIMUM_THUMB_SIZE;
}
public float getScrollOffset(ScrollContainer container) {
final float thumbSize = getMaxThumbSize(container) - calculateMainAxisSize(container);
if (this.scrollType == ScrollType.HORIZONTAL) {
return container.getHorizontalScrollOffset()
/ (float) (container.getActualWidth() - container.getVisibleWidth())
* thumbSize;
} else {
return container.getVerticalScrollOffset()
/ (float) (container.getActualHeight() - container.getVisibleHeight())
* thumbSize;
}
}
public float calculateMainAxisSize(ScrollContainer container) {
final int visibleSize = getVisibleSize(container);
final int actualSize = getActualSize(container);
final int trackSize = getMaxThumbSize(container);
return Math.max(Math.min(trackSize, (trackSize / (float) actualSize) * visibleSize), getMinThumbSize());
}
public Rectangle4i trackBounds(ScrollContainer container) {
if (this.scrollType == ScrollType.HORIZONTAL) {
if (this.scrollPlace == ScrollPlace.START) {
return new Rectangle4i(
container.x + this.marginStart,
container.y - this.padding - this.scrollbarSize,
getMaxTrackSize(container),
this.scrollbarSize);
} else {
return new Rectangle4i(
container.x + this.marginStart,
container.y + container.h + this.padding,
getMaxTrackSize(container),
this.scrollbarSize);
}
} else {
if (this.scrollPlace == ScrollPlace.START) {
return new Rectangle4i(
container.x - this.padding - this.scrollbarSize,
container.y + this.marginStart,
this.scrollbarSize,
getMaxTrackSize(container));
} else {
return new Rectangle4i(
container.x + container.w + this.padding,
container.y + this.marginStart,
this.scrollbarSize,
getMaxTrackSize(container));
}
}
}
public Rectangle4i thumbBounds(ScrollContainer container) {
final int mainAxisSize = (int) calculateMainAxisSize(container);
final int offset = (int) Math.ceil(getScrollOffset(container));
final Rectangle4i bounds = trackBounds(container);
if (this.scrollType == ScrollType.HORIZONTAL) {
return new Rectangle4i(bounds.x + this.thumbPadding + offset, bounds.y, mainAxisSize, bounds.h);
} else {
return new Rectangle4i(bounds.x, bounds.y + this.thumbPadding + offset, bounds.w, mainAxisSize);
}
}
public boolean setScrollOffset(ScrollContainer container, int offset) {
if (this.scrollType == ScrollType.HORIZONTAL) {
return container.setHorizontalScrollOffset(offset);
} else {
return container.setVerticalScrollOffset(offset);
}
}
public boolean onClick(ScrollContainer container, int mx, int my, int button) {
final Rectangle4i bounds = trackBounds(container);
if (bounds.contains(mx, my)) {
final float mainAxisSize = calculateMainAxisSize(container);
final float thumbSize = getMaxThumbSize(container) - mainAxisSize;
final Rectangle4i thumbBounds = thumbBounds(container);
if (this.scrollType == ScrollType.HORIZONTAL) {
final int relativeX = mx - bounds.x - this.thumbPadding;
if (mx < thumbBounds.x || mx > thumbBounds.x + thumbBounds.w) {
this.handleClickOffset = mainAxisSize / 2;
} else {
this.handleClickOffset = mx - thumbBounds.x;
}
final float newOffset = ((relativeX - this.handleClickOffset)
* (container.getActualWidth() - container.getVisibleWidth())) / thumbSize;
container.setHorizontalScrollOffset((int) newOffset);
} else {
final int relativeY = my - bounds.y - this.thumbPadding;
if (my < thumbBounds.y || my > thumbBounds.y + thumbBounds.h) {
this.handleClickOffset = mainAxisSize / 2f;
} else {
this.handleClickOffset = my - thumbBounds.y;
}
final float newOffset = ((relativeY - this.handleClickOffset)
* (container.getActualHeight() - container.getVisibleHeight())) / thumbSize;
container.setVerticalScrollOffset((int) newOffset);
}
return true;
}
return false;
}
public boolean onMouseDragged(ScrollContainer container, int mx, int my, int buttonId, long heldTime) {
if (this.handleClickOffset >= 0) {
final Rectangle4i bounds = trackBounds(container);
final float mainAxisSize = calculateMainAxisSize(container);
final float thumbSize = getMaxThumbSize(container) - mainAxisSize;
if (this.scrollType == ScrollType.HORIZONTAL) {
final int relativeX = mx - bounds.x - this.thumbPadding;
final float newOffset = ((relativeX - this.handleClickOffset)
* (container.getActualWidth() - container.getVisibleWidth())) / thumbSize;
container.setHorizontalScrollOffset((int) newOffset);
} else {
int relativeY = my - bounds.y - this.thumbPadding;
final float newOffset = ((relativeY - this.handleClickOffset)
* (container.getActualHeight() - container.getVisibleHeight())) / thumbSize;
container.setVerticalScrollOffset((int) newOffset);
}
return true;
}
return false;
}
public boolean onClickReleased(ScrollContainer container, int mx, int my, int buttonId) {
if (this.handleClickOffset >= 0) {
this.handleClickOffset = -1;
return true;
}
return false;
}
public boolean isMouseDragged() {
return this.handleClickOffset >= 0;
}
public void draw(ScrollContainer container, int mx, int my, float opacity) {
if (opacity <= 0 && this.overflowType == OverflowType.OVERLAY) {
return;
}
if (this.overflowType != OverflowType.OVERLAY) {
opacity = 1;
}
final Rectangle4i trackBounds = trackBounds(container);
final Rectangle4i thumbBounds = thumbBounds(container);
final boolean selected = isMouseDragged() || thumbBounds.contains(mx, my);
final boolean disabled = getVisibleSize(container) >= getActualSize(container);
if (this.trackTexture != null) {
drawTexture(this.trackTexture, this.trackSliceStart, this.trackSliceEnd, trackBounds, false, opacity);
} else {
drawTrackRect(container, trackBounds, opacity);
}
if (this.thumbTexture != null) {
drawTexture(this.thumbTexture, this.thumbSliceStart, this.thumbSliceEnd, thumbBounds, disabled, opacity);
} else {
drawThumbRect(container, thumbBounds, selected, opacity);
}
}
private void drawTrackRect(ScrollContainer container, Rectangle4i bounds, float opacity) {
final float trackSize = scrollbarSize / 3f;
final Color trackColor = new Color(
BACKGROUND_COLOR.getRed(),
BACKGROUND_COLOR.getGreen(),
BACKGROUND_COLOR.getBlue(),
(int) (BACKGROUND_COLOR.getAlpha() * opacity));
if (this.scrollType == ScrollType.HORIZONTAL) {
NEIClientUtils.drawRect(bounds.x, bounds.y + trackSize, bounds.w, trackSize, trackColor);
} else {
NEIClientUtils.drawRect(bounds.x + trackSize, bounds.y, trackSize, bounds.h, trackColor);
}
}
private void drawThumbRect(ScrollContainer container, Rectangle4i bounds, boolean selected, float opacity) {
final Color color = selected ? THUMB_SELECTED_COLOR : THUMB_COLOR;
final Color thumbColor = new Color(
color.getRed(),
color.getGreen(),
color.getBlue(),
(int) (color.getAlpha() * opacity));
NEIClientUtils.drawRect(bounds.x, bounds.y, bounds.w, bounds.h, thumbColor);
}
private void drawTexture(DrawableResource texture, int sliceStart, int sliceEnd, Rectangle4i bounds,
boolean disabled, float opacity) {
final float c = disabled ? 0.65f : 1f;
GL11.glColor4f(c, c, c, opacity);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
if (this.scrollType == ScrollType.HORIZONTAL) {
if (this.scrollPlace == ScrollPlace.START) {
texture.draw(
bounds.x,
bounds.y + (bounds.h - texture.getHeight()) / 2,
bounds.w,
texture.getHeight(),
sliceStart,
sliceEnd,
0,
0);
} else {
texture.draw(bounds.x, bounds.y, bounds.w, texture.getHeight(), sliceStart, sliceEnd, 0, 0);
}
} else {
if (this.scrollPlace == ScrollPlace.START) {
texture.draw(
bounds.x + (bounds.w - texture.getWidth()) / 2,
bounds.y,
texture.getWidth(),
bounds.h,
0,
0,
sliceStart,
sliceEnd);
} else {
texture.draw(bounds.x, bounds.y, texture.getWidth(), bounds.h, 0, 0, sliceStart, sliceEnd);
}
}
}
}
@@ -0,0 +1,408 @@
package codechicken.nei.scroll;
import java.awt.Point;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Predicate;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
import codechicken.lib.gui.GuiDraw;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.Widget;
import codechicken.nei.WidgetContainer;
import codechicken.nei.scroll.ScrollBar.OverflowType;
import codechicken.nei.scroll.ScrollBar.ScrollType;
public class ScrollContainer extends WidgetContainer {
/** The mouse scroll wheel scroll speed */
protected static final int MOUSE_SCROLL_SPEED = 16;
/** The keyboard arrow keys scroll speed */
protected static final int KEYBOARD_SCROLL_SPEED = 36;
/** The scrollbar will fade away over this many ticks */
protected static final int FADE_TICKS = 24;
protected int xScroll = 0;
protected int yScroll = 0;
protected int actualWidth = 0;
protected int actualHeight = 0;
protected int paddingInlineStart = 0;
protected int paddingInlineEnd = 0;
protected int paddingBlockStart = 0;
protected int paddingBlockEnd = 0;
protected final Map<Widget, Point> relativePostion = new HashMap<>();
protected ScrollBar horizontalScrollBar;
protected ScrollBar verticalScrollBar;
protected int fade = 0;
public Rectangle4i boundsOutside() {
int width = this.w;
int height = this.h;
int x = this.x;
int y = this.y;
if (canScrollVertical() && (this.verticalScrollBar.getOverflowType() == OverflowType.SCROLL
|| this.verticalScrollBar.getOverflowType() == OverflowType.AUTO)) {
final Rectangle4i trackBounds = this.verticalScrollBar.trackBounds(this);
x = Math.min(x, trackBounds.x);
y = Math.min(y, trackBounds.y);
height = Math.max(this.y + height, trackBounds.y + trackBounds.h) - y;
width = Math.max(this.x + width, trackBounds.x + trackBounds.w) - x;
}
if (canScrollHorizontal() && (this.horizontalScrollBar.getOverflowType() == OverflowType.SCROLL
|| this.horizontalScrollBar.getOverflowType() == OverflowType.AUTO)) {
final Rectangle4i trackBounds = this.horizontalScrollBar.trackBounds(this);
x = Math.min(x, trackBounds.x);
y = Math.min(y, trackBounds.y);
height = Math.max(this.y + height, trackBounds.y + trackBounds.h) - y;
width = Math.max(this.x + width, trackBounds.x + trackBounds.w) - x;
}
return new Rectangle4i(x, y, width, height);
}
public Rectangle4i boundsInside() {
return new Rectangle4i(
x + this.paddingInlineStart,
y + this.paddingBlockStart,
getVisibleWidth(),
getVisibleHeight());
}
@Override
public void clear() {
super.clear();
this.relativePostion.clear();
}
@Override
public boolean removeIf(Predicate<Widget> filter) {
this.relativePostion.keySet().removeIf(filter);
return super.removeIf(filter);
}
public void addWidget(Widget widget) {
super.addWidget(widget);
this.relativePostion.put(widget, new Point(widget.x, widget.y));
}
public Point getWidgetPosition(Widget widget) {
return this.relativePostion.get(widget);
}
public void setPaddingInline(int start, int end) {
this.paddingInlineStart = start;
this.paddingInlineEnd = end;
}
public void setPaddingBlock(int start, int end) {
this.paddingBlockStart = start;
this.paddingBlockEnd = end;
}
public int getVisibleWidth() {
return this.w - this.paddingInlineStart - this.paddingInlineEnd;
}
public int getActualWidth() {
return this.actualWidth;
}
public boolean setHorizontalScrollOffset(int offset) {
if (!canScrollHorizontal() && getVisibleWidth() < getActualWidth()) {
offset = 0;
}
final int scroll = this.xScroll;
this.xScroll = Math.max(0, Math.min(getActualWidth() - getVisibleWidth(), offset));
if (scroll != this.xScroll) {
for (Widget widget : this.widgets) {
widget.x += scroll - this.xScroll;
}
this.fade = FADE_TICKS;
return true;
}
return false;
}
public int getHorizontalScrollOffset() {
return this.xScroll;
}
public boolean canScrollHorizontal() {
return this.horizontalScrollBar != null && (this.horizontalScrollBar.getOverflowType() != OverflowType.NONE
&& getVisibleWidth() < getActualWidth()
|| this.horizontalScrollBar.getOverflowType() == OverflowType.SCROLL);
}
public ScrollBar getHorizontalScroll() {
return this.horizontalScrollBar;
}
public ScrollContainer setHorizontalScroll() {
return setHorizontalScroll(ScrollBar.defaultScrollBar());
}
public ScrollContainer setHorizontalScroll(ScrollBar scrollBar) {
this.horizontalScrollBar = scrollBar;
if (this.horizontalScrollBar != null) {
this.horizontalScrollBar.setScrollType(ScrollType.HORIZONTAL);
}
return this;
}
public int getVisibleHeight() {
return this.h - this.paddingBlockStart - this.paddingBlockEnd;
}
public int getActualHeight() {
return this.actualHeight;
}
public boolean setVerticalScrollOffset(int offset) {
if (!canScrollVertical() && getVisibleHeight() < getActualHeight()) {
offset = 0;
}
final int scroll = this.yScroll;
this.yScroll = Math.max(0, Math.min(getActualHeight() - getVisibleHeight(), offset));
if (scroll != this.yScroll) {
for (Widget widget : this.widgets) {
widget.y += scroll - this.yScroll;
}
this.fade = FADE_TICKS;
return true;
}
return false;
}
public int getVerticalScrollOffset() {
return this.yScroll;
}
public boolean canScrollVertical() {
return this.verticalScrollBar != null && (this.verticalScrollBar.getOverflowType() != OverflowType.NONE
&& getVisibleHeight() < getActualHeight()
|| this.verticalScrollBar.getOverflowType() == OverflowType.SCROLL);
}
public ScrollBar getVerticalScroll() {
return this.verticalScrollBar;
}
public ScrollContainer setVerticalScroll() {
return setVerticalScroll(ScrollBar.defaultScrollBar());
}
public ScrollContainer setVerticalScroll(ScrollBar scrollBar) {
this.verticalScrollBar = scrollBar;
if (this.verticalScrollBar != null) {
this.verticalScrollBar.setScrollType(ScrollType.VERTICAL);
}
return this;
}
@Override
public void draw(int mousex, int mousey) {
final boolean canScrollVertical = canScrollVertical();
final boolean canScrollHorizontal = canScrollHorizontal();
if (canScrollVertical || canScrollHorizontal) {
GuiHelper.useScissor(
this.x + this.paddingInlineStart,
this.y + this.paddingBlockStart,
this.w - this.paddingInlineStart - this.paddingInlineEnd,
this.h - this.paddingBlockStart - this.paddingBlockEnd,
() -> drawContent(mousex, mousey));
GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_LIGHTING_BIT);
if (canScrollVertical) {
this.verticalScrollBar.draw(this, mousex, mousey, getScrollBarOpacity());
}
if (canScrollHorizontal) {
this.horizontalScrollBar.draw(this, mousex, mousey, getScrollBarOpacity());
}
GL11.glPopAttrib();
} else {
drawContent(mousex, mousey);
}
}
protected void drawContent(int mousex, int mousey) {
GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
GL11.glPushMatrix();
GL11.glColor4f(1, 1, 1, 1);
super.draw(mousex, mousey);
GL11.glPopMatrix();
GL11.glPopAttrib();
}
private float getScrollBarOpacity() {
return Math.min(2f * this.fade, FADE_TICKS) / FADE_TICKS;
}
@Override
public void update() {
this.actualHeight = 0;
this.actualWidth = 0;
for (Map.Entry<Widget, Point> entry : this.relativePostion.entrySet()) {
entry.getKey().x = entry.getValue().x;
entry.getKey().y = entry.getValue().y;
}
super.update();
final int x = this.x + this.paddingInlineStart - this.xScroll;
final int y = this.y + this.paddingBlockStart - this.yScroll;
for (Widget widget : this.widgets) {
this.actualWidth = Math.max(this.actualWidth, widget.x + widget.w);
this.actualHeight = Math.max(this.actualHeight, widget.y + widget.h);
widget.x += x;
widget.y += y;
}
if (this.fade > 0) {
final Point mouse = GuiDraw.getMousePosition();
if (canScrollVertical() && (this.verticalScrollBar.isMouseDragged()
|| this.verticalScrollBar.trackBounds(this).contains(mouse.x, mouse.y))) {
this.fade = FADE_TICKS;
} else if (canScrollHorizontal() && (this.horizontalScrollBar.isMouseDragged()
|| this.horizontalScrollBar.trackBounds(this).contains(mouse.x, mouse.y))) {
this.fade = FADE_TICKS;
} else {
this.fade--;
}
}
setHorizontalScrollOffset(this.xScroll);
setVerticalScrollOffset(this.yScroll);
}
@Override
public boolean onMouseWheel(int direction, int mousex, int mousey) {
if (super.onMouseWheel(direction, mousex, mousey)) {
return true;
}
if (boundsOutside().contains(mousex, mousey)) {
if (canScrollHorizontal() && (NEIClientUtils.shiftKey()
|| this.horizontalScrollBar.trackBounds(this).contains(mousex, mousey))) {
this.horizontalScrollBar.setScrollOffset(this, this.xScroll - direction * MOUSE_SCROLL_SPEED);
return true;
}
if (canScrollVertical()) {
this.verticalScrollBar.setScrollOffset(this, this.yScroll - direction * MOUSE_SCROLL_SPEED);
return true;
}
}
return false;
}
@Override
public boolean handleClick(int mousex, int mousey, int button) {
if (canScrollVertical() && this.verticalScrollBar.onClick(this, mousex, mousey, button)) {
return true;
}
if (canScrollHorizontal() && this.horizontalScrollBar.onClick(this, mousex, mousey, button)) {
return true;
}
if (super.handleClick(mousex, mousey, button)) {
return true;
}
return false;
}
@Override
public void mouseDragged(int mousex, int mousey, int button, long heldTime) {
if (canScrollVertical() && this.verticalScrollBar.onMouseDragged(this, mousex, mousey, button, heldTime)) {
return;
}
if (canScrollHorizontal() && this.horizontalScrollBar.onMouseDragged(this, mousex, mousey, button, heldTime)) {
return;
}
super.mouseDragged(mousex, mousey, button, heldTime);
}
@Override
public void mouseUp(int mousex, int mousey, int button) {
if (canScrollVertical()) {
this.verticalScrollBar.onClickReleased(this, mousex, mousey, button);
}
if (canScrollHorizontal()) {
this.horizontalScrollBar.onClickReleased(this, mousex, mousey, button);
}
super.mouseUp(mousex, mousey, button);
}
@Override
public boolean handleKeyPress(int keyCode, char keyChar) {
if (this.isFocused()) {
switch (keyCode) {
case Keyboard.KEY_UP:
return canScrollVertical()
&& this.verticalScrollBar.setScrollOffset(this, this.yScroll - KEYBOARD_SCROLL_SPEED);
case Keyboard.KEY_DOWN:
return canScrollVertical()
&& this.verticalScrollBar.setScrollOffset(this, this.yScroll + KEYBOARD_SCROLL_SPEED);
case Keyboard.KEY_LEFT:
return canScrollHorizontal()
&& this.horizontalScrollBar.setScrollOffset(this, this.xScroll - KEYBOARD_SCROLL_SPEED);
case Keyboard.KEY_RIGHT:
return canScrollHorizontal()
&& this.horizontalScrollBar.setScrollOffset(this, this.xScroll + KEYBOARD_SCROLL_SPEED);
}
}
return super.handleKeyPress(keyCode, keyChar);
}
}
@@ -14,4 +14,8 @@ public abstract class AbstractSearchExpressionVisitor<T> extends SearchExpressio
return searchParser;
}
public T fail() {
return defaultResult();
}
}
@@ -20,7 +20,7 @@ import codechicken.nei.api.ItemFilter;
public class ItemFilterVisitor extends AbstractSearchExpressionVisitor<ItemFilter> {
private static final Pattern REGEX_ESCAPED_SPACE_PATTERN = Pattern.compile("([^\\\\](?:\\\\\\\\)+)?\\\\ ");
private static final Pattern PLAIN_TEXT_ESCAPED_PATTERN = Pattern.compile("\\\\(.)");
private static final Pattern ESCAPED_SYMBOL_PATTERN = Pattern.compile("\\\\(.)");
private static final Pattern ESCAPED_QUOTE_PATTERN = Pattern.compile("\\\\\"");
private static final Pattern ESCAPED_SPACE_PATTERN = Pattern.compile("\\\\ ");
@@ -37,6 +37,20 @@ public class ItemFilterVisitor extends AbstractSearchExpressionVisitor<ItemFilte
}
}
// Should only be called for collecting ingredients permutations
@Override
public ItemFilter visitRecipeSearchExpression(SearchExpressionParser.RecipeSearchExpressionContext ctx) {
if (ctx.recipeClauseExpression() != null) {
final List<ItemFilter> anyFilters = new ArrayList<>();
final List<ItemFilter> allFilters = new ArrayList<>();
for (SearchExpressionParser.RecipeClauseExpressionContext clauseCtx : ctx.recipeClauseExpression()) {
addIngredientPermutationItemFilter(clauseCtx.searchExpression(), anyFilters, allFilters);
}
return constructFilter(anyFilters, allFilters);
}
return defaultResult();
}
@Override
public ItemFilter visitOrExpression(SearchExpressionParser.OrExpressionContext ctx) {
return visitChildren(ctx, AnyMultiItemFilter::new);
@@ -55,21 +69,21 @@ public class ItemFilterVisitor extends AbstractSearchExpressionVisitor<ItemFilte
@Override
public ItemFilter visitPrefixedExpression(SearchExpressionParser.PrefixedExpressionContext ctx) {
if (ctx.token() != null) {
final String cleanText = getTokenCleanText(ctx.token());
final String cleanPattern = getCleanPattern(ctx.token());
final SearchTokenParser.ISearchParserProvider provider = searchParser.getProvider(ctx.token().prefix);
if (cleanText == null || provider == null) {
if (cleanPattern == null || provider == null) {
return defaultResult();
}
return provider.getFilter(cleanText);
return provider.getFilter(cleanPattern);
}
return defaultResult();
}
@Override
public ItemFilter visitToken(SearchExpressionParser.TokenContext ctx) {
final String cleanText = getTokenCleanText(ctx);
if (cleanText != null) {
return getAlwaysProvidersFilter(cleanText);
final String cleanPattern = getCleanPattern(ctx);
if (cleanPattern != null) {
return getAlwaysProvidersFilter(cleanPattern);
}
return defaultResult();
}
@@ -79,36 +93,61 @@ public class ItemFilterVisitor extends AbstractSearchExpressionVisitor<ItemFilte
return new NothingItemFilter();
}
private String getTokenCleanText(SearchExpressionParser.TokenContext ctx) {
String cleanText = null;
if (ctx.PLAIN_TEXT() != null) {
cleanText = Pattern.quote(
PLAIN_TEXT_ESCAPED_PATTERN.matcher(ctx.PLAIN_TEXT().getSymbol().getText())
private void addIngredientPermutationItemFilter(SearchExpressionParser.SearchExpressionContext ctx,
List<ItemFilter> anyFilters, List<ItemFilter> allFilters) {
// Only for ingredients or default
if (ctx.type == 0 || ctx.type == 3) {
if (ctx.allRecipe) {
allFilters.add(visit(ctx));
} else {
anyFilters.add(visit(ctx));
}
}
}
private ItemFilter constructFilter(List<ItemFilter> anyFilters, List<ItemFilter> allFilters) {
if (anyFilters.isEmpty()) {
return constructFilter(allFilters, AllMultiItemFilter::new);
}
if (allFilters.isEmpty()) {
return constructFilter(anyFilters, AnyMultiItemFilter::new);
}
final List<ItemFilter> filters = new ArrayList<>();
filters.add(constructFilter(allFilters, AllMultiItemFilter::new));
filters.add(constructFilter(anyFilters, AnyMultiItemFilter::new));
return constructFilter(filters, AllMultiItemFilter::new);
}
private String getCleanPattern(SearchExpressionParser.TokenContext ctx) {
String cleanPattern = null;
if (ctx.plainText() != null) {
cleanPattern = Pattern.quote(
ESCAPED_SYMBOL_PATTERN.matcher(ctx.plainText().getText())
// Unescape everything in search expression
.replaceAll("$1"));
} else if (ctx.regex() != null) {
if (ctx.regex().REGEX_CONTENT() != null) {
cleanText = ctx.regex().REGEX_CONTENT().getSymbol().getText();
cleanPattern = ctx.regex().REGEX_CONTENT().getSymbol().getText();
final int spaceModeEnabled = NEIClientConfig.getIntSetting("inventory.search.spaceMode");
// Unescape spaces
if (spaceModeEnabled == 1) {
cleanText = REGEX_ESCAPED_SPACE_PATTERN.matcher(cleanText).replaceAll("$1 ");
cleanPattern = REGEX_ESCAPED_SPACE_PATTERN.matcher(cleanPattern).replaceAll("$1 ");
}
}
} else if (ctx.quoted() != null) {
if (ctx.quoted().QUOTED_CONTENT() != null) {
cleanText = ctx.quoted().QUOTED_CONTENT().getSymbol().getText();
cleanPattern = ctx.quoted().QUOTED_CONTENT().getSymbol().getText();
// Unescape quotes
cleanText = ESCAPED_QUOTE_PATTERN.matcher(cleanText).replaceAll("\"");
cleanText = Pattern.quote(cleanText);
cleanPattern = ESCAPED_QUOTE_PATTERN.matcher(cleanPattern).replaceAll("\"");
cleanPattern = Pattern.quote(cleanPattern);
final int spaceModeEnabled = NEIClientConfig.getIntSetting("inventory.search.spaceMode");
// Unescape spaces
if (spaceModeEnabled == 1) {
cleanText = ESCAPED_SPACE_PATTERN.matcher(cleanText).replaceAll(" ");
cleanPattern = ESCAPED_SPACE_PATTERN.matcher(cleanPattern).replaceAll(" ");
}
}
}
return cleanText;
return cleanPattern;
}
private ItemFilter visitChildren(ParserRuleContext node, Function<List<ItemFilter>, ItemFilter> filterConstructor) {
@@ -62,8 +62,8 @@ public class SearchExpressionFormatVisitor extends AbstractSearchExpressionVisit
private String getTokenCleanText(SearchExpressionParser.TokenContext ctx, Character prefix) {
String cleanText = null;
final int spaceModeEnabled = NEIClientConfig.getIntSetting("inventory.search.spaceMode");
if (ctx.PLAIN_TEXT() != null) {
cleanText = ctx.PLAIN_TEXT().getSymbol().getText();
if (ctx.plainText() != null) {
cleanText = ctx.plainText().getText();
// Unescape spaces
if (spaceModeEnabled == 1) {
cleanText = ESCAPED_SPACE_PATTERN.matcher(cleanText).replaceAll(" ");
@@ -52,6 +52,17 @@ public class SearchExpressionUtils {
}
public static <T> T visitSearchExpression(String text, AbstractSearchExpressionVisitor<T> visitor) {
SearchExpressionParser parser = createSearchExpressionParser(text, visitor.getSearchParser(), visitor);
SearchExpressionParser.RecipeSearchExpressionContext recipeCtx = parser.recipeSearchExpression();
// Manually check whether it's not a recipe expression, because parser would parse it either way
if (recipeCtx.recipeClauseExpression() != null && recipeCtx.recipeClauseExpression().size() == 1
&& recipeCtx.recipeClauseExpression(0).searchExpression().type == 3) {
return visitor.visitSearchExpression(recipeCtx.recipeClauseExpression(0).searchExpression());
}
return visitor.fail();
}
public static <T> T visitRecipeSearchExpression(String text, AbstractSearchExpressionVisitor<T> visitor) {
SearchExpressionParser parser = createSearchExpressionParser(text, visitor.getSearchParser(), visitor);
return visitor.visitRecipeSearchExpression(parser.recipeSearchExpression());
}
@@ -0,0 +1,396 @@
package codechicken.nei.util;
import java.io.BufferedWriter;
import java.io.File;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Stream;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.StatCollector;
import net.minecraft.util.StringTranslate;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import codechicken.nei.ClientHandler;
import codechicken.nei.ItemList;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.SubsetWidget;
import codechicken.nei.api.API;
import codechicken.nei.recipe.StackInfo;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.registry.LanguageRegistry;
import cpw.mods.fml.relauncher.ReflectionHelper;
public class ItemUntranslator {
private class LanguageRegistryPatch implements AutoCloseable {
// RAII-style helper that temporarily swaps language data in
// LanguageRegistry / StringTranslate using reflection. This allows
// reading translation entries for a different language (eg. en_US)
// even when the game is using another language at runtime.
private String secondLanguage = "en_US";
private String language;
private static Map<String, Properties> modLanguageDataSymlink;
private Properties languageDataCache;
private static Map<String, String> secondLanguageListCache;
private static Map<String, String> languageListCache;
private static Field languageListField;
private static Field fieldStringTranslateInstance;
static {
try {
final Field modLanguageDataField = ReflectionHelper
.findField(LanguageRegistry.class, "modLanguageData");
languageListField = ReflectionHelper.findField(StringTranslate.class, "languageList", "field_74816_c");
fieldStringTranslateInstance = ReflectionHelper
.findField(StringTranslate.class, "instance", "field_74817_a");
modLanguageDataSymlink = (Map<String, Properties>) modLanguageDataField
.get(LanguageRegistry.instance());
languageListCache = (Map<String, String>) languageListField.get(fieldStringTranslateInstance.get(null));
} catch (Throwable e) {
languageListField = null;
fieldStringTranslateInstance = null;
}
}
private LanguageRegistryPatch(String secondLanguage) {
this.language = FMLCommonHandler.instance().getCurrentLanguage();
this.secondLanguage = secondLanguage;
patchLanguageRegistry();
patchStringTranslate();
}
@Override
public void close() {
restoreStringTranslate();
restoreLanguageRegistry();
}
private void patchLanguageRegistry() {
this.languageDataCache = modLanguageDataSymlink.get(this.language);
modLanguageDataSymlink.put(this.language, modLanguageDataSymlink.get(this.secondLanguage));
}
private void patchStringTranslate() {
if (languageListField != null) {
if (secondLanguageListCache == null) {
secondLanguageListCache = new HashMap<>(languageListCache);
modLanguageDataSymlink.get(secondLanguage)
.forEach((k, v) -> secondLanguageListCache.put((String) k, (String) v));
}
try {
languageListField.set(fieldStringTranslateInstance.get(null), secondLanguageListCache);
} catch (IllegalAccessException e) {
throw new RuntimeException("Failed to access StringTranslate language list", e);
}
}
}
private void restoreLanguageRegistry() {
final String language = FMLCommonHandler.instance().getCurrentLanguage();
modLanguageDataSymlink.put(language, languageDataCache);
languageDataCache = null;
}
private void restoreStringTranslate() {
if (languageListField != null && languageListCache != null) {
try {
languageListField.set(fieldStringTranslateInstance.get(null), languageListCache);
} catch (IllegalAccessException e) {
throw new RuntimeException("Failed to restore StringTranslate language list", e);
}
}
}
}
private static final String CONFIG_FILE = "untranslator.cfg";
private static final ItemUntranslator instance = new ItemUntranslator();
private final Map<String, String> secondNames = new HashMap<>();
private final Map<String, String> processedNames = new HashMap<>();
static {
API.addSubset("Untranslated", item -> instance.getItemStackDisplayName(item).isEmpty());
}
private ItemUntranslator() {}
public static ItemUntranslator getInstance() {
return instance;
}
public void generateUntranslatedNames() {
final Map<String, String> items = new HashMap<>();
items.put("language", FMLCommonHandler.instance().getCurrentLanguage());
for (Fluid fluid : FluidRegistry.getRegisteredFluids().values()) {
items.put(
fluid.getUnlocalizedName().toLowerCase(),
stripFormatting(StatCollector.translateToLocal(fluid.getUnlocalizedName())));
}
for (CreativeTabs tab : CreativeTabs.creativeTabArray) {
final List<ItemStack> tabItems = new ArrayList<>();
tab.displayAllReleventItems(tabItems);
for (ItemStack stack : tabItems) {
collectDisplayNameForStack(stack, items);
}
}
for (ItemStack stack : ItemList.items) {
collectDisplayNameForStack(stack, items);
}
for (FluidContainerData data : FluidContainerRegistry.getRegisteredFluidContainerData()) {
if (data.filledContainer != null) {
collectDisplayNameForStack(data.filledContainer, items);
}
}
for (Map.Entry<String, String> entry : LanguageRegistryPatch.languageListCache.entrySet()) {
final String key = entry.getKey().toLowerCase();
if (key.endsWith(".name") && !items.containsKey(key) && !entry.getValue().contains("%")) {
items.put(key, entry.getValue());
}
}
saveMappings(items);
}
private void collectDisplayNameForStack(ItemStack stack, Map<String, String> items) {
final String displayName = stripFormatting(stack.getDisplayName());
final String guidKey = determineGUIDForGeneration(stack, displayName, items);
if (!items.containsKey(guidKey)) {
items.put(guidKey, displayName);
}
}
private String determineGUIDForGeneration(ItemStack stack, String displayName, Map<String, String> items) {
final String unlocalizedName = stack.getUnlocalizedName().toLowerCase();
if (displayName.equals(stripFormatting(StatCollector.translateToLocal(unlocalizedName)))) {
return unlocalizedName;
}
if (!unlocalizedName.endsWith(".name")
&& displayName.equals(stripFormatting(StatCollector.translateToLocal(unlocalizedName + ".name")))) {
return unlocalizedName + ".name";
}
final FluidStack fluid = StackInfo.getFluid(stack);
if (fluid != null) {
final String fluidUnlocalizedName = fluid.getUnlocalizedName().toLowerCase();
if (displayName.equals(items.get(fluidUnlocalizedName))) {
return fluidUnlocalizedName;
}
if (!fluidUnlocalizedName.startsWith("fluid.")
&& displayName.equals(items.get("fluid." + fluidUnlocalizedName))) {
return "fluid." + fluidUnlocalizedName;
}
return (Item.itemRegistry.getNameForObject(stack.getItem()) + ":"
+ stack.getItemDamage()
+ "@"
+ fluid.getUnlocalizedName()).toLowerCase();
}
if (stack.hasTagCompound()) {
try {
final ItemStack stackCopy = new ItemStack(stack.getItem(), 1, stack.getItemDamage());
if (displayName.equals(stripFormatting(stackCopy.getDisplayName()))) {
return (Item.itemRegistry.getNameForObject(stack.getItem()) + ":" + stack.getItemDamage())
.toLowerCase();
}
} catch (Exception e) {}
}
return StackInfo.getItemStackGUID(stack);
}
private String stripFormatting(String name) {
return EnumChatFormatting.getTextWithoutFormattingCodes(name).trim();
}
public synchronized String getItemStackDisplayName(ItemStack stack) {
if (stack == null || this.secondNames.isEmpty()) {
return "";
}
final String guidKey = StackInfo.getItemStackGUID(stack);
return this.processedNames.computeIfAbsent(guidKey, stackKey -> {
String displayName = this.secondNames.get(stackKey);
if (displayName == null) {
final String guid = findBestGUIDForLookup(stack);
displayName = this.secondNames
.computeIfAbsent(guid == null ? stackKey : guid, g -> getFallbackDisplayName(stack));
}
return displayName.equals(stripFormatting(stack.getDisplayName())) ? "" : displayName;
});
}
public String findBestGUIDForLookup(ItemStack stack) {
String guidKey = (Item.itemRegistry.getNameForObject(stack.getItem()) + ":" + stack.getItemDamage())
.toLowerCase();
if (this.secondNames.containsKey(guidKey)) {
return guidKey;
}
final FluidStack fluid = StackInfo.getFluid(stack);
if (fluid != null) {
guidKey = (Item.itemRegistry.getNameForObject(stack.getItem()) + ":"
+ stack.getItemDamage()
+ "@"
+ fluid.getUnlocalizedName()).toLowerCase();
if (this.secondNames.containsKey(guidKey)) {
return guidKey;
}
final String fluidUnlocalizedName = fluid.getUnlocalizedName().toLowerCase();
if (!fluidUnlocalizedName.startsWith("fluid.")
&& this.secondNames.containsKey("fluid." + fluidUnlocalizedName)) {
return "fluid." + fluidUnlocalizedName;
}
if (this.secondNames.containsKey(fluidUnlocalizedName)) {
return fluidUnlocalizedName;
}
}
final String unlocalizedName = stack.getUnlocalizedName().toLowerCase();
if (!unlocalizedName.endsWith(".name") && this.secondNames.containsKey(unlocalizedName + ".name")) {
return unlocalizedName + ".name";
}
if (this.secondNames.containsKey(unlocalizedName)) {
return unlocalizedName;
}
return null;
}
private String getFallbackDisplayName(ItemStack stack) {
final String unlocalizedName = stack.getUnlocalizedName();
final String secondLanguage = this.secondNames.get("language");
String name = LanguageRegistry.instance().getStringLocalization(unlocalizedName, secondLanguage);
if (name == null && !unlocalizedName.endsWith(".name")) {
name = LanguageRegistry.instance().getStringLocalization(unlocalizedName + ".name", secondLanguage);
}
if (name == null || name.contains("%")) {
try (LanguageRegistryPatch lrPatch = new LanguageRegistryPatch(secondLanguage)) {
name = stack.getDisplayName();
}
}
final FluidStack fluid = StackInfo.getFluid(stack);
if (fluid != null) {
final String unlocalizedFluidName = fluid.getUnlocalizedName().toLowerCase();
String fluidName = this.secondNames.get(unlocalizedFluidName);
if (fluidName == null && !unlocalizedFluidName.startsWith("fluid.")) {
fluidName = this.secondNames.get("fluid." + unlocalizedFluidName);
}
if (fluidName != null && name != null && !name.isEmpty()) {
return name.replace(fluid.getLocalizedName(), fluidName);
} else {
name = fluidName;
}
}
return name == null ? "" : name;
}
protected void saveMappings(Map<String, String> items) {
try (BufferedWriter writer = Files.newBufferedWriter(
(new File(NEIClientConfig.configDir, CONFIG_FILE)).toPath(),
StandardCharsets.UTF_8)) {
for (Map.Entry<String, String> entry : items.entrySet()) {
if (entry.getValue().isEmpty()) continue;
writer.write(entry.getKey() + "=" + entry.getValue());
writer.newLine();
}
} catch (Exception e) {
NEIClientConfig.logger.error("Error saving untranslator", e);
}
NEIClientConfig.logger.info("Untranslator saved");
}
public void unload() {
this.secondNames.clear();
LanguageRegistryPatch.secondLanguageListCache = null;
this.processedNames.clear();
}
public void load() {
unload();
this.secondNames.clear();
if (ClientHandler.loadSettingsFile(CONFIG_FILE, null, this::parseStream)
|| ClientHandler.loadSettingsResource(CONFIG_FILE, this::parseStream)) {
NEIClientConfig.logger.info("Untranslator loaded");
}
if (!this.secondNames.containsKey("language")
|| FMLCommonHandler.instance().getCurrentLanguage().equals(this.secondNames.get("language"))) {
this.secondNames.clear();
}
SubsetWidget.updateHiddenItems();
}
private void parseStream(Stream<String> lines) {
lines.forEach(line -> {
final int sepIndex = line.indexOf('=');
if (sepIndex != -1) {
this.secondNames.put(line.substring(0, sepIndex).trim(), line.substring(sepIndex + 1).trim());
}
});
}
}
@@ -0,0 +1,63 @@
package codechicken.nei.util;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
public class SlotInaccessible extends Slot {
private ItemStack itemStack = null;
public SlotInaccessible(ItemStack itemStack, int xDisplayPosition, int yDisplayPosition) {
super(null, 0, xDisplayPosition, yDisplayPosition);
this.itemStack = itemStack;
}
@Override
public void onSlotChange(final ItemStack par1ItemStack, final ItemStack par2ItemStack) {}
@Override
public void onPickupFromSlot(final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack) {}
@Override
public boolean isItemValid(final ItemStack par1ItemStack) {
return false;
}
@Override
public ItemStack getStack() {
return this.itemStack;
}
@Override
public void putStack(final ItemStack par1ItemStack) {}
@Override
public void onSlotChanged() {}
@Override
public int getSlotStackLimit() {
return 0;
}
@Override
public ItemStack decrStackSize(final int par1) {
return null;
}
@Override
public boolean isSlotInInventory(final IInventory par1IInventory, final int par2) {
return false;
}
@Override
public boolean canTakeStack(final EntityPlayer par1EntityPlayer) {
return false;
}
@Override
public int getSlotIndex() {
return 0;
}
}
@@ -0,0 +1,5 @@
# This file contains a list of GUIs that can use the DefaultBookmarkContainerHandler for bookmarks.
# It serves as an alternative to API.registerBookmarkContainerHandler and is intended for cases
# where you can't modify the mod itself and its GUI doesn't have custom slots.
# Each line in this file should either be a comment (starting with '#') or a guiContainer class name.
# If you delete this file, it will be regenerated with the default bookmark containers list.
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more