From 939845a9edda803085cd5866e506469cc6eefe7d Mon Sep 17 00:00:00 2001 From: slprime <31038811+slprime@users.noreply.github.com> Date: Wed, 23 Sep 2026 00:14:39 +0300 Subject: [PATCH 01/11] Add List View to Recipe (#1041) --- .../nei/ItemsListTooltipLineHandler.java | 125 +++++++ .../nei/ItemsTooltipLineHandler.java | 167 ++++++++- .../nei/bookmark/tree/GuiCraftingTree.java | 44 ++- .../nei/bookmark/tree/StatsPanel.java | 6 +- .../AcceptsFollowingTooltipLineHandler.java | 14 +- .../recipe/RecipeItemsTooltipLineHandler.java | 332 ++++++++++++++++++ src/main/resources/assets/nei/lang/en_US.lang | 4 + 7 files changed, 654 insertions(+), 38 deletions(-) create mode 100644 src/main/java/codechicken/nei/ItemsListTooltipLineHandler.java create mode 100644 src/main/java/codechicken/nei/recipe/RecipeItemsTooltipLineHandler.java diff --git a/src/main/java/codechicken/nei/ItemsListTooltipLineHandler.java b/src/main/java/codechicken/nei/ItemsListTooltipLineHandler.java new file mode 100644 index 00000000..4aad640e --- /dev/null +++ b/src/main/java/codechicken/nei/ItemsListTooltipLineHandler.java @@ -0,0 +1,125 @@ +package codechicken.nei; + +import static codechicken.lib.gui.GuiDraw.fontRenderer; + +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumChatFormatting; + +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + +import codechicken.lib.gui.GuiDraw; +import codechicken.nei.guihook.GuiContainerManager; + +public class ItemsListTooltipLineHandler extends ItemsTooltipLineHandler { + + protected static final int NAME_MARGIN = 2; + + protected final List names = new ArrayList<>(); + protected int tailCount = 0; + + public ItemsListTooltipLineHandler(String label, List items, int maxRows) { + super(label, items, true, maxRows); + + this.rows = Math.min(maxRows, this.length); + this.count = this.length > this.rows ? this.rows - 1 : this.length; + + int width = fontRenderer.getStringWidth(this.label) + 15; + + for (int index = 0; index < this.count; index++) { + final String name = this.items.get(index).getDisplayName(); + this.names.add(name); + width = Math.max(width, SLOT_SIZE + NAME_MARGIN + fontRenderer.getStringWidth(name)); + } + + if (this.count < this.length) { + final int tail = this.length - this.count; + width = Math.max(width, Math.min(tail, MAX_COLUMNS) * SLOT_SIZE); + + final int fit = width / SLOT_SIZE; + + if (tail <= fit) { + this.tailCount = tail; + } else { + final String text = "+" + (tail - fit); + this.tailCount = Math + .max(0, fit - (int) Math.ceil((float) (fontRenderer.getStringWidth(text) - 2) / SLOT_SIZE)); + } + } + + this.size.width = this.length > 0 ? width : 0; + this.size.height = this.length > 0 ? this.rows * SLOT_SIZE + fontRenderer.FONT_HEIGHT + 2 + MARGIN_TOP : 0; + } + + @Override + public void setLabel(String label) { + this.label = label; + this.size.width = Math.max(this.size.width, fontRenderer.getStringWidth(this.label) + 15); + } + + @Override + public void draw(int x, int y) { + if (this.length == 0) return; + + y += MARGIN_TOP; + + fontRenderer.drawStringWithShadow(this.labelColor + this.label + ":", x, y, 0); + + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + + GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_LIGHTING_BIT); + RenderHelper.enableGUIStandardItemLighting(); + + final int xTranslation = x; + final int yTranslation = y + fontRenderer.FONT_HEIGHT + 2; + final int zTranslation = GuiContainerManager.TOOLTIP_Z_OFFSET; + GL11.glTranslatef(xTranslation, yTranslation, zTranslation); + + for (int index = 0; index < this.count; index++) { + drawSlot(0, index * SLOT_SIZE, index); + } + + for (int index = 0; index < this.tailCount; index++) { + drawSlot(index * SLOT_SIZE, this.count * SLOT_SIZE, this.count + index); + } + + NEIClientUtils.gl2DRenderContext(() -> { + final int textShift = ICON_OFFSET + Math.round((ICON_SIZE - fontRenderer.FONT_HEIGHT) / 2f); + + for (int index = 0; index < this.count; index++) { + fontRenderer.drawStringWithShadow( + EnumChatFormatting.GRAY + this.names.get(index), + SLOT_SIZE + NAME_MARGIN, + index * SLOT_SIZE + textShift, + 0xFFFFFF); + } + + final int hidden = this.length - this.count - this.tailCount; + + if (hidden > 0) { + final String text = "+" + hidden; + fontRenderer.drawStringWithShadow( + EnumChatFormatting.GRAY + text, + this.size.width - fontRenderer.getStringWidth(text) - 2, + this.count * SLOT_SIZE + textShift, + 0xFFFFFF); + } + }); + + GL11.glTranslatef(-xTranslation, -yTranslation, -zTranslation); + GL11.glPopAttrib(); + } + + protected void drawSlot(int x, int y, int index) { + if (this.activeStackIndex == index) { + NEIClientUtils.gl2DRenderContext(() -> GuiDraw.drawRect(x, y, SLOT_SIZE, SLOT_SIZE, 0x66555555)); + } + + drawStackWithAmount(x, y, index); + } + +} diff --git a/src/main/java/codechicken/nei/ItemsTooltipLineHandler.java b/src/main/java/codechicken/nei/ItemsTooltipLineHandler.java index 2ff46a40..1471bde8 100644 --- a/src/main/java/codechicken/nei/ItemsTooltipLineHandler.java +++ b/src/main/java/codechicken/nei/ItemsTooltipLineHandler.java @@ -4,6 +4,7 @@ import static codechicken.lib.gui.GuiDraw.fontRenderer; import java.awt.Dimension; import java.util.ArrayList; +import java.util.IdentityHashMap; import java.util.List; import java.util.Map; @@ -17,22 +18,151 @@ import org.lwjgl.opengl.GL12; import codechicken.lib.gui.GuiDraw; import codechicken.lib.gui.GuiDraw.ITooltipLineHandler; +import codechicken.lib.vec.Rectangle4i; +import codechicken.nei.NEIClientUtils.Alignment; import codechicken.nei.guihook.GuiContainerManager; import codechicken.nei.recipe.StackInfo; import codechicken.nei.util.ReadableNumberConverter; public class ItemsTooltipLineHandler implements ITooltipLineHandler { + @FunctionalInterface + public interface AmountRenderer { + + void draw(int x, int y, ItemStack stack, long amount); + } + + public static class NoAmountRenderer implements AmountRenderer { + + @Override + public void draw(int x, int y, ItemStack stack, long amount) { + GuiContainerManager.drawItem(x, y, stack, true, ""); + } + + protected static void drawAmountText(String text, Rectangle4i rect, int color, Alignment alignment) { + NEIClientUtils.drawNEIOverlayText(text, rect, 1, color, true, alignment); + } + } + + public static class TotalAmountRenderer extends NoAmountRenderer { + + private static class AmountText { + + public final String text; + public final Alignment alignment; + + public AmountText(String text, Alignment alignment) { + this.text = text; + this.alignment = alignment; + } + } + + private final Map cache = new IdentityHashMap<>(); + + @Override + public void draw(int x, int y, ItemStack stack, long amount) { + super.draw(x, y, stack, amount); + drawAmount(new Rectangle4i(x, y, SLOT_SIZE - 2, SLOT_SIZE - 2), stack, amount); + } + + protected void drawAmount(Rectangle4i rect, ItemStack stack, long amount) { + final AmountText amountText = this.cache.computeIfAbsent(stack, key -> { + final boolean isFluidDisplay = StackInfo.isFluidDisplayItem(key); + final String text = formatAmount(key, amount); + + return new AmountText( + isFluidDisplay && !text.isEmpty() ? text + "L" : text, + isFluidDisplay ? Alignment.BottomLeft : Alignment.BottomRight); + }); + + if (!amountText.text.isEmpty()) { + drawAmountText(amountText.text, rect, 0xFFFFFF, amountText.alignment); + } + } + + protected String formatAmount(ItemStack stack, long amount) { + return amount == 0 ? "" : ReadableNumberConverter.INSTANCE.toWideReadableForm(amount); + } + } + + public static class StacksAmountRenderer extends NoAmountRenderer { + + private static class StacksText { + + public final String stacks; + public final String remainder; + public final int color; + + public StacksText(String stacks, String remainder, int color) { + this.stacks = stacks; + this.remainder = remainder; + this.color = color; + } + } + + private final Map cache = new IdentityHashMap<>(); + + @Override + public void draw(int x, int y, ItemStack stack, long amount) { + super.draw(x, y, stack, amount); + drawAmount(new Rectangle4i(x, y, SLOT_SIZE - 2, SLOT_SIZE - 2), stack, amount); + } + + protected void drawAmount(Rectangle4i rect, ItemStack stack, long amount) { + final StacksText stacksText = this.cache.computeIfAbsent(stack, key -> formatAmount(key, amount)); + + if (!stacksText.stacks.isEmpty()) { + drawAmountText(stacksText.stacks, rect, stacksText.color, Alignment.TopLeft); + } + + if (!stacksText.remainder.isEmpty()) { + drawAmountText(stacksText.remainder, rect, stacksText.color, Alignment.BottomRight); + } + } + + private StacksText formatAmount(ItemStack stack, long amount) { + final long stackSize = StackInfo.isFluidDisplayItem(stack) ? FLUID_STACK_SIZE + : Math.max(1, stack.getMaxStackSize()); + final long stacks = amount / stackSize; + final long remainder = amount % stackSize; + final String prefix = getPrefix(stack); + + return new StacksText( + stacks > 0 ? prefix + "x" + ReadableNumberConverter.INSTANCE.toWideReadableForm(stacks) : "", + remainder > 0 + ? (stacks > 0 ? "+" : prefix) + + ReadableNumberConverter.INSTANCE.toWideReadableForm(remainder) + : "", + getColor(stack)); + } + + protected String getPrefix(ItemStack stack) { + return ""; + } + + protected int getColor(ItemStack stack) { + return 0xFFFFFF; + } + } + protected static final int SLOT_SIZE = 18; + protected static final int ICON_SIZE = 16; + protected static final int ICON_OFFSET = 1; protected static final int MAX_COLUMNS = 11; protected static final int MARGIN_TOP = 2; + protected static final int FLUID_STACK_SIZE = 144; + + protected final List items; + protected final List amounts = new ArrayList<>(); + + protected AmountRenderer amountRenderer; protected String label; protected EnumChatFormatting labelColor = EnumChatFormatting.GRAY; - protected List items; + protected int activeStackIndex = -1; protected Dimension size = new Dimension(); - protected boolean saveStackSize = false; + protected int columns = 0; protected int count = 0; protected int rows = 0; @@ -45,7 +175,7 @@ public class ItemsTooltipLineHandler implements ITooltipLineHandler { public ItemsTooltipLineHandler(String label, List items, boolean saveStackSize, int maxRows) { this.label = label; this.items = groupingItemStacks(items); - this.saveStackSize = saveStackSize; + this.amountRenderer = saveStackSize ? new TotalAmountRenderer() : new NoAmountRenderer(); this.length = this.items.size(); if (this.length > 0) { @@ -69,6 +199,11 @@ public class ItemsTooltipLineHandler implements ITooltipLineHandler { } + public ItemsTooltipLineHandler setAmountRenderer(AmountRenderer amountRenderer) { + this.amountRenderer = amountRenderer; + return this; + } + public void setActiveStack(ItemStack activeStack) { final ItemStack realStack = items.stream().filter(stack -> NEIClientUtils.areStacksSameType(stack, activeStack)) .findFirst().orElse(null); @@ -126,19 +261,15 @@ public class ItemsTooltipLineHandler implements ITooltipLineHandler { } for (int index = 0; index < this.count && index + indexShift < this.items.size(); index++) { - ItemStack drawStack = this.items.get(index + indexShift); int col = index % this.columns; int row = index / this.columns; - String stackSize = !this.saveStackSize || drawStack.stackSize == 0 ? "" - : ReadableNumberConverter.INSTANCE.toWideReadableForm(drawStack.stackSize); - if (this.activeStackIndex == index + indexShift) { NEIClientUtils.gl2DRenderContext( - () -> GuiDraw.drawRect(col * SLOT_SIZE - 1, row * SLOT_SIZE - 1, 18, 18, 0x66555555)); + () -> GuiDraw.drawRect(col * SLOT_SIZE, row * SLOT_SIZE, SLOT_SIZE, SLOT_SIZE, 0x66555555)); } - drawItem(col * SLOT_SIZE, row * SLOT_SIZE, drawStack, stackSize); + drawStackWithAmount(col * SLOT_SIZE, row * SLOT_SIZE, index + indexShift); } if (this.count < this.items.size()) { @@ -157,25 +288,23 @@ public class ItemsTooltipLineHandler implements ITooltipLineHandler { GL11.glPopAttrib(); } - protected void drawItem(int x, int y, ItemStack drawStack, String stackSize) { - GuiContainerManager.drawItem(x, y, drawStack, true, stackSize); + protected void drawStackWithAmount(int x, int y, int index) { + this.amountRenderer.draw(x + ICON_OFFSET, y + ICON_OFFSET, this.items.get(index), this.amounts.get(index)); } private List groupingItemStacks(List items) { final List result = new ArrayList<>(); for (Map.Entry entry : ItemStackAmount.of(items).entrySet()) { - final ItemStack stack = StackInfo.loadFromNBT(entry.getKey(), Math.max(0, entry.getValue())); - - if (stack != null && StackInfo.isFluidDisplayItem(stack)) { - stack.stackSize = 0; - } - - result.add(stack); + result.add(StackInfo.loadFromNBT(entry.getKey(), 0)); + this.amounts.add(Math.max(0, entry.getValue())); } if (result.isEmpty()) { - result.addAll(items); + for (ItemStack stack : items) { + result.add(stack); + this.amounts.add(0L); + } } return result; diff --git a/src/main/java/codechicken/nei/bookmark/tree/GuiCraftingTree.java b/src/main/java/codechicken/nei/bookmark/tree/GuiCraftingTree.java index 37ac8b84..7b9f158b 100644 --- a/src/main/java/codechicken/nei/bookmark/tree/GuiCraftingTree.java +++ b/src/main/java/codechicken/nei/bookmark/tree/GuiCraftingTree.java @@ -67,6 +67,7 @@ import codechicken.nei.recipe.GuiRecipeButton.UpdateRecipeButtonsEvent; import codechicken.nei.recipe.GuiRecipeTab; import codechicken.nei.recipe.Recipe; import codechicken.nei.recipe.Recipe.RecipeId; +import codechicken.nei.recipe.RecipeItemsTooltipLineHandler; import codechicken.nei.recipe.RecipeTooltipLineHandler; import codechicken.nei.recipe.StackInfo; import codechicken.nei.util.EmptyContainer; @@ -134,6 +135,7 @@ public class GuiCraftingTree extends GuiContainer implements INEIGuiHandler, IGu private RecipeTooltipLineHandler recipeTooltipLineHandler; private AcceptsFollowingTooltipLineHandler acceptsFollowingTooltipLineHandler; + private RecipeItemsTooltipLineHandler recipeItemsTooltipLineHandler; private final CraftingTreeState uiState = new CraftingTreeState(); private final CraftingTreeToolbar toolbar; @@ -939,12 +941,15 @@ public class GuiCraftingTree extends GuiContainer implements INEIGuiHandler, IGu if (toolbarTooltip != null) { currenttip.add(toolbarTooltip); } else if (this.hoveredBadgeHandler != null) { - final RecipeId recipeId = this.hoveredBadgeHandler.prefItem != null - ? this.hoveredBadgeHandler.prefItem.recipeId - : null; - final long multiplier = this.hoveredBadgeHandler.multiplier; + final ItemTreeSlot node = this.hoveredBadgeHandler; + final RecipeId recipeId = node.prefItem != null ? node.prefItem.recipeId : null; + + if (recipeId != null && NEIClientUtils.shiftKey()) { + addRecipeItemsTooltipLine(recipeId, node.multiplier, currenttip); + } else { + addRecipeTooltipLine(recipeId, node.multiplier, currenttip); + } - addRecipeTooltipLine(recipeId, multiplier, currenttip); } else { if (this.statsPanelVisible) { @@ -960,6 +965,14 @@ public class GuiCraftingTree extends GuiContainer implements INEIGuiHandler, IGu EnumChatFormatting.GRAY + NEIClientUtils.translate( "bookmark.tree.stats.handler_iterations", handlerStatsSlot.stats.iterations)); + } else if (widget instanceof StatsPanel.ItemStatsSlot itemStatsSlot && itemStatsSlot.recipeId != null) { + if (NEIClientUtils.shiftKey()) { + addRecipeItemsTooltipLine(itemStatsSlot.recipeId, itemStatsSlot.multiplier, currenttip); + } else { + currenttip.add(itemStatsSlot.stack.getDisplayName() + GuiDraw.TOOLTIP_LINESPACE); + + addRecipeTooltipLine(itemStatsSlot.recipeId, itemStatsSlot.multiplier, currenttip); + } } } @@ -968,6 +981,19 @@ public class GuiCraftingTree extends GuiContainer implements INEIGuiHandler, IGu return currenttip; } + private void addRecipeItemsTooltipLine(RecipeId recipeId, long multiplier, List currenttip) { + + if (this.recipeItemsTooltipLineHandler == null + || this.recipeItemsTooltipLineHandler.getMultiplier() != multiplier + || !this.recipeItemsTooltipLineHandler.getRecipeId().equals(recipeId)) { + this.recipeItemsTooltipLineHandler = new RecipeItemsTooltipLineHandler(recipeId, multiplier) + .setUseInventory(true); + } + + currenttip.add(this.recipeItemsTooltipLineHandler.getTitle() + GuiDraw.TOOLTIP_LINESPACE); + currenttip.add(GuiDraw.TOOLTIP_HANDLER + GuiDraw.getTipLineId(this.recipeItemsTooltipLineHandler)); + } + private void addRecipeTooltipLine(RecipeId recipeId, long multiplier, List currenttip) { if (recipeId == null) { @@ -1078,14 +1104,6 @@ public class GuiCraftingTree extends GuiContainer implements INEIGuiHandler, IGu } else { this.acceptsFollowingTooltipLineHandler = null; - - if (this.statsPanelVisible) { - final Widget widget = this.statsPanel.getWidgetUnderMouse(mousex, mousey); - if (widget instanceof StatsPanel.ItemStatsSlot itemStatsSlot) { - addRecipeTooltipLine(itemStatsSlot.recipeId, itemStatsSlot.multiplier, currenttip); - } - } - } return currenttip; diff --git a/src/main/java/codechicken/nei/bookmark/tree/StatsPanel.java b/src/main/java/codechicken/nei/bookmark/tree/StatsPanel.java index 14403435..9bea115f 100644 --- a/src/main/java/codechicken/nei/bookmark/tree/StatsPanel.java +++ b/src/main/java/codechicken/nei/bookmark/tree/StatsPanel.java @@ -88,6 +88,10 @@ class StatsPanel extends ScrollContainer { this(stack, stackSize, icon, null, 1); } + public ItemStack getStack() { + return StackInfo.withAmount(this.stack, stackSize); + } + @Override public void draw(int mx, int my) { @@ -519,7 +523,7 @@ class StatsPanel extends ScrollContainer { public ItemStack getStackMouseOver(int mouseX, int mouseY) { final Widget widget = getWidgetUnderMouse(mouseX, mouseY); - return widget instanceof ItemStatsSlot slot ? slot.stack : null; + return widget instanceof ItemStatsSlot slot && slot.recipeId == null ? slot.getStack() : null; } public void setHighlight(SearchResult searchResult) { diff --git a/src/main/java/codechicken/nei/recipe/AcceptsFollowingTooltipLineHandler.java b/src/main/java/codechicken/nei/recipe/AcceptsFollowingTooltipLineHandler.java index 6343fb87..944efbaa 100644 --- a/src/main/java/codechicken/nei/recipe/AcceptsFollowingTooltipLineHandler.java +++ b/src/main/java/codechicken/nei/recipe/AcceptsFollowingTooltipLineHandler.java @@ -20,6 +20,7 @@ public class AcceptsFollowingTooltipLineHandler extends ItemsTooltipLineHandler super(NEIClientUtils.translate("recipe.accepts"), items, false, maxRows); this.tooltipGUID = tooltipGUID; setActiveStack(activeStack); + setAmountRenderer(new FavoriteAmountRenderer()); } public static AcceptsFollowingTooltipLineHandler of(Object tooltipGUID, List items, @@ -38,12 +39,15 @@ public class AcceptsFollowingTooltipLineHandler extends ItemsTooltipLineHandler return null; } - @Override - protected void drawItem(int x, int y, ItemStack drawStack, String stackSize) { - super.drawItem(x, y, drawStack, stackSize); + protected static class FavoriteAmountRenderer extends NoAmountRenderer { - if (FavoriteRecipes.containsManual(drawStack)) { - NEIClientUtils.drawNEIOverlayText("F", x, y); + @Override + public void draw(int x, int y, ItemStack stack, long amount) { + super.draw(x, y, stack, amount); + + if (FavoriteRecipes.containsManual(stack)) { + NEIClientUtils.drawNEIOverlayText("F", x, y); + } } } diff --git a/src/main/java/codechicken/nei/recipe/RecipeItemsTooltipLineHandler.java b/src/main/java/codechicken/nei/recipe/RecipeItemsTooltipLineHandler.java new file mode 100644 index 00000000..6ea6d54e --- /dev/null +++ b/src/main/java/codechicken/nei/recipe/RecipeItemsTooltipLineHandler.java @@ -0,0 +1,332 @@ +package codechicken.nei.recipe; + +import java.awt.Dimension; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumChatFormatting; + +import codechicken.lib.gui.GuiDraw.ITooltipLineHandler; +import codechicken.lib.vec.Rectangle4i; +import codechicken.nei.ItemStackAmount; +import codechicken.nei.ItemsListTooltipLineHandler; +import codechicken.nei.ItemsTooltipLineHandler; +import codechicken.nei.ItemsTooltipLineHandler.StacksAmountRenderer; +import codechicken.nei.ItemsTooltipLineHandler.TotalAmountRenderer; +import codechicken.nei.NEIClientUtils; +import codechicken.nei.PositionedStack; +import codechicken.nei.api.IGuiContainerOverlay; +import codechicken.nei.recipe.Recipe.RecipeId; +import codechicken.nei.recipe.Recipe.RecipeIngredient; +import codechicken.nei.util.ReadableNumberConverter; + +public class RecipeItemsTooltipLineHandler implements ITooltipLineHandler { + + protected static class ChanceTotalAmountRenderer extends TotalAmountRenderer { + + protected final Set approximate; + + public ChanceTotalAmountRenderer(Set approximate) { + this.approximate = approximate; + } + + @Override + protected String formatAmount(ItemStack stack, long amount) { + final String text = super.formatAmount(stack, amount); + + if (!this.approximate.contains(stack)) { + return text; + } else if (!text.isEmpty()) { + return EnumChatFormatting.GOLD + "~" + text; + } else if (amount == 0) { + return EnumChatFormatting.GOLD + "~0"; + } + + return text; + } + } + + protected static class ChanceStacksAmountRenderer extends StacksAmountRenderer { + + protected static final int APPROXIMATE_COLOR = 0xFFAA00; + + protected final Set approximate; + + public ChanceStacksAmountRenderer(Set approximate) { + this.approximate = approximate; + } + + @Override + protected void drawAmount(Rectangle4i rect, ItemStack stack, long amount) { + if (amount == 0) { + Badge.notConsumed().draw(rect); + } else { + super.drawAmount(rect, stack, amount); + } + } + + @Override + protected String getPrefix(ItemStack stack) { + return this.approximate.contains(stack) ? "~" : ""; + } + + @Override + protected int getColor(ItemStack stack) { + return this.approximate.contains(stack) ? APPROXIMATE_COLOR : super.getColor(stack); + } + } + + protected static final int MAX_ROWS = 15; + + protected final RecipeId recipeId; + protected final long multiplier; + protected boolean useInventory = false; + + protected final List lines = new ArrayList<>(); + protected final Dimension size = new Dimension(); + protected String title = ""; + protected boolean created = false; + + public RecipeItemsTooltipLineHandler(RecipeId recipeId, long multiplier) { + this.recipeId = recipeId; + this.multiplier = multiplier; + } + + public RecipeItemsTooltipLineHandler setUseInventory(boolean useInventory) { + this.useInventory = useInventory; + this.created = false; + return this; + } + + public RecipeId getRecipeId() { + return this.recipeId; + } + + public long getMultiplier() { + return this.multiplier; + } + + public boolean isUseInventory() { + return this.useInventory; + } + + public String getTitle() { + ensureCreated(); + return this.title; + } + + @Override + public Dimension getSize() { + ensureCreated(); + return this.size; + } + + protected void ensureCreated() { + if (!this.created) { + this.created = true; + createLines(); + } + } + + @Override + public void draw(int x, int y) { + if (this.size.height == 0) return; + + for (ItemsTooltipLineHandler line : this.lines) { + line.draw(x, y); + y += line.getSize().height; + } + } + + protected static int getIngredientOrder(ItemStack stack) { + return StackInfo.isFluidDisplayItem(stack) ? 2 : stack.stackSize == 0 ? 0 : 1; + } + + protected void createLines() { + this.lines.clear(); + this.size.setSize(0, 0); + + final RecipeHandlerRef handlerRef = RecipeHandlerRef.of(this.recipeId); + + if (handlerRef == null) { + return; + } + + final Recipe recipe = Recipe.of(handlerRef); + final Set approximateResults = new HashSet<>(); + final Set approximateIngredients = new HashSet<>(); + final List results = multiplyItems(recipe.getResults(), false, approximateResults); + final List ingredients = multiplyItems(recipe.getIngredients(), true, approximateIngredients); + final ItemStackAmount ingredientsAmount = ItemStackAmount.of(ingredients); + + ingredients.sort(Comparator.comparingInt(RecipeItemsTooltipLineHandler::getIngredientOrder)); + + this.title = handlerRef.handler.getRecipeName().trim() + " (x" + + ReadableNumberConverter.INSTANCE.toWideReadableForm(this.multiplier) + + ")"; + + addResultLine(results, approximateResults); + addRequiredLine(ingredients, approximateIngredients); + + if (this.useInventory) { + final List needed = subtractItems(ingredientsAmount, getInventoryItems()); + final ItemStackAmount neededAmount = ItemStackAmount.of(needed); + final ItemStackAmount consumedAmount = ItemStackAmount.of(ingredientsAmount); + consumedAmount.removeIf(entry -> entry.getValue() <= 0); + + if (!neededAmount.equals(consumedAmount)) { + addNeededLine( + needed, + approximateIngredients, + needed.size() == 1 || ingredientsAmount.size() + neededAmount.size() <= MAX_ROWS); + } + } + + int width = 0; + int height = 0; + + for (ItemsTooltipLineHandler line : this.lines) { + width = Math.max(width, line.getSize().width); + height += line.getSize().height; + } + + this.size.setSize(width, height); + } + + protected void addResultLine(List items, Set approximate) { + final String label = NEIClientUtils.translate("recipe.items.results"); + final ItemsTooltipLineHandler line = items.size() == 1 ? new ItemsListTooltipLineHandler(label, items, MAX_ROWS) + : new ItemsTooltipLineHandler(label, items); + + if (line.isEmpty()) { + return; + } + + line.setLabelColor(EnumChatFormatting.GREEN); + + final Set approximateItems = Collections.newSetFromMap(new IdentityHashMap<>()); + + for (ItemStack stack : line.getItems()) { + if (approximate.contains(StackInfo.itemStackToNBT(stack, false))) { + approximateItems.add(stack); + } + } + + line.setAmountRenderer(new ChanceTotalAmountRenderer(approximateItems)); + + this.lines.add(line); + } + + protected void addRequiredLine(List items, Set approximate) { + final String label = NEIClientUtils.translate("recipe.items.ingredients"); + final ItemsTooltipLineHandler line = new ItemsListTooltipLineHandler(label, items, MAX_ROWS); + + if (line.isEmpty()) { + return; + } + + line.setLabelColor(EnumChatFormatting.YELLOW); + + final Set approximateItems = Collections.newSetFromMap(new IdentityHashMap<>()); + + for (ItemStack stack : line.getItems()) { + if (approximate.contains(StackInfo.itemStackToNBT(stack, false))) { + approximateItems.add(stack); + } + } + + line.setAmountRenderer(new ChanceStacksAmountRenderer(approximateItems)); + + this.lines.add(line); + } + + protected void addNeededLine(List items, Set approximate, boolean vertical) { + final String label = NEIClientUtils.translate("recipe.items.ingredients_needed"); + final ItemsTooltipLineHandler line = vertical ? new ItemsListTooltipLineHandler(label, items, MAX_ROWS) + : new ItemsTooltipLineHandler(label, items); + + if (line.isEmpty()) { + return; + } + + line.setLabelColor(EnumChatFormatting.RED); + + final Set approximateItems = Collections.newSetFromMap(new IdentityHashMap<>()); + + for (ItemStack stack : line.getItems()) { + if (approximate.contains(StackInfo.itemStackToNBT(stack, false))) { + approximateItems.add(stack); + } + } + + line.setAmountRenderer(new ChanceStacksAmountRenderer(approximateItems)); + + this.lines.add(line); + } + + protected List multiplyItems(List items, boolean ingredients, + Set approximate) { + final ItemStackAmount chanceAmounts = new ItemStackAmount(); + final List result = new ArrayList<>(); + + for (RecipeIngredient item : items) { + chanceAmounts.add(item.getItemStack(), (long) item.getAmount() * item.getChance()); + } + + for (Map.Entry entry : chanceAmounts.entrySet()) { + final long amount = entry.getValue() * this.multiplier; + final long entryAmount = ingredients + ? (amount + PositionedStack.CHANCE_FULL - 1) / PositionedStack.CHANCE_FULL + : amount / PositionedStack.CHANCE_FULL; + final ItemStack stack = StackInfo.loadFromNBT(entry.getKey(), entryAmount); + + if (amount % PositionedStack.CHANCE_FULL != 0) { + approximate.add(entry.getKey()); + } + + result.add(stack); + } + + return result; + } + + protected static ItemStackAmount getInventoryItems() { + GuiScreen screen = NEIClientUtils.mc().currentScreen; + + if (screen instanceof IGuiContainerOverlay overlay) { + screen = overlay.getFirstScreen(); + } + + if (screen instanceof GuiContainer container) { + return AutoCraftingManager.getInventoryItems(container); + } + + return new ItemStackAmount(); + } + + protected static List subtractItems(ItemStackAmount items, ItemStackAmount subtrahend) { + final List result = new ArrayList<>(); + + for (Map.Entry entry : items.entrySet()) { + final ItemStack stack = StackInfo.loadFromNBT(entry.getKey(), 0); + final long amount = entry.getValue() - subtrahend.getOrDefault(stack, 0L); + + if (amount > 0) { + result.add(StackInfo.withAmount(stack, amount)); + } + } + + return result; + } + +} diff --git a/src/main/resources/assets/nei/lang/en_US.lang b/src/main/resources/assets/nei/lang/en_US.lang index 4f53afa2..4e55a7e6 100644 --- a/src/main/resources/assets/nei/lang/en_US.lang +++ b/src/main/resources/assets/nei/lang/en_US.lang @@ -667,6 +667,10 @@ nei.recipe.badge.ncp.tooltip=Considered in parallel calculation, but not get con nei.recipe.badge.chance.consume=Consume Chance: %s nei.recipe.badge.chance.output=Output Chance: %s +nei.recipe.items.results=Results +nei.recipe.items.ingredients=Ingredients +nei.recipe.items.ingredients_needed=Ingredients Needed + # Deprecated nei.recipe.fuel.required=%s required # Deprecated From 0ec87a8b9eb32018ce134a7476669ddd24cb5e0c Mon Sep 17 00:00:00 2001 From: slprime <31038811+slprime@users.noreply.github.com> Date: Fri, 25 Sep 2026 22:08:15 +0300 Subject: [PATCH 02/11] Refactoring Chain Tooltip (#1044) --- .../nei/CompositeTooltipLineHandler.java | 101 +++++ .../nei/ItemsListTooltipLineHandler.java | 125 ------ .../nei/ItemsTooltipLineHandler.java | 179 +++++++-- .../java/codechicken/nei/NEIClientConfig.java | 7 - .../nei/bookmark/tree/GuiCraftingTree.java | 14 +- .../nei/bookmark/tree/StatsPanel.java | 9 +- .../nei/recipe/GuiOverlayButton.java | 7 +- .../codechicken/nei/recipe/GuiRecipeTab.java | 18 + .../recipe/RecipeItemsTooltipLineHandler.java | 61 +-- .../chain/RecipeChainTooltipLineHandler.java | 357 ++++++++++-------- src/main/resources/assets/nei/lang/en_US.lang | 7 - src/main/resources/assets/nei/lang/ru_RU.lang | 5 - src/main/resources/assets/nei/lang/uk_UA.lang | 7 - 13 files changed, 478 insertions(+), 419 deletions(-) create mode 100644 src/main/java/codechicken/nei/CompositeTooltipLineHandler.java delete mode 100644 src/main/java/codechicken/nei/ItemsListTooltipLineHandler.java diff --git a/src/main/java/codechicken/nei/CompositeTooltipLineHandler.java b/src/main/java/codechicken/nei/CompositeTooltipLineHandler.java new file mode 100644 index 00000000..b10202ae --- /dev/null +++ b/src/main/java/codechicken/nei/CompositeTooltipLineHandler.java @@ -0,0 +1,101 @@ +package codechicken.nei; + +import java.awt.Dimension; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +import codechicken.lib.gui.GuiDraw; +import codechicken.lib.gui.GuiDraw.ITooltipLineHandler; + +public abstract class CompositeTooltipLineHandler implements ITooltipLineHandler { + + protected static final int SCREEN_MARGIN = 8 * 2 + 10; + protected static final int RESERVED_HEIGHT = 40; + + protected final List lines = new ArrayList<>(); + protected final Dimension size = new Dimension(); + + protected boolean created = false; + protected int screenHeight = 0; + + protected abstract void createLines(); + + protected boolean needsUpdate() { + return false; + } + + @Override + public Dimension getSize() { + ensureCreated(); + return this.size; + } + + @Override + public void draw(int x, int y) { + if (this.size.height == 0) return; + + for (ItemsTooltipLineHandler line : this.lines) { + line.draw(x, y); + y += line.getSize().height; + } + } + + protected void ensureCreated() { + boolean update = needsUpdate(); + update = this.screenHeight != (this.screenHeight = GuiDraw.displaySize().height) || update; + + if (this.created && !update) { + return; + } + + this.created = true; + this.lines.clear(); + this.size.setSize(0, 0); + + createLines(); + fitToScreen(); + + for (ItemsTooltipLineHandler line : this.lines) { + this.size.width = Math.max(this.size.width, line.getSize().width); + this.size.height += line.getSize().height; + } + } + + protected void fitToScreen() { + if (this.lines.isEmpty()) { + return; + } + + final List ordered = new ArrayList<>(this.lines); + ordered.sort(Comparator.comparingInt(ItemsTooltipLineHandler::getRows)); + + int budget = availableHeight() / ItemsTooltipLineHandler.SLOT_SIZE; + int rest = ordered.size(); + + for (ItemsTooltipLineHandler line : ordered) { + final int fair = Math.max(1, budget / rest); + + if (line.getRows() > fair) { + line.setMaxRows(fair); + } + + budget -= line.getRows(); + rest--; + } + } + + protected int availableHeight() { + return GuiDraw.displaySize().height - SCREEN_MARGIN + - RESERVED_HEIGHT + - this.lines.size() * ItemsTooltipLineHandler.headerHeight(); + } + + protected static int maxLineRows() { + final int height = GuiDraw.displaySize().height - SCREEN_MARGIN + - RESERVED_HEIGHT + - ItemsTooltipLineHandler.headerHeight(); + return Math.max(1, height / ItemsTooltipLineHandler.SLOT_SIZE); + } + +} diff --git a/src/main/java/codechicken/nei/ItemsListTooltipLineHandler.java b/src/main/java/codechicken/nei/ItemsListTooltipLineHandler.java deleted file mode 100644 index 4aad640e..00000000 --- a/src/main/java/codechicken/nei/ItemsListTooltipLineHandler.java +++ /dev/null @@ -1,125 +0,0 @@ -package codechicken.nei; - -import static codechicken.lib.gui.GuiDraw.fontRenderer; - -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.client.renderer.RenderHelper; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumChatFormatting; - -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL12; - -import codechicken.lib.gui.GuiDraw; -import codechicken.nei.guihook.GuiContainerManager; - -public class ItemsListTooltipLineHandler extends ItemsTooltipLineHandler { - - protected static final int NAME_MARGIN = 2; - - protected final List names = new ArrayList<>(); - protected int tailCount = 0; - - public ItemsListTooltipLineHandler(String label, List items, int maxRows) { - super(label, items, true, maxRows); - - this.rows = Math.min(maxRows, this.length); - this.count = this.length > this.rows ? this.rows - 1 : this.length; - - int width = fontRenderer.getStringWidth(this.label) + 15; - - for (int index = 0; index < this.count; index++) { - final String name = this.items.get(index).getDisplayName(); - this.names.add(name); - width = Math.max(width, SLOT_SIZE + NAME_MARGIN + fontRenderer.getStringWidth(name)); - } - - if (this.count < this.length) { - final int tail = this.length - this.count; - width = Math.max(width, Math.min(tail, MAX_COLUMNS) * SLOT_SIZE); - - final int fit = width / SLOT_SIZE; - - if (tail <= fit) { - this.tailCount = tail; - } else { - final String text = "+" + (tail - fit); - this.tailCount = Math - .max(0, fit - (int) Math.ceil((float) (fontRenderer.getStringWidth(text) - 2) / SLOT_SIZE)); - } - } - - this.size.width = this.length > 0 ? width : 0; - this.size.height = this.length > 0 ? this.rows * SLOT_SIZE + fontRenderer.FONT_HEIGHT + 2 + MARGIN_TOP : 0; - } - - @Override - public void setLabel(String label) { - this.label = label; - this.size.width = Math.max(this.size.width, fontRenderer.getStringWidth(this.label) + 15); - } - - @Override - public void draw(int x, int y) { - if (this.length == 0) return; - - y += MARGIN_TOP; - - fontRenderer.drawStringWithShadow(this.labelColor + this.label + ":", x, y, 0); - - GL11.glEnable(GL12.GL_RESCALE_NORMAL); - - GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_LIGHTING_BIT); - RenderHelper.enableGUIStandardItemLighting(); - - final int xTranslation = x; - final int yTranslation = y + fontRenderer.FONT_HEIGHT + 2; - final int zTranslation = GuiContainerManager.TOOLTIP_Z_OFFSET; - GL11.glTranslatef(xTranslation, yTranslation, zTranslation); - - for (int index = 0; index < this.count; index++) { - drawSlot(0, index * SLOT_SIZE, index); - } - - for (int index = 0; index < this.tailCount; index++) { - drawSlot(index * SLOT_SIZE, this.count * SLOT_SIZE, this.count + index); - } - - NEIClientUtils.gl2DRenderContext(() -> { - final int textShift = ICON_OFFSET + Math.round((ICON_SIZE - fontRenderer.FONT_HEIGHT) / 2f); - - for (int index = 0; index < this.count; index++) { - fontRenderer.drawStringWithShadow( - EnumChatFormatting.GRAY + this.names.get(index), - SLOT_SIZE + NAME_MARGIN, - index * SLOT_SIZE + textShift, - 0xFFFFFF); - } - - final int hidden = this.length - this.count - this.tailCount; - - if (hidden > 0) { - final String text = "+" + hidden; - fontRenderer.drawStringWithShadow( - EnumChatFormatting.GRAY + text, - this.size.width - fontRenderer.getStringWidth(text) - 2, - this.count * SLOT_SIZE + textShift, - 0xFFFFFF); - } - }); - - GL11.glTranslatef(-xTranslation, -yTranslation, -zTranslation); - GL11.glPopAttrib(); - } - - protected void drawSlot(int x, int y, int index) { - if (this.activeStackIndex == index) { - NEIClientUtils.gl2DRenderContext(() -> GuiDraw.drawRect(x, y, SLOT_SIZE, SLOT_SIZE, 0x66555555)); - } - - drawStackWithAmount(x, y, index); - } - -} diff --git a/src/main/java/codechicken/nei/ItemsTooltipLineHandler.java b/src/main/java/codechicken/nei/ItemsTooltipLineHandler.java index 1471bde8..9b6575ab 100644 --- a/src/main/java/codechicken/nei/ItemsTooltipLineHandler.java +++ b/src/main/java/codechicken/nei/ItemsTooltipLineHandler.java @@ -150,10 +150,14 @@ public class ItemsTooltipLineHandler implements ITooltipLineHandler { protected static final int ICON_OFFSET = 1; protected static final int MAX_COLUMNS = 11; protected static final int MARGIN_TOP = 2; + protected static final int LABEL_MARGIN = 15; + protected static final int NAME_MARGIN = 2; + protected static final int DEFAULT_MAX_ROWS = 5; protected static final int FLUID_STACK_SIZE = 144; protected final List items; protected final List amounts = new ArrayList<>(); + protected final List names = new ArrayList<>(); protected AmountRenderer amountRenderer; @@ -163,40 +167,115 @@ public class ItemsTooltipLineHandler implements ITooltipLineHandler { protected int activeStackIndex = -1; protected Dimension size = new Dimension(); - protected int columns = 0; - protected int count = 0; - protected int rows = 0; + protected final boolean showNames; + protected int length = 0; + protected int rows = 0; + protected int nameRows = 0; + protected int gridColumns = 0; + protected int gridCount = 0; + + public static ItemsTooltipLineHandler grid(String label, List items, int maxRows) { + return new ItemsTooltipLineHandler(label, items, true, maxRows, false); + } + + public static ItemsTooltipLineHandler list(String label, List items, int maxRows) { + return new ItemsTooltipLineHandler(label, items, true, maxRows, true); + } public ItemsTooltipLineHandler(String label, List items) { - this(label, items, true, 5); + this(label, items, true, DEFAULT_MAX_ROWS, false); } public ItemsTooltipLineHandler(String label, List items, boolean saveStackSize, int maxRows) { + this(label, items, saveStackSize, maxRows, false); + } + + protected ItemsTooltipLineHandler(String label, List items, boolean saveStackSize, int maxRows, + boolean showNames) { this.label = label; this.items = groupingItemStacks(items); this.amountRenderer = saveStackSize ? new TotalAmountRenderer() : new NoAmountRenderer(); this.length = this.items.size(); + this.showNames = showNames; - if (this.length > 0) { - this.columns = Math.min(MAX_COLUMNS, this.length); - this.rows = Math.min(maxRows, (int) Math.ceil((float) this.length / this.columns)); + setMaxRows(maxRows); + } - this.size.width = Math.max(this.columns * SLOT_SIZE, fontRenderer.getStringWidth(this.label) + 15); - this.size.height = this.rows * SLOT_SIZE + fontRenderer.FONT_HEIGHT + 2 + MARGIN_TOP; + protected static int headerHeight() { + return fontRenderer.FONT_HEIGHT + 2 + MARGIN_TOP; + } - this.count = Math.min( - this.length, - Math.min( - this.columns * this.rows, - this.length > MAX_COLUMNS * maxRows ? (MAX_COLUMNS * maxRows) : Integer.MAX_VALUE)); + public ItemsTooltipLineHandler setMaxRows(int maxRows) { + if (this.length == 0) { + return this; + } - if (this.items.size() > this.count) { - String text = "+" + (this.items.size() - this.count); - this.count -= (int) Math.ceil((float) (fontRenderer.getStringWidth(text) - 2) / SLOT_SIZE); + this.names.clear(); + this.nameRows = 0; + + if (!this.showNames || !layoutWithNames(maxRows)) { + layoutAsGrid(maxRows); + } + + this.size.height = this.rows * SLOT_SIZE + headerHeight(); + + return this; + } + + public int getRows() { + return this.rows; + } + + protected boolean layoutWithNames(int maxRows) { + final int maxNames = this.length <= maxRows ? this.length : maxRows - 1; + final int[] lineWidth = new int[maxNames + 1]; + lineWidth[0] = labelWidth(); + + for (int index = 0; index < maxNames; index++) { + final String name = this.items.get(index).getDisplayName(); + this.names.add(name); + lineWidth[index + 1] = Math + .max(lineWidth[index], SLOT_SIZE + NAME_MARGIN + fontRenderer.getStringWidth(name)); + } + + for (int named = maxNames; named >= 0; named--) { + final int rest = this.length - named; + final int width = Math.max(lineWidth[named], Math.min(rest, MAX_COLUMNS) * SLOT_SIZE); + final int columns = Math.max(1, width / SLOT_SIZE); + final int restRows = (int) Math.ceil((float) rest / columns); + + if (named + restRows <= maxRows) { + this.nameRows = named; + this.gridColumns = columns; + this.gridCount = rest; + this.rows = named + restRows; + this.size.width = width; + return true; } } + this.names.clear(); + return false; + } + + protected void layoutAsGrid(int maxRows) { + this.gridColumns = Math.min(MAX_COLUMNS, this.length); + this.rows = Math.min(maxRows, (int) Math.ceil((float) this.length / this.gridColumns)); + this.gridCount = Math.min(this.length, this.gridColumns * this.rows); + this.size.width = Math.max(this.gridColumns * SLOT_SIZE, labelWidth()); + + if (this.gridCount < this.length) { + this.gridCount -= reservedColumns(this.length - this.gridCount); + } + } + + protected int labelWidth() { + return fontRenderer.getStringWidth(this.label) + LABEL_MARGIN; + } + + protected int reservedColumns(int hidden) { + return (int) Math.ceil((float) (fontRenderer.getStringWidth("+" + hidden) - 2) / SLOT_SIZE); } public ItemsTooltipLineHandler setAmountRenderer(AmountRenderer amountRenderer) { @@ -233,7 +312,7 @@ public class ItemsTooltipLineHandler implements ITooltipLineHandler { public void setLabel(String label) { this.label = label; - this.size.width = Math.max(this.columns * SLOT_SIZE, fontRenderer.getStringWidth(this.label) + 15); + this.size.width = Math.max(this.size.width, labelWidth()); } @Override @@ -254,40 +333,62 @@ public class ItemsTooltipLineHandler implements ITooltipLineHandler { final int zTranslation = GuiContainerManager.TOOLTIP_Z_OFFSET; GL11.glTranslatef(xTranslation, yTranslation, zTranslation); - int indexShift = 0; + final int gridShift = gridIndexShift(); - if (this.activeStackIndex != -1) { - indexShift = Math.max(0, Math.min(this.items.size() - this.count, this.activeStackIndex - this.count + 2)); + for (int index = 0; index < this.nameRows; index++) { + drawSlot(0, index * SLOT_SIZE, index); } - for (int index = 0; index < this.count && index + indexShift < this.items.size(); index++) { - int col = index % this.columns; - int row = index / this.columns; + for (int index = 0; index < this.gridCount; index++) { + drawSlot( + (index % this.gridColumns) * SLOT_SIZE, + (this.nameRows + index / this.gridColumns) * SLOT_SIZE, + this.nameRows + gridShift + index); + } - if (this.activeStackIndex == index + indexShift) { - NEIClientUtils.gl2DRenderContext( - () -> GuiDraw.drawRect(col * SLOT_SIZE, row * SLOT_SIZE, SLOT_SIZE, SLOT_SIZE, 0x66555555)); + NEIClientUtils.gl2DRenderContext(() -> { + final int textShift = ICON_OFFSET + Math.round((ICON_SIZE - fontRenderer.FONT_HEIGHT) / 2f); + + for (int index = 0; index < this.nameRows; index++) { + fontRenderer.drawStringWithShadow( + EnumChatFormatting.GRAY + this.names.get(index), + SLOT_SIZE + NAME_MARGIN, + index * SLOT_SIZE + textShift, + 0xFFFFFF); } - drawStackWithAmount(col * SLOT_SIZE, row * SLOT_SIZE, index + indexShift); - } + final int hidden = this.length - this.nameRows - this.gridCount; - if (this.count < this.items.size()) { - final String text = "+" + (this.items.size() - this.count); - - NEIClientUtils.gl2DRenderContext(() -> { + if (hidden > 0) { + final String text = "+" + hidden; fontRenderer.drawStringWithShadow( - text, - MAX_COLUMNS * SLOT_SIZE - fontRenderer.getStringWidth(text) - 2, - (this.rows - 1) * SLOT_SIZE + (SLOT_SIZE - fontRenderer.FONT_HEIGHT) / 2, - 0xee555555); - }); - } + EnumChatFormatting.GRAY + text, + this.size.width - fontRenderer.getStringWidth(text) - 2, + (this.rows - 1) * SLOT_SIZE + textShift, + 0xFFFFFF); + } + }); GL11.glTranslatef(-xTranslation, -yTranslation, -zTranslation); GL11.glPopAttrib(); } + protected int gridIndexShift() { + if (this.nameRows > 0 || this.activeStackIndex == -1) { + return 0; + } + + return Math.max(0, Math.min(this.length - this.gridCount, this.activeStackIndex - this.gridCount + 2)); + } + + protected void drawSlot(int x, int y, int index) { + if (this.activeStackIndex == index) { + NEIClientUtils.gl2DRenderContext(() -> GuiDraw.drawRect(x, y, SLOT_SIZE, SLOT_SIZE, 0x66555555)); + } + + drawStackWithAmount(x, y, index); + } + protected void drawStackWithAmount(int x, int y, int index) { this.amountRenderer.draw(x + ICON_OFFSET, y + ICON_OFFSET, this.items.get(index), this.amounts.get(index)); } diff --git a/src/main/java/codechicken/nei/NEIClientConfig.java b/src/main/java/codechicken/nei/NEIClientConfig.java index 7f1a3ed2..88b98899 100644 --- a/src/main/java/codechicken/nei/NEIClientConfig.java +++ b/src/main/java/codechicken/nei/NEIClientConfig.java @@ -212,9 +212,6 @@ public class NEIClientConfig { .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)); - tag.getTag("inventory.bookmarks.ignorePotionOverlap").setComment("Ignore overlap with potion effect HUD") .getBooleanValue(false); API.addOption(new OptionToggleButton("inventory.bookmarks.ignorePotionOverlap", true)); @@ -1153,10 +1150,6 @@ public class NEIClientConfig { return getBooleanSetting("inventory.bookmarks.ignorePotionOverlap"); } - public static int recipeChainDir() { - return getIntSetting("inventory.bookmarks.recipeChainDir"); - } - public static boolean optimizeGuiOverlapComputation() { return getBooleanSetting("inventory.optimize_gui_overlap_computation"); } diff --git a/src/main/java/codechicken/nei/bookmark/tree/GuiCraftingTree.java b/src/main/java/codechicken/nei/bookmark/tree/GuiCraftingTree.java index 7b9f158b..f4a95710 100644 --- a/src/main/java/codechicken/nei/bookmark/tree/GuiCraftingTree.java +++ b/src/main/java/codechicken/nei/bookmark/tree/GuiCraftingTree.java @@ -13,7 +13,6 @@ import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; -import java.util.stream.Stream; import javax.imageio.ImageIO; @@ -116,7 +115,7 @@ public class GuiCraftingTree extends GuiContainer implements INEIGuiHandler, IGu private static final int PADDING = 9; private static final int PADDING_TOP = 22; - private static LRUCache handlerTitleCache = new LRUCache<>(100); + private final LRUCache handlerTitleCache = new LRUCache<>(100); private GuiScreen prevGui; private boolean isFirstScreen = true; @@ -919,15 +918,8 @@ public class GuiCraftingTree extends GuiContainer implements INEIGuiHandler, IGu super.keyTyped(typedChar, keyCode); } - private static String getHandlerTitle(String handlerName) { - return handlerTitleCache.computeIfAbsent( - handlerName, - hname -> Stream - .concat( - GuiCraftingRecipe.craftinghandlers.stream(), - GuiCraftingRecipe.serialCraftingHandlers.stream()) - .filter(handler -> hname.equals(GuiRecipeTab.getHandlerInfo(handler).getHandlerName())) - .findFirst().map(handler -> handler.getRecipeName().trim()).orElse(hname)); + private String getHandlerTitle(String handlerName) { + return this.handlerTitleCache.computeIfAbsent(handlerName, GuiRecipeTab::getHandlerTitle); } @Override diff --git a/src/main/java/codechicken/nei/bookmark/tree/StatsPanel.java b/src/main/java/codechicken/nei/bookmark/tree/StatsPanel.java index 9bea115f..7fa0d760 100644 --- a/src/main/java/codechicken/nei/bookmark/tree/StatsPanel.java +++ b/src/main/java/codechicken/nei/bookmark/tree/StatsPanel.java @@ -3,6 +3,7 @@ package codechicken.nei.bookmark.tree; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -122,7 +123,7 @@ class StatsPanel extends ScrollContainer { GL11.glPushMatrix(); GL11.glColor4f(1, 1, 1, 1); - GL11.glTranslatef(badgeX, y - 6 * scale, 3.0f); + GL11.glTranslatef(badgeX, y - 6 * scale, 10.0f); GL11.glScalef(scale, scale, 1.0f); if (this.info.hasImageOrItem()) { @@ -715,8 +716,14 @@ class StatsPanel extends ScrollContainer { private List collectHandlers(RecipeChainMath math) { final Map handlerStats = new HashMap<>(); final List widgets = new ArrayList<>(); + final Set countedRecipes = new HashSet<>(); for (BookmarkItem item : math.recipeResults) { + // a recipe adds one result item per output, count it only once + if (!countedRecipes.add(item.recipeId)) { + continue; + } + final HandlerStats stats = handlerStats .computeIfAbsent(item.recipeId.getHandlerName(), k -> new HandlerStats()); stats.iterations += item.getMultiplier(); diff --git a/src/main/java/codechicken/nei/recipe/GuiOverlayButton.java b/src/main/java/codechicken/nei/recipe/GuiOverlayButton.java index 6d0e729e..922960df 100644 --- a/src/main/java/codechicken/nei/recipe/GuiOverlayButton.java +++ b/src/main/java/codechicken/nei/recipe/GuiOverlayButton.java @@ -262,11 +262,8 @@ public class GuiOverlayButton extends GuiRecipeButton { .map(state -> state.getSlot().item).collect(Collectors.toList()); if (!items.isEmpty()) { - this.missedMaterialsTooltipLineHandler = new ItemsTooltipLineHandler( - NEIClientUtils.translate("recipe.overlay.missing"), - items, - true, - Integer.MAX_VALUE); + this.missedMaterialsTooltipLineHandler = ItemsTooltipLineHandler + .grid(NEIClientUtils.translate("recipe.overlay.missing"), items, Integer.MAX_VALUE); } else { this.missedMaterialsTooltipLineHandler = null; } diff --git a/src/main/java/codechicken/nei/recipe/GuiRecipeTab.java b/src/main/java/codechicken/nei/recipe/GuiRecipeTab.java index 4eadd71d..e218c65c 100644 --- a/src/main/java/codechicken/nei/recipe/GuiRecipeTab.java +++ b/src/main/java/codechicken/nei/recipe/GuiRecipeTab.java @@ -181,6 +181,24 @@ public abstract class GuiRecipeTab extends Widget { return res; } + public static String getHandlerTitle(String handlerName) { + String title = findRecipeName(GuiCraftingRecipe.craftinghandlers, handlerName); + if (title == null) title = findRecipeName(GuiCraftingRecipe.serialCraftingHandlers, handlerName); + if (title == null) title = findRecipeName(GuiUsageRecipe.usagehandlers, handlerName); + if (title == null) title = findRecipeName(GuiUsageRecipe.serialUsageHandlers, handlerName); + + return title != null ? title : handlerName; + } + + private static String findRecipeName(List handlers, String handlerName) { + for (int index = 0; index < handlers.size(); index++) { + final IRecipeHandler handler = handlers.get(index); + if (handlerName.equals(getHandlerInfo(handler).getHandlerName())) return handler.getRecipeName().trim(); + } + + return null; + } + public static String getHandlerMod(String name, String name2) { HandlerInfo info = getHandlerInfo(name, name2); if (info == null) return "Unknown"; diff --git a/src/main/java/codechicken/nei/recipe/RecipeItemsTooltipLineHandler.java b/src/main/java/codechicken/nei/recipe/RecipeItemsTooltipLineHandler.java index 6ea6d54e..4fc1478c 100644 --- a/src/main/java/codechicken/nei/recipe/RecipeItemsTooltipLineHandler.java +++ b/src/main/java/codechicken/nei/recipe/RecipeItemsTooltipLineHandler.java @@ -1,6 +1,5 @@ package codechicken.nei.recipe; -import java.awt.Dimension; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; @@ -16,10 +15,9 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumChatFormatting; -import codechicken.lib.gui.GuiDraw.ITooltipLineHandler; import codechicken.lib.vec.Rectangle4i; +import codechicken.nei.CompositeTooltipLineHandler; import codechicken.nei.ItemStackAmount; -import codechicken.nei.ItemsListTooltipLineHandler; import codechicken.nei.ItemsTooltipLineHandler; import codechicken.nei.ItemsTooltipLineHandler.StacksAmountRenderer; import codechicken.nei.ItemsTooltipLineHandler.TotalAmountRenderer; @@ -30,7 +28,7 @@ import codechicken.nei.recipe.Recipe.RecipeId; import codechicken.nei.recipe.Recipe.RecipeIngredient; import codechicken.nei.util.ReadableNumberConverter; -public class RecipeItemsTooltipLineHandler implements ITooltipLineHandler { +public class RecipeItemsTooltipLineHandler extends CompositeTooltipLineHandler { protected static class ChanceTotalAmountRenderer extends TotalAmountRenderer { @@ -86,16 +84,10 @@ public class RecipeItemsTooltipLineHandler implements ITooltipLineHandler { } } - protected static final int MAX_ROWS = 15; - protected final RecipeId recipeId; protected final long multiplier; protected boolean useInventory = false; - - protected final List lines = new ArrayList<>(); - protected final Dimension size = new Dimension(); protected String title = ""; - protected boolean created = false; public RecipeItemsTooltipLineHandler(RecipeId recipeId, long multiplier) { this.recipeId = recipeId; @@ -125,37 +117,12 @@ public class RecipeItemsTooltipLineHandler implements ITooltipLineHandler { return this.title; } - @Override - public Dimension getSize() { - ensureCreated(); - return this.size; - } - - protected void ensureCreated() { - if (!this.created) { - this.created = true; - createLines(); - } - } - - @Override - public void draw(int x, int y) { - if (this.size.height == 0) return; - - for (ItemsTooltipLineHandler line : this.lines) { - line.draw(x, y); - y += line.getSize().height; - } - } - protected static int getIngredientOrder(ItemStack stack) { return StackInfo.isFluidDisplayItem(stack) ? 2 : stack.stackSize == 0 ? 0 : 1; } + @Override protected void createLines() { - this.lines.clear(); - this.size.setSize(0, 0); - final RecipeHandlerRef handlerRef = RecipeHandlerRef.of(this.recipeId); if (handlerRef == null) { @@ -188,25 +155,17 @@ public class RecipeItemsTooltipLineHandler implements ITooltipLineHandler { addNeededLine( needed, approximateIngredients, - needed.size() == 1 || ingredientsAmount.size() + neededAmount.size() <= MAX_ROWS); + needed.size() == 1 || ingredientsAmount.size() + neededAmount.size() <= maxLineRows()); } } - int width = 0; - int height = 0; - - for (ItemsTooltipLineHandler line : this.lines) { - width = Math.max(width, line.getSize().width); - height += line.getSize().height; - } - - this.size.setSize(width, height); } protected void addResultLine(List items, Set approximate) { final String label = NEIClientUtils.translate("recipe.items.results"); - final ItemsTooltipLineHandler line = items.size() == 1 ? new ItemsListTooltipLineHandler(label, items, MAX_ROWS) - : new ItemsTooltipLineHandler(label, items); + final ItemsTooltipLineHandler line = items.size() == 1 + ? ItemsTooltipLineHandler.list(label, items, maxLineRows()) + : ItemsTooltipLineHandler.grid(label, items, maxLineRows()); if (line.isEmpty()) { return; @@ -229,7 +188,7 @@ public class RecipeItemsTooltipLineHandler implements ITooltipLineHandler { protected void addRequiredLine(List items, Set approximate) { final String label = NEIClientUtils.translate("recipe.items.ingredients"); - final ItemsTooltipLineHandler line = new ItemsListTooltipLineHandler(label, items, MAX_ROWS); + final ItemsTooltipLineHandler line = ItemsTooltipLineHandler.list(label, items, maxLineRows()); if (line.isEmpty()) { return; @@ -252,8 +211,8 @@ public class RecipeItemsTooltipLineHandler implements ITooltipLineHandler { protected void addNeededLine(List items, Set approximate, boolean vertical) { final String label = NEIClientUtils.translate("recipe.items.ingredients_needed"); - final ItemsTooltipLineHandler line = vertical ? new ItemsListTooltipLineHandler(label, items, MAX_ROWS) - : new ItemsTooltipLineHandler(label, items); + final ItemsTooltipLineHandler line = vertical ? ItemsTooltipLineHandler.list(label, items, maxLineRows()) + : ItemsTooltipLineHandler.grid(label, items, maxLineRows()); if (line.isEmpty()) { return; diff --git a/src/main/java/codechicken/nei/recipe/chain/RecipeChainTooltipLineHandler.java b/src/main/java/codechicken/nei/recipe/chain/RecipeChainTooltipLineHandler.java index 584a7ecd..80d1dfd1 100644 --- a/src/main/java/codechicken/nei/recipe/chain/RecipeChainTooltipLineHandler.java +++ b/src/main/java/codechicken/nei/recipe/chain/RecipeChainTooltipLineHandler.java @@ -1,30 +1,123 @@ package codechicken.nei.recipe.chain; -import java.awt.Dimension; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; +import java.util.HashSet; +import java.util.IdentityHashMap; import java.util.List; import java.util.Map; +import java.util.Set; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumChatFormatting; +import org.lwjgl.opengl.GL11; + import codechicken.lib.gui.GuiDraw; -import codechicken.lib.gui.GuiDraw.ITooltipLineHandler; +import codechicken.nei.ColorUtils; +import codechicken.nei.CompositeTooltipLineHandler; import codechicken.nei.ItemSorter; import codechicken.nei.ItemStackAmount; import codechicken.nei.ItemsTooltipLineHandler; -import codechicken.nei.NEIClientConfig; +import codechicken.nei.ItemsTooltipLineHandler.AmountRenderer; +import codechicken.nei.ItemsTooltipLineHandler.StacksAmountRenderer; +import codechicken.nei.ItemsTooltipLineHandler.TotalAmountRenderer; import codechicken.nei.NEIClientUtils; import codechicken.nei.bookmark.BookmarkItem; +import codechicken.nei.drawable.DrawableResource; +import codechicken.nei.guihook.GuiContainerManager; import codechicken.nei.recipe.AutoCraftingManager; import codechicken.nei.recipe.GuiRecipe; +import codechicken.nei.recipe.GuiRecipeTab; +import codechicken.nei.recipe.HandlerInfo; import codechicken.nei.recipe.Recipe.RecipeId; import codechicken.nei.recipe.StackInfo; -public class RecipeChainTooltipLineHandler implements ITooltipLineHandler { +public class RecipeChainTooltipLineHandler extends CompositeTooltipLineHandler { + + protected static class MissingStacksAmountRenderer extends StacksAmountRenderer { + + protected static final int MISSING_COLOR = 0xFF5555; + + protected final Set missing; + private final Map cache = new IdentityHashMap<>(); + + public MissingStacksAmountRenderer(Set missing) { + this.missing = missing; + } + + @Override + protected int getColor(ItemStack stack) { + return this.cache.computeIfAbsent(stack, key -> this.missing.contains(StackInfo.itemStackToNBT(key, false))) + ? MISSING_COLOR + : super.getColor(stack); + } + } + + protected static class HandlerIconRenderer extends TotalAmountRenderer { + + protected static final int ICON_SIZE = 16; + protected static final float BADGE_SCALE = 0.6f; + protected static final float BADGE_OFFSET = 3f; + // slots are drawn edge to edge, so the badge has to clear the 3d model of the neighbour slot + protected static final float BADGE_Z = 10f; + + protected final Map handlers; + private final Map cache = new IdentityHashMap<>(); + private final Map titleCache = new HashMap<>(); + + public HandlerIconRenderer(Map handlers) { + this.handlers = handlers; + } + + @Override + public void draw(int x, int y, ItemStack stack, long amount) { + super.draw(x, y, stack, amount); + drawHandlerBadge( + x, + y, + this.cache.computeIfAbsent(stack, key -> this.handlers.get(StackInfo.itemStackToNBT(key, false)))); + } + + protected void drawHandlerBadge(int x, int y, HandlerInfo handlerInfo) { + if (handlerInfo == null) return; + + GL11.glPushMatrix(); + GL11.glColor4f(1, 1, 1, 1); + GL11.glTranslatef(x - BADGE_OFFSET * BADGE_SCALE, y - BADGE_OFFSET * BADGE_SCALE, BADGE_Z); + GL11.glScalef(BADGE_SCALE, BADGE_SCALE, 1.0f); + + if (handlerInfo.hasImageOrItem()) { + final DrawableResource image = handlerInfo.getImage(); + + if (image != null) { + NEIClientUtils.gl2DRenderContext(() -> image.draw(0, 0)); + } else { + GuiContainerManager.drawItem(0, 0, handlerInfo.getItemStack(), true, ""); + } + + } else { + drawBadgeText(handlerInfo.getHandlerName()); + } + + GL11.glPopMatrix(); + } + + protected void drawBadgeText(String handlerName) { + final String title = this.titleCache.computeIfAbsent(handlerName, GuiRecipeTab::getHandlerTitle); + final String text = title.isEmpty() ? "??" : title.substring(0, Math.min(2, title.length())); + + NEIClientUtils.gl2DRenderContext( + () -> GuiDraw.fontRenderer.drawStringWithShadow( + text, + (ICON_SIZE - GuiDraw.fontRenderer.getStringWidth(text)) / 2, + (ICON_SIZE - GuiDraw.fontRenderer.FONT_HEIGHT) / 2, + ColorUtils.buttonLabelNormal.getColor())); + } + } public final int groupId; public final boolean crafting; @@ -32,16 +125,9 @@ public class RecipeChainTooltipLineHandler implements ITooltipLineHandler { protected final List initialItems; protected final Map outputRecipes; - protected ItemsTooltipLineHandler available; - protected ItemsTooltipLineHandler inputs; - protected ItemsTooltipLineHandler outputs; - protected ItemsTooltipLineHandler remainder; - protected ItemsTooltipLineHandler craftingNeeded; protected boolean lastShiftKey = false; protected boolean lastControlKey = false; - protected Dimension size = new Dimension(); - public RecipeChainTooltipLineHandler(int groupId, boolean crafting, RecipeChainMath math) { this.groupId = groupId; this.crafting = crafting; @@ -50,20 +136,32 @@ public class RecipeChainTooltipLineHandler implements ITooltipLineHandler { this.outputRecipes = new HashMap<>(this.math.outputRecipes); } - private void onUpdate() { + @Override + protected boolean needsUpdate() { + final boolean shiftChanged = this.lastShiftKey != (this.lastShiftKey = NEIClientUtils.shiftKey()); + return this.lastControlKey != (this.lastControlKey = NEIClientUtils.controlKey()) || shiftChanged; + } + + @Override + protected void createLines() { + if (this.outputRecipes.isEmpty() && !this.lastShiftKey) { + return; + } + final List available = new ArrayList<>(); final List inputs = new ArrayList<>(); final List outputs = new ArrayList<>(); final List remainder = new ArrayList<>(); final List craftingNeeded = new ArrayList<>(); + final Map craftingHandlers = new HashMap<>(); final ItemStackAmount inventory = new ItemStackAmount(); final GuiContainer currentGui = NEIClientUtils.getGuiContainer(); - if (this.lastShiftKey && !(currentGui instanceof GuiRecipe)) { + if (this.lastShiftKey && currentGui != null && !(currentGui instanceof GuiRecipe)) { inventory.putAll(AutoCraftingManager.getInventoryItems(currentGui)); } - if (!this.math.outputRecipes.isEmpty()) { + if (!this.outputRecipes.isEmpty()) { this.math.initialItems.clear(); this.math.outputRecipes.clear(); this.math.outputRecipes.putAll(this.outputRecipes); @@ -105,7 +203,7 @@ public class RecipeChainTooltipLineHandler implements ITooltipLineHandler { } } else { - this.math.initialItems.addAll(initialItems); + this.math.initialItems.addAll(this.initialItems); } this.math.refresh(); @@ -138,26 +236,24 @@ public class RecipeChainTooltipLineHandler implements ITooltipLineHandler { if (amount > 0) { if (math.outputRecipes.containsKey(item.recipeId)) { outputs.add(item.getItemStack(amount)); - } else if (this.lastShiftKey) { + } else { remainder.add(item.getItemStack(amount)); } } } - if (this.lastShiftKey) { - for (ItemStack stack : math.containerItemsInventory) { - if (stack != null) { - remainder.add(stack.copy()); - } + for (ItemStack stack : math.containerItemsInventory) { + if (stack != null) { + remainder.add(stack.copy()); } - for (ItemStack stack : math.containerItemsCrafting) { - if (stack != null) { - remainder.add(stack.copy()); - } + } + for (ItemStack stack : math.containerItemsCrafting) { + if (stack != null) { + remainder.add(stack.copy()); } } - } else if (this.lastShiftKey) { + } else { for (BookmarkItem item : this.math.initialItems) { if (inventory.contains(item.itemStack)) { @@ -175,161 +271,100 @@ public class RecipeChainTooltipLineHandler implements ITooltipLineHandler { inputs.add(item.getItemStack()); } } - } + if (this.lastShiftKey) { for (Map.Entry item : this.math.requiredAmount.entrySet()) { - if (item.getKey().type == BookmarkItem.BookmarkItemType.RESULT && item.getValue() != 0) - craftingNeeded.add(item.getKey().getItemStack(item.getValue())); + if (item.getKey().type == BookmarkItem.BookmarkItemType.RESULT && item.getValue() != 0) { + final ItemStack stack = item.getKey().getItemStack(item.getValue()); + + craftingNeeded.add(stack); + putHandlerInfo(craftingHandlers, stack, item.getKey().recipeId); + } } } - inputs.sort( - Comparator.comparing((ItemStack stack) -> StackInfo.getFluid(stack) != null) - .thenComparingInt(stack -> -1 * stack.stackSize).thenComparing(ItemSorter.instance)); - outputs.sort( - Comparator.comparing((ItemStack stack) -> StackInfo.getFluid(stack) != null) - .thenComparingInt(stack -> -1 * stack.stackSize).thenComparing(ItemSorter.instance)); - remainder.sort( - Comparator.comparing((ItemStack stack) -> StackInfo.getFluid(stack) != null) - .thenComparingInt(stack -> -1 * stack.stackSize).thenComparing(ItemSorter.instance)); - - this.inputs = new ItemsTooltipLineHandler( - this.lastShiftKey ? NEIClientUtils.translate("bookmark.crafting_chain.missing") - : NEIClientUtils.translate("bookmark.crafting_chain.input"), - inputs, - true, - Integer.MAX_VALUE); - - this.available = new ItemsTooltipLineHandler( - NEIClientUtils.translate("bookmark.crafting_chain.available"), - available, - true, - Integer.MAX_VALUE); - - this.outputs = new ItemsTooltipLineHandler( - NEIClientUtils.translate("bookmark.crafting_chain.output"), - outputs, - true, - Integer.MAX_VALUE); - - this.remainder = new ItemsTooltipLineHandler( - NEIClientUtils.translate("bookmark.crafting_chain.remainder"), - remainder, - true, - Integer.MAX_VALUE); - - this.craftingNeeded = new ItemsTooltipLineHandler( - NEIClientUtils.translate("bookmark.crafting_chain.needed"), - craftingNeeded, - true, - Integer.MAX_VALUE); + final Set missing = new HashSet<>(); if (this.lastShiftKey) { - this.inputs.setLabelColor(EnumChatFormatting.RED); - this.available.setLabelColor(EnumChatFormatting.GREEN); - this.craftingNeeded.setLabelColor(EnumChatFormatting.BLUE); - } - - this.size.height = this.size.width = 0; - - if (!this.inputs.isEmpty() || !this.outputs.isEmpty() - || !this.remainder.isEmpty() - || !this.available.isEmpty()) { - - if (!this.math.outputRecipes.isEmpty()) { - this.size.height = 2 + GuiDraw.fontRenderer.FONT_HEIGHT; + for (ItemStack stack : inputs) { + missing.add(StackInfo.itemStackToNBT(stack, false)); } - this.size.width = Math.max( - this.inputs.getSize().width, - Math.max( - this.outputs.getSize().width, - Math.max( - this.remainder.getSize().width, - Math.max(this.available.getSize().width, this.craftingNeeded.getSize().width)))); - - this.size.height += this.inputs.getSize().height + this.outputs.getSize().height - + this.remainder.getSize().height - + this.available.getSize().height - + this.craftingNeeded.getSize().height; } + // items with a shortage are already in the inputs list, holding the missing amount instead of the required one + final List covered = new ArrayList<>(); + + for (ItemStack stack : available) { + if (!missing.contains(StackInfo.itemStackToNBT(stack, false))) { + covered.add(stack); + } + } + + final Comparator comparator = Comparator + .comparing((ItemStack stack) -> StackInfo.getFluid(stack) != null) + .thenComparingInt(stack -> -1 * stack.stackSize).thenComparing(ItemSorter.instance); + + inputs.sort(comparator); + covered.sort(comparator); + outputs.sort(comparator); + remainder.sort(comparator); + + // missing items stay on top of the list + inputs.addAll(covered); + + if (this.lastShiftKey) { + outputs.addAll(remainder); + } + + addLine( + NEIClientUtils.translate("bookmark.crafting_chain"), + outputs, + outputs.size() == 1, + EnumChatFormatting.AQUA, + new TotalAmountRenderer()); + + addLine( + NEIClientUtils.translate("bookmark.crafting_chain.needed"), + craftingNeeded, + false, + EnumChatFormatting.BLUE, + new HandlerIconRenderer(craftingHandlers)); + + addLine( + NEIClientUtils.translate("bookmark.crafting_chain.input"), + inputs, + this.lastShiftKey, + EnumChatFormatting.YELLOW, + this.lastShiftKey ? new MissingStacksAmountRenderer(missing) : new TotalAmountRenderer()); } - @Override - public Dimension getSize() { - boolean update = this.outputs == null; - update = this.lastShiftKey != (this.lastShiftKey = NEIClientUtils.shiftKey()) || update; - update = this.lastControlKey != (this.lastControlKey = NEIClientUtils.controlKey()) || update; - - if (update) { - onUpdate(); + protected static void putHandlerInfo(Map handlers, ItemStack stack, + RecipeId recipeId) { + if (recipeId == null) { + return; } - return this.size; + + final HandlerInfo handlerInfo = GuiRecipeTab.getHandlerInfo(recipeId.getHandlerName(), null); + + handlers.put( + StackInfo.itemStackToNBT(stack, false), + handlerInfo != null ? handlerInfo : GuiRecipeTab.DEFAULT_HANDLER_INFO); } - @Override - public void draw(int x, int y) { - if (this.size.height == 0) return; + protected void addLine(String label, List items, boolean vertical, EnumChatFormatting labelColor, + AmountRenderer amountRenderer) { + final ItemsTooltipLineHandler line = vertical ? ItemsTooltipLineHandler.list(label, items, maxLineRows()) + : ItemsTooltipLineHandler.grid(label, items, maxLineRows()); - if (!this.math.outputRecipes.isEmpty()) { - GuiDraw.fontRenderer.drawStringWithShadow( - EnumChatFormatting.AQUA + NEIClientUtils.translate("bookmark.crafting_chain"), - x, - y + 2, - 0xee555555); - - y += 2 + GuiDraw.fontRenderer.FONT_HEIGHT; + if (line.isEmpty()) { + return; } - if (NEIClientConfig.recipeChainDir() == 0) { - if (!this.inputs.isEmpty()) { - this.inputs.draw(x, y); - y += this.inputs.getSize().height; - } - - if (!this.available.isEmpty()) { - this.available.draw(x, y); - y += this.available.getSize().height; - } - - if (!this.craftingNeeded.isEmpty()) { - this.craftingNeeded.draw(x, y); - y += this.craftingNeeded.getSize().height; - } - - if (!this.outputs.isEmpty()) { - this.outputs.draw(x, y); - y += this.outputs.getSize().height; - } - - } else { - - if (!this.outputs.isEmpty()) { - this.outputs.draw(x, y); - y += this.outputs.getSize().height; - } - - if (!this.inputs.isEmpty()) { - this.inputs.draw(x, y); - y += this.inputs.getSize().height; - } - - if (!this.craftingNeeded.isEmpty()) { - this.craftingNeeded.draw(x, y); - y += this.craftingNeeded.getSize().height; - } - - if (!this.available.isEmpty()) { - this.available.draw(x, y); - y += this.available.getSize().height; - } - } - - if (!this.remainder.isEmpty()) { - this.remainder.draw(x, y); - } + line.setLabelColor(labelColor); + line.setAmountRenderer(amountRenderer); + this.lines.add(line); } } diff --git a/src/main/resources/assets/nei/lang/en_US.lang b/src/main/resources/assets/nei/lang/en_US.lang index 4e55a7e6..87874ab3 100644 --- a/src/main/resources/assets/nei/lang/en_US.lang +++ b/src/main/resources/assets/nei/lang/en_US.lang @@ -48,11 +48,7 @@ nei.bookmark.recipe.toggle_collapse=Toggle Collapse/Expand nei.bookmark.recipe.chat_link=Send Recipe to Chat nei.bookmark.crafting_chain=Crafting Chain nei.bookmark.crafting_chain.input=Ingredients -nei.bookmark.crafting_chain.missing=Missing Items -nei.bookmark.crafting_chain.output=Results -nei.bookmark.crafting_chain.remainder=Remainders nei.bookmark.crafting_chain.needed=Required Crafts -nei.bookmark.crafting_chain.available=Available Items nei.bookmark.tree.title=Crafting Tree nei.bookmark.tree.empty=No crafting chain to display nei.bookmark.tree.overlay=Use for recipe tree @@ -284,9 +280,6 @@ nei.options.inventory.bookmarks.enabled.false=Hidden nei.options.inventory.bookmarks.animation=REI Style Animation in Bookmarks nei.options.inventory.bookmarks.animation.true=Yes nei.options.inventory.bookmarks.animation.false=No -nei.options.inventory.bookmarks.recipeChainDir=Crafting Chain Info Direction -nei.options.inventory.bookmarks.recipeChainDir.0=Input First -nei.options.inventory.bookmarks.recipeChainDir.1=Output First nei.options.inventory.bookmarks.recipeTooltipsMode=Show Recipe Tooltips in Bookmarks nei.options.inventory.bookmarks.recipeTooltipsMode.0=None nei.options.inventory.bookmarks.recipeTooltipsMode.1=In Horizontal View diff --git a/src/main/resources/assets/nei/lang/ru_RU.lang b/src/main/resources/assets/nei/lang/ru_RU.lang index 6a1da14f..5e170214 100644 --- a/src/main/resources/assets/nei/lang/ru_RU.lang +++ b/src/main/resources/assets/nei/lang/ru_RU.lang @@ -23,8 +23,6 @@ nei.bookmark.group.pull_items_shift=Переместить недостающи nei.bookmark.group.chat_link=Отправить группу в чат nei.bookmark.crafting_chain=Цепочка крафта nei.bookmark.crafting_chain.input=Ингредиенты -nei.bookmark.crafting_chain.output=Результаты -nei.bookmark.crafting_chain.remainder=Остатки nei.itempanel.quantity.default=Одна стопка nei.itempanel.loading=Загрузка списка предметов... @@ -184,9 +182,6 @@ nei.options.inventory.bookmarks.enabled.false=Скрытая nei.options.inventory.bookmarks.animation=Анимация в стиле REI в закладках nei.options.inventory.bookmarks.animation.true=Да nei.options.inventory.bookmarks.animation.false=Нет -nei.options.inventory.bookmarks.recipeChainDir=Направление информации о цепочке крафта -nei.options.inventory.bookmarks.recipeChainDir.0=Сначала ингредиенты -nei.options.inventory.bookmarks.recipeChainDir.1=Сначала результат nei.options.inventory.bookmarks.recipeTooltipsMode=Показывать подсказки рецептов в закладках nei.options.inventory.bookmarks.recipeTooltipsMode.0=Нет nei.options.inventory.bookmarks.recipeTooltipsMode.1=В горизонтальном виде diff --git a/src/main/resources/assets/nei/lang/uk_UA.lang b/src/main/resources/assets/nei/lang/uk_UA.lang index 69a162bc..fb802921 100644 --- a/src/main/resources/assets/nei/lang/uk_UA.lang +++ b/src/main/resources/assets/nei/lang/uk_UA.lang @@ -47,11 +47,7 @@ nei.bookmark.recipe.toggle_collapse=Згорнути/Розгорнути nei.bookmark.recipe.chat_link=Надіслати рецепт у чат nei.bookmark.crafting_chain=Ланцюжок крафту nei.bookmark.crafting_chain.input=Інгредієнти -nei.bookmark.crafting_chain.missing=Відсутні предмети -nei.bookmark.crafting_chain.output=Результати -nei.bookmark.crafting_chain.remainder=Залишки nei.bookmark.crafting_chain.needed=Необхідні крафти -nei.bookmark.crafting_chain.available=Доступні предмети nei.inventory.search.placeholder=Пошук... nei.itempanel.quantity.default=Один стек nei.itempanel.loading=Завантаження списку предметів... @@ -236,9 +232,6 @@ nei.options.inventory.bookmarks.enabled.false=Прихована nei.options.inventory.bookmarks.animation=Анімація закладок у стилі REI nei.options.inventory.bookmarks.animation.true=Так nei.options.inventory.bookmarks.animation.false=Ні -nei.options.inventory.bookmarks.recipeChainDir=Напрямок ланцюжка крафту -nei.options.inventory.bookmarks.recipeChainDir.0=Спочатку інгредієнти -nei.options.inventory.bookmarks.recipeChainDir.1=Спочатку результат nei.options.inventory.bookmarks.recipeTooltipsMode=Показувати підказки рецептів у закладках nei.options.inventory.bookmarks.recipeTooltipsMode.0=Ніколи nei.options.inventory.bookmarks.recipeTooltipsMode.1=У горизонтальному вигляді From 55c9811a2b747c4e4a6e4744457f4e78ce6a01cc Mon Sep 17 00:00:00 2001 From: slprime <31038811+slprime@users.noreply.github.com> Date: Fri, 25 Sep 2026 22:17:38 +0300 Subject: [PATCH 03/11] Fix search autofocus losing the first typed character (#1045) --- .../java/codechicken/nei/AutoFocusWidget.java | 81 ++++++++++++++++--- .../java/codechicken/nei/LayoutManager.java | 2 + 2 files changed, 70 insertions(+), 13 deletions(-) diff --git a/src/main/java/codechicken/nei/AutoFocusWidget.java b/src/main/java/codechicken/nei/AutoFocusWidget.java index e0b553ef..583e1275 100644 --- a/src/main/java/codechicken/nei/AutoFocusWidget.java +++ b/src/main/java/codechicken/nei/AutoFocusWidget.java @@ -7,8 +7,10 @@ import java.util.ArrayList; import java.util.List; import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiTextField; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.settings.GameSettings; +import net.minecraft.util.ChatAllowedCharacters; import org.lwjgl.input.Keyboard; @@ -30,6 +32,8 @@ public class AutoFocusWidget implements IContainerInputHandler { protected boolean autofocus = false; protected Point mouse; + protected Point pendingMouse; + protected GuiTextField textInputHolder; public AutoFocusWidget() { GuiContainerManager.addInputHandler(this); @@ -38,32 +42,83 @@ public class AutoFocusWidget implements IContainerInputHandler { public void load(GuiContainer gui) { this.autofocus = LayoutManager.searchField.isVisible() && NEIClientConfig.searchWidgetAutofocus() != 0 && isAllowedGuiAutoSearchFocus(gui); - this.mouse = getMousePosition(); + this.mouse = null; + this.pendingMouse = null; + + if (this.autofocus) { + beginTextInput(); + } + } + + protected void beginTextInput() { + if (this.textInputHolder == null) { + this.textInputHolder = new GuiTextField(Minecraft.getMinecraft().fontRenderer, 0, 0, 0, 0); + } + + this.textInputHolder.setFocused(true); + } + + protected void endTextInput() { + if (this.textInputHolder != null) { + this.textInputHolder.setFocused(false); + } + } + + public void guiTick() { + if (!this.autofocus) { + return; + } + + final Point current = getMousePosition(); + + if (this.mouse == null) { + if (current.equals(this.pendingMouse)) { + this.mouse = current; + } + + this.pendingMouse = current; + } else if (!this.mouse.equals(current)) { + cancel(); + } + } + + protected void cancel() { + if (this.autofocus) { + this.autofocus = false; + endTextInput(); + } } @Override public boolean keyTyped(GuiContainer gui, char keyChar, int keyCode) { if (this.autofocus) { - this.autofocus = false; - - if (!this.mouse.equals(getMousePosition())) { - return false; - } if (NEIClientConfig.searchWidgetAutofocus() == 2 && GameSettings.isKeyDown(Minecraft.getMinecraft().gameSettings.keyBindInventory)) { + cancel(); return false; } if (keyCode == Keyboard.KEY_RETURN || keyCode == Keyboard.KEY_NUMPADENTER || keyCode == Keyboard.KEY_ESCAPE) { + cancel(); return false; } + if (!ChatAllowedCharacters.isAllowedCharacter(keyChar)) { + return false; + } + + this.autofocus = false; + LayoutManager.searchField.setFocus(true); + endTextInput(); + + final String oldText = LayoutManager.searchField.text(); LayoutManager.searchField.handleKeyPress(keyCode, keyChar); - return true; + + return !LayoutManager.searchField.text().equals(oldText); } return false; @@ -76,13 +131,13 @@ public class AutoFocusWidget implements IContainerInputHandler { @Override public boolean mouseClicked(GuiContainer gui, int mousex, int mousey, int button) { - this.autofocus = false; + cancel(); return false; } @Override public boolean mouseScrolled(GuiContainer gui, int mousex, int mousey, int scrolled) { - this.autofocus = false; + cancel(); return false; } @@ -91,22 +146,22 @@ public class AutoFocusWidget implements IContainerInputHandler { @Override public void onMouseClicked(GuiContainer gui, int mousex, int mousey, int button) { - this.autofocus = false; + cancel(); } @Override public void onMouseDragged(GuiContainer gui, int mousex, int mousey, int button, long heldTime) { - this.autofocus = false; + cancel(); } @Override public void onMouseScrolled(GuiContainer gui, int mousex, int mousey, int scrolled) { - this.autofocus = false; + cancel(); } @Override public void onMouseUp(GuiContainer gui, int mousex, int mousey, int button) { - this.autofocus = false; + cancel(); } protected boolean isAllowedGuiAutoSearchFocus(GuiContainer gui) { diff --git a/src/main/java/codechicken/nei/LayoutManager.java b/src/main/java/codechicken/nei/LayoutManager.java index bb10c9d6..9db9e197 100644 --- a/src/main/java/codechicken/nei/LayoutManager.java +++ b/src/main/java/codechicken/nei/LayoutManager.java @@ -803,6 +803,8 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH if (!isEnabled()) return; + AutoFocusWidget.instance.guiTick(); + for (Widget widget : drawWidgets) widget.update(); } From 382278bebb94a1e97db93e0b51b97a5662ad21ff Mon Sep 17 00:00:00 2001 From: slprime <31038811+slprime@users.noreply.github.com> Date: Fri, 25 Sep 2026 23:36:57 +0300 Subject: [PATCH 04/11] Fix Keybinding Category Names (#1046) --- src/main/resources/assets/nei/lang/cs_CZ.lang | 4 ++-- src/main/resources/assets/nei/lang/de_DE.lang | 4 ++-- src/main/resources/assets/nei/lang/et_EE.lang | 4 ++-- src/main/resources/assets/nei/lang/fr_FR.lang | 4 ++-- src/main/resources/assets/nei/lang/it_IT.lang | 4 ++-- src/main/resources/assets/nei/lang/ko_KR.lang | 4 ++-- src/main/resources/assets/nei/lang/pl_PL.lang | 4 ++-- src/main/resources/assets/nei/lang/pt_BR.lang | 4 ++-- src/main/resources/assets/nei/lang/sk_SK.lang | 4 ++-- src/main/resources/assets/nei/lang/tr_TR.lang | 4 ++-- src/main/resources/assets/nei/lang/zh_CN.lang | 4 ++-- src/main/resources/assets/nei/lang/zh_TW.lang | 4 ++-- 12 files changed, 24 insertions(+), 24 deletions(-) diff --git a/src/main/resources/assets/nei/lang/cs_CZ.lang b/src/main/resources/assets/nei/lang/cs_CZ.lang index 1cc75c88..51919a9c 100644 --- a/src/main/resources/assets/nei/lang/cs_CZ.lang +++ b/src/main/resources/assets/nei/lang/cs_CZ.lang @@ -59,7 +59,7 @@ nei.options.wbutton.tip.0=Používám globální nastavení nei.options.wbutton.tip.1=Přepisuji globální nastavení nei.options.keys=Nastavení kláves -nei.options.keys.gui=Inventář +nei.options.keys.gui=NEI Inventář nei.options.keys.recipe.recipe=Recept nei.options.keys.recipe.usage=Použití nei.options.keys.gui.enchant=Očarování @@ -69,7 +69,7 @@ nei.options.keys.gui.prev=Předchozí stránka nei.options.keys.gui.next=Další stránka nei.options.keys.gui.hide=Přepnout viditelnost NEI nei.options.keys.gui.search=Zaměřit vyhledávací pole -nei.options.keys.world=Svět +nei.options.keys.world=NEI Svět nei.options.keys.world.chunkoverlay=Ohraničení chunku nei.options.keys.world.moboverlay=Označení míst spawnu monster nei.options.keys.world.highlight_tips=Informace o bloku diff --git a/src/main/resources/assets/nei/lang/de_DE.lang b/src/main/resources/assets/nei/lang/de_DE.lang index acd407f0..0e592bff 100644 --- a/src/main/resources/assets/nei/lang/de_DE.lang +++ b/src/main/resources/assets/nei/lang/de_DE.lang @@ -63,7 +63,7 @@ nei.options.wbutton.tip.0=Nutzt globale Einstellungen nei.options.wbutton.tip.1=Übergeht globale Einstellungen nei.options.keys=Tastenbelegung -nei.options.keys.gui=Inventar +nei.options.keys.gui=NEI Inventar nei.options.keys.recipe.recipe=Rezept nei.options.keys.recipe.usage=Nutzung nei.options.keys.gui.enchant=Verzauberungen @@ -73,7 +73,7 @@ nei.options.keys.gui.prev=Vorherige Seite nei.options.keys.gui.next=Nächste Seite nei.options.keys.gui.hide=Verstelle NEI-Sichtbarkeit nei.options.keys.gui.search=Fokussiere Such-Leiste -nei.options.keys.world=Welt +nei.options.keys.world=NEI Welt nei.options.keys.world.chunkoverlay=Chunk-Grenzen-Overlay nei.options.keys.world.moboverlay=Mob-Spawn-Overlay nei.options.keys.world.highlight_tips=Highlight-Tooltips diff --git a/src/main/resources/assets/nei/lang/et_EE.lang b/src/main/resources/assets/nei/lang/et_EE.lang index 5e3e834c..14c90a8e 100644 --- a/src/main/resources/assets/nei/lang/et_EE.lang +++ b/src/main/resources/assets/nei/lang/et_EE.lang @@ -62,7 +62,7 @@ nei.options.wbutton.tip.0=Kasutab globaalseid seadeid nei.options.wbutton.tip.1=Globaalsete seadmete ületegemine nei.options.keys=Klahviseosed -nei.options.keys.gui=Seljakott +nei.options.keys.gui=NEI Seljakott nei.options.keys.recipe.recipe=Retsept nei.options.keys.recipe.usage=Kasutus nei.options.keys.gui.enchant=Loitsud @@ -72,7 +72,7 @@ nei.options.keys.gui.prev=Eel. Leht nei.options.keys.gui.next=Järg. Leht nei.options.keys.gui.hide=Lülita NEI nähtavust nei.options.keys.gui.search=Fokuseeri otsingu riba -nei.options.keys.world=Maailm +nei.options.keys.world=NEI Maailm nei.options.keys.world.chunkoverlay=Chunk'i ääre ülekate nei.options.keys.world.moboverlay=Koletiste sündimis ülekate nei.options.keys.world.highlight_tips=Highlight Tooltips diff --git a/src/main/resources/assets/nei/lang/fr_FR.lang b/src/main/resources/assets/nei/lang/fr_FR.lang index f2e3eca2..59a90e97 100644 --- a/src/main/resources/assets/nei/lang/fr_FR.lang +++ b/src/main/resources/assets/nei/lang/fr_FR.lang @@ -60,7 +60,7 @@ nei.options.wbutton.tip.0=Utilisation des paramètres globaux nei.options.wbutton.tip.1=Annuler l'utilisation des paramètres globaux nei.options.keys=Raccourcis clavier -nei.options.keys.gui=Inventaire +nei.options.keys.gui=NEI Inventaire nei.options.keys.recipe.recipe=Recette nei.options.keys.recipe.usage=Usage nei.options.keys.gui.enchant=Enchantements @@ -70,7 +70,7 @@ nei.options.keys.gui.prev=Recette suivante nei.options.keys.gui.next=Page suivante nei.options.keys.gui.hide=Afficher ou cacher NEI nei.options.keys.gui.search=Sélectionner la barre de recherche -nei.options.keys.world=Monde +nei.options.keys.world=NEI Monde nei.options.keys.world.chunkoverlay=Overlay limitation des chunks nei.options.keys.world.moboverlay=Overlay spawn des monstres nei.options.keys.world.highlight_tips=Mettez en surbrillance les info-bulles diff --git a/src/main/resources/assets/nei/lang/it_IT.lang b/src/main/resources/assets/nei/lang/it_IT.lang index 65b3c7e7..3e7e8afc 100644 --- a/src/main/resources/assets/nei/lang/it_IT.lang +++ b/src/main/resources/assets/nei/lang/it_IT.lang @@ -63,7 +63,7 @@ nei.options.wbutton.tip.0=Usando le opzioni globali nei.options.wbutton.tip.1=Sovrascrivendo le opzioni globali nei.options.keys=Controlli -nei.options.keys.gui=Inventario +nei.options.keys.gui=NEI Inventario nei.options.keys.recipe.recipe=Ricetta nei.options.keys.recipe.usage=Usi nei.options.keys.gui.enchant=Incantare @@ -73,7 +73,7 @@ nei.options.keys.gui.prev=Pagina precedente nei.options.keys.gui.next=Pagina successiva nei.options.keys.gui.hide=Modifica visibilità NEI nei.options.keys.gui.search=Attiva barra di ricerca -nei.options.keys.world=Mondo +nei.options.keys.world=NEI Mondo nei.options.keys.world.chunkoverlay=Mostra confini dei chunk nei.options.keys.world.moboverlay=Mostra spawn dei mob nei.options.keys.world.highlight_tips=Esalta tooltips diff --git a/src/main/resources/assets/nei/lang/ko_KR.lang b/src/main/resources/assets/nei/lang/ko_KR.lang index 388c1691..f19581c1 100644 --- a/src/main/resources/assets/nei/lang/ko_KR.lang +++ b/src/main/resources/assets/nei/lang/ko_KR.lang @@ -58,7 +58,7 @@ nei.options.wbutton.tip.0=글로벌로 세팅 nei.options.wbutton.tip.1=전역 설정 nei.options.keys=키 바인딩 -nei.options.keys.gui=인벤토리 +nei.options.keys.gui=NEI 인벤토리 nei.options.keys.recipe.recipe=레시피 nei.options.keys.recipe.usage=사용법 nei.options.keys.gui.enchant=인첸트 @@ -68,7 +68,7 @@ nei.options.keys.gui.prev=이전 페이지 nei.options.keys.gui.next=다음 페이지 nei.options.keys.gui.hide=NEI 활성/비활성화 nei.options.keys.gui.search=빠른 검색 -nei.options.keys.world=월드 +nei.options.keys.world=NEI 월드 nei.options.keys.world.chunkoverlay=청크경계 확인 nei.options.keys.world.moboverlay=몹스폰 확인 nei.options.keys.world.highlight_tips=하이라이트 툴팁 diff --git a/src/main/resources/assets/nei/lang/pl_PL.lang b/src/main/resources/assets/nei/lang/pl_PL.lang index 679d4e91..3cbbedb2 100644 --- a/src/main/resources/assets/nei/lang/pl_PL.lang +++ b/src/main/resources/assets/nei/lang/pl_PL.lang @@ -59,7 +59,7 @@ nei.options.wbutton.tip.0=Używanie ustawień globalnych nei.options.wbutton.tip.1=Nadpisywanie ustawienia globalnego nei.options.keys=Ustawienia klawiszy -nei.options.keys.gui=Ekwipunek +nei.options.keys.gui=NEI Ekwipunek nei.options.keys.recipe.recipe=Recepta nei.options.keys.recipe.usage=Użytek nei.options.keys.gui.enchant=Zaklęcia @@ -69,7 +69,7 @@ nei.options.keys.gui.prev=Poprzednia strona nei.options.keys.gui.next=Następna strona nei.options.keys.gui.hide=Przełącz widzialność NEI nei.options.keys.gui.search=Ustaw ostrość na pasek wyszukiwania -nei.options.keys.world=Świat +nei.options.keys.world=NEI Świat nei.options.keys.world.chunkoverlay=Nakładka granic chunków nei.options.keys.world.moboverlay=Nakładka pojawiania się mobów nei.options.keys.world.highlight_tips=Podpowiedzi podświetleń diff --git a/src/main/resources/assets/nei/lang/pt_BR.lang b/src/main/resources/assets/nei/lang/pt_BR.lang index c8b20d37..10885ad9 100644 --- a/src/main/resources/assets/nei/lang/pt_BR.lang +++ b/src/main/resources/assets/nei/lang/pt_BR.lang @@ -59,7 +59,7 @@ nei.options.wbutton.tip.0=Usando configurações globais nei.options.wbutton.tip.1=Substituindo configurações globais nei.options.keys=Atalhos de Teclado -nei.options.keys.gui=Inventário +nei.options.keys.gui=NEI Inventário nei.options.keys.recipe.recipe=Receita nei.options.keys.recipe.usage=Uso nei.options.keys.gui.enchant=Encantamentos @@ -69,7 +69,7 @@ nei.options.keys.gui.prev=Pág. Anterior nei.options.keys.gui.next=Próxima Pág. nei.options.keys.gui.hide=Trocar Visibilidade do NEI nei.options.keys.gui.search=Focar na Barra de Buscas -nei.options.keys.world=Mundo +nei.options.keys.world=NEI Mundo nei.options.keys.world.chunkoverlay=Sobreposição de Fronteira de Chunks nei.options.keys.world.moboverlay=Sobreposição de Spawn de Mobs nei.options.keys.world.highlight_tips=Destacar Dicas diff --git a/src/main/resources/assets/nei/lang/sk_SK.lang b/src/main/resources/assets/nei/lang/sk_SK.lang index 093a7ea0..efa02c09 100644 --- a/src/main/resources/assets/nei/lang/sk_SK.lang +++ b/src/main/resources/assets/nei/lang/sk_SK.lang @@ -59,7 +59,7 @@ nei.options.wbutton.tip.0=Používajú sa globálne nastavenia nei.options.wbutton.tip.1=Globálne nastavenia sú nahradené nei.options.keys=Klávesové skratky -nei.options.keys.gui=Inventár +nei.options.keys.gui=NEI Inventár nei.options.keys.recipe.recipe=Recept nei.options.keys.recipe.usage=Použitie nei.options.keys.gui.enchant=Očarovania @@ -69,7 +69,7 @@ nei.options.keys.gui.prev=Predchádzajúca strana nei.options.keys.gui.next=Nasledujúca strana nei.options.keys.gui.hide=Prepni viditeľnosť NEI nei.options.keys.gui.search=Zamerania na vyhľadávací riadok -nei.options.keys.world=Svet +nei.options.keys.world=NEI Svet nei.options.keys.world.chunkoverlay=Vrstva hraníc chunkov nei.options.keys.world.moboverlay=Vrstva zrodenia sa monštier nei.options.keys.world.highlight_tips=Zvýraznenie opisov diff --git a/src/main/resources/assets/nei/lang/tr_TR.lang b/src/main/resources/assets/nei/lang/tr_TR.lang index 3492ec93..ebfd2825 100644 --- a/src/main/resources/assets/nei/lang/tr_TR.lang +++ b/src/main/resources/assets/nei/lang/tr_TR.lang @@ -59,7 +59,7 @@ nei.options.wbutton.tip.0=Genel ayarları kullanıyorsunuz nei.options.wbutton.tip.1=Genel ayarların üstüne yazılıyor nei.options.keys=Tuşlar -nei.options.keys.gui=Envanter +nei.options.keys.gui=NEI Envanter nei.options.keys.recipe.recipe=Tarifler nei.options.keys.recipe.usage=Kullanım yeri nei.options.keys.gui.enchant=Büylüler @@ -69,7 +69,7 @@ nei.options.keys.gui.prev=Önceki sayfa nei.options.keys.gui.next=Sonraki sayfa nei.options.keys.gui.hide=Nei görünürlük ayarı nei.options.keys.gui.search=Arama çubuğu odağı -nei.options.keys.world=Dünya +nei.options.keys.world=NEI Dünya nei.options.keys.world.chunkoverlay=Chunk sınır yerleşimi nei.options.keys.world.moboverlay=Mob Spawn yerleşimi nei.options.keys.world.highlight_tips=Nesne ipucu diff --git a/src/main/resources/assets/nei/lang/zh_CN.lang b/src/main/resources/assets/nei/lang/zh_CN.lang index 67767661..886a8082 100644 --- a/src/main/resources/assets/nei/lang/zh_CN.lang +++ b/src/main/resources/assets/nei/lang/zh_CN.lang @@ -88,7 +88,7 @@ nei.options.wbutton.tip.1=覆写全局设置 nei.options.keys=按键绑定 nei.options.keys.showenchant=显示附魔值 -nei.options.keys.gui=物品栏 +nei.options.keys.gui=NEI 物品栏 nei.options.keys.recipe.recipe=查看合成 nei.options.keys.recipe.usage=查看用途 nei.options.keys.gui.enchant=附魔 @@ -110,7 +110,7 @@ nei.options.keys.gui.getnextsearch=下一个搜索 nei.options.keys.copy.name=复制物品名称 (Ctrl +) nei.options.keys.copy.oredict=复制物品矿词词典 (Ctrl +) nei.options.keys.copy.identifier=复制物品ID (Ctrl +) -nei.options.keys.world=世界 +nei.options.keys.world=NEI 世界 nei.options.keys.world.chunkoverlay=区块(chunks)边界显示 nei.options.keys.world.moboverlay=刷怪区域显示 nei.options.keys.world.highlight_tips=显示选中方块名称 diff --git a/src/main/resources/assets/nei/lang/zh_TW.lang b/src/main/resources/assets/nei/lang/zh_TW.lang index 098d5a5d..af644f22 100644 --- a/src/main/resources/assets/nei/lang/zh_TW.lang +++ b/src/main/resources/assets/nei/lang/zh_TW.lang @@ -58,7 +58,7 @@ nei.options.wbutton.tip.0=使用全局設定 nei.options.wbutton.tip.1=覆蓋全局設定 nei.options.keys=按鍵設定 -nei.options.keys.gui=物品欄 +nei.options.keys.gui=NEI 物品欄 nei.options.keys.recipe.recipe=合成表 nei.options.keys.recipe.usage=用途 nei.options.keys.gui.enchant=附魔 @@ -68,7 +68,7 @@ nei.options.keys.gui.prev=上一頁 nei.options.keys.gui.next=下一頁 nei.options.keys.gui.hide=隱藏/顯示NEI界面 nei.options.keys.gui.search=焦點搜索欄 -nei.options.keys.world=世界 +nei.options.keys.world=NEI 世界 nei.options.keys.world.chunkoverlay=區塊邊界顯示 nei.options.keys.world.moboverlay=怪物生成區域顯示 nei.options.keys.world.highlight_tips=高亮工具提示 From 3c472a02cb349f34d98e6b5131936167cb7e3cba Mon Sep 17 00:00:00 2001 From: slprime <31038811+slprime@users.noreply.github.com> Date: Sat, 26 Sep 2026 01:06:38 +0300 Subject: [PATCH 05/11] Add Flowinf Texture to PositionStack (#1047) --- .../java/codechicken/nei/PositionedStack.java | 106 +++++++---------- .../codechicken/nei/item/FluidDrawer.java | 108 ++++++++++++++++++ .../resources/assets/nei/csv/handlers.csv | 8 +- 3 files changed, 154 insertions(+), 68 deletions(-) create mode 100644 src/main/java/codechicken/nei/item/FluidDrawer.java diff --git a/src/main/java/codechicken/nei/PositionedStack.java b/src/main/java/codechicken/nei/PositionedStack.java index c892b424..5cbd657b 100644 --- a/src/main/java/codechicken/nei/PositionedStack.java +++ b/src/main/java/codechicken/nei/PositionedStack.java @@ -6,22 +6,18 @@ import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.client.renderer.texture.TextureMap; 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.FluidStack; import net.minecraftforge.oredict.OreDictionary; -import org.lwjgl.opengl.GL11; - import codechicken.nei.api.ItemFilter; import codechicken.nei.api.ItemInfo; import codechicken.nei.guihook.GuiContainerManager; +import codechicken.nei.item.FluidDrawer; +import codechicken.nei.item.FluidDrawer.FillDirection; import codechicken.nei.recipe.Badge; import codechicken.nei.recipe.GuiRecipe; import codechicken.nei.recipe.StackInfo; @@ -255,7 +251,9 @@ public class PositionedStack implements Cloneable { public static class Fluid extends PositionedStack { /** The tank size the fill level is measured against, in mB. 0 means "always render full". */ - public int capacity = 0; + protected int capacity = 0; + protected boolean flowingTexture = false; + protected FillDirection fillDirection = FillDirection.AUTO; private ItemStack cachedFluidItem; private FluidStack cachedFluidStack; @@ -272,7 +270,34 @@ public class PositionedStack implements Cloneable { super(object, x, y, false); this.width = width; this.height = height; - this.capacity = capacity; + setCapacity(capacity); + } + + public int getCapacity() { + return this.capacity; + } + + public Fluid setCapacity(int capacity) { + this.capacity = Math.max(capacity, 0); + return this; + } + + public boolean hasFlowingTexture() { + return this.flowingTexture; + } + + public Fluid setFlowingTexture(boolean flowingTexture) { + this.flowingTexture = flowingTexture; + return this; + } + + public FillDirection getFillDirection() { + return this.fillDirection; + } + + public Fluid setFillDirection(FillDirection fillDirection) { + this.fillDirection = fillDirection == null ? FillDirection.AUTO : fillDirection; + return this; } protected FluidStack getFluidStack() { @@ -313,62 +338,15 @@ public class PositionedStack implements Cloneable { return; } - final int tankCapacity = this.capacity > 0 ? this.capacity : fluidStack.amount; - int fillHeight = tankCapacity > 0 - ? (int) ((long) this.height * Math.min(fluidStack.amount, tankCapacity) / tankCapacity) - : 0; - - if (fluidStack.amount > 0 && fillHeight <= 0) { - fillHeight = 1; - } - - if (fillHeight > 0) { - drawFluid(this.relx, this.rely, this.width, this.height, fillHeight, fluidStack); - } - } - - private static void drawFluid(int x, int y, int width, int height, int fillHeight, FluidStack fluidStack) { - final IIcon icon = fluidStack.getFluid().getIcon(fluidStack); - - if (icon == null) { - return; - } - - final int color = fluidStack.getFluid().getColor(fluidStack); - final float red = (color >> 16 & 0xFF) / 255F; - final float green = (color >> 8 & 0xFF) / 255F; - final float blue = (color & 0xFF) / 255F; - - Minecraft.getMinecraft().getTextureManager().bindTexture(TextureMap.locationBlocksTexture); - GL11.glColor4f(red, green, blue, 1F); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - GL11.glDisable(GL11.GL_LIGHTING); - - final Tessellator tessellator = Tessellator.instance; - - tessellator.startDrawingQuads(); - for (int tx = 0; tx < width; tx += 16) { - final int tileWidth = Math.min(16, width - tx); - final double u2 = icon.getMinU() + (icon.getMaxU() - icon.getMinU()) * tileWidth / 16D; - - for (int ty = 0; ty < fillHeight; ty += 16) { - final int tileHeight = Math.min(16, fillHeight - ty); - final double v2 = icon.getMinV() + (icon.getMaxV() - icon.getMinV()) * tileHeight / 16D; - final int bottomY = y + height - ty; - final int topY = bottomY - tileHeight; - - tessellator.addVertexWithUV(x + tx, bottomY, 0, icon.getMinU(), v2); - tessellator.addVertexWithUV(x + tx + tileWidth, bottomY, 0, u2, v2); - tessellator.addVertexWithUV(x + tx + tileWidth, topY, 0, u2, icon.getMinV()); - tessellator.addVertexWithUV(x + tx, topY, 0, icon.getMinU(), icon.getMinV()); - } - } - tessellator.draw(); - - GL11.glDisable(GL11.GL_BLEND); - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glColor4f(1F, 1F, 1F, 1F); + FluidDrawer.drawFluid( + this.relx, + this.rely, + this.width, + this.height, + this.capacity, + fluidStack, + this.flowingTexture, + this.fillDirection); } } } diff --git a/src/main/java/codechicken/nei/item/FluidDrawer.java b/src/main/java/codechicken/nei/item/FluidDrawer.java new file mode 100644 index 00000000..78886959 --- /dev/null +++ b/src/main/java/codechicken/nei/item/FluidDrawer.java @@ -0,0 +1,108 @@ +package codechicken.nei.item; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.texture.TextureMap; +import net.minecraft.util.IIcon; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; + +import org.lwjgl.opengl.GL11; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +@SideOnly(Side.CLIENT) +public class FluidDrawer { + + public enum FillDirection { + + AUTO, + UP, + DOWN, + LEFT, + RIGHT; + + public boolean isHorizontal() { + return this == LEFT || this == RIGHT; + } + + public FillDirection resolve(FluidStack fluidStack) { + if (this != AUTO) return this; + return fluidStack.getFluid().isGaseous(fluidStack) ? DOWN : UP; + } + } + + private FluidDrawer() {} + + public static void drawFluid(int x, int y, int width, int height, int capacity, FluidStack fluidStack, + boolean flowing, FillDirection direction) { + final Fluid fluid = fluidStack.getFluid(); + IIcon icon = flowing ? fluid.getFlowingIcon() : null; + + if (icon == null) { + icon = fluid.getIcon(fluidStack); + } + + if (icon == null || fluidStack.amount <= 0) { + return; + } + + direction = direction.resolve(fluidStack); + + final int tankSize = direction.isHorizontal() ? width : height; + final int tankCapacity = capacity > 0 ? capacity : fluidStack.amount; + final int fillSize = Math + .max(1, (int) ((long) tankSize * Math.min(fluidStack.amount, tankCapacity) / tankCapacity)); + + final int fillWidth = direction.isHorizontal() ? Math.min(fillSize, width) : width; + final int fillHeight = direction.isHorizontal() ? height : Math.min(fillSize, height); + final int fillX = direction == FillDirection.LEFT ? x + width - fillWidth : x; + final int fillY = direction == FillDirection.DOWN ? y : y + height - fillHeight; + final boolean anchorRight = direction == FillDirection.LEFT; + final boolean anchorBottom = direction != FillDirection.DOWN; + + final int color = fluid.getColor(fluidStack); + final float red = (color >> 16 & 0xFF) / 255F; + final float green = (color >> 8 & 0xFF) / 255F; + final float blue = (color & 0xFF) / 255F; + + Minecraft.getMinecraft().getTextureManager().bindTexture(TextureMap.locationBlocksTexture); + GL11.glColor3f(red, green, blue); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glDisable(GL11.GL_LIGHTING); + + final Tessellator tessellator = Tessellator.instance; + + tessellator.startDrawingQuads(); + for (int tx = 0; tx < fillWidth; tx += 16) { + final int tileWidth = Math.min(16, fillWidth - tx); + // a cropped tile keeps the texture edge that stays seamless against the neighbouring tile + final double uSize = (icon.getMaxU() - icon.getMinU()) * tileWidth / 16D; + final double uMin = anchorRight ? icon.getMaxU() - uSize : icon.getMinU(); + final double uMax = anchorRight ? icon.getMaxU() : icon.getMinU() + uSize; + final int leftX = anchorRight ? fillX + fillWidth - tx - tileWidth : fillX + tx; + final int rightX = leftX + tileWidth; + + for (int ty = 0; ty < fillHeight; ty += 16) { + final int tileHeight = Math.min(16, fillHeight - ty); + final double vSize = (icon.getMaxV() - icon.getMinV()) * tileHeight / 16D; + final double vMin = anchorBottom ? icon.getMaxV() - vSize : icon.getMinV(); + final double vMax = anchorBottom ? icon.getMaxV() : icon.getMinV() + vSize; + final int bottomY = anchorBottom ? fillY + fillHeight - ty : fillY + ty + tileHeight; + final int topY = bottomY - tileHeight; + + tessellator.addVertexWithUV(leftX, bottomY, 0, uMin, vMax); + tessellator.addVertexWithUV(rightX, bottomY, 0, uMax, vMax); + tessellator.addVertexWithUV(rightX, topY, 0, uMax, vMin); + tessellator.addVertexWithUV(leftX, topY, 0, uMin, vMin); + } + } + tessellator.draw(); + + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glColor4f(1F, 1F, 1F, 1F); + } +} diff --git a/src/main/resources/assets/nei/csv/handlers.csv b/src/main/resources/assets/nei/csv/handlers.csv index 3595981e..ae04ae67 100644 --- a/src/main/resources/assets/nei/csv/handlers.csv +++ b/src/main/resources/assets/nei/csv/handlers.csv @@ -228,11 +228,11 @@ com.djgiannuzz.thaumcraftneiplugin.nei.recipehandler.InfusionRecipeHandler,Thaum ru.timeconqueror.tcneiadditions.nei.arcaneworkbench.ArcaneCraftingShapedHandler,Thaumcraft,Thaumcraft:blockTable:15,,Thaumcraft,TRUE,,4,138,,2,,,,,,, ru.timeconqueror.tcneiadditions.nei.AspectCombinationHandler,Thaumcraft,Thaumcraft:ItemResearchNotes,,Thaumcraft,TRUE,,,130,,2,,,,,,In sets of 5. Each one is ~30 height, ru.timeconqueror.tcneiadditions.nei.AspectFromItemStackHandler,Thaumcraft,Thaumcraft:ItemResearchNotes,,Thaumcraft,TRUE,,,140,,2,,,,,,, -tconstruct.plugins.nei.RecipeHandlerAlloying,Tinker's Construct,TConstruct:Smeltery,,TConstruct,TRUE,,,65,,5,,,,,,, -tconstruct.plugins.nei.RecipeHandlerCastingBasin,Tinker's Construct,TConstruct:SearedBlock:2,,TConstruct,TRUE,,,65,,5,,,,,,, -tconstruct.plugins.nei.RecipeHandlerCastingTable,Tinker's Construct,TConstruct:SearedBlock,,TConstruct,TRUE,,,65,,5,,,,,,, +tconstruct.plugins.nei.RecipeHandlerAlloying,Tinker's Construct,TConstruct:Smeltery,,TConstruct,TRUE,,3,63,,5,,,,,,, +tconstruct.plugins.nei.RecipeHandlerCastingBasin,Tinker's Construct,TConstruct:SearedBlock:2,,TConstruct,TRUE,,2,57,,5,,,,,,, +tconstruct.plugins.nei.RecipeHandlerCastingTable,Tinker's Construct,TConstruct:SearedBlock,,TConstruct,TRUE,,2,57,,5,,,,,,, tconstruct.plugins.nei.RecipeHandlerDryingRack,Tinker's Construct,TConstruct:Armor.DryingRack,,TConstruct,TRUE,,,55,,5,,,,,,, -tconstruct.plugins.nei.RecipeHandlerMelting,Tinker's Construct,TConstruct:LavaTank:2,,TConstruct,TRUE,,,65,,5,,,,,,, +tconstruct.plugins.nei.RecipeHandlerMelting,Tinker's Construct,TConstruct:LavaTank:2,,TConstruct,TRUE,,-1,60,,5,,,,,,, tconstruct.plugins.nei.RecipeHandlerToolMaterials,Tinker's Construct,TConstruct:ToolStationBlock,,TConstruct,TRUE,,,110,,3,,,,,,"Longer if more modifiers, I went through the whole list", net.p455w0rd.wirelesscraftingterminal.integration.modules.NEIHelpers.NEIAEShapedRecipeHandler,Wireless Crafting Terminal,ae2wct:wirelessCraftingTerminal,,ae2wct,TRUE,,,,,,,,,,,, alkalus.main.nei.NEI_Handler_Cauldron,Witchery,witchery:cauldron,,WitcheryExtras,TRUE,,,65,,5,,,,,,, From a54c414595bb7e1f4a86dfa6daf67d7a68ae1ace Mon Sep 17 00:00:00 2001 From: slprime <31038811+slprime@users.noreply.github.com> Date: Sun, 27 Sep 2026 07:39:27 +0300 Subject: [PATCH 06/11] Add Recipe Groups to GuiRecipe (#1049) --- .../java/codechicken/nei/FavoriteRecipes.java | 17 + .../java/codechicken/nei/PositionedStack.java | 13 +- .../nei/recipe/FireworkRecipeHandler.java | 277 ++++-- .../codechicken/nei/recipe/GuiRecipe.java | 45 +- .../nei/recipe/GuiRecipeButton.java | 14 +- .../nei/recipe/IRecipeHandler.java | 8 + .../nei/recipe/NEIRecipeWidget.java | 688 --------------- .../nei/recipe/RecipeHandlerRef.java | 12 +- .../nei/recipe/RecipePageManager.java | 63 +- .../nei/recipe/RecipeTooltipLineHandler.java | 9 +- .../nei/recipe/SearchRecipeHandler.java | 9 +- .../nei/recipe/debug/DebugHandlerWidget.java | 4 +- .../nei/recipe/widget/PermutationsCycler.java | 99 +++ .../nei/recipe/widget/RecipeGroup.java | 210 +++++ .../nei/recipe/widget/RecipeWidget.java | 834 ++++++++++++++++++ src/main/resources/assets/nei/lang/en_US.lang | 2 + 16 files changed, 1464 insertions(+), 840 deletions(-) delete mode 100644 src/main/java/codechicken/nei/recipe/NEIRecipeWidget.java create mode 100644 src/main/java/codechicken/nei/recipe/widget/PermutationsCycler.java create mode 100644 src/main/java/codechicken/nei/recipe/widget/RecipeGroup.java create mode 100644 src/main/java/codechicken/nei/recipe/widget/RecipeWidget.java diff --git a/src/main/java/codechicken/nei/FavoriteRecipes.java b/src/main/java/codechicken/nei/FavoriteRecipes.java index f0271d3b..66dbe105 100644 --- a/src/main/java/codechicken/nei/FavoriteRecipes.java +++ b/src/main/java/codechicken/nei/FavoriteRecipes.java @@ -8,6 +8,7 @@ import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; @@ -16,6 +17,7 @@ import java.util.Map; import java.util.Objects; import java.util.Set; +import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -322,6 +324,21 @@ public class FavoriteRecipes { return getFavorite(stack) != null; } + public static void toggleFavoriteItem(ItemStack stack) { + if (stack == null) return; + + if (containsManual(stack)) { + setFavorite(stack, null); + } else { + setFavorite( + stack, + RecipeId.of( + stack, + FavoriteRecipes.FAVORITE_ITEM, + Arrays.asList(new ItemStack(Blocks.fire, 1), stack))); + } + } + public static void setFavorite(ItemStack stack, RecipeId recipeId) { if (stack == null) return; diff --git a/src/main/java/codechicken/nei/PositionedStack.java b/src/main/java/codechicken/nei/PositionedStack.java index 5cbd657b..2f11f649 100644 --- a/src/main/java/codechicken/nei/PositionedStack.java +++ b/src/main/java/codechicken/nei/PositionedStack.java @@ -4,6 +4,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; +import java.util.function.Function; import java.util.stream.Collectors; import net.minecraft.init.Blocks; @@ -42,7 +43,8 @@ public class PositionedStack implements Cloneable { protected boolean permutated = false; protected String acceptsLabel; - protected List tooltip; + + protected Function> tooltip; protected List badges; public PositionedStack(Object object, int x, int y, boolean genPerms) { @@ -115,11 +117,15 @@ public class PositionedStack implements Cloneable { } public void setTooltip(List tooltip) { - this.tooltip = tooltip; + this.tooltip = tooltip == null ? null : item -> tooltip; + } + + public void setTooltipProvider(Function> provider) { + this.tooltip = provider; } public List getTooltip() { - return this.tooltip; + return this.tooltip == null ? null : this.tooltip.apply(this.item); } public int getChance() { @@ -135,7 +141,6 @@ public class PositionedStack implements Cloneable { PositionedStack pStack = (PositionedStack) super.clone(); pStack.items = Arrays.stream(this.items).map(ItemStack::copy).toArray(ItemStack[]::new); pStack.item = this.item == null ? null : this.item.copy(); - pStack.tooltip = this.tooltip == null ? null : new ArrayList<>(this.tooltip); pStack.badges = this.badges == null ? null : new ArrayList<>(this.badges); return pStack; } catch (CloneNotSupportedException e) { diff --git a/src/main/java/codechicken/nei/recipe/FireworkRecipeHandler.java b/src/main/java/codechicken/nei/recipe/FireworkRecipeHandler.java index ff03bbd2..92c20806 100644 --- a/src/main/java/codechicken/nei/recipe/FireworkRecipeHandler.java +++ b/src/main/java/codechicken/nei/recipe/FireworkRecipeHandler.java @@ -1,121 +1,242 @@ package codechicken.nei.recipe; -import java.awt.Point; import java.awt.Rectangle; import java.util.ArrayList; import java.util.Arrays; -import java.util.LinkedList; +import java.util.Collections; import java.util.List; import net.minecraft.init.Items; import net.minecraft.inventory.InventoryCrafting; -import net.minecraft.item.Item; +import net.minecraft.item.ItemDye; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.RecipeFireworks; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; -import codechicken.lib.gui.GuiDraw; import codechicken.nei.InventoryCraftingDummy; import codechicken.nei.NEIClientUtils; -import codechicken.nei.PositionedStack; import codechicken.nei.guihook.GuiContainerManager; public class FireworkRecipeHandler extends ShapelessRecipeHandler { public class CachedFireworkRecipe extends CachedShapelessRecipe { - final LinkedList itemList = new LinkedList<>(); - - public final Object[] baseIngredients; - public final Object extraIngred; public final int recipeType; + public final Object groupId; - public CachedFireworkRecipe(Object[] base, Object extra, int type) { - super(new ItemStack(Items.fireworks)); - this.baseIngredients = base; - this.extraIngred = extra; + public CachedFireworkRecipe(List ingredients, ItemStack result, int type, Object groupId) { + super(ingredients, result); this.recipeType = type; - - cycle(); - } - - public void cycle() { - itemList.clear(); - itemList.addAll(Arrays.asList(baseIngredients)); - int extras = (cycleticks / 40) % (10 - itemList.size()); - for (int i = 0; i < extras; i++) itemList.add(extraIngred); - setIngredients(itemList); - - List ingreds = getIngredients(); - for (int i = 0; i < 9; i++) - inventoryCrafting.setInventorySlotContents(i, i < ingreds.size() ? ingreds.get(i).item : null); - - if (!recipeFireworks.matches(inventoryCrafting, null)) throw new RuntimeException("Invalid Recipe?"); - setResult(recipeFireworks.getCraftingResult(null)); + this.groupId = groupId; } } + // indexed by the "Type" explosion tag + private static final ItemStack[] SHAPES = { null, new ItemStack(Items.fire_charge), + new ItemStack(Items.gold_nugget), new ItemStack(Items.skull, 1, Short.MAX_VALUE), + new ItemStack(Items.feather) }; + private final InventoryCrafting inventoryCrafting = new InventoryCraftingDummy(); private final RecipeFireworks recipeFireworks = new RecipeFireworks(); - - public final ArrayList mfireworks = new ArrayList<>(); + private ItemStack usageIngredient = null; public FireworkRecipeHandler() { super(); stackorder = new int[][] { { 0, 0 }, { 1, 0 }, { 2, 0 }, { 0, 1 }, { 1, 1 }, { 2, 1 }, { 0, 2 }, { 1, 2 }, { 2, 2 } }; - loadAllFireworks(); } - private void loadAllFireworks() { - // charges - Item[] shapes = new Item[] { null, Items.fire_charge, Items.gold_nugget, Items.feather, Items.skull }; - Item[] effects = new Item[] { null, Items.diamond, Items.glowstone_dust }; - for (Item shape : shapes) - for (Item effect : effects) genRecipe(Items.gunpowder, shape, effect, Items.dye, Items.dye, 0); - - // fireworks - genRecipe(Items.gunpowder, Items.paper, Items.firework_charge, 2); - genRecipe(Items.gunpowder, Items.gunpowder, Items.paper, Items.firework_charge, 2); - genRecipe(Items.gunpowder, Items.gunpowder, Items.gunpowder, Items.paper, Items.firework_charge, 2); - - // setup a valid charge to use for the recolour recipe - for (int i = 0; i < 9; i++) inventoryCrafting.setInventorySlotContents(i, null); - inventoryCrafting.setInventorySlotContents(0, new ItemStack(Items.gunpowder)); - inventoryCrafting.setInventorySlotContents(1, new ItemStack(Items.dye)); - recipeFireworks.matches(inventoryCrafting, null); - ItemStack charge = recipeFireworks.getCraftingResult(null); - genRecipe(charge, Items.dye, Items.dye, 1); + @Override + public Object getRecipeGroupId(int recipe) { + return this.arecipes.get(recipe) instanceof CachedFireworkRecipe firework ? firework.groupId : null; } - private void genRecipe(Object... params) { - int numIngreds = 0; - for (int i = 0; i < params.length - 2; i++) if (params[i] != null) numIngreds++; + private void loadChargeRecipes() { + final List> dyeSets = new ArrayList<>(); - for (int i = 0; i < params.length - 1; i++) - if (params[i] instanceof Item) params[i] = new ItemStack((Item) params[i], 1, Short.MAX_VALUE); + for (int dye = 0; dye < ItemDye.field_150922_c.length; dye++) { + dyeSets.add(Collections.singletonList(new ItemStack(Items.dye, 1, dye))); + } - Object[] ingreds = new Object[numIngreds]; - for (int i = 0, j = 0; i < params.length - 2; i++) if (params[i] != null) ingreds[j++] = params[i]; + for (ItemStack shape : SHAPES) { + for (int effect = 0; effect < 4; effect++) { + addRecipes(getChargeBase(shape, (effect & 1) != 0, (effect & 2) != 0), dyeSets, 0); + } + } - mfireworks - .add(new CachedFireworkRecipe(ingreds, params[params.length - 2], (Integer) params[params.length - 1])); + final ItemStack charge = craft(Arrays.asList(new ItemStack(Items.gunpowder), new ItemStack(Items.dye))); + addRecipes(Collections.singletonList(charge), dyeSets, 1); + } + + private void loadRocketRecipes() { + final ItemStack charge = craft(Arrays.asList(new ItemStack(Items.gunpowder), new ItemStack(Items.dye))); + final List> chargeSets = new ArrayList<>(); + + for (int count = 0; count < 9; count++) { + chargeSets.add(Collections.nCopies(count, charge)); + } + + for (int flight = 1; flight <= 3; flight++) { + addRecipes(getRocketBase(flight), chargeSets, 2); + } + } + + private void loadExactChargeRecipes(NBTTagCompound explosion) { + final byte type = explosion.getByte("Type"); + + if (explosion.hasKey("FadeColors")) { + final NBTTagCompound baseTag = new NBTTagCompound(); + final ItemStack charge = new ItemStack(Items.firework_charge); + + baseTag.setTag("Explosion", explosion.copy()); + baseTag.getCompoundTag("Explosion").removeTag("FadeColors"); + charge.setTagCompound(baseTag); + + addRecipes(Collections.singletonList(charge), getDyeSets(explosion.getIntArray("FadeColors")), 1); + } else if (type >= 0 && type < SHAPES.length) { + addRecipes( + getChargeBase(SHAPES[type], explosion.getBoolean("Flicker"), explosion.getBoolean("Trail")), + getDyeSets(explosion.getIntArray("Colors")), + 0); + } + } + + private void loadExactRocketRecipes(NBTTagCompound fireworks) { + final NBTTagList explosions = fireworks.getTagList("Explosions", 10); + final List charges = new ArrayList<>(); + + for (int i = 0; i < explosions.tagCount(); i++) { + final ItemStack charge = new ItemStack(Items.firework_charge); + charge.setTagCompound(new NBTTagCompound()); + charge.getTagCompound().setTag("Explosion", explosions.getCompoundTagAt(i)); + charges.add(charge); + } + + addRecipes(getRocketBase(fireworks.getByte("Flight")), Collections.singletonList(charges), 2); + } + + private static List getChargeBase(ItemStack shape, boolean flicker, boolean trail) { + final List base = new ArrayList<>(); + base.add(new ItemStack(Items.gunpowder)); + + if (shape != null) { + base.add(shape); + } + + if (flicker) { + base.add(new ItemStack(Items.glowstone_dust)); + } + + if (trail) { + base.add(new ItemStack(Items.diamond)); + } + + return base; + } + + private static List getRocketBase(int flight) { + final List base = new ArrayList<>(); + + for (int i = 0; i < flight; i++) { + base.add(new ItemStack(Items.gunpowder)); + } + + base.add(new ItemStack(Items.paper)); + + return base; + } + + private static List> getDyeSets(int[] colors) { + final List dyes = new ArrayList<>(); + + for (int color : colors) { + for (int dye = 0; dye < ItemDye.field_150922_c.length; dye++) { + if (ItemDye.field_150922_c[dye] == color) { + dyes.add(new ItemStack(Items.dye, 1, dye)); + break; + } + } + } + + if (dyes.isEmpty() || dyes.size() != colors.length) { + return Collections.emptyList(); + } + + if (Arrays.stream(colors).distinct().count() > 1) { + return Collections.singletonList(dyes); + } + + final List> dyeSets = new ArrayList<>(); + + for (int count = 1; count < 9; count++) { + dyeSets.add(Collections.nCopies(count, dyes.get(0))); + } + + return dyeSets; + } + + private void addRecipes(List base, List> extraSets, int type) { + final Object groupId = new Object(); + + for (List extras : extraSets) { + final List ingredients = new ArrayList<>(base); + ingredients.addAll(extras); + + final ItemStack result = craft(ingredients); + + if (result != null) { + final CachedFireworkRecipe recipe = new CachedFireworkRecipe(ingredients, result, type, groupId); + + if (usageIngredient == null || recipe.contains(recipe.ingredients, usageIngredient)) { + arecipes.add(recipe); + } + } + } + } + + private ItemStack craft(List ingredients) { + + if (ingredients.size() > 9) { + return null; + } + + for (int i = 0; i < 9; i++) { + inventoryCrafting.setInventorySlotContents(i, i < ingredients.size() ? ingredients.get(i) : null); + } + + return recipeFireworks.matches(inventoryCrafting, null) ? recipeFireworks.getCraftingResult(inventoryCrafting) + : null; } @Override public void loadCraftingRecipes(ItemStack result) { - for (CachedFireworkRecipe recipe : mfireworks) { - if (recipe.result.item.getItem() == result.getItem()) { - recipe.cycle(); - arecipes.add(recipe); + final NBTTagCompound tag = result.getTagCompound(); + + if (result.getItem() == Items.firework_charge) { + if (tag != null) { + loadExactChargeRecipes(tag.getCompoundTag("Explosion")); + } + + if (arecipes.isEmpty()) { + loadChargeRecipes(); + } + } else if (result.getItem() == Items.fireworks) { + if (tag != null) { + loadExactRocketRecipes(tag.getCompoundTag("Fireworks")); + } + + if (arecipes.isEmpty()) { + loadRocketRecipes(); } } - // show random recolouring recipes as well } @Override public void loadCraftingRecipes(String outputId, Object... results) { if (outputId.equals("crafting") && getClass() == FireworkRecipeHandler.class) { - arecipes.addAll(mfireworks); + loadChargeRecipes(); + loadRocketRecipes(); } else { super.loadCraftingRecipes(outputId, results); } @@ -123,20 +244,9 @@ public class FireworkRecipeHandler extends ShapelessRecipeHandler { @Override public void loadUsageRecipes(ItemStack ingredient) { - for (CachedFireworkRecipe recipe : mfireworks) { - if (recipe.contains(recipe.ingredients, ingredient)) { - recipe.cycle(); - arecipes.add(recipe); - } - } - } - - @Override - public void onUpdate() { - if (!NEIClientUtils.shiftKey()) { - cycleticks++; - if (cycleticks % 20 == 0) for (CachedRecipe crecipe : arecipes) ((CachedFireworkRecipe) crecipe).cycle(); - } + usageIngredient = ingredient; + loadChargeRecipes(); + loadRocketRecipes(); } @Override @@ -147,11 +257,8 @@ public class FireworkRecipeHandler extends ShapelessRecipeHandler { @Override public List handleTooltip(GuiRecipe gui, List currenttip, int recipe) { currenttip = super.handleTooltip(gui, currenttip, recipe); - Point mousepos = GuiDraw.getMousePosition(); - Point relMouse = new Point(mousepos.x - gui.guiLeft, mousepos.y - gui.guiTop); - Point recipepos = gui.getRecipePosition(recipe); if (currenttip.isEmpty() && GuiContainerManager.getStackMouseOver(gui) == null - && new Rectangle(recipepos.x, recipepos.y, 166, 55).contains(relMouse)) + && new Rectangle(0, 0, 166, 55).contains(gui.getRecipeMousePosition(recipe))) currenttip.add( NEIClientUtils.translate( "recipe.firework.tooltip" + ((CachedFireworkRecipe) arecipes.get(recipe)).recipeType)); diff --git a/src/main/java/codechicken/nei/recipe/GuiRecipe.java b/src/main/java/codechicken/nei/recipe/GuiRecipe.java index 17e1c5f9..2740664b 100644 --- a/src/main/java/codechicken/nei/recipe/GuiRecipe.java +++ b/src/main/java/codechicken/nei/recipe/GuiRecipe.java @@ -52,6 +52,7 @@ import codechicken.nei.guihook.IContainerTooltipHandler; import codechicken.nei.guihook.IGuiClientSide; import codechicken.nei.guihook.IGuiHandleMouseWheel; import codechicken.nei.recipe.Recipe.RecipeId; +import codechicken.nei.recipe.widget.RecipeWidget; import codechicken.nei.scroll.ScrollBar; import codechicken.nei.scroll.ScrollBar.OverflowType; import codechicken.nei.scroll.ScrollBar.ScrollPlace; @@ -523,7 +524,7 @@ public abstract class GuiRecipe extends GuiContainer i } public int openTargetRecipe(RecipeId recipeId) { - int refIndex = -1; + int recipeIndex = -1; int recipetype = 0; this.recipeId = recipeId; @@ -537,10 +538,9 @@ public abstract class GuiRecipe extends GuiContainer i recipetype = j; if (!this.recipeId.getIngredients().isEmpty()) { - refIndex = SearchRecipeHandler.findFirst( + recipeIndex = SearchRecipeHandler.findFirst( localHandler, - recipeIndex -> this.recipeId - .equalsIngredients(localHandler.getIngredientStacks(recipeIndex))); + ri -> this.recipeId.equalsIngredients(localHandler.getIngredientStacks(ri))); } break; @@ -549,17 +549,17 @@ public abstract class GuiRecipe extends GuiContainer i } setRecipePage(recipetype); - this.handlerPages.gotoRefIndex(Math.max(0, refIndex)); + this.handlerPages.gotoRecipeIndex(Math.max(0, recipeIndex)); - return refIndex; + return recipeIndex; } public Recipe getFocusedRecipe() { final Point mouse = GuiDraw.getMousePosition(); final Widget activeWidget = this.container.getWidgetUnderMouse(mouse.x, mouse.y); - if (activeWidget instanceof NEIRecipeWidget recipeWidget && recipeWidget.isFocusedRecipe(mouse.x, mouse.y)) { - return recipeWidget.getRecipe(); + if (activeWidget instanceof RecipeWidget recipeWidget && recipeWidget.isFocusedRecipe(mouse.x, mouse.y)) { + return Recipe.of(recipeWidget.getRecipeHandlerRef()); } return null; @@ -569,7 +569,7 @@ public abstract class GuiRecipe extends GuiContainer i final Point mouse = GuiDraw.getMousePosition(); final Widget activeWidget = this.container.getWidgetUnderMouse(mouse.x, mouse.y); - if (activeWidget instanceof NEIRecipeWidget recipeWidget) { + if (activeWidget instanceof RecipeWidget recipeWidget) { final PositionedStack hovered = recipeWidget.getPositionedStackMouseOver(mouse.x, mouse.y); if (hovered != null) { @@ -586,7 +586,7 @@ public abstract class GuiRecipe extends GuiContainer i final EmptyContainer slotcontainer = (EmptyContainer) inventorySlots; slotcontainer.setActiveStack(null); - if (activeWidget instanceof NEIRecipeWidget recipeWidget) { + if (activeWidget instanceof RecipeWidget recipeWidget) { final PositionedStack hovered = recipeWidget.getPositionedStackMouseOver(mousex, mousey); if (hovered != null) { @@ -844,7 +844,7 @@ public abstract class GuiRecipe extends GuiContainer i List currenttip) { final Widget activeWidget = this.container.getWidgetUnderMouse(mousex, mousey); - if (activeWidget instanceof NEIRecipeWidget recipeWidget) { + if (activeWidget instanceof RecipeWidget recipeWidget) { currenttip = recipeWidget.handleItemTooltip(itemstack, mousex, mousey, currenttip); } @@ -891,7 +891,7 @@ public abstract class GuiRecipe extends GuiContainer i this.recipetype = this.currenthandlers.indexOf(this.handler.original); setRecipePage(this.recipetype); - this.handlerPages.changePage(currentPage); + this.handlerPages.changePage(currentPage - this.handlerPages.getCurrentPageIndex()); refreshContainer(); } @@ -1014,8 +1014,23 @@ public abstract class GuiRecipe extends GuiContainer i return this.firstGuiGeneral; } - public Point getRecipePosition(int recipe) { - return getRefIndexPosition(getRecipeIndices().indexOf(recipe)); + public Point getRecipePosition(int recipeIndex) { + + for (Widget widget : this.container.getWidgets()) { + if (widget instanceof RecipeWidget recipeWidget && recipeWidget.containsRecipeIndex(recipeIndex)) { + return new Point( + recipeWidget.x - this.guiLeft, + recipeWidget.y - this.guiTop + recipeWidget.getHandlerInfo().getYShift()); + } + } + + return new Point(0, 0); + } + + public Point getRecipeMousePosition(int recipeIndex) { + final Point mouse = GuiDraw.getMousePosition(); + final Point recipePosition = getRecipePosition(recipeIndex); + return new Point(mouse.x - this.guiLeft - recipePosition.x, mouse.y - this.guiTop - recipePosition.y); } protected Point getRefIndexPosition(int refIndex) { @@ -1027,7 +1042,7 @@ public abstract class GuiRecipe extends GuiContainer i final List children = this.container.getWidgets(); if (refIndex >= 0 && refIndex < children.size() - && children.get(refIndex) instanceof NEIRecipeWidget recipeWidget) { + && children.get(refIndex) instanceof RecipeWidget recipeWidget) { return new Point( recipeWidget.x - this.guiLeft, recipeWidget.y - this.guiTop + recipeWidget.getHandlerInfo().getYShift()); diff --git a/src/main/java/codechicken/nei/recipe/GuiRecipeButton.java b/src/main/java/codechicken/nei/recipe/GuiRecipeButton.java index f24d9f92..31f4f0a3 100644 --- a/src/main/java/codechicken/nei/recipe/GuiRecipeButton.java +++ b/src/main/java/codechicken/nei/recipe/GuiRecipeButton.java @@ -15,12 +15,12 @@ public abstract class GuiRecipeButton extends GuiNEIButton { public static class UpdateRecipeButtonsEvent extends GuiScreenEvent { public List buttonList; - public NEIRecipeWidget recipeWidget; + public RecipeHandlerRef handlerRef; - public UpdateRecipeButtonsEvent(GuiRecipe gui, NEIRecipeWidget recipeWidget, + public UpdateRecipeButtonsEvent(GuiRecipe gui, RecipeHandlerRef handlerRef, List buttonList) { super(gui); - this.recipeWidget = recipeWidget; + this.handlerRef = handlerRef; this.buttonList = new ArrayList<>(buttonList); } @@ -29,16 +29,16 @@ public abstract class GuiRecipeButton extends GuiNEIButton { public HandlerInfo handlerInfo; - public Pre(GuiRecipe gui, NEIRecipeWidget recipeWidget, HandlerInfo handlerInfo) { - super(gui, recipeWidget, new ArrayList<>()); + public Pre(GuiRecipe gui, RecipeHandlerRef handlerRef, HandlerInfo handlerInfo) { + super(gui, handlerRef, new ArrayList<>()); this.handlerInfo = handlerInfo; } } public static class Post extends UpdateRecipeButtonsEvent { - public Post(GuiRecipe gui, NEIRecipeWidget recipeWidget, List buttonList) { - super(gui, recipeWidget, buttonList); + public Post(GuiRecipe gui, RecipeHandlerRef handlerRef, List buttonList) { + super(gui, handlerRef, buttonList); } } } diff --git a/src/main/java/codechicken/nei/recipe/IRecipeHandler.java b/src/main/java/codechicken/nei/recipe/IRecipeHandler.java index 0afcacd3..5f87eeb4 100644 --- a/src/main/java/codechicken/nei/recipe/IRecipeHandler.java +++ b/src/main/java/codechicken/nei/recipe/IRecipeHandler.java @@ -91,6 +91,14 @@ public interface IRecipeHandler { */ PositionedStack getResultStack(int recipe); + /** + * @param recipe The recipe index to get the group id for. + * @return An id shared by every recipe in this recipe's group, or {@code null} if this recipe isn't grouped. + */ + default Object getRecipeGroupId(int recipe) { + return null; + } + /** * A tick function called for updating progress bars and cycling damage items. */ diff --git a/src/main/java/codechicken/nei/recipe/NEIRecipeWidget.java b/src/main/java/codechicken/nei/recipe/NEIRecipeWidget.java deleted file mode 100644 index 2856e66a..00000000 --- a/src/main/java/codechicken/nei/recipe/NEIRecipeWidget.java +++ /dev/null @@ -1,688 +0,0 @@ -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.init.Blocks; -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.lib.vec.Rectangle4i; -import codechicken.nei.FavoriteRecipes; -import codechicken.nei.KeyManager; -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.recipe.Recipe.RecipeId; -import codechicken.nei.recipe.debug.DebugHandlerWidget; -import codechicken.nei.util.NEIMouseUtils; - -public class NEIRecipeWidget extends Widget { - - protected AcceptsFollowingTooltipLineHandler acceptsFollowingTooltipLineHandler; - protected final Map favoriteIndexes = new WeakHashMap<>(); - protected final Map> permutations = new WeakHashMap<>(); - protected final Map> badgeCache = new WeakHashMap<>(); - protected int favoriteRevision = -1; - protected boolean update = true; - protected int cycleticks = 0; - protected int lastcycle = -1; - - protected final RecipeHandlerRef handlerRef; - protected final HandlerInfo handlerInfo; - - protected boolean showAsWidget = false; - protected List 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() { - - if (this.showAsWidget || !this.handlerInfo.isAllowOverflowY()) { - final int recipeHeight = this.handlerRef.handler.getRecipeHeight(this.handlerRef.recipeIndex); - this.w = Math.max(166, this.handlerInfo.getWidth()); - this.h = recipeHeight > 0 ? recipeHeight : this.handlerInfo.getHeight(); - this.h += this.handlerInfo.getYShift(); - } - - this.update = true; - } - - public List getRecipeButtons() { - - if (this.recipeButtons == null) { - if (!getOutputs().isEmpty()) { - this.recipeButtons = initButtons(); - } else { - this.recipeButtons = Collections.emptyList(); - } - } - - return Collections.unmodifiableList(this.recipeButtons); - } - - protected List 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 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, - getDefaultButtons()); - MinecraftForge.EVENT_BUS.post(postEvent); - return postEvent.buttonList; - } - - } else { - return getDefaultButtons(); - } - - } - - protected List getDefaultButtons() { - GuiContainer guiContainer = NEIClientUtils.getGuiContainer(); - final List buttons = new ArrayList<>(); - final boolean showFavorites = NEIClientConfig.favoritesEnabled() && handlerInfo.getShowFavoritesButton(); - final boolean showOverlay = handlerInfo.getShowOverlayButton(); - final int x = Math.min(166, 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.update) { - this.update = false; - - if (!NEIClientUtils.shiftKey() && ((this.cycleticks++) / 20) != this.lastcycle || this.lastcycle == -1) { - this.lastcycle = this.cycleticks / 20; - updatePermutations(); - - for (GuiRecipeButton button : getRecipeButtonsIfInit()) { - button.onPermutationsChanged(); - } - } - - for (GuiRecipeButton button : getRecipeButtons()) { - button.update(); - } - } - - 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()) { - - if (!this.permutations.containsKey(pStack)) { - updatePermutationsFor(pStack); - } - - drawItem(pStack, mouseX, mouseY, yShift, true); - } - - for (PositionedStack pStack : getCatalysts()) { - - if (!this.permutations.containsKey(pStack)) { - updatePermutationsFor(pStack); - } - - drawItem(pStack, mouseX, mouseY, yShift, true); - } - - for (PositionedStack pStack : getOutputs()) { - drawItem(pStack, mouseX, mouseY, yShift, false); - } - - GuiContainerManager.disableMatrixStackLogging(); - - this.handlerRef.handler.drawForeground(this.handlerRef.recipeIndex); - - final GuiRecipeButton overlayButton = forEachButtons( - button -> (this.showAsWidget ? button instanceof GuiOverlayButton : button.contains(mouseX, mouseY)) - ? button - : null, - null); - - if (overlayButton != null) { - 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; - } - } - - DebugHandlerWidget.instance.drawGuiPlaceholder(this); - } - - protected void drawItem(PositionedStack pStack, int mouseX, int mouseY, int yShift, boolean input) { - pStack.draw(mouseX - this.x, mouseY - this.y - yShift); - - if (this.handlerInfo.getShowBadge()) { - drawBadge(pStack, input); - } - - if (pStack.contains(mouseX - this.x, mouseY - this.y - yShift)) { - NEIClientUtils.gl2DRenderContext( - () -> GuiDraw.drawRect(pStack.relx, pStack.rely, pStack.width, pStack.height, 0x80FFFFFF)); - } - } - - protected List getBadges(PositionedStack pStack, boolean input) { - - return this.badgeCache.computeIfAbsent(pStack, k -> { - final List badges = k.getBadges(); - - if (badges == null) { - - if (input) { - if (StackInfo.getAmount(pStack.item) == 0) { - return Collections.singletonList(Badge.notConsumed()); - } else if (pStack.getChance() == 0) { - return Collections.singletonList(Badge.notConsumedParallel()); - } else if (pStack.getChance() != PositionedStack.CHANCE_FULL) { - return Collections.singletonList( - Badge.consumeChance(pStack.getChance() / (float) PositionedStack.CHANCE_FULL)); - } - } else if (pStack.getChance() != PositionedStack.CHANCE_FULL) { - return Collections.singletonList( - Badge.outputChance(pStack.getChance() / (float) PositionedStack.CHANCE_FULL)); - } - - return Collections.emptyList(); - } - - return badges; - }); - - } - - protected void drawBadge(PositionedStack pStack, boolean input) { - final List badges = getBadges(pStack, input); - - for (Badge badge : badges) { - badge.draw(new Rectangle4i(pStack.relx, pStack.rely, pStack.width, pStack.height)); - } - } - - @Override - public boolean handleKeyPress(int keyID, char keyChar) { - - if (NEIClientConfig.favoritesEnabled() - && KeyManager.isHashDown("bookmark.favorite_item", NEIClientUtils.SHIFT_HASH)) { - final Point mouse = GuiDraw.getMousePosition(); - final int yShift = this.handlerInfo.getYShift(); - PositionedStack pStackOver = null; - - for (PositionedStack pStack : getInputs()) { - if (pStack.contains(mouse.x - this.x, mouse.y - this.y - yShift)) { - pStackOver = pStack; - break; - } - } - - if (pStackOver != null) { - - if (FavoriteRecipes.containsManual(pStackOver.item)) { - FavoriteRecipes.setFavorite(pStackOver.item, null); - } else { - FavoriteRecipes.setFavorite( - pStackOver.item, - RecipeId.of( - pStackOver.item, - FavoriteRecipes.FAVORITE_ITEM, - Arrays.asList(new ItemStack(Blocks.fire, 1), pStackOver.item))); - } - - return true; - } - - } - - 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 handleTooltip(int mouseX, int mouseY, List tooltip) { - final GuiRecipe guiRecipe = getGuiRecipe(); - - if (guiRecipe == null) { - return tooltip; - } - - final List 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 handleItemTooltip(ItemStack itemstack, int mousex, int mousey, List tooltip) { - final GuiRecipe guiRecipe = getGuiRecipe(); - - if (guiRecipe == null) { - return tooltip; - } - - tooltip = this.handlerRef.handler.handleItemTooltip(guiRecipe, itemstack, tooltip, this.handlerRef.recipeIndex); - - if (itemstack != null) { - final PositionedStack hovered = getPositionedStackMouseOver(mousex, mousey); - - if (hovered != null) { - if (this.handlerInfo.getShowBadge()) { - final List badges = getBadges(hovered, getOutputs().indexOf(hovered) == -1); - - for (Badge badge : badges) { - if (badge.getTooltip() != null && !badge.getTooltip().isEmpty()) { - tooltip.addAll(badge.getTooltip()); - } - } - } - - final List customTooltip = hovered.getTooltip(); - - if (customTooltip != null && !customTooltip.isEmpty()) { - tooltip.addAll(customTooltip); - } - } - - if (hovered == null || !NEIClientConfig.showCycledIngredientsTooltip() - || this.permutations.getOrDefault(hovered, Collections.emptyList()).size() <= 1 - || getOutputs().indexOf(hovered) != -1) { - this.acceptsFollowingTooltipLineHandler = null; - } else if (this.acceptsFollowingTooltipLineHandler == null - || this.acceptsFollowingTooltipLineHandler.tooltipGUID != hovered) { - this.acceptsFollowingTooltipLineHandler = AcceptsFollowingTooltipLineHandler - .of(hovered, this.permutations.get(hovered), hovered.item); - - if (this.acceptsFollowingTooltipLineHandler != null && hovered.getAcceptsLabel() != null) { - this.acceptsFollowingTooltipLineHandler.setLabel(hovered.getAcceptsLabel()); - } - } - } 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 handleHotkeys(int mouseX, int mouseY, Map hotkeys) { - final int yShift = this.handlerInfo.getYShift(); - final Map 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")); - } - - if (getInputs().stream().anyMatch( - pStack -> this.permutations.getOrDefault(pStack, Collections.emptyList()).size() > 1 - && pStack.contains(mouseX - this.x, mouseY - this.y - yShift))) { - hotkeys.put( - KeyManager.getKeyName("bookmark.favorite_item", NEIClientUtils.SHIFT_HASH), - NEIClientUtils.translate("recipe.favorite.toggle")); - } - - 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 && this.permutations.getOrDefault(overStack, Collections.emptyList()).size() > 1) { - final List items = this.permutations.get(overStack); - 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 list, ItemStack stack) { - for (int i = 0; i < list.size(); i++) { - if (NEIServerUtils.areStacksSameTypeCraftingWithNBT(list.get(i), stack)) { - return i; - } - } - return -1; - } - - protected R forEachButtons(Function 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 GuiRecipeguiRecipe) { - return guiRecipe; - } - - return null; - } - - protected GuiContainer getFirstGui() { - final GuiContainer guiContainer = NEIClientUtils.getGuiContainer(); - - if (guiContainer instanceof GuiRecipeguiRecipe) { - return guiRecipe.firstGui; - } - - return guiContainer; - } - - protected void updatePermutations() { - final int rev = FavoriteRecipes.getRevision(); - - if (this.favoriteRevision != rev) { - this.favoriteRevision = rev; - this.acceptsFollowingTooltipLineHandler = null; - this.favoriteIndexes.clear(); - this.permutations.clear(); - this.badgeCache.clear(); - } - - for (PositionedStack pStack : getInputs()) { - updatePermutationsFor(pStack); - } - - for (PositionedStack pStack : getCatalysts()) { - updatePermutationsFor(pStack); - } - - if (this.acceptsFollowingTooltipLineHandler != null) { - this.acceptsFollowingTooltipLineHandler - .setActiveStack(((PositionedStack) this.acceptsFollowingTooltipLineHandler.tooltipGUID).item); - } - - } - - private void updatePermutationsFor(PositionedStack pStack) { - List perms = this.permutations.get(pStack); - int favoriteIndex = this.favoriteIndexes.getOrDefault(pStack, -1); - boolean needsUpdate = false; - - if (perms == null) { - perms = pStack.getFilteredPermutations(); - favoriteIndex = -1; - - if (perms.size() > 1) { - for (ItemStack item : perms) { - if (!FavoriteRecipes.containsManual(item)) break; - favoriteIndex++; - } - } - - this.permutations.put(pStack, perms); - this.favoriteIndexes.put(pStack, favoriteIndex); - needsUpdate = true; - } - - if (perms.size() > 1 || needsUpdate) { - final int size = favoriteIndex != -1 ? favoriteIndex + 1 : perms.size(); - - if (size > 0) { - pStack.setPermutationToRender(perms.get(this.lastcycle % size)); - } - } - } - - protected List getInputs() { - return this.handlerRef.handler.getIngredientStacks(this.handlerRef.recipeIndex); - } - - protected List 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 getCatalysts() { - if (this.handlerRef.handler.getResultStack(this.handlerRef.recipeIndex) == null) { - return Collections.emptyList(); - } - return this.handlerRef.handler.getOtherStacks(this.handlerRef.recipeIndex); - } - -} diff --git a/src/main/java/codechicken/nei/recipe/RecipeHandlerRef.java b/src/main/java/codechicken/nei/recipe/RecipeHandlerRef.java index 57520575..626dc675 100644 --- a/src/main/java/codechicken/nei/recipe/RecipeHandlerRef.java +++ b/src/main/java/codechicken/nei/recipe/RecipeHandlerRef.java @@ -36,12 +36,12 @@ public class RecipeHandlerRef { .getCraftingHandlers("recipeId", recipeId.getResult(), recipeId); for (ICraftingHandler handler : handlers) { - int refIndex = SearchRecipeHandler.findFirst( + int recipeIndex = SearchRecipeHandler.findFirst( handler, - recipeIndex -> recipeId.equalsIngredients(handler.getIngredientStacks(recipeIndex))); + index -> recipeId.equalsIngredients(handler.getIngredientStacks(index))); - if (refIndex >= 0) { - return new RecipeHandlerRef(handler, refIndex); + if (recipeIndex >= 0) { + return new RecipeHandlerRef(handler, recipeIndex); } } @@ -66,10 +66,6 @@ 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); diff --git a/src/main/java/codechicken/nei/recipe/RecipePageManager.java b/src/main/java/codechicken/nei/recipe/RecipePageManager.java index 9001ad57..654a4d41 100644 --- a/src/main/java/codechicken/nei/recipe/RecipePageManager.java +++ b/src/main/java/codechicken/nei/recipe/RecipePageManager.java @@ -2,10 +2,13 @@ package codechicken.nei.recipe; import java.util.ArrayList; import java.util.Collections; +import java.util.HashMap; import java.util.List; +import java.util.Map; import codechicken.nei.NEIClientConfig; import codechicken.nei.Widget; +import codechicken.nei.recipe.widget.RecipeWidget; import codechicken.nei.scroll.ScrollContainer; public class RecipePageManager { @@ -16,7 +19,6 @@ public class RecipePageManager { private String cacheKey = ""; private int currentPageIndex = -1; - private List recipeIndices = new ArrayList<>(); private List> pageWidgets = new ArrayList<>(); public RecipePageManager(SearchRecipeHandler handler, HandlerInfo handlerInfo, ScrollContainer container) { @@ -52,12 +54,28 @@ public class RecipePageManager { final int width = Math.max(166, this.handlerInfo.getWidth()); final List searchRecipes = this.handler.getFilteredRecipes(); final int numRecipes = searchRecipes.size(); + final List> groupedRecipes = new ArrayList<>(); + final Map groupEndIndices = new HashMap<>(); List widgets = new ArrayList<>(); int shiftY = 0; for (int i = 0; i < numRecipes; i++) { final int recipeIndex = searchRecipes.get(i); - final NEIRecipeWidget widget = RecipeHandlerRef.of(this.handler.original, recipeIndex).getRecipeWidget(); + final Object groupId = this.handler.original.getRecipeGroupId(recipeIndex); + final int groupIndex = groupId != null + ? groupEndIndices.computeIfAbsent(groupId, k -> groupedRecipes.size()) + : groupedRecipes.size(); + + if (groupedRecipes.size() <= groupIndex) { + groupedRecipes.add(new ArrayList<>()); + } + + groupedRecipes.get(groupIndex).add(recipeIndex); + } + + for (int groupIndex = 0; groupIndex < groupedRecipes.size(); groupIndex++) { + final RecipeWidget widget = new RecipeWidget(this.handler.original, groupedRecipes.get(groupIndex)); + widget.w = width; if (allowOverflowY) { @@ -109,29 +127,21 @@ public class RecipePageManager { } this.currentPageIndex = page; - this.recipeIndices = new ArrayList<>(); - - for (Widget widget : getCurrentPageWidgets()) { - if (widget instanceof NEIRecipeWidget recipeWidget) { - this.recipeIndices.add(recipeWidget.getRecipeHandlerRef().recipeIndex); - } - } - this.container.setVerticalScrollOffset(0); } - public void gotoRefIndex(int refIndex) { - int page = 0; + public boolean gotoRecipeIndex(int recipeIndex) { - for (int i = 0; i < this.pageWidgets.size(); i++) { - refIndex -= this.pageWidgets.get(i).size(); - if (refIndex < 0) { - page = i; - break; + for (int page = 0; page < this.pageWidgets.size(); page++) { + for (Widget widget : this.pageWidgets.get(page)) { + if (widget instanceof RecipeWidget recipeWidget && recipeWidget.containsRecipeIndex(recipeIndex)) { + changePage(page - this.currentPageIndex); + return true; + } } } - changePage(page); + return false; } public List getCurrentPageWidgets() { @@ -143,7 +153,7 @@ public class RecipePageManager { int shiftY = 0; for (Widget widget : currentWidgets) { - if (widget instanceof NEIRecipeWidget recipeWidget) { + if (widget instanceof RecipeWidget recipeWidget) { recipeWidget.setLocation(2, shiftY); } shiftY += widget.h; @@ -153,7 +163,20 @@ public class RecipePageManager { } public List getRecipeIndices() { - return this.recipeIndices; + + if (this.pageWidgets.isEmpty()) { + return Collections.emptyList(); + } + + final List recipeIndices = new ArrayList<>(); + + for (Widget widget : this.pageWidgets.get(this.currentPageIndex)) { + if (widget instanceof RecipeWidget recipeWidget) { + recipeIndices.add(recipeWidget.getRecipeHandlerRef().recipeIndex); + } + } + + return recipeIndices; } } diff --git a/src/main/java/codechicken/nei/recipe/RecipeTooltipLineHandler.java b/src/main/java/codechicken/nei/recipe/RecipeTooltipLineHandler.java index 147d7a53..b11f5c3e 100644 --- a/src/main/java/codechicken/nei/recipe/RecipeTooltipLineHandler.java +++ b/src/main/java/codechicken/nei/recipe/RecipeTooltipLineHandler.java @@ -12,6 +12,7 @@ import codechicken.nei.drawable.DrawableBuilder; import codechicken.nei.drawable.DrawableResource; import codechicken.nei.guihook.GuiContainerManager; import codechicken.nei.recipe.Recipe.RecipeId; +import codechicken.nei.recipe.widget.RecipeWidget; import codechicken.nei.scroll.GuiHelper; import codechicken.nei.util.ReadableNumberConverter; @@ -30,7 +31,7 @@ public class RecipeTooltipLineHandler implements ITooltipLineHandler { protected String recipeName = ""; protected GuiRecipe gui = null; protected RecipeHandlerRef handlerRef = null; - protected NEIRecipeWidget widget = null; + protected RecipeWidget widget = null; protected RecipeId recipeId = null; protected boolean createdGui = false; protected long multiplier = 0; @@ -63,13 +64,13 @@ public class RecipeTooltipLineHandler implements ITooltipLineHandler { this.handlerRef = RecipeHandlerRef.of(this.recipeId); this.createdGui = true; - if (handlerRef != null) { - this.widget = new NEIRecipeWidget(this.handlerRef); + if (this.handlerRef != null) { + this.widget = new RecipeWidget(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(); + this.recipeName = this.handlerRef.handler.getRecipeName().trim(); } } diff --git a/src/main/java/codechicken/nei/recipe/SearchRecipeHandler.java b/src/main/java/codechicken/nei/recipe/SearchRecipeHandler.java index 92f73614..23e8b079 100644 --- a/src/main/java/codechicken/nei/recipe/SearchRecipeHandler.java +++ b/src/main/java/codechicken/nei/recipe/SearchRecipeHandler.java @@ -52,15 +52,10 @@ class SearchRecipeHandler { public static int findFirst(IRecipeHandler handler, IntPredicate predicate) { final IRecipeFilter filter = searchingAvailable(handler) ? GuiRecipe.getRecipeListFilter() : null; - int refIndex = -1; for (int recipeIndex = 0; recipeIndex < handler.numRecipes(); recipeIndex++) { - if (filter == null || mathRecipe(handler, recipeIndex, filter)) { - refIndex++; - - if (predicate.test(recipeIndex)) { - return refIndex; - } + if ((filter == null || mathRecipe(handler, recipeIndex, filter)) && predicate.test(recipeIndex)) { + return recipeIndex; } } diff --git a/src/main/java/codechicken/nei/recipe/debug/DebugHandlerWidget.java b/src/main/java/codechicken/nei/recipe/debug/DebugHandlerWidget.java index 9931642a..70f64a57 100644 --- a/src/main/java/codechicken/nei/recipe/debug/DebugHandlerWidget.java +++ b/src/main/java/codechicken/nei/recipe/debug/DebugHandlerWidget.java @@ -37,9 +37,9 @@ import codechicken.nei.recipe.GuiRecipeButton; import codechicken.nei.recipe.GuiRecipeTab; import codechicken.nei.recipe.HandlerInfo; import codechicken.nei.recipe.IRecipeHandler; -import codechicken.nei.recipe.NEIRecipeWidget; import codechicken.nei.recipe.TemplateRecipeHandler; import codechicken.nei.recipe.TemplateRecipeHandler.RecipeTransferRect; +import codechicken.nei.recipe.widget.RecipeWidget; import codechicken.nei.scroll.ScrollContainer; public class DebugHandlerWidget extends Widget { @@ -532,7 +532,7 @@ public class DebugHandlerWidget extends Widget { } } - public void drawGuiPlaceholder(NEIRecipeWidget widget) { + public void drawGuiPlaceholder(RecipeWidget widget) { if (!this.showWidget) return; NEIClientUtils.gl2DRenderContext(() -> { diff --git a/src/main/java/codechicken/nei/recipe/widget/PermutationsCycler.java b/src/main/java/codechicken/nei/recipe/widget/PermutationsCycler.java new file mode 100644 index 00000000..cfc3eed1 --- /dev/null +++ b/src/main/java/codechicken/nei/recipe/widget/PermutationsCycler.java @@ -0,0 +1,99 @@ +package codechicken.nei.recipe.widget; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.function.Function; + +import net.minecraft.item.ItemStack; + +import codechicken.nei.FavoriteRecipes; +import codechicken.nei.NEIServerUtils; + +public class PermutationsCycler { + + protected final Map> permutations; + protected final Map favoriteCounts; + protected final Function> loader; + protected Runnable onInvalidate = null; + + protected int favoriteRevision = -1; + + public PermutationsCycler(Map> storage, Map favoriteStorage, + Function> loader) { + this.permutations = storage; + this.favoriteCounts = favoriteStorage; + this.loader = loader; + } + + public PermutationsCycler onInvalidate(Runnable callback) { + this.onInvalidate = callback; + return this; + } + + public boolean validate() { + final int rev = FavoriteRecipes.getRevision(); + + if (this.favoriteRevision != rev) { + this.favoriteRevision = rev; + this.permutations.clear(); + this.favoriteCounts.clear(); + + if (this.onInvalidate != null) { + this.onInvalidate.run(); + } + + return true; + } + + return false; + } + + public boolean contains(K key) { + validate(); + return this.permutations.containsKey(key); + } + + public List get(K key) { + validate(); + List items = this.permutations.get(key); + + if (items == null) { + items = new ArrayList<>(this.loader.apply(key)); + items.sort(Comparator.comparing(FavoriteRecipes::containsManual).reversed()); + + int favoriteCount = 0; + + if (items.size() > 1) { + for (ItemStack stack : items) { + if (!FavoriteRecipes.containsManual(stack)) break; + favoriteCount++; + } + } + + this.permutations.put(key, items); + this.favoriteCounts.put(key, favoriteCount); + } + + return items; + } + + public ItemStack getCycled(K key, int cycle) { + final List items = get(key); + final int favoriteCount = this.favoriteCounts.getOrDefault(key, 0); + final int size = favoriteCount > 0 ? favoriteCount : items.size(); + + return size > 0 ? items.get(cycle % size) : null; + } + + public static int indexOf(List list, ItemStack stack) { + for (int i = 0; i < list.size(); i++) { + if (NEIServerUtils.areStacksSameType(list.get(i), stack)) { + return i; + } + } + return -1; + } + +} diff --git a/src/main/java/codechicken/nei/recipe/widget/RecipeGroup.java b/src/main/java/codechicken/nei/recipe/widget/RecipeGroup.java new file mode 100644 index 00000000..010a5298 --- /dev/null +++ b/src/main/java/codechicken/nei/recipe/widget/RecipeGroup.java @@ -0,0 +1,210 @@ +package codechicken.nei.recipe.widget; + +import java.awt.Point; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import net.minecraft.item.ItemStack; + +import codechicken.nei.FavoriteRecipes; +import codechicken.nei.PositionedStack; +import codechicken.nei.recipe.GuiRecipeTab; +import codechicken.nei.recipe.HandlerInfo; +import codechicken.nei.recipe.IRecipeHandler; + +public class RecipeGroup { + + private static final List SINGLE_MEMBER = Collections.singletonList(0); + + private final IRecipeHandler handler; + private final List recipeIndices; + private final HandlerInfo handlerInfo; + private final PermutationsCycler slotPermutations; + + private List allowedMembers = null; + + public RecipeGroup(IRecipeHandler handler, List recipeIndices) { + this.handler = handler; + this.recipeIndices = new ArrayList<>(recipeIndices); + this.handlerInfo = GuiRecipeTab.getHandlerInfo(handler); + this.slotPermutations = new PermutationsCycler( + new HashMap<>(), + new HashMap<>(), + this::collectSlotPermutations).onInvalidate(() -> this.allowedMembers = null); + } + + public int size() { + return this.recipeIndices.size(); + } + + public IRecipeHandler getHandler() { + return this.handler; + } + + public int getRecipeIndex(int member) { + return this.recipeIndices.get(member); + } + + public HandlerInfo getHandlerInfo() { + return this.handlerInfo; + } + + public boolean contains(int recipeIndex) { + return this.recipeIndices.contains(recipeIndex); + } + + public List getPermutations(Point slotKey) { + return this.slotPermutations.get(slotKey); + } + + public List getInputs(int member) { + return this.handler.getIngredientStacks(getRecipeIndex(member)); + } + + public List getOutputs(int member) { + final int recipeIndex = getRecipeIndex(member); + final PositionedStack pStackResult = this.handler.getResultStack(recipeIndex); + return pStackResult != null ? Arrays.asList(pStackResult) : this.handler.getOtherStacks(recipeIndex); + } + + public List getCatalysts(int member) { + final int recipeIndex = getRecipeIndex(member); + + if (this.handler.getResultStack(recipeIndex) == null) { + return Collections.emptyList(); + } + + return this.handler.getOtherStacks(recipeIndex); + } + + public List getCyclingStacks(int member) { + final List stacks = new ArrayList<>(getInputs(member)); + stacks.addAll(getCatalysts(member)); + return stacks; + } + + public Point getSlotKey(PositionedStack pStack) { + return new Point(pStack.relx, pStack.rely); + } + + public PositionedStack getSlot(int member, Point slotKey) { + + for (PositionedStack pStack : getCyclingStacks(member)) { + if (pStack.relx == slotKey.x && pStack.rely == slotKey.y) { + return pStack; + } + } + + return null; + } + + public PositionedStack getOutputSlot(int member, Point slotKey) { + + for (PositionedStack pStack : getOutputs(member)) { + if (pStack.relx == slotKey.x && pStack.rely == slotKey.y) { + return pStack; + } + } + + return null; + } + + public List getOutputVariants(Point slotKey) { + final List items = new ArrayList<>(); + + for (int member = 0; member < size(); member++) { + final PositionedStack slot = getOutputSlot(member, slotKey); + + if (slot != null && PermutationsCycler.indexOf(items, slot.item) == -1) { + items.add(slot.item); + } + } + + return items; + } + + public List getAllowedMembers() { + this.slotPermutations.validate(); + + if (size() == 1) { + return SINGLE_MEMBER; + } + + if (this.allowedMembers == null) { + final Set favoriteSlots = new HashSet<>(); + + for (int member = 0; member < size(); member++) { + for (PositionedStack pStack : getCyclingStacks(member)) { + final Point slotKey = getSlotKey(pStack); + final List items = getPermutations(slotKey); + + if (items.size() > 1 && items.stream().anyMatch(FavoriteRecipes::containsManual)) { + favoriteSlots.add(slotKey); + } + } + } + + this.allowedMembers = filterMembers(favoriteSlots); + } + + return this.allowedMembers; + } + + protected List filterMembers(Set favoriteSlots) { + final List indices = new ArrayList<>(); + int minMisses = Integer.MAX_VALUE; + + for (int member = 0; member < size(); member++) { + final int misses = countMissingFavorites(member, favoriteSlots); + + if (misses < minMisses) { + minMisses = misses; + indices.clear(); + } + + if (misses == minMisses) { + indices.add(member); + } + } + + return indices; + } + + protected int countMissingFavorites(int member, Set favoriteSlots) { + int misses = 0; + + for (Point slotKey : favoriteSlots) { + final PositionedStack slot = getSlot(member, slotKey); + + if (slot != null && slot.getFilteredPermutations().stream().noneMatch(FavoriteRecipes::containsManual)) { + misses++; + } + } + + return misses; + } + + protected List collectSlotPermutations(Point slotKey) { + final List items = new ArrayList<>(); + + for (int member = 0; member < size(); member++) { + final PositionedStack slot = getSlot(member, slotKey); + + if (slot != null) { + for (ItemStack stack : slot.getFilteredPermutations()) { + if (PermutationsCycler.indexOf(items, stack) == -1) { + items.add(stack); + } + } + } + } + + return items; + } + +} diff --git a/src/main/java/codechicken/nei/recipe/widget/RecipeWidget.java b/src/main/java/codechicken/nei/recipe/widget/RecipeWidget.java new file mode 100644 index 00000000..00120e97 --- /dev/null +++ b/src/main/java/codechicken/nei/recipe/widget/RecipeWidget.java @@ -0,0 +1,834 @@ +package codechicken.nei.recipe.widget; + +import java.awt.Point; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.WeakHashMap; +import java.util.function.Function; + +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.lib.vec.Rectangle4i; +import codechicken.nei.FavoriteRecipes; +import codechicken.nei.ItemsTooltipLineHandler; +import codechicken.nei.KeyManager; +import codechicken.nei.NEIClientConfig; +import codechicken.nei.NEIClientUtils; +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.AcceptsFollowingTooltipLineHandler; +import codechicken.nei.recipe.Badge; +import codechicken.nei.recipe.GuiFavoriteButton; +import codechicken.nei.recipe.GuiOverlayButton; +import codechicken.nei.recipe.GuiRecipe; +import codechicken.nei.recipe.GuiRecipeButton; +import codechicken.nei.recipe.GuiRecipeButton.UpdateRecipeButtonsEvent; +import codechicken.nei.recipe.HandlerInfo; +import codechicken.nei.recipe.IRecipeHandler; +import codechicken.nei.recipe.RecipeHandlerRef; +import codechicken.nei.recipe.StackInfo; +import codechicken.nei.recipe.debug.DebugHandlerWidget; +import codechicken.nei.util.NEIMouseUtils; + +public class RecipeWidget extends Widget { + + protected static final int TICKS_PER_CYCLE = 20; + + protected final RecipeGroup group; + protected final IRecipeHandler handler; + protected final HandlerInfo handlerInfo; + + protected final PermutationsCycler renderPermutations; + + protected final Map> badgeCache = new WeakHashMap<>(); + protected final Map> buttonCache = new HashMap<>(); + + protected AcceptsFollowingTooltipLineHandler acceptsTooltip; + protected ItemsTooltipLineHandler variantsTooltip; + protected Point variantsSlotKey; + + protected int activeMember = 0; + protected int memberCursor = -1; + protected int slotCycle = 0; + protected int cycleticks = 0; + protected int lastcycle = -1; + + protected boolean showAsWidget = false; + protected boolean update = true; + + public RecipeWidget(RecipeHandlerRef handlerRef) { + this(handlerRef.handler, Collections.singletonList(handlerRef.recipeIndex)); + } + + public RecipeWidget(IRecipeHandler handler, List recipeIndices) { + this(new RecipeGroup(handler, recipeIndices)); + } + + public RecipeWidget(RecipeGroup group) { + this.group = group; + this.handler = group.getHandler(); + this.handlerInfo = group.getHandlerInfo(); + this.renderPermutations = new PermutationsCycler( + new WeakHashMap<>(), + new WeakHashMap<>(), + PositionedStack::getFilteredPermutations).onInvalidate(() -> { + this.badgeCache.clear(); + this.acceptsTooltip = null; + }); + update(); + } + + public RecipeHandlerRef getRecipeHandlerRef() { + return RecipeHandlerRef.of(this.handler, getRecipeIndex()); + } + + protected int getRecipeIndex() { + return this.group.getRecipeIndex(this.activeMember); + } + + public boolean containsRecipeIndex(int recipeIndex) { + return this.group.contains(recipeIndex); + } + + public HandlerInfo getHandlerInfo() { + return this.handlerInfo; + } + + public void setLocation(int x, int y) { + this.x = x; + this.y = y; + } + + public void showAsWidget(boolean show) { + this.showAsWidget = show; + } + + @Override + public void update() { + + if (this.showAsWidget || !this.handlerInfo.isAllowOverflowY()) { + int maxHeight = 0; + + for (int member = 0; member < this.group.size(); member++) { + final int recipeHeight = this.handler.getRecipeHeight(this.group.getRecipeIndex(member)); + + if (recipeHeight > 0) { + maxHeight = Math.max(maxHeight, recipeHeight); + } + } + + this.w = Math.max(166, this.handlerInfo.getWidth()); + this.h = (maxHeight > 0 ? maxHeight : this.handlerInfo.getHeight()) + this.handlerInfo.getYShift(); + } + + this.update = true; + } + + public List getRecipeButtons() { + return this.buttonCache.computeIfAbsent(this.activeMember, this::createButtons); + } + + protected List getRecipeButtonsIfInit() { + return this.buttonCache.getOrDefault(this.activeMember, Collections.emptyList()); + } + + protected List createButtons(int member) { + + if (this.group.getOutputs(member).isEmpty()) { + return Collections.emptyList(); + } + + return Collections + .unmodifiableList(initButtons(RecipeHandlerRef.of(this.handler, this.group.getRecipeIndex(member)))); + } + + protected List initButtons(RecipeHandlerRef ref) { + final GuiRecipe guiRecipe = getGuiRecipe(); + + if (guiRecipe != null) { + final UpdateRecipeButtonsEvent.Pre preEvent = new UpdateRecipeButtonsEvent.Pre( + guiRecipe, + ref, + this.handlerInfo); + + if (MinecraftForge.EVENT_BUS.post(preEvent)) { + return preEvent.buttonList; + } else { + final UpdateRecipeButtonsEvent.Post postEvent = new UpdateRecipeButtonsEvent.Post( + guiRecipe, + ref, + getDefaultButtons(ref)); + MinecraftForge.EVENT_BUS.post(postEvent); + return postEvent.buttonList; + } + + } else { + return getDefaultButtons(ref); + } + + } + + protected List getDefaultButtons(RecipeHandlerRef ref) { + GuiContainer guiContainer = NEIClientUtils.getGuiContainer(); + final List buttons = new ArrayList<>(); + final boolean showFavorites = NEIClientConfig.favoritesEnabled() && handlerInfo.getShowFavoritesButton(); + final boolean showOverlay = handlerInfo.getShowOverlayButton(); + final int x = Math.min(166, 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, ref, x, y)); + y -= GuiRecipeButton.BUTTON_HEIGHT + 1; + } + + if (showFavorites) { + buttons.add(new GuiFavoriteButton(ref, x, y)); + } + + return buttons; + } + + @Override + public void draw(int mouseX, int mouseY) { + final int yShift = this.handlerInfo.getYShift(); + + if (this.update) { + this.update = false; + + if (tickCycle()) { + + if (this.showAsWidget || !contains(mouseX, mouseY)) { + nextMember(); + } + + updatePermutations(this.lastcycle); + } + + for (GuiRecipeButton button : getRecipeButtons()) { + button.update(); + } + } + + final int recipeIndex = getRecipeIndex(); + + GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_LIGHTING_BIT); + GL11.glTranslatef(this.x, this.y + yShift, 0); + + this.handler.drawBackground(recipeIndex); + + RenderHelper.enableGUIStandardItemLighting(); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + GL11.glColor4f(1, 1, 1, 1); + + GuiContainerManager.enableMatrixStackLogging(); + + for (PositionedStack pStack : getInputs()) { + + if (!this.renderPermutations.contains(pStack)) { + updatePermutationsFor(pStack); + } + + drawItem(pStack, mouseX, mouseY, yShift, true); + } + + for (PositionedStack pStack : getCatalysts()) { + + if (!this.renderPermutations.contains(pStack)) { + updatePermutationsFor(pStack); + } + + drawItem(pStack, mouseX, mouseY, yShift, true); + } + + for (PositionedStack pStack : getOutputs()) { + drawItem(pStack, mouseX, mouseY, yShift, false); + } + + GuiContainerManager.disableMatrixStackLogging(); + + this.handler.drawForeground(recipeIndex); + + final GuiRecipeButton overlayButton = forEachButtons( + button -> (this.showAsWidget ? button instanceof GuiOverlayButton : button.contains(mouseX, mouseY)) + ? button + : null, + null); + + if (overlayButton != null) { + 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; + } + } + + DebugHandlerWidget.instance.drawGuiPlaceholder(this); + } + + protected void drawItem(PositionedStack pStack, int mouseX, int mouseY, int yShift, boolean input) { + pStack.draw(mouseX - this.x, mouseY - this.y - yShift); + + if (this.handlerInfo.getShowBadge()) { + drawBadge(pStack, input); + } + + if (pStack.contains(mouseX - this.x, mouseY - this.y - yShift)) { + NEIClientUtils.gl2DRenderContext( + () -> GuiDraw.drawRect(pStack.relx, pStack.rely, pStack.width, pStack.height, 0x80FFFFFF)); + } + } + + protected List getBadges(PositionedStack pStack, boolean input) { + + return this.badgeCache.computeIfAbsent(pStack, k -> { + final List badges = k.getBadges(); + + if (badges == null) { + + if (input) { + if (StackInfo.getAmount(pStack.item) == 0) { + return Collections.singletonList(Badge.notConsumed()); + } else if (pStack.getChance() == 0) { + return Collections.singletonList(Badge.notConsumedParallel()); + } else if (pStack.getChance() != PositionedStack.CHANCE_FULL) { + return Collections.singletonList( + Badge.consumeChance(pStack.getChance() / (float) PositionedStack.CHANCE_FULL)); + } + } else if (pStack.getChance() != PositionedStack.CHANCE_FULL) { + return Collections.singletonList( + Badge.outputChance(pStack.getChance() / (float) PositionedStack.CHANCE_FULL)); + } + + return Collections.emptyList(); + } + + return badges; + }); + + } + + protected void drawBadge(PositionedStack pStack, boolean input) { + final List badges = getBadges(pStack, input); + + for (Badge badge : badges) { + badge.draw(new Rectangle4i(pStack.relx, pStack.rely, pStack.width, pStack.height)); + } + } + + @Override + public boolean handleKeyPress(int keyID, char keyChar) { + + if (NEIClientConfig.favoritesEnabled() + && KeyManager.isHashDown("bookmark.favorite_item", NEIClientUtils.SHIFT_HASH)) { + final Point mouse = GuiDraw.getMousePosition(); + final PositionedStack hovered = getCyclingStackMouseOver(mouse.x, mouse.y); + + if (hovered != null && getPermutations(hovered).size() > 1) { + FavoriteRecipes.toggleFavoriteItem(hovered.item); + return true; + } + + } + + 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.handler.mouseClicked(guiRecipe, button, getRecipeIndex()); + } + + @Override + public List handleTooltip(int mouseX, int mouseY, List tooltip) { + final GuiRecipe guiRecipe = getGuiRecipe(); + + if (guiRecipe == null) { + return tooltip; + } + + final List buttonTooltip = forEachButtons( + button -> button.contains(mouseX, mouseY) ? button.handleTooltip(tooltip) : null, + null); + + if (buttonTooltip != null) { + return buttonTooltip; + } + + return this.handler.handleTooltip(guiRecipe, tooltip, getRecipeIndex()); + } + + @Override + public List handleItemTooltip(ItemStack itemstack, int mousex, int mousey, List tooltip) { + final GuiRecipe guiRecipe = getGuiRecipe(); + + if (guiRecipe == null) { + return tooltip; + } + + tooltip = this.handler.handleItemTooltip(guiRecipe, itemstack, tooltip, getRecipeIndex()); + final PositionedStack cycling = itemstack != null ? getCyclingStackMouseOver(mousex, mousey) : null; + final PositionedStack hovered = cycling != null ? cycling + : itemstack != null ? getOutputStackMouseOver(mousex, mousey) : null; + + if (hovered != null) { + if (this.handlerInfo.getShowBadge()) { + final List badges = getBadges(hovered, cycling != null); + + for (Badge badge : badges) { + if (badge.getTooltip() != null && !badge.getTooltip().isEmpty()) { + tooltip.addAll(badge.getTooltip()); + } + } + } + + final List customTooltip = hovered.getTooltip(); + + if (customTooltip != null && !customTooltip.isEmpty()) { + tooltip.addAll(customTooltip); + } + } + + final Point slotKey = cycling != null ? this.group.getSlotKey(cycling) : null; + + if (slotKey == null || !NEIClientConfig.showCycledIngredientsTooltip() + || this.group.getPermutations(slotKey).size() <= 1) { + this.acceptsTooltip = null; + } else if (this.acceptsTooltip == null || !slotKey.equals(this.acceptsTooltip.tooltipGUID)) { + this.acceptsTooltip = AcceptsFollowingTooltipLineHandler + .of(slotKey, this.group.getPermutations(slotKey), cycling.item); + + if (this.acceptsTooltip != null && cycling.getAcceptsLabel() != null) { + this.acceptsTooltip.setLabel(cycling.getAcceptsLabel()); + } + } + + if (this.acceptsTooltip != null) { + tooltip.add(GuiDraw.TOOLTIP_HANDLER + GuiDraw.getTipLineId(this.acceptsTooltip)); + } + + final Point outputKey = cycling == null && hovered != null && this.group.size() > 1 + ? this.group.getSlotKey(hovered) + : null; + + if (outputKey == null || !NEIClientConfig.showCycledIngredientsTooltip()) { + this.variantsTooltip = null; + this.variantsSlotKey = null; + } else if (!outputKey.equals(this.variantsSlotKey)) { + final List variants = this.group.getOutputVariants(outputKey); + + this.variantsSlotKey = outputKey; + this.variantsTooltip = variants.size() > 1 + ? new ItemsTooltipLineHandler(NEIClientUtils.translate("recipe.group"), variants, false, 4) + : null; + + if (this.variantsTooltip != null) { + this.variantsTooltip.setActiveStack(hovered.item); + } + } + + if (this.variantsTooltip != null) { + tooltip.add(GuiDraw.TOOLTIP_HANDLER + GuiDraw.getTipLineId(this.variantsTooltip)); + } + + return tooltip; + } + + @Override + public Map handleHotkeys(int mouseX, int mouseY, Map hotkeys) { + final Map buttonHotkeys = forEachButtons( + button -> button.contains(mouseX, mouseY) ? button.handleHotkeys(mouseX, mouseY, hotkeys) : null, + hotkeys); + final PositionedStack hovered = getCyclingStackMouseOver(mouseX, mouseY); + + if (hovered != null && getPermutations(hovered).size() > 1) { + hotkeys.put( + KeyManager.getKeyName("bookmark.favorite_item", NEIClientUtils.SHIFT_HASH), + NEIClientUtils.translate("recipe.favorite.toggle")); + } + + if (hovered == null && this.group.size() > 1 && getOutputStackMouseOver(mouseX, mouseY) != null) { + hotkeys.put( + NEIClientUtils.getKeyName( + NEIClientUtils.SHIFT_HASH, + NEIMouseUtils.MOUSE_BTN_NONE + NEIMouseUtils.MOUSE_SCROLL), + NEIClientUtils.translate("recipe.group.scroll", this.activeMember + 1, this.group.size())); + } + + if (hovered != null && this.acceptsTooltip != 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 (NEIClientUtils.shiftKey()) { + final PositionedStack hovered = getCyclingStackMouseOver(mx, my); + + if (hovered != null && scrollPermutations(scroll, hovered)) { + return true; + } + + if (hovered == null && getOutputStackMouseOver(mx, my) != null && scrollMembers(scroll)) { + return true; + } + } + + final GuiRecipe guiRecipe = getGuiRecipe(); + return guiRecipe != null && this.handler.mouseScrolled(guiRecipe, scroll, getRecipeIndex()); + } + + protected boolean scrollPermutations(int scroll, PositionedStack hovered) { + final Point slotKey = this.group.getSlotKey(hovered); + final List items = this.group.getPermutations(slotKey); + + if (items.size() <= 1) { + return false; + } + + final List slots = new ArrayList<>(this.group.size()); + + for (int member = 0; member < this.group.size(); member++) { + slots.add(this.group.getSlot(member, slotKey)); + } + + final int anchor = getCursorMember(); + final int currentItem = PermutationsCycler.indexOf(items, hovered.item); + final List variants = new ArrayList<>(); + int current = 0; + + for (int itemIndex = 0; itemIndex < items.size(); itemIndex++) { + final ItemStack stack = items.get(itemIndex); + int member = containsStack(slots.get(this.activeMember), stack) ? this.activeMember : -1; + + for (int offset = 0; member == -1 && offset < slots.size(); offset++) { + if (containsStack(slots.get((anchor + offset) % slots.size()), stack)) { + member = (anchor + offset) % slots.size(); + } + } + + if (member != -1) { + if (itemIndex == currentItem) { + current = variants.size(); + } + variants.add(new int[] { itemIndex, member }); + } + } + + if (variants.isEmpty()) { + return false; + } + + final int[] next = variants.get(((current - scroll) % variants.size() + variants.size()) % variants.size()); + switchMember(next[1], items.get(next[0])); + + return true; + } + + protected boolean scrollMembers(int scroll) { + final int size = this.group.size(); + + if (size <= 1) { + return false; + } + + switchMember(((this.activeMember - scroll) % size + size) % size, null); + + return true; + } + + protected void switchMember(int member, ItemStack stack) { + final Map rendered = new HashMap<>(); + + for (PositionedStack pStack : getCyclingStacks()) { + rendered.put(this.group.getSlotKey(pStack), pStack.item); + } + + setActiveMember(member); + + for (PositionedStack pStack : getCyclingStacks()) { + final ItemStack renderStack = containsStack(pStack, stack) ? stack + : rendered.get(this.group.getSlotKey(pStack)); + + if (containsStack(pStack, renderStack)) { + pStack.setPermutationToRender(renderStack); + } + } + + updateTooltipActiveStack(); + notifyPermutationsChanged(); + } + + protected boolean tickCycle() { + + if (!NEIClientUtils.shiftKey() && (this.cycleticks++ / TICKS_PER_CYCLE) != this.lastcycle + || this.lastcycle == -1) { + this.lastcycle = this.cycleticks / TICKS_PER_CYCLE; + return true; + } + + return false; + } + + protected void nextMember() { + final List allowed = this.group.getAllowedMembers(); + + this.memberCursor = (this.memberCursor + 1) % allowed.size(); + setActiveMember(allowed.get(this.memberCursor)); + } + + protected int getCursorMember() { + final List allowed = this.group.getAllowedMembers(); + return allowed.get(Math.max(0, this.memberCursor) % allowed.size()); + } + + protected void updatePermutations(int cycle) { + this.slotCycle = cycle; + + for (PositionedStack pStack : getCyclingStacks()) { + updatePermutationsFor(pStack); + } + + updateTooltipActiveStack(); + notifyPermutationsChanged(); + } + + protected void updateTooltipActiveStack() { + + if (this.acceptsTooltip != null && this.acceptsTooltip.tooltipGUID instanceof Point slotKey) { + final PositionedStack pStack = this.group.getSlot(this.activeMember, slotKey); + + if (pStack != null) { + this.acceptsTooltip.setActiveStack(pStack.item); + } + } + + if (this.variantsTooltip != null) { + final PositionedStack pStack = this.group.getOutputSlot(this.activeMember, this.variantsSlotKey); + + if (pStack != null) { + this.variantsTooltip.setActiveStack(pStack.item); + } + } + + } + + protected void updatePermutationsFor(PositionedStack pStack) { + + if (!this.renderPermutations.contains(pStack) || this.renderPermutations.get(pStack).size() > 1) { + final ItemStack stack = this.renderPermutations.getCycled(pStack, this.slotCycle); + + if (stack != null) { + pStack.setPermutationToRender(stack); + } + } + + } + + protected void setActiveMember(int member) { + + if (member != this.activeMember) { + this.activeMember = member; + + for (GuiRecipeButton button : getRecipeButtonsIfInit()) { + button.update(); + } + } + + } + + protected boolean containsStack(PositionedStack pStack, ItemStack stack) { + return pStack != null && stack != null + && PermutationsCycler.indexOf(pStack.getFilteredPermutations(), stack) != -1; + } + + protected List getPermutations(PositionedStack pStack) { + return this.group.getPermutations(this.group.getSlotKey(pStack)); + } + + protected void notifyPermutationsChanged() { + for (GuiRecipeButton button : getRecipeButtonsIfInit()) { + button.onPermutationsChanged(); + } + } + + protected R forEachButtons(Function 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 PositionedStack cycling = getCyclingStackMouseOver(mx, my); + return cycling != null ? cycling : getOutputStackMouseOver(mx, my); + } + + protected PositionedStack getOutputStackMouseOver(int mx, int my) { + final int yShift = this.handlerInfo.getYShift(); + + for (PositionedStack pStack : getOutputs()) { + if (pStack.contains(mx - this.x, my - this.y - yShift)) { + return pStack; + } + } + + return null; + } + + protected PositionedStack getCyclingStackMouseOver(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; + } + } + + 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 GuiRecipeguiRecipe) { + return guiRecipe; + } + + return null; + } + + protected List getInputs() { + return this.group.getInputs(this.activeMember); + } + + protected List getOutputs() { + return this.group.getOutputs(this.activeMember); + } + + protected List getCatalysts() { + return this.group.getCatalysts(this.activeMember); + } + + protected List getCyclingStacks() { + return this.group.getCyclingStacks(this.activeMember); + } + +} diff --git a/src/main/resources/assets/nei/lang/en_US.lang b/src/main/resources/assets/nei/lang/en_US.lang index 87874ab3..5e69212e 100644 --- a/src/main/resources/assets/nei/lang/en_US.lang +++ b/src/main/resources/assets/nei/lang/en_US.lang @@ -682,6 +682,8 @@ nei.recipe.concurrent.usage=Concurrent Usage - Total nei.recipe.concurrent.crafting=Concurrent Crafting - Total nei.recipe.accepts=Accepts following nei.recipe.accepts.scroll=Change Item +nei.recipe.group=Variants +nei.recipe.group.scroll=Change Variant (%s/%s) nei.recipe.overlay=Recipe Overlay nei.recipe.overlay.missing=Missing following From f84c4ef2bd5bf8a5e9dcf7b9cfe428f9aa06a236 Mon Sep 17 00:00:00 2001 From: slprime <31038811+slprime@users.noreply.github.com> Date: Sun, 27 Sep 2026 08:09:52 +0300 Subject: [PATCH 07/11] Rename PositionStack.Fluid to Tank (#1051) --- .../java/codechicken/nei/PositionedStack.java | 41 +++++++++++++++---- 1 file changed, 34 insertions(+), 7 deletions(-) diff --git a/src/main/java/codechicken/nei/PositionedStack.java b/src/main/java/codechicken/nei/PositionedStack.java index 2f11f649..50ba1aff 100644 --- a/src/main/java/codechicken/nei/PositionedStack.java +++ b/src/main/java/codechicken/nei/PositionedStack.java @@ -14,8 +14,12 @@ import net.minecraft.util.EnumChatFormatting; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.oredict.OreDictionary; +import org.lwjgl.opengl.GL11; + import codechicken.nei.api.ItemFilter; import codechicken.nei.api.ItemInfo; +import codechicken.nei.drawable.DrawableBuilder; +import codechicken.nei.drawable.DrawableResource; import codechicken.nei.guihook.GuiContainerManager; import codechicken.nei.item.FluidDrawer; import codechicken.nei.item.FluidDrawer.FillDirection; @@ -253,25 +257,26 @@ public class PositionedStack implements Cloneable { public void draw(int mousex, int mousey) {} } - public static class Fluid extends PositionedStack { + public static class Tank extends PositionedStack { /** The tank size the fill level is measured against, in mB. 0 means "always render full". */ protected int capacity = 0; protected boolean flowingTexture = false; protected FillDirection fillDirection = FillDirection.AUTO; + protected DrawableResource overlay; private ItemStack cachedFluidItem; private FluidStack cachedFluidStack; - public Fluid(Object object, int x, int y, boolean genPerms) { + public Tank(Object object, int x, int y, boolean genPerms) { super(object, x, y, genPerms); } - public Fluid(Object object, int x, int y) { + public Tank(Object object, int x, int y) { this(object, x, y, true); } - public Fluid(Object object, int x, int y, int width, int height, int capacity) { + public Tank(Object object, int x, int y, int width, int height, int capacity) { super(object, x, y, false); this.width = width; this.height = height; @@ -282,7 +287,7 @@ public class PositionedStack implements Cloneable { return this.capacity; } - public Fluid setCapacity(int capacity) { + public Tank setCapacity(int capacity) { this.capacity = Math.max(capacity, 0); return this; } @@ -291,7 +296,7 @@ public class PositionedStack implements Cloneable { return this.flowingTexture; } - public Fluid setFlowingTexture(boolean flowingTexture) { + public Tank setFlowingTexture(boolean flowingTexture) { this.flowingTexture = flowingTexture; return this; } @@ -300,11 +305,24 @@ public class PositionedStack implements Cloneable { return this.fillDirection; } - public Fluid setFillDirection(FillDirection fillDirection) { + public Tank setFillDirection(FillDirection fillDirection) { this.fillDirection = fillDirection == null ? FillDirection.AUTO : fillDirection; return this; } + public DrawableResource getOverlay() { + return this.overlay; + } + + public Tank setOverlay(String resourceLocation, int u, int v, int width, int height) { + return setOverlay(new DrawableBuilder(resourceLocation, u, v, width, height).build()); + } + + public Tank setOverlay(DrawableResource overlay) { + this.overlay = overlay; + return this; + } + protected FluidStack getFluidStack() { if (this.item != this.cachedFluidItem) { @@ -352,6 +370,15 @@ public class PositionedStack implements Cloneable { fluidStack, this.flowingTexture, this.fillDirection); + + if (this.overlay != null) { + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glDisable(GL11.GL_LIGHTING); + this.overlay.draw(this.relx, this.rely); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_BLEND); + } } } } From 58681874109124b8bf0f2c9a2feb944648052b54 Mon Sep 17 00:00:00 2001 From: slprime <31038811+slprime@users.noreply.github.com> Date: Sun, 27 Sep 2026 11:00:27 +0300 Subject: [PATCH 08/11] Save Tree State (#1052) --- .../java/codechicken/nei/NEIClientConfig.java | 8 +++++++ .../nei/bookmark/tree/CraftingTreeCanvas.java | 6 ++++- .../nei/bookmark/tree/CraftingTreeState.java | 14 ++++++++++++ .../nei/bookmark/tree/GuiCraftingTree.java | 22 +++++++++++++------ src/main/resources/assets/nei/lang/en_US.lang | 3 +++ src/main/resources/assets/nei/lang/ru_RU.lang | 3 +++ 6 files changed, 48 insertions(+), 8 deletions(-) diff --git a/src/main/java/codechicken/nei/NEIClientConfig.java b/src/main/java/codechicken/nei/NEIClientConfig.java index 88b98899..13a0fceb 100644 --- a/src/main/java/codechicken/nei/NEIClientConfig.java +++ b/src/main/java/codechicken/nei/NEIClientConfig.java @@ -224,6 +224,10 @@ public class NEIClientConfig { .getBooleanValue(false); API.addOption(new OptionToggleButton("inventory.bookmarks.bookmarkRecipeWithCount", true)); + tag.getTag("inventory.bookmarks.craftingTreeZoomWithoutModifier") + .setComment("Zoom Crafting Tree with mouse wheel without holding Ctrl").getBooleanValue(false); + API.addOption(new OptionToggleButton("inventory.bookmarks.craftingTreeZoomWithoutModifier", true)); + tag.getTag("inventory.guirecipe.jeiStyleTabs").setComment("Enable/disable JEI Style Tabs") .getBooleanValue(true); API.addOption(new OptionToggleButtonBoubs("inventory.guirecipe.jeiStyleTabs", true)); @@ -1150,6 +1154,10 @@ public class NEIClientConfig { return getBooleanSetting("inventory.bookmarks.ignorePotionOverlap"); } + public static boolean craftingTreeZoomWithoutModifier() { + return getBooleanSetting("inventory.bookmarks.craftingTreeZoomWithoutModifier"); + } + public static boolean optimizeGuiOverlapComputation() { return getBooleanSetting("inventory.optimize_gui_overlap_computation"); } diff --git a/src/main/java/codechicken/nei/bookmark/tree/CraftingTreeCanvas.java b/src/main/java/codechicken/nei/bookmark/tree/CraftingTreeCanvas.java index 749662a0..64296042 100644 --- a/src/main/java/codechicken/nei/bookmark/tree/CraftingTreeCanvas.java +++ b/src/main/java/codechicken/nei/bookmark/tree/CraftingTreeCanvas.java @@ -142,7 +142,11 @@ class CraftingTreeCanvas { public int treeWidth = 0; public int treeHeight = 0; - private final Camera camera = new Camera(); + private final Camera camera; + + public CraftingTreeCanvas(Camera camera) { + this.camera = camera; + } public void setViewport(int x, int y, int w, int h) { this.camera.setViewport(x, y, w, h); diff --git a/src/main/java/codechicken/nei/bookmark/tree/CraftingTreeState.java b/src/main/java/codechicken/nei/bookmark/tree/CraftingTreeState.java index f54a9f53..1bdb2bc1 100644 --- a/src/main/java/codechicken/nei/bookmark/tree/CraftingTreeState.java +++ b/src/main/java/codechicken/nei/bookmark/tree/CraftingTreeState.java @@ -2,9 +2,12 @@ package codechicken.nei.bookmark.tree; import java.util.EnumSet; import java.util.HashSet; +import java.util.Map; import java.util.Set; +import java.util.WeakHashMap; import codechicken.nei.NEIClientConfig; +import codechicken.nei.bookmark.BookmarkGroup; import codechicken.nei.bookmark.BookmarkItem; class CraftingTreeState { @@ -25,6 +28,8 @@ class CraftingTreeState { HANDLERS } + private static final Map GROUP_STATES = new WeakHashMap<>(); + private static final String KEY_STATS_VISIBLE = "craftingTree.statsVisible"; private static final String KEY_STATS_SECTIONS = "craftingTree.statsSections"; private static final String KEY_USE_INVENTORY_SNAPSHOT = "craftingTree.useInventorySnapshot"; @@ -35,6 +40,8 @@ class CraftingTreeState { public boolean useInventorySnapshot = false; public CollapseMode collapseMode = CollapseMode.EXPANDED; + public boolean initialized; + public final Camera camera = new Camera(); public final Set collapsedItems = new HashSet<>(); public ItemTreeSlot replaceRecipeNode; @@ -65,6 +72,9 @@ class CraftingTreeState { ? collapseModes[savedCollapseMode] : CollapseMode.EXPANDED; this.replaceRecipeNode = null; + this.searchItemResult = null; + this.searchStatsResult = null; + this.camera.endDrag(); } public void toggleStatsPanelVisible() { @@ -98,6 +108,10 @@ class CraftingTreeState { NEIClientConfig.world.nbt.setInteger(KEY_COLLAPSE_MODE, this.collapseMode.ordinal()); } + public static CraftingTreeState of(BookmarkGroup group) { + return GROUP_STATES.computeIfAbsent(group, g -> new CraftingTreeState()); + } + public SearchResult activeSearchResult() { return this.searchItemResult != null ? this.searchItemResult : this.searchStatsResult; } diff --git a/src/main/java/codechicken/nei/bookmark/tree/GuiCraftingTree.java b/src/main/java/codechicken/nei/bookmark/tree/GuiCraftingTree.java index f4a95710..01d05aea 100644 --- a/src/main/java/codechicken/nei/bookmark/tree/GuiCraftingTree.java +++ b/src/main/java/codechicken/nei/bookmark/tree/GuiCraftingTree.java @@ -39,6 +39,7 @@ import codechicken.lib.gui.GuiDraw; import codechicken.nei.KeyManager; import codechicken.nei.LRUCache; import codechicken.nei.NEICPH; +import codechicken.nei.NEIClientConfig; import codechicken.nei.NEIClientUtils; import codechicken.nei.PositionedStack; import codechicken.nei.SearchField.GuiSearchField; @@ -118,7 +119,6 @@ public class GuiCraftingTree extends GuiContainer implements INEIGuiHandler, IGu private final LRUCache handlerTitleCache = new LRUCache<>(100); private GuiScreen prevGui; - private boolean isFirstScreen = true; private final BookmarkGrid grid; private final int groupId; @@ -127,7 +127,7 @@ public class GuiCraftingTree extends GuiContainer implements INEIGuiHandler, IGu private final StatsPanel statsPanel = new StatsPanel(); private final StatsSectionsMenu statsSectionsMenu = new StatsSectionsMenu(); - private final CraftingTreeCanvas canvas = new CraftingTreeCanvas(); + private final CraftingTreeCanvas canvas; private boolean statsPanelVisible; private GuiSearchField searchField; @@ -136,7 +136,7 @@ public class GuiCraftingTree extends GuiContainer implements INEIGuiHandler, IGu private AcceptsFollowingTooltipLineHandler acceptsFollowingTooltipLineHandler; private RecipeItemsTooltipLineHandler recipeItemsTooltipLineHandler; - private final CraftingTreeState uiState = new CraftingTreeState(); + private final CraftingTreeState uiState; private final CraftingTreeToolbar toolbar; private ItemTreeSlot hoveredNode; @@ -148,6 +148,8 @@ public class GuiCraftingTree extends GuiContainer implements INEIGuiHandler, IGu this.grid = grid; this.groupId = groupId; + this.uiState = CraftingTreeState.of(grid.getGroup(groupId)); + this.canvas = new CraftingTreeCanvas(this.uiState.camera); this.toolbar = new CraftingTreeToolbar(this.uiState); } @@ -284,7 +286,7 @@ public class GuiCraftingTree extends GuiContainer implements INEIGuiHandler, IGu this.canvas.graph.rebuild(this.math); - if (this.isFirstScreen) { + if (!this.uiState.initialized) { updateCollapsedItems(); } else { this.canvas.recalculateCoordinates(this.collapsedRecipes, this.uiState.collapsedItems, anchor); @@ -292,8 +294,8 @@ public class GuiCraftingTree extends GuiContainer implements INEIGuiHandler, IGu rebuildStatsPanel(); - if (this.isFirstScreen) { - this.isFirstScreen = false; + if (!this.uiState.initialized) { + this.uiState.initialized = true; this.canvas.fitToView(); } } @@ -842,7 +844,7 @@ public class GuiCraftingTree extends GuiContainer implements INEIGuiHandler, IGu (int) mouse.getY(), direction, NEIClientUtils.shiftKey(), - NEIClientUtils.controlKey()); + NEIClientUtils.controlKey() || NEIClientConfig.craftingTreeZoomWithoutModifier()); } private boolean handleItemWheel(int wheel, Point2D mouse) { @@ -904,6 +906,12 @@ public class GuiCraftingTree extends GuiContainer implements INEIGuiHandler, IGu } } + if (keyCode == this.mc.gameSettings.keyBindInventory.getKeyCode()) { + this.mc.displayGuiScreen(this.prevGui); + NEICPH.sendRequestContainer(); + return; + } + if (this.statsPanelVisible && KeyManager.isKeyDown("recipe.recipe")) { final Point2D mouse = getMousePosition(); final Widget widget = this.statsPanel.getWidgetUnderMouse((int) mouse.getX(), (int) mouse.getY()); diff --git a/src/main/resources/assets/nei/lang/en_US.lang b/src/main/resources/assets/nei/lang/en_US.lang index 5e69212e..887dcc49 100644 --- a/src/main/resources/assets/nei/lang/en_US.lang +++ b/src/main/resources/assets/nei/lang/en_US.lang @@ -306,6 +306,9 @@ nei.options.inventory.bookmarks.bookmarkItemsWithRecipe.false=No nei.options.inventory.bookmarks.bookmarkRecipeWithCount=Bookmark recipe with count nei.options.inventory.bookmarks.bookmarkRecipeWithCount.true=Yes nei.options.inventory.bookmarks.bookmarkRecipeWithCount.false=No +nei.options.inventory.bookmarks.craftingTreeZoomWithoutModifier=Tree Zoom without Ctrl +nei.options.inventory.bookmarks.craftingTreeZoomWithoutModifier.true=Yes +nei.options.inventory.bookmarks.craftingTreeZoomWithoutModifier.false=No nei.options.inventory.favorites=Favorites nei.options.inventory.favorites.enabled=Visibility nei.options.inventory.favorites.enabled.true=Visible diff --git a/src/main/resources/assets/nei/lang/ru_RU.lang b/src/main/resources/assets/nei/lang/ru_RU.lang index 5e170214..e3098a8f 100644 --- a/src/main/resources/assets/nei/lang/ru_RU.lang +++ b/src/main/resources/assets/nei/lang/ru_RU.lang @@ -197,6 +197,9 @@ nei.options.inventory.bookmarks.ignorePotionOverlap.false=Нет nei.options.inventory.bookmarks.worldSpecific=Закладки для конкретного мира nei.options.inventory.bookmarks.worldSpecific.true=Да nei.options.inventory.bookmarks.worldSpecific.false=Нет +nei.options.inventory.bookmarks.craftingTreeZoomWithoutModifier=Масштаб дерева без Ctrl +nei.options.inventory.bookmarks.craftingTreeZoomWithoutModifier.true=Да +nei.options.inventory.bookmarks.craftingTreeZoomWithoutModifier.false=Нет nei.options.inventory.guirecipe=Интерфейс рецептов nei.options.inventory.guirecipe.jeiStyleTabs=Вкладки в стиле JEI nei.options.inventory.guirecipe.jeiStyleTabs.true=Да From 18abb880f895102e8ffa9bf7934e60795a79648e Mon Sep 17 00:00:00 2001 From: slprime <31038811+slprime@users.noreply.github.com> Date: Sun, 27 Sep 2026 14:13:27 +0300 Subject: [PATCH 09/11] Add widget size to recipe event (#1053) --- .../codechicken/nei/recipe/GuiRecipeButton.java | 15 ++++++++++----- .../nei/recipe/widget/RecipeWidget.java | 4 ++++ 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/src/main/java/codechicken/nei/recipe/GuiRecipeButton.java b/src/main/java/codechicken/nei/recipe/GuiRecipeButton.java index 31f4f0a3..4b2455ec 100644 --- a/src/main/java/codechicken/nei/recipe/GuiRecipeButton.java +++ b/src/main/java/codechicken/nei/recipe/GuiRecipeButton.java @@ -16,11 +16,15 @@ public abstract class GuiRecipeButton extends GuiNEIButton { public List buttonList; public RecipeHandlerRef handlerRef; + public int width; + public int height; - public UpdateRecipeButtonsEvent(GuiRecipe gui, RecipeHandlerRef handlerRef, + public UpdateRecipeButtonsEvent(GuiRecipe gui, RecipeHandlerRef handlerRef, int width, int height, List buttonList) { super(gui); this.handlerRef = handlerRef; + this.width = width; + this.height = height; this.buttonList = new ArrayList<>(buttonList); } @@ -29,16 +33,17 @@ public abstract class GuiRecipeButton extends GuiNEIButton { public HandlerInfo handlerInfo; - public Pre(GuiRecipe gui, RecipeHandlerRef handlerRef, HandlerInfo handlerInfo) { - super(gui, handlerRef, new ArrayList<>()); + public Pre(GuiRecipe gui, RecipeHandlerRef handlerRef, int width, int height, HandlerInfo handlerInfo) { + super(gui, handlerRef, width, height, new ArrayList<>()); this.handlerInfo = handlerInfo; } } public static class Post extends UpdateRecipeButtonsEvent { - public Post(GuiRecipe gui, RecipeHandlerRef handlerRef, List buttonList) { - super(gui, handlerRef, buttonList); + public Post(GuiRecipe gui, RecipeHandlerRef handlerRef, int width, int height, + List buttonList) { + super(gui, handlerRef, width, height, buttonList); } } } diff --git a/src/main/java/codechicken/nei/recipe/widget/RecipeWidget.java b/src/main/java/codechicken/nei/recipe/widget/RecipeWidget.java index 00120e97..ab88a10f 100644 --- a/src/main/java/codechicken/nei/recipe/widget/RecipeWidget.java +++ b/src/main/java/codechicken/nei/recipe/widget/RecipeWidget.java @@ -163,6 +163,8 @@ public class RecipeWidget extends Widget { final UpdateRecipeButtonsEvent.Pre preEvent = new UpdateRecipeButtonsEvent.Pre( guiRecipe, ref, + this.w, + this.h, this.handlerInfo); if (MinecraftForge.EVENT_BUS.post(preEvent)) { @@ -171,6 +173,8 @@ public class RecipeWidget extends Widget { final UpdateRecipeButtonsEvent.Post postEvent = new UpdateRecipeButtonsEvent.Post( guiRecipe, ref, + this.w, + this.h, getDefaultButtons(ref)); MinecraftForge.EVENT_BUS.post(postEvent); return postEvent.buttonList; From 9f3697bb6794976cf3c79dbb44b0e0455613e548 Mon Sep 17 00:00:00 2001 From: danyadev Date: Sun, 27 Sep 2026 18:21:56 +0300 Subject: [PATCH 10/11] fix cycling for fluid permutations (#1048) Co-authored-by: Martin Robertz --- src/main/java/codechicken/nei/item/ItemFluidDisplay.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/codechicken/nei/item/ItemFluidDisplay.java b/src/main/java/codechicken/nei/item/ItemFluidDisplay.java index 5391fdca..72404cb1 100644 --- a/src/main/java/codechicken/nei/item/ItemFluidDisplay.java +++ b/src/main/java/codechicken/nei/item/ItemFluidDisplay.java @@ -41,6 +41,7 @@ public class ItemFluidDisplay extends Item implements IFluidContainerItem { public ItemFluidDisplay() { setUnlocalizedName("nei.fluidDisplay"); setMaxStackSize(1); + setHasSubtypes(true); INSTANCE = this; } From a685efb3b7612d00f8c1f5c3cc2553d8fd5fb6df Mon Sep 17 00:00:00 2001 From: slprime <31038811+slprime@users.noreply.github.com> Date: Mon, 28 Sep 2026 00:19:29 +0300 Subject: [PATCH 11/11] Recipe Group Optimization (#1054) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- .../java/codechicken/nei/FavoriteRecipes.java | 4 + .../java/codechicken/nei/PositionedStack.java | 2 +- .../nei/recipe/GuiCraftingRecipe.java | 22 +- .../codechicken/nei/recipe/GuiRecipe.java | 11 + .../nei/recipe/RecipePageManager.java | 40 ++ .../nei/recipe/widget/PermutationsCycler.java | 17 + .../nei/recipe/widget/RecipeGroup.java | 380 ++++++++++++++--- .../nei/recipe/widget/RecipeWidget.java | 389 +++++++++++------- src/main/resources/assets/nei/lang/en_US.lang | 2 +- src/main/resources/assets/nei/lang/ru_RU.lang | 1 + .../assets/nei/textures/pinned_pause.png | Bin 0 -> 554 bytes 11 files changed, 654 insertions(+), 214 deletions(-) create mode 100644 src/main/resources/assets/nei/textures/pinned_pause.png diff --git a/src/main/java/codechicken/nei/FavoriteRecipes.java b/src/main/java/codechicken/nei/FavoriteRecipes.java index 66dbe105..7749d7d1 100644 --- a/src/main/java/codechicken/nei/FavoriteRecipes.java +++ b/src/main/java/codechicken/nei/FavoriteRecipes.java @@ -316,6 +316,10 @@ public class FavoriteRecipes { load(); } + public static boolean hasManual() { + return manualFavorites.size() > 0; + } + public static boolean containsManual(ItemStack stack) { return getManualFavorite(stack) != null; } diff --git a/src/main/java/codechicken/nei/PositionedStack.java b/src/main/java/codechicken/nei/PositionedStack.java index 50ba1aff..f72c9766 100644 --- a/src/main/java/codechicken/nei/PositionedStack.java +++ b/src/main/java/codechicken/nei/PositionedStack.java @@ -163,7 +163,7 @@ public class PositionedStack implements Cloneable { } public List getFilteredPermutations(ItemFilter additionalFilter) { - List items = Arrays.asList(this.items); + List items = new ArrayList<>(Arrays.asList(this.items)); items = filteringPermutations(items, item -> !ItemInfo.isHidden(item)); items = filteringPermutations(items, PresetsList.getItemFilter()); diff --git a/src/main/java/codechicken/nei/recipe/GuiCraftingRecipe.java b/src/main/java/codechicken/nei/recipe/GuiCraftingRecipe.java index 34b0d17e..b9d2b20e 100644 --- a/src/main/java/codechicken/nei/recipe/GuiCraftingRecipe.java +++ b/src/main/java/codechicken/nei/recipe/GuiCraftingRecipe.java @@ -4,6 +4,7 @@ import java.awt.Point; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; +import java.util.List; import java.util.Set; import java.util.function.UnaryOperator; import java.util.stream.Collectors; @@ -35,6 +36,7 @@ public class GuiCraftingRecipe extends GuiRecipe { public static GuiRecipe createRecipeGui(String outputId, boolean open, Object... results) { final Minecraft mc = NEIClientUtils.mc(); final RecipeId recipeId; + List pinnedIngredients = null; for (int i = 0; i < results.length; i++) { if (results[i] instanceof ItemStack stack) { @@ -46,6 +48,12 @@ public class GuiCraftingRecipe extends GuiRecipe { recipeId = getRecipeId(mc.currentScreen, (ItemStack) results[0]); } else if ("recipeId".equals(outputId)) { recipeId = (RecipeId) results[1]; + + // optional third argument: ingredients to pin the found recipe with + if (results.length > 2 && results[2] instanceof Listlist) { + pinnedIngredients = extractIngredients(list); + } + } else { recipeId = getCurrentRecipeId(mc.currentScreen); } @@ -65,13 +73,25 @@ public class GuiCraftingRecipe extends GuiRecipe { mc.displayGuiScreen(gui); } - gui.openTargetRecipe(recipeId); + gui.openTargetRecipe(recipeId, pinnedIngredients); return gui; } return null; } + private static List extractIngredients(List list) { + final List ingredients = new ArrayList<>(list.size()); + + for (Object item : list) { + if (item instanceof ItemStack stack) { + ingredients.add(stack); + } + } + + return ingredients; + } + public static ArrayList getCraftingHandlers(String outputId, Object... results) { ArrayList craftinghandlers = GuiCraftingRecipe.craftinghandlers; ArrayList serialCraftingHandlers = GuiCraftingRecipe.serialCraftingHandlers; diff --git a/src/main/java/codechicken/nei/recipe/GuiRecipe.java b/src/main/java/codechicken/nei/recipe/GuiRecipe.java index 2740664b..4ecea6b4 100644 --- a/src/main/java/codechicken/nei/recipe/GuiRecipe.java +++ b/src/main/java/codechicken/nei/recipe/GuiRecipe.java @@ -524,6 +524,13 @@ public abstract class GuiRecipe extends GuiContainer i } public int openTargetRecipe(RecipeId recipeId) { + return openTargetRecipe(recipeId, null); + } + + /** + * @param pinnedIngredients when not null, the found recipe is paused with these ingredients shown + */ + public int openTargetRecipe(RecipeId recipeId, List pinnedIngredients) { int recipeIndex = -1; int recipetype = 0; @@ -551,6 +558,10 @@ public abstract class GuiRecipe extends GuiContainer i setRecipePage(recipetype); this.handlerPages.gotoRecipeIndex(Math.max(0, recipeIndex)); + if (pinnedIngredients != null && recipeIndex >= 0) { + this.handlerPages.pinRecipe(recipeIndex, pinnedIngredients); + } + return recipeIndex; } diff --git a/src/main/java/codechicken/nei/recipe/RecipePageManager.java b/src/main/java/codechicken/nei/recipe/RecipePageManager.java index 654a4d41..b386ccd4 100644 --- a/src/main/java/codechicken/nei/recipe/RecipePageManager.java +++ b/src/main/java/codechicken/nei/recipe/RecipePageManager.java @@ -6,6 +6,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import net.minecraft.item.ItemStack; + import codechicken.nei.NEIClientConfig; import codechicken.nei.Widget; import codechicken.nei.recipe.widget.RecipeWidget; @@ -42,6 +44,8 @@ public class RecipePageManager { } this.cacheKey = cacheKey; + + final List pausedWidgets = getPausedWidgets(); this.pageWidgets.clear(); final boolean allowOverflowY = this.handlerInfo.isAllowOverflowY(); @@ -76,6 +80,15 @@ public class RecipePageManager { for (int groupIndex = 0; groupIndex < groupedRecipes.size(); groupIndex++) { final RecipeWidget widget = new RecipeWidget(this.handler.original, groupedRecipes.get(groupIndex)); + // keep the pause of the rebuilt widgets + for (RecipeWidget paused : pausedWidgets) { + final int pausedIndex = paused.getRecipeHandlerRef().recipeIndex; + + if (widget.containsRecipeIndex(pausedIndex)) { + widget.pinRecipe(pausedIndex, paused.getPinnedIngredients()); + } + } + widget.w = width; if (allowOverflowY) { @@ -144,6 +157,33 @@ public class RecipePageManager { return false; } + private List getPausedWidgets() { + final List paused = new ArrayList<>(); + + for (List widgets : this.pageWidgets) { + for (Widget widget : widgets) { + if (widget instanceof RecipeWidget recipeWidget && recipeWidget.isPaused()) { + paused.add(recipeWidget); + } + } + } + + return paused; + } + + public boolean pinRecipe(int recipeIndex, List ingredients) { + + for (List widgets : this.pageWidgets) { + for (Widget widget : widgets) { + if (widget instanceof RecipeWidget recipeWidget && recipeWidget.containsRecipeIndex(recipeIndex)) { + return recipeWidget.pinRecipe(recipeIndex, ingredients); + } + } + } + + return false; + } + public List getCurrentPageWidgets() { if (this.pageWidgets.isEmpty()) { return Collections.emptyList(); diff --git a/src/main/java/codechicken/nei/recipe/widget/PermutationsCycler.java b/src/main/java/codechicken/nei/recipe/widget/PermutationsCycler.java index cfc3eed1..723853c8 100644 --- a/src/main/java/codechicken/nei/recipe/widget/PermutationsCycler.java +++ b/src/main/java/codechicken/nei/recipe/widget/PermutationsCycler.java @@ -1,6 +1,7 @@ package codechicken.nei.recipe.widget; import java.util.ArrayList; +import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Map; @@ -50,6 +51,11 @@ public class PermutationsCycler { return false; } + public void invalidate() { + this.favoriteRevision = -1; + validate(); + } + public boolean contains(K key) { validate(); return this.permutations.containsKey(key); @@ -79,6 +85,11 @@ public class PermutationsCycler { return items; } + public int getFavoriteCount(K key) { + get(key); + return this.favoriteCounts.getOrDefault(key, 0); + } + public ItemStack getCycled(K key, int cycle) { final List items = get(key); final int favoriteCount = this.favoriteCounts.getOrDefault(key, 0); @@ -96,4 +107,10 @@ public class PermutationsCycler { return -1; } + // Hash key with the same equality as NEIServerUtils.areStacksSameType + public static Object getStackKey(ItemStack stack) { + return Arrays + .asList(stack.getItem(), stack.getHasSubtypes() ? stack.getItemDamage() : 0, stack.stackTagCompound); + } + } diff --git a/src/main/java/codechicken/nei/recipe/widget/RecipeGroup.java b/src/main/java/codechicken/nei/recipe/widget/RecipeGroup.java index 010a5298..1a7a5738 100644 --- a/src/main/java/codechicken/nei/recipe/widget/RecipeGroup.java +++ b/src/main/java/codechicken/nei/recipe/widget/RecipeGroup.java @@ -2,23 +2,109 @@ package codechicken.nei.recipe.widget; import java.awt.Point; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.Set; import net.minecraft.item.ItemStack; import codechicken.nei.FavoriteRecipes; +import codechicken.nei.NEIServerUtils; import codechicken.nei.PositionedStack; import codechicken.nei.recipe.GuiRecipeTab; import codechicken.nei.recipe.HandlerInfo; import codechicken.nei.recipe.IRecipeHandler; +import codechicken.nei.recipe.StackInfo; public class RecipeGroup { + // position and items of a stack at load time, the handler may change the stack later + protected static class StackState { + + public final int relx; + public final int rely; + public final ItemStack[] items; + + public StackState(PositionedStack pStack) { + this.relx = pStack.relx; + this.rely = pStack.rely; + this.items = pStack.items; + } + } + + // filtered permutations of a slot, favorites first, with their indices in PositionedStack.items + protected static class FilteredSlot { + + public final List items; + public final int[] indices; + public final int favoriteCount; + + public FilteredSlot(PositionedStack pStack) { + this.items = pStack.getFilteredPermutations(); + this.indices = new int[this.items.size()]; + + // filtering keeps the original instances, so an identity lookup finds the source index + for (int i = 0; i < this.indices.length; i++) { + this.indices[i] = indexOfInstance(pStack.items, this.items.get(i)); + } + + int favoriteCount = 0; + + while (this.items.size() > 1 && favoriteCount < this.items.size() + && FavoriteRecipes.containsManual(this.items.get(favoriteCount))) { + favoriteCount++; + } + + this.favoriteCount = favoriteCount; + } + + private static int indexOfInstance(ItemStack[] items, ItemStack stack) { + for (int i = 0; i < items.length; i++) { + if (items[i] == stack) { + return i; + } + } + return 0; + } + } + + protected static class MemberStacks { + + public final List inputs; + public final List outputs; + public final List auxiliaries; + public final List cycling; + public final List states = new ArrayList<>(); + public final Map slots = new HashMap<>(); + public final Map filtered = new HashMap<>(); + + public MemberStacks(List inputs, List outputs, + List auxiliaries) { + this.inputs = inputs; + this.outputs = outputs; + this.auxiliaries = auxiliaries; + + if (auxiliaries.isEmpty()) { + this.cycling = inputs; + } else { + this.cycling = new ArrayList<>(inputs); + this.cycling.addAll(auxiliaries); + } + + for (PositionedStack pStack : this.cycling) { + this.slots.putIfAbsent(new Point(pStack.relx, pStack.rely), pStack); + } + + for (PositionedStack pStack : inputs) this.states.add(new StackState(pStack)); + for (PositionedStack pStack : outputs) this.states.add(new StackState(pStack)); + for (PositionedStack pStack : auxiliaries) this.states.add(new StackState(pStack)); + } + } + private static final List SINGLE_MEMBER = Collections.singletonList(0); private final IRecipeHandler handler; @@ -26,16 +112,33 @@ public class RecipeGroup { private final HandlerInfo handlerInfo; private final PermutationsCycler slotPermutations; + private final MemberStacks[] memberStacks; + private Map slotStacks = null; + private final Set sharedSlots = new HashSet<>(); private List allowedMembers = null; + private Boolean cycling = null; public RecipeGroup(IRecipeHandler handler, List recipeIndices) { this.handler = handler; this.recipeIndices = new ArrayList<>(recipeIndices); this.handlerInfo = GuiRecipeTab.getHandlerInfo(handler); + this.memberStacks = new MemberStacks[this.recipeIndices.size()]; this.slotPermutations = new PermutationsCycler( new HashMap<>(), new HashMap<>(), - this::collectSlotPermutations).onInvalidate(() -> this.allowedMembers = null); + this::collectSlotPermutations).onInvalidate(() -> { + this.allowedMembers = null; + this.cycling = null; + this.slotStacks = null; + + for (MemberStacks stacks : this.memberStacks) { + if (stacks != null) { + stacks.filtered.clear(); + } + } + + this.sharedSlots.clear(); + }); } public int size() { @@ -58,34 +161,49 @@ public class RecipeGroup { return this.recipeIndices.contains(recipeIndex); } + public int indexOf(int recipeIndex) { + return this.recipeIndices.indexOf(recipeIndex); + } + public List getPermutations(Point slotKey) { return this.slotPermutations.get(slotKey); } + public boolean hasPermutation(int member, Point slotKey, ItemStack stack) { + this.slotPermutations.validate(); + + if (stack == null) { + return false; + } + + final List permutations = getFilteredPermutations(member, slotKey); + return permutations != null && PermutationsCycler.indexOf(permutations, stack) != -1; + } + + // the given member if it has the item in the slot, otherwise the next member that has it + public int findMember(Point slotKey, ItemStack stack, int from) { + + for (int step = 0; step < size(); step++) { + final int member = (from + step) % size(); + + if (hasPermutation(member, slotKey, stack)) { + return member; + } + } + + return -1; + } + public List getInputs(int member) { - return this.handler.getIngredientStacks(getRecipeIndex(member)); + return getStacks(member).inputs; } public List getOutputs(int member) { - final int recipeIndex = getRecipeIndex(member); - final PositionedStack pStackResult = this.handler.getResultStack(recipeIndex); - return pStackResult != null ? Arrays.asList(pStackResult) : this.handler.getOtherStacks(recipeIndex); - } - - public List getCatalysts(int member) { - final int recipeIndex = getRecipeIndex(member); - - if (this.handler.getResultStack(recipeIndex) == null) { - return Collections.emptyList(); - } - - return this.handler.getOtherStacks(recipeIndex); + return getStacks(member).outputs; } public List getCyclingStacks(int member) { - final List stacks = new ArrayList<>(getInputs(member)); - stacks.addAll(getCatalysts(member)); - return stacks; + return getStacks(member).cycling; } public Point getSlotKey(PositionedStack pStack) { @@ -93,39 +211,108 @@ public class RecipeGroup { } public PositionedStack getSlot(int member, Point slotKey) { - - for (PositionedStack pStack : getCyclingStacks(member)) { - if (pStack.relx == slotKey.x && pStack.rely == slotKey.y) { - return pStack; - } - } - - return null; + return getStacks(member).slots.get(slotKey); } - public PositionedStack getOutputSlot(int member, Point slotKey) { + protected MemberStacks getStacks(int member) { - for (PositionedStack pStack : getOutputs(member)) { - if (pStack.relx == slotKey.x && pStack.rely == slotKey.y) { - return pStack; - } + if (this.memberStacks[member] == null) { + this.memberStacks[member] = loadStacks(member); } - return null; + return this.memberStacks[member]; } - public List getOutputVariants(Point slotKey) { - final List items = new ArrayList<>(); + protected MemberStacks loadStacks(int member) { + final int recipeIndex = getRecipeIndex(member); + final List inputs = new ArrayList<>(this.handler.getIngredientStacks(recipeIndex)); + final PositionedStack pStackResult = this.handler.getResultStack(recipeIndex); + final List others = new ArrayList<>(this.handler.getOtherStacks(recipeIndex)); - for (int member = 0; member < size(); member++) { - final PositionedStack slot = getOutputSlot(member, slotKey); + if (pStackResult != null) { + return new MemberStacks(inputs, Collections.singletonList(pStackResult), others); + } - if (slot != null && PermutationsCycler.indexOf(items, slot.item) == -1) { - items.add(slot.item); + return new MemberStacks(inputs, others, Collections.emptyList()); + } + + // re-reads the member stacks from the handler, keeps the cached instances when nothing changed + public void refresh(int member) { + + if (this.memberStacks[member] == null) { + return; + } + + final MemberStacks stacks = loadStacks(member); + + if (!isSameStacks(this.memberStacks[member], stacks)) { + this.memberStacks[member] = stacks; + this.slotPermutations.invalidate(); + } + } + + // index into PositionedStack.items of the permutation to render, -1 when the slot is unknown + public int getCycledPermutationIndex(int member, Point slotKey, int index) { + this.slotPermutations.validate(); + + final FilteredSlot filtered = getFilteredSlot(member, slotKey); + + if (filtered == null || filtered.indices.length == 0) { + return -1; + } + + final int size = filtered.favoriteCount > 0 ? filtered.favoriteCount : filtered.indices.length; + return filtered.indices[index % size]; + } + + protected boolean isSameStacks(MemberStacks stacksA, MemberStacks stacksB) { + + if (stacksA.inputs.size() != stacksB.inputs.size() || stacksA.outputs.size() != stacksB.outputs.size() + || stacksA.auxiliaries.size() != stacksB.auxiliaries.size()) { + return false; + } + + for (int i = 0; i < stacksA.states.size(); i++) { + final StackState stateA = stacksA.states.get(i); + final StackState stateB = stacksB.states.get(i); + + if (stateA.relx != stateB.relx || stateA.rely != stateB.rely || !isSameItems(stateA.items, stateB.items)) { + return false; } } - return items; + return true; + } + + protected boolean isSameItems(ItemStack[] itemsA, ItemStack[] itemsB) { + + if (itemsA == itemsB) { + return true; + } + + if (itemsA.length != itemsB.length) { + return false; + } + + for (int i = 0; i < itemsA.length; i++) { + if (!isSameStack(itemsA[i], itemsB[i])) { + return false; + } + } + + return true; + } + + // true when the group has something to cycle: several members or a slot with several permutations + public boolean canCycle() { + this.slotPermutations.validate(); + + if (this.cycling == null) { + this.cycling = size() > 1 || getStacks(0).slots.keySet().stream() + .anyMatch(slotKey -> getFilteredPermutations(0, slotKey).size() > 1); + } + + return this.cycling; } public List getAllowedMembers() { @@ -135,17 +322,20 @@ public class RecipeGroup { return SINGLE_MEMBER; } - if (this.allowedMembers == null) { - final Set favoriteSlots = new HashSet<>(); + if (this.allowedMembers == null && !FavoriteRecipes.hasManual()) { + this.allowedMembers = new ArrayList<>(size()); for (int member = 0; member < size(); member++) { - for (PositionedStack pStack : getCyclingStacks(member)) { - final Point slotKey = getSlotKey(pStack); - final List items = getPermutations(slotKey); + this.allowedMembers.add(member); + } - if (items.size() > 1 && items.stream().anyMatch(FavoriteRecipes::containsManual)) { - favoriteSlots.add(slotKey); - } + } else if (this.allowedMembers == null) { + final Set favoriteSlots = new HashSet<>(); + + for (Point slotKey : getSlotStacks().keySet()) { + // a shared slot gives every member the same misses, so it can't affect the filter + if (!this.sharedSlots.contains(slotKey) && this.slotPermutations.getFavoriteCount(slotKey) > 0) { + favoriteSlots.add(slotKey); } } @@ -155,6 +345,72 @@ public class RecipeGroup { return this.allowedMembers; } + protected Map getSlotStacks() { + + if (this.slotStacks == null) { + this.slotStacks = new LinkedHashMap<>(); + + for (int member = 0; member < size(); member++) { + for (PositionedStack pStack : getCyclingStacks(member)) { + final PositionedStack[] stacks = this.slotStacks + .computeIfAbsent(getSlotKey(pStack), key -> new PositionedStack[size()]); + + if (stacks[member] == null) { + stacks[member] = pStack; + } + } + } + + for (Map.Entry entry : this.slotStacks.entrySet()) { + if (isSharedSlot(entry.getValue())) { + this.sharedSlots.add(entry.getKey()); + } + } + } + + return this.slotStacks; + } + + // all members hold the same permutations in this slot + protected boolean isSharedSlot(PositionedStack[] stacks) { + ItemStack[] first = null; + + for (PositionedStack pStack : stacks) { + if (pStack == null) { + continue; + } + + if (first == null) { + first = pStack.items; + } else if (!isSameItems(first, pStack.items)) { + return false; + } + } + + return true; + } + + protected boolean isSameStack(ItemStack stackA, ItemStack stackB) { + return stackA == stackB || NEIServerUtils.areStacksSameType(stackA, stackB) + && StackInfo.getAmount(stackA) == StackInfo.getAmount(stackB); + } + + protected List getFilteredPermutations(int member, Point slotKey) { + final FilteredSlot filtered = getFilteredSlot(member, slotKey); + return filtered != null ? filtered.items : null; + } + + protected FilteredSlot getFilteredSlot(int member, Point slotKey) { + final MemberStacks stacks = getStacks(member); + final PositionedStack slot = stacks.slots.get(slotKey); + + if (slot == null) { + return null; + } + + return stacks.filtered.computeIfAbsent(slotKey, key -> new FilteredSlot(slot)); + } + protected List filterMembers(Set favoriteSlots) { final List indices = new ArrayList<>(); int minMisses = Integer.MAX_VALUE; @@ -179,9 +435,9 @@ public class RecipeGroup { int misses = 0; for (Point slotKey : favoriteSlots) { - final PositionedStack slot = getSlot(member, slotKey); + final List permutations = getFilteredPermutations(member, slotKey); - if (slot != null && slot.getFilteredPermutations().stream().noneMatch(FavoriteRecipes::containsManual)) { + if (permutations != null && permutations.stream().noneMatch(FavoriteRecipes::containsManual)) { misses++; } } @@ -190,21 +446,31 @@ public class RecipeGroup { } protected List collectSlotPermutations(Point slotKey) { - final List items = new ArrayList<>(); + + if (!getSlotStacks().containsKey(slotKey)) { + return Collections.emptyList(); + } + + final Map items = new LinkedHashMap<>(); + final boolean shared = this.sharedSlots.contains(slotKey); for (int member = 0; member < size(); member++) { - final PositionedStack slot = getSlot(member, slotKey); + final List permutations = getFilteredPermutations(member, slotKey); - if (slot != null) { - for (ItemStack stack : slot.getFilteredPermutations()) { - if (PermutationsCycler.indexOf(items, stack) == -1) { - items.add(stack); + if (permutations != null) { + for (ItemStack stack : permutations) { + if (stack != null) { + items.putIfAbsent(PermutationsCycler.getStackKey(stack), stack); } } + + if (shared) { + break; + } } } - return items; + return new ArrayList<>(items.values()); } } diff --git a/src/main/java/codechicken/nei/recipe/widget/RecipeWidget.java b/src/main/java/codechicken/nei/recipe/widget/RecipeWidget.java index ab88a10f..6099e7b9 100644 --- a/src/main/java/codechicken/nei/recipe/widget/RecipeWidget.java +++ b/src/main/java/codechicken/nei/recipe/widget/RecipeWidget.java @@ -2,6 +2,7 @@ package codechicken.nei.recipe.widget; import java.awt.Point; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -21,7 +22,6 @@ import org.lwjgl.opengl.GL12; import codechicken.lib.gui.GuiDraw; import codechicken.lib.vec.Rectangle4i; import codechicken.nei.FavoriteRecipes; -import codechicken.nei.ItemsTooltipLineHandler; import codechicken.nei.KeyManager; import codechicken.nei.NEIClientConfig; import codechicken.nei.NEIClientUtils; @@ -29,6 +29,8 @@ import codechicken.nei.PositionedStack; import codechicken.nei.Widget; import codechicken.nei.api.IGuiContainerOverlay; import codechicken.nei.api.ShortcutInputHandler; +import codechicken.nei.drawable.DrawableBuilder; +import codechicken.nei.drawable.DrawableResource; import codechicken.nei.guihook.GuiContainerManager; import codechicken.nei.recipe.AcceptsFollowingTooltipLineHandler; import codechicken.nei.recipe.Badge; @@ -47,28 +49,35 @@ import codechicken.nei.util.NEIMouseUtils; public class RecipeWidget extends Widget { protected static final int TICKS_PER_CYCLE = 20; + protected static final DrawableResource PAUSE_MARKER = new DrawableBuilder( + "nei:textures/pinned_pause.png", + 0, + 0, + 8, + 8).setTextureSize(8, 8).build(); + protected static final int PAUSE_MARKER_OFFSET = 1; protected final RecipeGroup group; protected final IRecipeHandler handler; protected final HandlerInfo handlerInfo; - protected final PermutationsCycler renderPermutations; - protected final Map> badgeCache = new WeakHashMap<>(); protected final Map> buttonCache = new HashMap<>(); protected AcceptsFollowingTooltipLineHandler acceptsTooltip; - protected ItemsTooltipLineHandler variantsTooltip; - protected Point variantsSlotKey; protected int activeMember = 0; - protected int memberCursor = -1; - protected int slotCycle = 0; + // single state counter: member = allowed[cycle % size], permutation index = cycle / size + protected int cycle = 0; protected int cycleticks = 0; protected int lastcycle = -1; + protected int favoriteRevision = FavoriteRecipes.getRevision(); protected boolean showAsWidget = false; protected boolean update = true; + protected boolean paused = false; + protected List pinnedIngredients = null; + protected Map pinnedSlots = Collections.emptyMap(); public RecipeWidget(RecipeHandlerRef handlerRef) { this(handlerRef.handler, Collections.singletonList(handlerRef.recipeIndex)); @@ -82,13 +91,6 @@ public class RecipeWidget extends Widget { this.group = group; this.handler = group.getHandler(); this.handlerInfo = group.getHandlerInfo(); - this.renderPermutations = new PermutationsCycler( - new WeakHashMap<>(), - new WeakHashMap<>(), - PositionedStack::getFilteredPermutations).onInvalidate(() -> { - this.badgeCache.clear(); - this.acceptsTooltip = null; - }); update(); } @@ -117,6 +119,104 @@ public class RecipeWidget extends Widget { this.showAsWidget = show; } + public boolean isPaused() { + return this.paused; + } + + public List getPinnedIngredients() { + return this.pinnedIngredients; + } + + public void setPaused(boolean paused) { + final boolean wasPaused = this.paused; + this.paused = paused && this.group.canCycle(); + + if (!this.paused) { + this.pinnedIngredients = null; + this.pinnedSlots = Collections.emptyMap(); + + if (wasPaused) { + syncCycle(); + } + } + } + + /** + * Pauses the widget on the recipe. Every given ingredient needs an input slot of its own that accepts it, otherwise + * the recipe is not pinned. + */ + public boolean pinRecipe(int recipeIndex, List ingredients) { + final int member = this.group.indexOf(recipeIndex); + + if (member < 0 || !this.group.canCycle()) { + return false; + } + + final Map slots = ingredients != null + ? matchIngredients(this.group.getInputs(member), ingredients) + : Collections.emptyMap(); + + if (slots == null) { + return false; + } + + this.pinnedIngredients = ingredients; + this.pinnedSlots = slots; + this.paused = true; + setActiveMember(member); + updatePermutations(); + + return true; + } + + // assigns each ingredient to its own slot (bipartite matching), null when some ingredient has no slot + private Map matchIngredients(List stacks, List ingredients) { + final int[] slotOwners = new int[stacks.size()]; + Arrays.fill(slotOwners, -1); + + for (int ingredient = 0; ingredient < ingredients.size(); ingredient++) { + if (!assignIngredient(ingredient, stacks, ingredients, slotOwners, new boolean[stacks.size()])) { + return null; + } + } + + final Map slots = new HashMap<>(); + + for (int slot = 0; slot < slotOwners.length; slot++) { + if (slotOwners[slot] != -1) { + slots.put(this.group.getSlotKey(stacks.get(slot)), ingredients.get(slotOwners[slot])); + } + } + + return slots; + } + + private boolean assignIngredient(int ingredient, List stacks, List ingredients, + int[] slotOwners, boolean[] visited) { + + for (int slot = 0; slot < stacks.size(); slot++) { + if (!visited[slot] && stacks.get(slot).getPermutationIndex(ingredients.get(ingredient)) != -1) { + visited[slot] = true; + + if (slotOwners[slot] == -1 + || assignIngredient(slotOwners[slot], stacks, ingredients, slotOwners, visited)) { + slotOwners[slot] = ingredient; + return true; + } + } + } + + return false; + } + + private void applyPinnedIngredient(PositionedStack pStack) { + final ItemStack ingredient = this.pinnedSlots.get(this.group.getSlotKey(pStack)); + + if (ingredient != null) { + pStack.setPermutationToRender(ingredient); + } + } + @Override public void update() { @@ -142,11 +242,11 @@ public class RecipeWidget extends Widget { return this.buttonCache.computeIfAbsent(this.activeMember, this::createButtons); } - protected List getRecipeButtonsIfInit() { + private List getRecipeButtonsIfInit() { return this.buttonCache.getOrDefault(this.activeMember, Collections.emptyList()); } - protected List createButtons(int member) { + private List createButtons(int member) { if (this.group.getOutputs(member).isEmpty()) { return Collections.emptyList(); @@ -156,7 +256,7 @@ public class RecipeWidget extends Widget { .unmodifiableList(initButtons(RecipeHandlerRef.of(this.handler, this.group.getRecipeIndex(member)))); } - protected List initButtons(RecipeHandlerRef ref) { + private List initButtons(RecipeHandlerRef ref) { final GuiRecipe guiRecipe = getGuiRecipe(); if (guiRecipe != null) { @@ -186,7 +286,7 @@ public class RecipeWidget extends Widget { } - protected List getDefaultButtons(RecipeHandlerRef ref) { + private List getDefaultButtons(RecipeHandlerRef ref) { GuiContainer guiContainer = NEIClientUtils.getGuiContainer(); final List buttons = new ArrayList<>(); final boolean showFavorites = NEIClientConfig.favoritesEnabled() && handlerInfo.getShowFavoritesButton(); @@ -217,13 +317,17 @@ public class RecipeWidget extends Widget { if (this.update) { this.update = false; - if (tickCycle()) { - - if (this.showAsWidget || !contains(mouseX, mouseY)) { - nextMember(); - } - - updatePermutations(this.lastcycle); + if (this.lastcycle == -1) { + this.lastcycle = 0; + applyCycle(); + } else if (tickCycle() && !isCycleFrozen(mouseX, mouseY)) { + this.cycle++; + applyCycle(); + } else if (this.favoriteRevision != FavoriteRecipes.getRevision()) { + this.favoriteRevision = FavoriteRecipes.getRevision(); + this.badgeCache.clear(); + this.acceptsTooltip = null; + updatePermutations(); } for (GuiRecipeButton button : getRecipeButtons()) { @@ -244,21 +348,7 @@ public class RecipeWidget extends Widget { GuiContainerManager.enableMatrixStackLogging(); - for (PositionedStack pStack : getInputs()) { - - if (!this.renderPermutations.contains(pStack)) { - updatePermutationsFor(pStack); - } - - drawItem(pStack, mouseX, mouseY, yShift, true); - } - - for (PositionedStack pStack : getCatalysts()) { - - if (!this.renderPermutations.contains(pStack)) { - updatePermutationsFor(pStack); - } - + for (PositionedStack pStack : getCyclingStacks()) { drawItem(pStack, mouseX, mouseY, yShift, true); } @@ -283,6 +373,10 @@ public class RecipeWidget extends Widget { GL11.glTranslatef(-this.x, -this.y - yShift, 0); GL11.glPopAttrib(); + if (this.paused) { + NEIClientUtils.gl2DRenderContext(this::drawPauseMarker); + } + if (!this.showAsWidget) { final Minecraft mc = NEIClientUtils.mc(); for (GuiRecipeButton button : getRecipeButtons()) { @@ -297,7 +391,22 @@ public class RecipeWidget extends Widget { DebugHandlerWidget.instance.drawGuiPlaceholder(this); } - protected void drawItem(PositionedStack pStack, int mouseX, int mouseY, int yShift, boolean input) { + private void drawPauseMarker() { + GL11.glColor4f(1, 1, 1, 1); + PAUSE_MARKER.draw(this.x + PAUSE_MARKER_OFFSET, this.y + PAUSE_MARKER_OFFSET); + } + + private boolean isPauseMarkerMouseOver(int mouseX, int mouseY) { + final int left = this.x + PAUSE_MARKER_OFFSET; + final int top = this.y + PAUSE_MARKER_OFFSET; + + return this.paused && mouseX >= left + && mouseX < left + PAUSE_MARKER.getWidth() + && mouseY >= top + && mouseY < top + PAUSE_MARKER.getHeight(); + } + + private void drawItem(PositionedStack pStack, int mouseX, int mouseY, int yShift, boolean input) { pStack.draw(mouseX - this.x, mouseY - this.y - yShift); if (this.handlerInfo.getShowBadge()) { @@ -310,7 +419,7 @@ public class RecipeWidget extends Widget { } } - protected List getBadges(PositionedStack pStack, boolean input) { + private List getBadges(PositionedStack pStack, boolean input) { return this.badgeCache.computeIfAbsent(pStack, k -> { final List badges = k.getBadges(); @@ -339,7 +448,7 @@ public class RecipeWidget extends Widget { } - protected void drawBadge(PositionedStack pStack, boolean input) { + private void drawBadge(PositionedStack pStack, boolean input) { final List badges = getBadges(pStack, input); for (Badge badge : badges) { @@ -357,6 +466,7 @@ public class RecipeWidget extends Widget { if (hovered != null && getPermutations(hovered).size() > 1) { FavoriteRecipes.toggleFavoriteItem(hovered.item); + setPaused(false); return true; } @@ -383,6 +493,12 @@ public class RecipeWidget extends Widget { @Override public boolean handleClick(int mouseX, int mouseY, int button) { + if (button == 0 && isPauseMarkerMouseOver(mouseX, mouseY)) { + NEIClientUtils.playClickSound(); + setPaused(false); + return true; + } + if (ShortcutInputHandler.handleMouseClick(getStackMouseOver(mouseX, mouseY))) { return true; } @@ -421,6 +537,11 @@ public class RecipeWidget extends Widget { return tooltip; } + if (isPauseMarkerMouseOver(mouseX, mouseY)) { + tooltip.add(NEIClientUtils.translate("recipe.pinned")); + return tooltip; + } + final List buttonTooltip = forEachButtons( button -> button.contains(mouseX, mouseY) ? button.handleTooltip(tooltip) : null, null); @@ -481,30 +602,6 @@ public class RecipeWidget extends Widget { tooltip.add(GuiDraw.TOOLTIP_HANDLER + GuiDraw.getTipLineId(this.acceptsTooltip)); } - final Point outputKey = cycling == null && hovered != null && this.group.size() > 1 - ? this.group.getSlotKey(hovered) - : null; - - if (outputKey == null || !NEIClientConfig.showCycledIngredientsTooltip()) { - this.variantsTooltip = null; - this.variantsSlotKey = null; - } else if (!outputKey.equals(this.variantsSlotKey)) { - final List variants = this.group.getOutputVariants(outputKey); - - this.variantsSlotKey = outputKey; - this.variantsTooltip = variants.size() > 1 - ? new ItemsTooltipLineHandler(NEIClientUtils.translate("recipe.group"), variants, false, 4) - : null; - - if (this.variantsTooltip != null) { - this.variantsTooltip.setActiveStack(hovered.item); - } - } - - if (this.variantsTooltip != null) { - tooltip.add(GuiDraw.TOOLTIP_HANDLER + GuiDraw.getTipLineId(this.variantsTooltip)); - } - return tooltip; } @@ -563,7 +660,7 @@ public class RecipeWidget extends Widget { return guiRecipe != null && this.handler.mouseScrolled(guiRecipe, scroll, getRecipeIndex()); } - protected boolean scrollPermutations(int scroll, PositionedStack hovered) { + private boolean scrollPermutations(int scroll, PositionedStack hovered) { final Point slotKey = this.group.getSlotKey(hovered); final List items = this.group.getPermutations(slotKey); @@ -571,46 +668,23 @@ public class RecipeWidget extends Widget { return false; } - final List slots = new ArrayList<>(this.group.size()); + final int current = Math.max(0, PermutationsCycler.indexOf(items, hovered.item)); + final int direction = scroll > 0 ? -1 : 1; - for (int member = 0; member < this.group.size(); member++) { - slots.add(this.group.getSlot(member, slotKey)); - } - - final int anchor = getCursorMember(); - final int currentItem = PermutationsCycler.indexOf(items, hovered.item); - final List variants = new ArrayList<>(); - int current = 0; - - for (int itemIndex = 0; itemIndex < items.size(); itemIndex++) { - final ItemStack stack = items.get(itemIndex); - int member = containsStack(slots.get(this.activeMember), stack) ? this.activeMember : -1; - - for (int offset = 0; member == -1 && offset < slots.size(); offset++) { - if (containsStack(slots.get((anchor + offset) % slots.size()), stack)) { - member = (anchor + offset) % slots.size(); - } - } + for (int step = 1; step <= items.size(); step++) { + final ItemStack stack = items.get(Math.floorMod(current + direction * step, items.size())); + final int member = this.group.findMember(slotKey, stack, this.activeMember); if (member != -1) { - if (itemIndex == currentItem) { - current = variants.size(); - } - variants.add(new int[] { itemIndex, member }); + switchMember(member, stack); + return true; } } - if (variants.isEmpty()) { - return false; - } - - final int[] next = variants.get(((current - scroll) % variants.size() + variants.size()) % variants.size()); - switchMember(next[1], items.get(next[0])); - - return true; + return false; } - protected boolean scrollMembers(int scroll) { + private boolean scrollMembers(int scroll) { final int size = this.group.size(); if (size <= 1) { @@ -622,14 +696,19 @@ public class RecipeWidget extends Widget { return true; } - protected void switchMember(int member, ItemStack stack) { + private void switchMember(int member, ItemStack stack) { final Map rendered = new HashMap<>(); + setPaused(false); + for (PositionedStack pStack : getCyclingStacks()) { rendered.put(this.group.getSlotKey(pStack), pStack.item); } setActiveMember(member); + syncCycle(); + this.group.refresh(member); + this.badgeCache.clear(); for (PositionedStack pStack : getCyclingStacks()) { final ItemStack renderStack = containsStack(pStack, stack) ? stack @@ -637,6 +716,8 @@ public class RecipeWidget extends Widget { if (containsStack(pStack, renderStack)) { pStack.setPermutationToRender(renderStack); + } else { + updatePermutationsFor(pStack); } } @@ -644,10 +725,9 @@ public class RecipeWidget extends Widget { notifyPermutationsChanged(); } - protected boolean tickCycle() { + private boolean tickCycle() { - if (!NEIClientUtils.shiftKey() && (this.cycleticks++ / TICKS_PER_CYCLE) != this.lastcycle - || this.lastcycle == -1) { + if ((this.cycleticks++ / TICKS_PER_CYCLE) != this.lastcycle) { this.lastcycle = this.cycleticks / TICKS_PER_CYCLE; return true; } @@ -655,20 +735,45 @@ public class RecipeWidget extends Widget { return false; } - protected void nextMember() { - final List allowed = this.group.getAllowedMembers(); + private boolean isCycleFrozen(int mouseX, int mouseY) { - this.memberCursor = (this.memberCursor + 1) % allowed.size(); - setActiveMember(allowed.get(this.memberCursor)); + if (this.paused || NEIClientUtils.shiftKey()) { + return true; + } + + return !this.showAsWidget && contains(mouseX, mouseY) + && (getPositionedStackMouseOver(mouseX, mouseY) != null + || forEachButtons(button -> button.contains(mouseX, mouseY) ? true : null, false)); } - protected int getCursorMember() { - final List allowed = this.group.getAllowedMembers(); - return allowed.get(Math.max(0, this.memberCursor) % allowed.size()); + private void applyCycle() { + + if (!this.paused) { + final List allowed = this.group.getAllowedMembers(); + setActiveMember(allowed.get(this.cycle % allowed.size())); + } + + this.group.refresh(this.activeMember); + updatePermutations(); } - protected void updatePermutations(int cycle) { - this.slotCycle = cycle; + private int getPermutationIndex() { + return this.cycle / this.group.getAllowedMembers().size(); + } + + // keep the permutation index, move the member part of the counter to the active member + private void syncCycle() { + final List allowed = this.group.getAllowedMembers(); + final int allowedIndex = allowed.indexOf(this.activeMember); + + if (allowedIndex >= 0) { + this.cycle = this.cycle / allowed.size() * allowed.size() + allowedIndex; + } + } + + private void updatePermutations() { + // badges depend on the rendered item + this.badgeCache.clear(); for (PositionedStack pStack : getCyclingStacks()) { updatePermutationsFor(pStack); @@ -678,7 +783,7 @@ public class RecipeWidget extends Widget { notifyPermutationsChanged(); } - protected void updateTooltipActiveStack() { + private void updateTooltipActiveStack() { if (this.acceptsTooltip != null && this.acceptsTooltip.tooltipGUID instanceof Point slotKey) { final PositionedStack pStack = this.group.getSlot(this.activeMember, slotKey); @@ -688,29 +793,20 @@ public class RecipeWidget extends Widget { } } - if (this.variantsTooltip != null) { - final PositionedStack pStack = this.group.getOutputSlot(this.activeMember, this.variantsSlotKey); - - if (pStack != null) { - this.variantsTooltip.setActiveStack(pStack.item); - } - } - } - protected void updatePermutationsFor(PositionedStack pStack) { + private void updatePermutationsFor(PositionedStack pStack) { + final int index = this.group + .getCycledPermutationIndex(this.activeMember, this.group.getSlotKey(pStack), getPermutationIndex()); - if (!this.renderPermutations.contains(pStack) || this.renderPermutations.get(pStack).size() > 1) { - final ItemStack stack = this.renderPermutations.getCycled(pStack, this.slotCycle); - - if (stack != null) { - pStack.setPermutationToRender(stack); - } + if (index >= 0) { + pStack.setPermutationToRender(index); } + applyPinnedIngredient(pStack); } - protected void setActiveMember(int member) { + private void setActiveMember(int member) { if (member != this.activeMember) { this.activeMember = member; @@ -722,22 +818,21 @@ public class RecipeWidget extends Widget { } - protected boolean containsStack(PositionedStack pStack, ItemStack stack) { - return pStack != null && stack != null - && PermutationsCycler.indexOf(pStack.getFilteredPermutations(), stack) != -1; + private boolean containsStack(PositionedStack pStack, ItemStack stack) { + return pStack != null && this.group.hasPermutation(this.activeMember, this.group.getSlotKey(pStack), stack); } - protected List getPermutations(PositionedStack pStack) { + private List getPermutations(PositionedStack pStack) { return this.group.getPermutations(this.group.getSlotKey(pStack)); } - protected void notifyPermutationsChanged() { + private void notifyPermutationsChanged() { for (GuiRecipeButton button : getRecipeButtonsIfInit()) { button.onPermutationsChanged(); } } - protected R forEachButtons(Function callback, R defaultValue) { + private R forEachButtons(Function callback, R defaultValue) { for (GuiRecipeButton button : getRecipeButtonsIfInit()) { button.xPosition += this.x; @@ -773,7 +868,7 @@ public class RecipeWidget extends Widget { return cycling != null ? cycling : getOutputStackMouseOver(mx, my); } - protected PositionedStack getOutputStackMouseOver(int mx, int my) { + private PositionedStack getOutputStackMouseOver(int mx, int my) { final int yShift = this.handlerInfo.getYShift(); for (PositionedStack pStack : getOutputs()) { @@ -785,16 +880,10 @@ public class RecipeWidget extends Widget { return null; } - protected PositionedStack getCyclingStackMouseOver(int mx, int my) { + private PositionedStack getCyclingStackMouseOver(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()) { + for (PositionedStack pStack : getCyclingStacks()) { if (pStack.contains(mx - this.x, my - this.y - yShift)) { return pStack; } @@ -809,7 +898,7 @@ public class RecipeWidget extends Widget { return pStack != null ? pStack.item : null; } - protected GuiRecipe getGuiRecipe() { + private GuiRecipe getGuiRecipe() { final GuiContainer guiContainer = NEIClientUtils.getGuiContainer(); if (guiContainer instanceof GuiRecipeguiRecipe) { @@ -819,18 +908,10 @@ public class RecipeWidget extends Widget { return null; } - protected List getInputs() { - return this.group.getInputs(this.activeMember); - } - protected List getOutputs() { return this.group.getOutputs(this.activeMember); } - protected List getCatalysts() { - return this.group.getCatalysts(this.activeMember); - } - protected List getCyclingStacks() { return this.group.getCyclingStacks(this.activeMember); } diff --git a/src/main/resources/assets/nei/lang/en_US.lang b/src/main/resources/assets/nei/lang/en_US.lang index 887dcc49..d9a176c6 100644 --- a/src/main/resources/assets/nei/lang/en_US.lang +++ b/src/main/resources/assets/nei/lang/en_US.lang @@ -685,8 +685,8 @@ nei.recipe.concurrent.usage=Concurrent Usage - Total nei.recipe.concurrent.crafting=Concurrent Crafting - Total nei.recipe.accepts=Accepts following nei.recipe.accepts.scroll=Change Item -nei.recipe.group=Variants nei.recipe.group.scroll=Change Variant (%s/%s) +nei.recipe.pinned=Click to resume cycling nei.recipe.overlay=Recipe Overlay nei.recipe.overlay.missing=Missing following diff --git a/src/main/resources/assets/nei/lang/ru_RU.lang b/src/main/resources/assets/nei/lang/ru_RU.lang index e3098a8f..076ec044 100644 --- a/src/main/resources/assets/nei/lang/ru_RU.lang +++ b/src/main/resources/assets/nei/lang/ru_RU.lang @@ -422,6 +422,7 @@ nei.recipe.profiler.usage=Профилирование использовани nei.recipe.concurrent.usage=Одновременное использование - всего nei.recipe.concurrent.crafting=Одновременный крафт - всего nei.recipe.accepts=Принимает следующее +nei.recipe.pinned=Нажмите, чтобы продолжить перебор nei.recipe.overlay=отображение рецепта nei.recipe.overlay.missing=Отсутствует следующее diff --git a/src/main/resources/assets/nei/textures/pinned_pause.png b/src/main/resources/assets/nei/textures/pinned_pause.png new file mode 100644 index 0000000000000000000000000000000000000000..6a2c26f7533fc92365ff350986bcc24a27bf5e0e GIT binary patch literal 554 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`jKx9jP7LeL$-D$|SkfJR9T^xl z_H+M9WCij$3p^r=85sBuf-vKbiP>*~8rm~MB1$5BeXNr6bM+Ea@{>~aDsl^esu>t; z>?;Zqle1Gx6p~WYGxKcK-|yb9u8^5xs~&FZYv5bpoSKp8QB{;0T;&&%T$P<{nWAoQ z$IE3?VFffHH?<^Dp&~aYuh^=>Rtapd6_5=Q)>pE#DN0GR3UYCSssQqAl`=|73as?? z%gf94%8m8%i_-NCEiEne4UF`SjC6r2bc-wVN)jt{^NN+B2DqdaCl_TFlw{`TDS!-2 zOv*1Uu~jN9%}lXMOH4CON=Y%*O-eLQ(KR$oNz_eDF*ejqF*Z&yH#M{{N;6DSf?8ja znTD`GuNWE(zyQ$)$>>wgQzXDnC zkO2h~Jakj@fI(Ug3_G1EGq{1_uH)(A7-G?zoWQ`u&)@(5h5@sPz@+8#7{9-}%bXm; n_F$5{X~LC;hiL~Ip13hIW^CQC@>SekP=tB9`njxgN@xNASU$5B literal 0 HcmV?d00001