Compare commits

..
Author SHA1 Message Date
slprime 463d8d1f12 fix counter label position 2026-11-25 23:43:56 +02:00
github-actions[bot]andGitHub GTNH Actions c7188f1952 Optimising images contained in recipe/ui-skin-sizes for #1165 (#1166)
Co-authored-by: GitHub GTNH Actions <[email protected]>
2026-11-25 21:22:16 +02:00
slprime db9dc1706b Improve recipe screen 2026-11-25 21:07:56 +02:00
a665a5be56 Fix item hotkeys on crafting tree Crafting slots (#1151)
Co-authored-by: Lorenzo <[email protected]>
Co-authored-by: Chitak 985 <[email protected]>
Co-authored-by: slprime <[email protected]>
2026-11-25 09:08:16 +02:00
slprime bdadcc37a6 Extract inventory and missing ingredient helpers (#1164) 2026-11-25 01:04:09 +02:00
62 changed files with 1694 additions and 1247 deletions

No files matched your search

@@ -11,9 +11,11 @@ public class ColorUtils {
textGray = color.rgb("textGray", "0x404040"),
textLightGray = color.rgb("textLightGray", "0x606060"),
recipeTitle = color.rgb("recipeTitle", "0xFFFFFF"),
recipeTitleBG = color.argb("recipeTitleBG", "0x30000000"),
recipeTitleHover = color.rgb("recipeTitleHover", "0xFFFF55"),
subsetWidget = color.rgb("subsetWidget", "0xAA00AA"),
recipeBadge = color.rgb("recipeBadge", "0xFDD835"),
subsetWidget = color.rgb("subsetWidget", "0xAA00AA"),
buttonLabelNormal = color.rgb("buttonLabelNormal", "0xE0E0E0"),
buttonLabelHover = color.rgb("buttonLabelHover", "0xFFFFA0"),
buttonLabelDisabled = color.rgb("buttonLabelDisabled", "0x601010"),
@@ -18,7 +18,6 @@ import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.ItemsGrid.ItemsGridSlot;
import codechicken.nei.ItemsGrid.MouseContext;
import codechicken.nei.NEIClientUtils.Alignment;
import codechicken.nei.recipe.AutoCraftingManager;
import codechicken.nei.recipe.GuiCraftingRecipe;
import codechicken.nei.recipe.GuiRecipe;
import codechicken.nei.recipe.ICraftingHandler;
@@ -268,7 +267,7 @@ public class ItemCraftablesPanel
if (firstGui != null && !ItemCraftablesPanel.guiBlacklist.contains(firstGui.getClass().getName())) {
final boolean showOnlyFavorites = NEIClientConfig
.getBooleanSetting("inventory.craftables.favoritesOnly");
final ItemStackAmount inv = AutoCraftingManager.getInventoryItems(firstGui);
final ItemStackAmount inv = ItemStackAmount.of(firstGui);
if (this.lastGuiContainer != firstGui
|| showOnlyFavorites && this.lastFavoritesCount != FavoriteRecipes.size()
@@ -317,7 +316,7 @@ public class ItemCraftablesPanel
final Map<ItemStack, RecipeId> availableRecipes = new HashMap<>();
if (!availableHandlers.isEmpty()) {
final Map<Item, List<ItemStack>> invByItem = indexInventoryByItem(snapshot.inventory.values());
final Map<Item, List<ItemStack>> invByItem = snapshot.inventory.groupByItem();
if (snapshot.showOnlyFavorites) {
for (IRecipeHandler handler : availableHandlers) {
@@ -349,16 +348,6 @@ public class ItemCraftablesPanel
return availableHandlers;
}
private static Map<Item, List<ItemStack>> indexInventoryByItem(List<ItemStack> invStacks) {
final Map<Item, List<ItemStack>> index = new HashMap<>();
for (ItemStack stack : invStacks) {
index.computeIfAbsent(stack.getItem(), i -> new ArrayList<>()).add(stack);
}
return index;
}
private void collectHandlerCandidates(IRecipeHandler handler, Map<Item, List<ItemStack>> invByItem,
List<RecipeCandidate> candidates) {
IntStream.range(0, handler.numRecipes()).parallel().forEach(recipeIndex -> {
@@ -448,36 +437,8 @@ public class ItemCraftablesPanel
return availableRecipes;
}
private boolean existsIngredients(List<PositionedStack> ingredients, Map<Item, List<ItemStack>> invByItem) {
final Map<ItemStack, Integer> usedItems = new HashMap<>();
for (PositionedStack pStack : ingredients) {
ItemStack used = null;
for (ItemStack permutation : pStack.items) {
final List<ItemStack> candidates = invByItem.get(permutation.getItem());
if (candidates == null) continue;
for (ItemStack is : candidates) {
if (usedItems.getOrDefault(is, is.stackSize) >= pStack.item.stackSize
&& NEIServerUtils.areStacksSameTypeCrafting(permutation, is)) {
used = is;
break;
}
}
if (used != null) break;
}
if (used != null) {
usedItems.put(used, usedItems.getOrDefault(used, used.stackSize) - pStack.item.stackSize);
} else {
return false;
}
}
return !usedItems.isEmpty();
private static boolean existsIngredients(List<PositionedStack> ingredients, Map<Item, List<ItemStack>> invByItem) {
return !ingredients.isEmpty() && NEIClientUtils.countMissingIngredients(ingredients, invByItem, 1) == 0;
}
}
@@ -1,12 +1,17 @@
package codechicken.nei;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.inventory.Slot;
import net.minecraft.inventory.SlotCrafting;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
@@ -96,6 +101,16 @@ public class ItemStackAmount {
return list;
}
public Map<Item, List<ItemStack>> groupByItem() {
final Map<Item, List<ItemStack>> groups = new HashMap<>();
for (ItemStack stack : values()) {
groups.computeIfAbsent(stack.getItem(), i -> new ArrayList<>()).add(stack);
}
return groups;
}
public int size() {
return this.itemMap.size();
}
@@ -140,4 +155,16 @@ public class ItemStackAmount {
return result;
}
public static ItemStackAmount of(GuiContainer gui) {
final ItemStackAmount result = new ItemStackAmount();
for (Slot slot : gui.inventorySlots.inventorySlots) {
if (slot.getHasStack() && !(slot instanceof SlotCrafting) && slot.canTakeStack(gui.mc.thePlayer)) {
result.add(slot.getStack());
}
}
return result;
}
}
@@ -11,8 +11,9 @@ import codechicken.nei.api.LayoutStyle;
public class LayoutStyleMinecraft extends LayoutStyle {
protected static final int BUTTON_SIZE = 20;
protected static final int MARGIN = 2;
public static final int BUTTON_SIZE = 20;
public static final int MARGIN = 2;
public static final int SUBSET_BAR_HEIGHT = 16;
public int buttonCount;
public int leftSize;
@@ -147,7 +148,7 @@ public class LayoutStyleMinecraft extends LayoutStyle {
LayoutManager.searchField.x += BUTTON_SIZE;
LayoutManager.searchField.w -= BUTTON_SIZE;
} else {
LayoutManager.dropDown.h = 16;
LayoutManager.dropDown.h = SUBSET_BAR_HEIGHT;
LayoutManager.dropDown.w = 150;
LayoutManager.dropDown.y = MARGIN;
LayoutManager.dropDown.x = (gui.width - LayoutManager.dropDown.w) / 2;
@@ -59,6 +59,7 @@ import codechicken.nei.config.preset.GuiPresetList;
import codechicken.nei.event.NEIConfigsLoadedEvent;
import codechicken.nei.moboverlay.MobOverlayScan;
import codechicken.nei.moboverlay.MobOverlayStyle;
import codechicken.nei.recipe.HandlerInfo;
import codechicken.nei.recipe.IRecipeHandler;
import codechicken.nei.recipe.InformationHandler;
import codechicken.nei.recipe.RecipeCatalysts;
@@ -270,9 +271,20 @@ public class NEIClientConfig {
.getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.guirecipe.infiniteScroll", true));
tag.getTag("inventory.guirecipe.evenRecipeSpacing").setComment("Spread recipes evenly across the page height")
.getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.guirecipe.evenRecipeSpacing", true));
tag.getTag("inventory.guirecipe.topMargin").setComment("Recipe GUI Top Margin").getIntValue(0);
API.addOption(new OptionIntegerField("inventory.guirecipe.topMargin", 0, 200));
tag.getTag("inventory.guirecipe.maxHeight").setComment("Recipe GUI Max Height").getIntValue(370);
API.addOption(new OptionIntegerField("inventory.guirecipe.maxHeight", 166, 4000));
tag.getTag("inventory.guirecipe.minWidth").setComment("Recipe GUI Min Width")
.getIntValue(HandlerInfo.DEFAULT_WIDTH);
API.addOption(new OptionIntegerField("inventory.guirecipe.minWidth", HandlerInfo.DEFAULT_WIDTH, 4000));
tag.getTag("inventory.guirecipe.shiftOverlayRecipe")
.setComment("Require holding shift to move items when overlaying recipe").getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.guirecipe.shiftOverlayRecipe", true));
@@ -538,6 +538,40 @@ public class NEIClientUtils extends NEIServerUtils {
return null;
}
public static int countMissingIngredients(List<PositionedStack> ingredients, Map<Item, List<ItemStack>> index,
int limit) {
Map<ItemStack, Integer> usedItems = new HashMap<>();
int missing = 0;
for (PositionedStack pStack : ingredients) {
ItemStack used = null;
for (ItemStack permutation : pStack.items) {
final List<ItemStack> candidates = index.get(permutation.getItem());
if (candidates == null) continue;
for (ItemStack is : candidates) {
if (usedItems.getOrDefault(is, is.stackSize) >= pStack.item.stackSize
&& NEIServerUtils.areStacksSameTypeCrafting(permutation, is)) {
used = is;
break;
}
}
if (used != null) break;
}
if (used != null) {
usedItems.put(used, usedItems.getOrDefault(used, used.stackSize) - pStack.item.stackSize);
} else if (++missing >= limit) {
return missing;
}
}
return missing;
}
public static boolean altKey() {
return Keyboard.isKeyDown(Keyboard.KEY_LMENU) || Keyboard.isKeyDown(Keyboard.KEY_RMENU);
}
@@ -30,7 +30,6 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
private static final MobOverlayScan MOB_OVERLAY_SCAN = new MobOverlayScan();
private static final MobOverlayFace MARKED_FACE = new MobOverlayFace();
private static final MobOverlayDisplayList MOB_OVERLAY_LIST = new MobOverlayDisplayList();
private static final byte[] COLUMN_CELLS = new byte[2 * MobOverlayScan.MAX_VERTICAL_RADIUS + 1];
public static void reset() {
mobOverlay = 0;
@@ -84,6 +83,10 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
GL11.glPopAttrib();
}
/**
* The model view matrix is relative to ({@code intOffsetX}, {@code intOffsetY}, {@code intOffsetZ}), the camera
* position cast to {@code int}.
*/
private static void renderMobSpawnOverlay(Entity entity, int intOffsetX, int intOffsetY, int intOffsetZ) {
if (mobOverlay == 0) {
MOB_OVERLAY_SCAN.clear();
@@ -107,49 +110,29 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
endMobOverlayDraw();
}
/**
* Add a marked face to {@link #MOB_OVERLAY_LIST} for each block of {@link #MOB_OVERLAY_SCAN} where mobs can spawn.
*/
private static void compileMobOverlayList(MobOverlayStyle style, long worldTicks) {
MOB_OVERLAY_LIST.beginCompile(MOB_OVERLAY_SCAN, style, worldTicks);
for (int chunkX = MOB_OVERLAY_SCAN.getMinChunkX(); chunkX <= MOB_OVERLAY_SCAN.getMaxChunkX(); chunkX++) {
for (int chunkZ = MOB_OVERLAY_SCAN.getMinChunkZ(); chunkZ <= MOB_OVERLAY_SCAN.getMaxChunkZ(); chunkZ++) {
if (!MOB_OVERLAY_LIST.beginChunk(MOB_OVERLAY_SCAN, chunkX, chunkZ)) continue;
MOB_OVERLAY_LIST.endChunk(compileChunkFaces(style, chunkX, chunkZ));
}
}
MOB_OVERLAY_LIST.endCompile(MOB_OVERLAY_SCAN);
}
private static boolean compileChunkFaces(MobOverlayStyle style, int chunkX, int chunkZ) {
final int CHUNK_WIDTH = 1 << MobOverlayScan.CHUNK_SHIFT;
final float alpha = style.computeAlpha();
final Tessellator tess = Tessellator.instance;
final int cornerX = chunkX << MobOverlayScan.CHUNK_SHIFT;
final int cornerZ = chunkZ << MobOverlayScan.CHUNK_SHIFT;
final int minX = MOB_OVERLAY_SCAN.getMinX();
final int minZ = MOB_OVERLAY_SCAN.getMinZ();
final int span = MOB_OVERLAY_SCAN.getSpan();
final int height = MOB_OVERLAY_SCAN.getHeight();
boolean hasFaces = false;
tess.startDrawing(style.glMode);
for (int i = Math.max(cornerX - minX, 0); i < Math.min(cornerX + CHUNK_WIDTH - minX, span); i++) {
for (int j = Math.max(cornerZ - minZ, 0); j < Math.min(cornerZ + CHUNK_WIDTH - minZ, span); j++) {
MOB_OVERLAY_SCAN.readColumn(i, j, COLUMN_CELLS);
for (int k = 0; k < height; k++) {
if (MobOverlayScan.extractSpawnMode(COLUMN_CELLS[k]) == 0) continue;
final int span = MOB_OVERLAY_SCAN.getSpan();
for (int i = 0; i < span; i++) {
for (int j = 0; j < span; j++) {
for (int k = 0; k < MOB_OVERLAY_SCAN.getHeight(); k++) {
if (MOB_OVERLAY_SCAN.readSpawnMode(i, k, j) == 0) continue;
MARKED_FACE.moveTo(
minX + i - cornerX,
k + MobOverlayScan.computeOverlayYOffset(COLUMN_CELLS[k]),
minZ + j - cornerZ);
MARKED_FACE.moveTo(i, k + MOB_OVERLAY_SCAN.readOverlayYOffset(i, k, j), j);
loadNeighbourModes(i, k, j);
MARKED_FACE.applyColor(style.colouring, alpha);
style.addVertices(MARKED_FACE);
hasFaces = true;
}
}
}
tess.draw();
return hasFaces;
MOB_OVERLAY_LIST.endCompile();
}
private static void beginMobOverlayDraw(MobOverlayStyle style) {
@@ -164,7 +147,7 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glLineWidth(1.5F);
// the outline of `MobOverlayStyle.CONNECTED` lies in the plane of the tint. When depth writes are on, the depth
// the outline of `MobOverlayStyle.CONNECTED` lies in the plane of the tint. With depth writes on, the depth
// test discards most of the outline
GL11.glDepthMask(false);
}
@@ -21,6 +21,7 @@ import codechicken.nei.BookmarkContainerInfo;
import codechicken.nei.FavoriteRecipes;
import codechicken.nei.ItemPanels;
import codechicken.nei.ItemQuantityField;
import codechicken.nei.ItemStackAmount;
import codechicken.nei.KeyManager;
import codechicken.nei.LayoutManager;
import codechicken.nei.NEIClientConfig;
@@ -717,7 +718,7 @@ public abstract class ShortcutInputHandler {
private static void autocraftingIgnoreInventory(RecipeChainMath math) {
final GuiContainer guiContainer = NEIClientUtils.getGuiContainer();
final List<ItemStack> playerInventory = AutoCraftingManager.getInventoryItems(guiContainer).values();
final List<ItemStack> playerInventory = ItemStackAmount.of(guiContainer).values();
final RecipeId rootRecipeId = math.createMasterRoot();
for (int i = 0; i < math.recipeIngredients.size(); i++) {
@@ -36,6 +36,7 @@ import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.ItemStackAmount;
import codechicken.nei.KeyManager;
import codechicken.nei.LRUCache;
import codechicken.nei.NEICPH;
@@ -60,7 +61,6 @@ import codechicken.nei.guihook.IGuiClientSide;
import codechicken.nei.guihook.IGuiHandleMouseWheel;
import codechicken.nei.guihook.IGuiHotkeyListener;
import codechicken.nei.recipe.AcceptsFollowingTooltipLineHandler;
import codechicken.nei.recipe.AutoCraftingManager;
import codechicken.nei.recipe.GuiCraftingRecipe;
import codechicken.nei.recipe.GuiOverlayButton;
import codechicken.nei.recipe.GuiRecipe;
@@ -284,10 +284,8 @@ public class GuiCraftingTree extends GuiContainer implements INEIGuiHandler, IGu
final GuiContainer firstGui = getFirstScreen();
if (firstGui != null) {
for (ItemStack stack : AutoCraftingManager.getInventoryItems(firstGui).values()) {
if (stack != null) {
this.math.initialItems.add(BookmarkItem.of(-1, stack));
}
for (ItemStack stack : ItemStackAmount.of(firstGui).values()) {
this.math.initialItems.add(BookmarkItem.of(-1, stack));
}
}
}
@@ -524,7 +524,7 @@ class StatsPanel extends ScrollContainer {
public ItemStack getStackMouseOver(int mouseX, int mouseY) {
final Widget widget = getWidgetUnderMouse(mouseX, mouseY);
return widget instanceof ItemStatsSlot slot && slot.recipeId == null ? slot.getStack() : null;
return widget instanceof ItemStatsSlot slot ? slot.getStack() : null;
}
public void setHighlight(SearchResult searchResult) {
@@ -3,25 +3,15 @@ package codechicken.nei.bookmark.tree;
import java.util.List;
import java.util.Map;
import net.minecraft.client.Minecraft;
import org.lwjgl.opengl.GL11;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.recipe.GuiRecipeButton;
import codechicken.nei.recipe.Recipe;
import codechicken.nei.recipe.RecipeHandlerRef;
import codechicken.nei.theme.UIRecipeTexture;
public class TreeOverlayButton extends GuiRecipeButton {
protected static final DrawableResource ICON_FILL = new DrawableBuilder(
"nei:textures/nei_sprites.png",
28,
76,
9,
10).build();
protected static final int BUTTON_ID_SHIFT = 4;
public final GuiCraftingTree treeGui;
@@ -50,16 +40,8 @@ public class TreeOverlayButton extends GuiRecipeButton {
}
@Override
protected void drawContent(Minecraft minecraft, int y, int x, boolean mouseOver) {
final int iconX = this.xPosition + (this.width - ICON_FILL.width - 1) / 2;
final int iconY = this.yPosition + (this.height - ICON_FILL.height) / 2;
GL11.glColor4f(1, 1, 1, this.enabled ? 1 : 0.5f);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
ICON_FILL.draw(iconX, iconY);
GL11.glDisable(GL11.GL_BLEND);
GL11.glColor4f(1, 1, 1, 1);
protected DrawableResource getIcon() {
return UIRecipeTexture.ICON_OVERLAY_FILL;
}
@Override
@@ -109,6 +109,8 @@ public class IMCHandler {
info.setShowFavoritesButton(!tag.hasKey("showFavoritesButton") || tag.getBoolean("showFavoritesButton"));
info.setShowOverlayButton(!tag.hasKey("showOverlayButton") || tag.getBoolean("showOverlayButton"));
info.setShowBadge(tag.hasKey("showBadge") && tag.getBoolean("showBadge"));
info.setWindowWidth(tag.getInteger("windowWidth"));
info.setRecipeSpacing(tag.getBoolean("recipeSpacing"));
GuiRecipeTab.handlerAdderFromIMC.remove(handler);
GuiRecipeTab.handlerAdderFromIMC.put(handler, info);
@@ -0,0 +1,57 @@
package codechicken.nei.drawable;
public interface Drawable {
@FunctionalInterface
public interface Painter {
public void draw(int x, int y, int width, int height);
}
public int getWidth();
public int getHeight();
public void draw(int x, int y, int width, int height);
default void draw(int x, int y) {
draw(x, y, getWidth(), getHeight());
}
public static Drawable of(int width, int height, Painter painter) {
return new Drawable() {
@Override
public int getWidth() {
return width;
}
@Override
public int getHeight() {
return height;
}
@Override
public void draw(int x, int y, int w, int h) {
painter.draw(x, y, w, h);
}
};
}
// every layer is drawn into the whole rectangle, the first one at the bottom
public static Drawable stack(Drawable... layers) {
int width = 0;
int height = 0;
for (Drawable layer : layers) {
width = Math.max(width, layer.getWidth());
height = Math.max(height, layer.getHeight());
}
return of(width, height, (x, y, w, h) -> {
for (Drawable layer : layers) {
layer.draw(x, y, w, h);
}
});
}
}
@@ -8,7 +8,7 @@ import org.lwjgl.opengl.GL11;
import codechicken.nei.Image;
public class DrawableResource extends Image {
public class DrawableResource extends Image implements Drawable {
private final ResourceLocation resourceLocation;
private final int textureWidth;
@@ -640,7 +640,7 @@ public class GuiContainerManager {
tooltip = handler.handleTooltip(window, mousex, mousey, tooltip);
}
ItemStack stack = getStackMouseOver(window);
ItemStack stack = tooltip.isEmpty() ? getStackMouseOver(window) : null;
boolean showTooltip = shouldShowTooltip(window);
if (tooltip.isEmpty() && showTooltip) { // mouseover tip, not holding an item
font = getFontRenderer(stack);
@@ -1,117 +1,65 @@
package codechicken.nei.moboverlay;
import java.util.Arrays;
import net.minecraft.client.renderer.GLAllocation;
import org.lwjgl.opengl.GL11;
/**
* {@code MobOverlayDisplayList} compiles the overlay quads of each chunk column of a {@link MobOverlayScan} box into
* one GL display list. A compile rebuilds only the lists whose {@link MobOverlayScan#readChunkVersion} changed.
*/
/** The mob spawn overlay quads, compiled into a GL display list. */
public final class MobOverlayDisplayList {
private static final int NO_LIST = -1;
private int firstListId = NO_LIST;
private int parentListId = NO_LIST;
private int anchorX;
private int anchorY;
private int anchorZ;
private int chunkSpan;
private boolean[] isCompiled = new boolean[0];
private boolean[] hasFaces = new boolean[0];
private int[] compiledChunkVersion = new int[0];
private int listId = -1;
private int modesVersion;
private MobOverlayStyle style;
private int minX;
private int minY;
private int minZ;
private long compiledTicks;
private int compilingChunk;
/**
* Compiles after a {@link MobOverlayScan#getModesVersion} change are debounced to one per {@code MIN_COMPILE_TICKS}
* ticks, because the version changes several times per second while the player moves fast, and a compile runs for a
* millisecond or more.
*/
public boolean isCompileDue(int currentModesVersion, MobOverlayStyle currentStyle, long worldTicks) {
final int MIN_COMPILE_TICKS = 5;
if (firstListId == NO_LIST || style != currentStyle) return true;
if (listId < 0 || style != currentStyle) return true;
// after a dimension change or a server switch, `worldTicks` can be lower than `compiledTicks`
final boolean isWaitOver = worldTicks - compiledTicks >= MIN_COMPILE_TICKS || worldTicks < compiledTicks;
return modesVersion != currentModesVersion && isWaitOver;
}
/**
* Quad positions are relative to block ({@link MobOverlayScan#getMinX}, {@link MobOverlayScan#getMinY},
* {@link MobOverlayScan#getMinZ}) of {@code scan}.
*/
public void beginCompile(MobOverlayScan scan, MobOverlayStyle newStyle, long worldTicks) {
if (chunkSpan != scan.getChunkSpan()) resize(scan.getChunkSpan());
if (style != newStyle) Arrays.fill(isCompiled, false);
if (listId < 0) listId = GLAllocation.generateDisplayLists(1);
modesVersion = scan.getModesVersion();
style = newStyle;
minX = scan.getMinX();
minY = scan.getMinY();
minZ = scan.getMinZ();
compiledTicks = worldTicks;
anchorX = scan.getMinX();
anchorY = scan.getMinY();
anchorZ = scan.getMinZ();
GL11.glNewList(listId, GL11.GL_COMPILE);
}
public boolean beginChunk(MobOverlayScan scan, int chunkX, int chunkZ) {
final int chunk = scan.findChunk(chunkX, chunkZ);
final int chunkVersion = scan.readChunkVersion(chunkX, chunkZ);
if (isCompiled[chunk] && compiledChunkVersion[chunk] == chunkVersion) return false;
isCompiled[chunk] = true;
compiledChunkVersion[chunk] = chunkVersion;
compilingChunk = chunk;
GL11.glNewList(firstListId + chunk, GL11.GL_COMPILE);
return true;
}
public void endChunk(boolean hasChunkFaces) {
GL11.glEndList();
hasFaces[compilingChunk] = hasChunkFaces;
}
public void endCompile(MobOverlayScan scan) {
GL11.glNewList(parentListId, GL11.GL_COMPILE);
for (int chunkX = scan.getMinChunkX(); chunkX <= scan.getMaxChunkX(); chunkX++) {
for (int chunkZ = scan.getMinChunkZ(); chunkZ <= scan.getMaxChunkZ(); chunkZ++) {
final int chunk = scan.findChunk(chunkX, chunkZ);
if (!hasFaces[chunk]) continue;
GL11.glPushMatrix();
GL11.glTranslated(
(chunkX << MobOverlayScan.CHUNK_SHIFT) - anchorX,
0,
(chunkZ << MobOverlayScan.CHUNK_SHIFT) - anchorZ);
GL11.glCallList(firstListId + chunk);
GL11.glPopMatrix();
}
}
public void endCompile() {
GL11.glEndList();
}
/** The model view matrix is relative to block ({@code cameraX}, {@code cameraY}, {@code cameraZ}). */
public void draw(int cameraX, int cameraY, int cameraZ) {
GL11.glPushMatrix();
GL11.glTranslated(anchorX - cameraX, anchorY - cameraY, anchorZ - cameraZ);
GL11.glCallList(parentListId);
GL11.glTranslated(minX - cameraX, minY - cameraY, minZ - cameraZ);
GL11.glCallList(listId);
GL11.glPopMatrix();
}
private void resize(int newChunkSpan) {
final int chunkCount = newChunkSpan * newChunkSpan;
delete();
chunkSpan = newChunkSpan;
firstListId = GLAllocation.generateDisplayLists(chunkCount + 1);
parentListId = firstListId + chunkCount;
isCompiled = new boolean[chunkCount];
hasFaces = new boolean[chunkCount];
compiledChunkVersion = new int[chunkCount];
}
public void delete() {
if (firstListId == NO_LIST) return;
if (listId < 0) return;
GLAllocation.deleteDisplayLists(firstListId);
firstListId = NO_LIST;
parentListId = NO_LIST;
chunkSpan = 0;
Arrays.fill(isCompiled, false);
GLAllocation.deleteDisplayLists(listId);
listId = -1;
}
}
@@ -2,7 +2,7 @@ package codechicken.nei.moboverlay;
import net.minecraft.client.renderer.Tessellator;
/** {@code MobOverlayFace} adds the vertices of the mark on one block's top face to {@link Tessellator#instance}. */
/** Vertex builder for one block's top face in the mob spawn overlay. */
public final class MobOverlayFace {
public static final byte OUTSIDE_SCAN = -2;
@@ -36,7 +36,7 @@ public final class MobOverlayFace {
public boolean isJoined(int offsetX, int offsetZ) {
final byte neighbourMode = neighbourModes[indexNeighbour(offsetX, offsetZ)];
// `MobOverlayStyle.CONNECTED` doesn't outline the edge of the scan
// no outline along the edge of the scan
return neighbourMode == neighbourModes[indexNeighbour(0, 0)] || neighbourMode == OUTSIDE_SCAN;
}
@@ -67,6 +67,7 @@ public final class MobOverlayFace {
addTexturedVertex(1, 0);
}
/** @param offsetX 0 at the west edge, 1 at the east edge */
public void addVertex(double offsetX, double offsetZ) {
Tessellator.instance.addVertex(x + offsetX, y, z + offsetZ);
}
@@ -1,7 +1,5 @@
package codechicken.nei.moboverlay;
import java.util.Arrays;
import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EnumCreatureType;
@@ -18,8 +16,11 @@ import net.minecraft.world.chunk.Chunk;
import codechicken.lib.math.MathHelper;
/**
* Spawn modes of the blocks in a box around the player. {@link #update} scans the blocks that enter the box, the
* columns of block and light changes, and a slice of the box on each tick.
* Spawn modes, and the tops of flat blocks such as carpets, in a box around the player. The spawn modes are from
* {@link Column#getSpawnMode}: 0 for no spawns, 1 for night only and 2 for any time. The box moves with the player once
* the player is a few blocks from the box's centre, and {@link #update} scans only the blocks that enter the box.
* {@link #update} rescans the column of a block or light change on the next tick. On each tick, {@link #update} also
* rescans a slice of the columns, for changes with no block update, such as a boat that moves into the box.
*/
public final class MobOverlayScan {
@@ -30,7 +31,6 @@ public final class MobOverlayScan {
public static final int MIN_VERTICAL_RADIUS = 4;
public static final int MAX_VERTICAL_RADIUS = 64;
public static final int DEFAULT_VERTICAL_RADIUS = 16;
public static final int CHUNK_SHIFT = 4;
private static final int RECENTRE_DISTANCE = 4;
private static final int VERTICAL_RECENTRE_DISTANCE = 2;
private static final int RESCAN_TICKS = 40;
@@ -47,21 +47,18 @@ public final class MobOverlayScan {
// a ring buffer over the box, indexed by `findCell()`. A cell has the spawn mode in the bits of `SPAWN_MODE_MASK`,
// and `Column.readCoverTop()` shifted left by `COVER_TOP_SHIFT`
private byte[] modes = new byte[0];
// indexed by `findColumn(x, z)`
private boolean[] dirty = new boolean[0];
private boolean hasDirtyColumns;
private int minX;
private int minY;
private int minZ;
// the slice rescan of `update()` continues from this column, numbered `(x - minX) * span + (z - minZ)`
private int nextRescanColumn;
private int modesVersion;
private int chunkSpan;
// The version of a chunk column changes when a cell in or beside the chunk column changes, and when an edge of the
// box moves into, out of, within or across the chunk column. A full scan and a vertical move change the version of
// every chunk column
private int[] chunkVersions = new int[0];
private int chunkVersionCount;
private boolean hasModes;
private long scannedTick;
// world of `modes`, with `changeListener` added
private World scannedWorld;
public void clear() {
@@ -74,17 +71,17 @@ public final class MobOverlayScan {
height = 0;
modes = new byte[0];
dirty = new boolean[0];
chunkSpan = 0;
chunkVersions = new int[0];
hasModes = false;
scannedWorld = null;
// a world isn't garbage-collected while `column.chunk` references a chunk of the world
// `Chunk.worldObj` references the world
column.chunk = null;
}
/**
* Scan every column in this call after {@link #clear}, a change of either radius, a world change, or a move of
* {@link #getSpan} blocks or more across or {@link #getHeight} blocks or more up or down.
* {@link #getSpan} blocks or more across or {@link #getHeight} blocks or more up or down. {@code newRadius} is
* clamped between {@link #MIN_RADIUS} and {@link #MAX_RADIUS}, and {@code newVerticalRadius} between
* {@link #MIN_VERTICAL_RADIUS} and {@link #MAX_VERTICAL_RADIUS}.
*/
public void update(Entity entity, int newRadius, int newVerticalRadius) {
final World world = entity.worldObj;
@@ -115,14 +112,11 @@ public final class MobOverlayScan {
if (isChanged) modesVersion++;
}
/** The version changes when a spawn mode or the top of a flat block changes, or the box moves. */
public int getModesVersion() {
return modesVersion;
}
public int getChunkSpan() {
return chunkSpan;
}
public int getSpan() {
return span;
}
@@ -143,44 +137,19 @@ public final class MobOverlayScan {
return minZ;
}
public int getMinChunkX() {
return minX >> CHUNK_SHIFT;
}
public int getMaxChunkX() {
return (minX + span - 1) >> CHUNK_SHIFT;
}
public int getMinChunkZ() {
return minZ >> CHUNK_SHIFT;
}
public int getMaxChunkZ() {
return (minZ + span - 1) >> CHUNK_SHIFT;
}
public int readChunkVersion(int chunkX, int chunkZ) {
return chunkVersions[findChunk(chunkX, chunkZ)];
}
/** {@code i} and {@code j} are from 0 to {@link #getSpan}, and {@code k} is from 0 to {@link #getHeight}. */
public byte readSpawnMode(int i, int k, int j) {
return extractSpawnMode(modes[findCell(minX + i, minY + k, minZ + j)]);
return (byte) (modes[findCell(minX + i, minY + k, minZ + j)] & SPAWN_MODE_MASK);
}
public void readColumn(int i, int j, byte[] columnCells) {
final int columnStart = findColumn(minX + i, minZ + j) * height;
final int bottomCell = Math.floorMod(minY, height);
System.arraycopy(modes, columnStart + bottomCell, columnCells, 0, height - bottomCell);
System.arraycopy(modes, columnStart, columnCells, height - bottomCell, bottomCell);
}
public static byte extractSpawnMode(byte cell) {
return (byte) (cell & SPAWN_MODE_MASK);
}
public static double computeOverlayYOffset(byte cell) {
/**
* Height of the overlay above the bottom of the block, so that a flat block such as a carpet does not cover the
* overlay. The indices are those of {@link #readSpawnMode}.
*/
public double readOverlayYOffset(int i, int k, int j) {
final double OVERLAY_GAP = 0.02;
return (double) (cell >> COVER_TOP_SHIFT) / COVER_TOP_STEPS + OVERLAY_GAP;
final int coverTopSteps = modes[findCell(minX + i, minY + k, minZ + j)] >> COVER_TOP_SHIFT;
return (double) coverTopSteps / COVER_TOP_STEPS + OVERLAY_GAP;
}
private void resize(int newRadius, int newVerticalRadius) {
@@ -190,8 +159,6 @@ public final class MobOverlayScan {
height = 2 * newVerticalRadius + 1;
modes = new byte[span * span * height];
dirty = new boolean[span * span];
chunkSpan = ((span - 1) >> CHUNK_SHIFT) + 2;
chunkVersions = new int[chunkSpan * chunkSpan];
hasModes = false;
nextRescanColumn = 0;
}
@@ -205,7 +172,6 @@ public final class MobOverlayScan {
scanColumn(x, z);
}
}
markAllChunks();
hasModes = true;
modesVersion++;
scannedTick = scannedWorld.getTotalWorldTime();
@@ -223,7 +189,6 @@ public final class MobOverlayScan {
final int offsetX = centreX - radius - minX;
if (Math.abs(offsetX) > RECENTRE_DISTANCE) {
final int enteringX = offsetX > 0 ? minX + span : minX + offsetX;
markMovedEdgeChunks(minX, offsetX, Axis.X);
minX += offsetX;
for (int x = enteringX; x < enteringX + Math.abs(offsetX); x++) {
for (int z = minZ; z < minZ + span; z++) {
@@ -236,7 +201,6 @@ public final class MobOverlayScan {
final int offsetZ = centreZ - radius - minZ;
if (Math.abs(offsetZ) > RECENTRE_DISTANCE) {
final int enteringZ = offsetZ > 0 ? minZ + span : minZ + offsetZ;
markMovedEdgeChunks(minZ, offsetZ, Axis.Z);
minZ += offsetZ;
for (int x = minX; x < minX + span; x++) {
for (int z = enteringZ; z < enteringZ + Math.abs(offsetZ); z++) {
@@ -256,7 +220,6 @@ public final class MobOverlayScan {
column.scan(enteringY, enteringY + Math.abs(offsetY));
}
}
markAllChunks();
isMoved = true;
}
return isMoved;
@@ -267,7 +230,7 @@ public final class MobOverlayScan {
boolean isChanged = false;
for (int x = minX; x < minX + span; x++) {
for (int z = minZ; z < minZ + span; z++) {
if (dirty[findColumn(x, z)]) isChanged |= rescanColumn(x, z);
if (dirty[findColumn(x, z)]) isChanged |= scanColumn(x, z);
}
}
return isChanged;
@@ -280,7 +243,7 @@ public final class MobOverlayScan {
for (; nextRescanColumn < sliceEnd; nextRescanColumn++) {
final int x = minX + nextRescanColumn / span;
final int z = minZ + nextRescanColumn % span;
isChanged |= rescanColumn(x, z);
isChanged |= scanColumn(x, z);
}
if (nextRescanColumn >= columnCount) nextRescanColumn = 0;
return isChanged;
@@ -293,60 +256,6 @@ public final class MobOverlayScan {
return column.scan(minY, minY + height);
}
private boolean rescanColumn(int x, int z) {
final boolean isChanged = scanColumn(x, z);
// the connected outline of a cell depends on the spawn modes of the cells beside the cell
if (isChanged) {
for (int offsetX = -1; offsetX <= 1; offsetX++) {
for (int offsetZ = -1; offsetZ <= 1; offsetZ++) {
markChunk((x + offsetX) >> CHUNK_SHIFT, (z + offsetZ) >> CHUNK_SHIFT);
}
}
}
return isChanged;
}
private void markMovedEdgeChunks(int oldMin, int offset, Axis moveAxis) {
final int lowFrom = Math.min(oldMin, oldMin + offset);
final int lowTo = Math.max(oldMin, oldMin + offset);
markStripChunks(lowFrom, lowTo, moveAxis);
markStripChunks(lowFrom + span - 1, lowTo + span - 1, moveAxis);
}
private void markStripChunks(int from, int to, Axis moveAxis) {
final int acrossMin = switch (moveAxis) {
case X -> minZ;
case Z -> minX;
};
final int minAcrossChunk = acrossMin >> CHUNK_SHIFT;
final int maxAcrossChunk = (acrossMin + span - 1) >> CHUNK_SHIFT;
for (int alongChunk = from >> CHUNK_SHIFT; alongChunk <= to >> CHUNK_SHIFT; alongChunk++) {
for (int acrossChunk = minAcrossChunk; acrossChunk <= maxAcrossChunk; acrossChunk++) {
final int chunkX = switch (moveAxis) {
case X -> alongChunk;
case Z -> acrossChunk;
};
final int chunkZ = switch (moveAxis) {
case X -> acrossChunk;
case Z -> alongChunk;
};
markChunk(chunkX, chunkZ);
}
}
}
private void markAllChunks() {
Arrays.fill(chunkVersions, ++chunkVersionCount);
}
private void markChunk(int chunkX, int chunkZ) {
chunkVersions[findChunk(chunkX, chunkZ)] = ++chunkVersionCount;
}
public int findChunk(int chunkX, int chunkZ) {
return Math.floorMod(chunkX, chunkSpan) * chunkSpan + Math.floorMod(chunkZ, chunkSpan);
}
private int findColumn(int x, int z) {
return Math.floorMod(x, span) * span + Math.floorMod(z, span);
}
@@ -355,6 +264,10 @@ public final class MobOverlayScan {
return findColumn(x, z) * height + Math.floorMod(y, height);
}
/**
* {@link #moveTo} reads a column's chunk, biome and highest non-air block in the box, and {@link #scan} reads the
* column's blocks.
*/
private final class Column {
private final Entity dummyEntity = new EntityPig(null);
@@ -372,8 +285,10 @@ public final class MobOverlayScan {
canBiomeSpawn = !biome.getSpawnableList(EnumCreatureType.monster).isEmpty()
&& biome.getSpawningChance() > 0;
chunk = scannedWorld.getChunkFromBlockCoords(x, z);
// `getHeightValue()` skips blocks with a light opacity of 0. A mob can spawn on some of these blocks, such
// as Tinkers' Construct slime grass, a hopper or a full snow block. Search for the highest non-air block
// `getHeightValue()` is the height above the highest block with a light opacity above 0. A block with a
// light opacity of 0 can be higher: Tinkers' Construct slime grass, a hopper or a snow layer. A mob can
// spawn on top of slime grass, a hopper or a full snow block. Search the blocks for the highest non-air
// block
final int SECTION_HEIGHT = 16;
int y = Math.min(minY + height - 1, chunk.getTopFilledSegment() + SECTION_HEIGHT - 1);
while (y >= minY && chunk.getBlock(x & 15, y, z & 15).isAir(chunk.worldObj, x, y, z)) y--;
@@ -393,15 +308,12 @@ public final class MobOverlayScan {
return isChanged;
}
/** The spawn mode of the block at height {@code y} in this column. */
private byte getSpawnMode(int y) {
if (y >= chunk.worldObj.getHeight()) {
return 0;
}
// vanilla `SpawnerAnimals.canCreatureTypeSpawnAtLocation()` rejects a normal cube in the cell (such as the
// inside of a stone block). Test the block before the light read
if (chunk.getBlock(x & 15, y, z & 15).isNormalCube()) return 0;
if (chunk.getSavedLightValue(EnumSkyBlock.Block, x & 15, y, z & 15) >= 8 || !SpawnerAnimals
.canCreatureTypeSpawnAtLocation(EnumCreatureType.monster, chunk.worldObj, x, y, z)) {
return 0;
@@ -425,6 +337,10 @@ public final class MobOverlayScan {
return (byte) (chunk.getSavedLightValue(EnumSkyBlock.Sky, x & 15, y, z & 15) >= 8 ? 1 : 2);
}
/**
* The top of the block at height {@code y}, in fractions of a block with {@link MobOverlayScan#COVER_TOP_STEPS}
* as the denominator, or 0 for a tall block.
*/
private int readCoverTop(int y) {
final double MAX_COVER_TOP = 0.25;
final Block block = chunk.getBlock(x & 15, y, z & 15);
@@ -436,6 +352,7 @@ public final class MobOverlayScan {
}
}
/** Marks the columns of the block and light changes in {@link #scannedWorld}. */
private final class ChangeListener implements IWorldAccess {
@Override
@@ -500,9 +417,4 @@ public final class MobOverlayScan {
hasDirtyColumns = true;
}
}
private enum Axis {
X,
Z
}
}
@@ -27,7 +27,9 @@ public enum MobOverlayStyle {
}
},
/** A light tint and a stronger connected-texture outline around each area of one spawn mode. */
/**
* A light tint, with a stronger outline around each area of one spawn mode, like a connected texture.
*/
CONNECTED(GL11.GL_QUADS) {
@Override
@@ -37,8 +39,7 @@ public enum MobOverlayStyle {
face.applyColor(Colouring.OVERLAY, MARK_ALPHA);
for (int offsetX = -1; offsetX <= 1; offsetX++) {
for (int offsetZ = -1; offsetZ <= 1; offsetZ++) {
// a corner cell is drawn when either edge next to the corner is outlined or when the corner is an
// inside corner
// a corner cell is drawn when either edge next to the corner is outlined, and on an inside corner
final boolean isOutline = !(face.isJoined(offsetX, offsetZ) && face.isJoined(offsetX, 0)
&& face.isJoined(0, offsetZ));
if (isOutline) face.addCell(offsetX, offsetZ, OUTLINE_WIDTH);
@@ -47,7 +48,7 @@ public enum MobOverlayStyle {
}
},
/** A small square in the middle of an untinted block. */
/** A small square in the middle of the block, with no tint. */
SQUARE(GL11.GL_QUADS) {
@Override
@@ -61,7 +62,7 @@ public enum MobOverlayStyle {
}
},
/** A pufferfish sticker on the block. */
/** The pufferfish sticker. */
PUFFERFISH("pufferfish", Colouring.STICKER) {
@Override
@@ -101,6 +102,7 @@ public enum MobOverlayStyle {
return DEFAULT;
}
/** @return the {@link #formatName} of every style, separated by commas */
public static String formatAllNames() {
final StringJoiner names = new StringJoiner(", ");
for (MobOverlayStyle style : values()) {
@@ -117,7 +119,7 @@ public enum MobOverlayStyle {
return switch (this) {
case CONNECTED -> TINT_ALPHA;
case SQUARE -> MARK_ALPHA;
// the lines of X are opaque, and the alpha of PUFFERFISH comes from the PNG
// opaque lines for X, and the alpha of the PNG for PUFFERFISH
case X, PUFFERFISH -> 1.0F;
};
}
@@ -125,9 +127,9 @@ public enum MobOverlayStyle {
public abstract void addVertices(MobOverlayFace face);
public enum Colouring {
/** Yellow marks where mobs spawn only at night and red marks where mobs spawn at any time. */
/** Yellow where mobs spawn only at night, red where mobs spawn at any time. */
OVERLAY,
/** Texture colours with a red tint where mobs spawn at any time. */
/** The texture's colours, tinted red where mobs spawn at any time. */
STICKER
}
}
@@ -1,45 +0,0 @@
# Mob overlay TODO: spawn rules from other mods
`MobOverlayScan` reads the block, the light and the biome of each cell. Some mods set the result of Forge's
`LivingSpawnEvent.CheckSpawn` from the monster's position, and `MobOverlayScan` doesn't call these handlers.
A monster spawns when the result is `ALLOW`, or when the result is `DEFAULT` and `getCanSpawnHere()` returns
true. So `ALLOW` skips the light test.
## DENY: marked cells where a monster can't spawn
GregTech and Extra Utilities measure a range from the centre of the block.
| mod in 2.9.0 | handler | range | on the client? |
|---|---|---|---|
| GregTech Monster Repellator | `GTSpawnEventHandler.denyMobSpawn()` | sphere. The radius is 4 + 12 × tier without power and 16 + 48 × tier with power | no. `MTEMonsterRepellent.onPostTick()` registers the range on the server only |
| Extra Utilities magnum torch | `EventHandlerServer.magnumTorchDenySpawn()` | ellipsoid 128 blocks out and 32 blocks up and down | maybe. `TileEntityAntiMobTorch` adds itself to the static `magnumTorchRegistry` and doesn't check the side. The bytecode is the source of this row, and the row isn't tested in game |
| Extra Utilities chandelier | the same handler | sphere, radius 16 | maybe. The chandelier's tile entity is a `TileEntityAntiMobTorch` too |
| Gadomancy aura pylon with Lux | `EventHandlerEntityServer.on(CheckSpawn)` | sphere, radius `AuraEffects.LUX.getRange()` | not checked. `AuraEffects.LUX` adds the pylon to `registeredLuxPylons` when the pylon's effect runs on an entity |
| Blood Magic Ward of Sacrosanctity (`AW028SpawnWard`) | `AlchemicalWizardryEventHooks.onLivingSpawnEvent()` | box from the ritual's horizontal and vertical radii | not checked. `RitualEffectSpawnWard` fills `respawnMap` |
| Botania Emptiness potion | `PotionEmptiness.onSpawn()` | sphere around each player with the effect | the player's potion effects |
| ServerUtilities | `ServerUtilitiesWorldEventHandler.onMobSpawned()` | chunks of the safe spawn area, and claimed chunks by the team's settings | no. The claims are server data |
| Et Futurum Requiem | `ServerEventHandler.spawnEvent()` | in the Nether, a cell above `ModBlocks.NETHER_WART` at meta 0, for a mob that doesn't fly | yes. The block below is in the client world |
## ALLOW: monsters spawn in unmarked lit cells
| mod in 2.9.0 | handler | range |
|---|---|---|
| Blood Magic Veil of Evil (`AW029VeilOfEvil`) | `AlchemicalWizardryEventHooks.onLivingSpawnEvent()` | box from the ritual's radii. Creepers are excluded |
| Botania Bloodthirst potion | `PotionBloodthirst.onSpawn()` | sphere around each player with the effect |
Thaumcraft 4.2.3.5 doesn't have a `CheckSpawn` handler. The list comes from a scan of the 2.9.0 pack's jars for
`LivingSpawnEvent$CheckSpawn`. Handlers that test only the mob type, the dimension or the mob count are left out:
AMDIForge, EnderZoo, Automagy, the Extra Utilities Underdark, and the slime handlers of Biomes O' Plenty and Botania.
The Extra Utilities siege handler (`EventHandlerSiege.SiegeCheckSpawn()`) isn't checked.
## To do
- [ ] Add an NEI API: a mod registers a cell test that returns `DENY`, `ALLOW` or `DEFAULT`. `MobOverlayScan` calls
each test for each cell in the box.
- [ ] Add an API call to mark an area dirty. `MobOverlayScan` then rescans the area when a range is added or
removed.
- [ ] Ask GregTech, Gadomancy, Blood Magic and ServerUtilities to send their ranges to the client.
- [ ] Test the Extra Utilities registry on a client with a dedicated server.
- [ ] Find out how the handlers combine. `GTSpawnEventHandler` returns early on `DENY`, and Blood Magic's handler
changes `ALLOW` to `DEFAULT`, so the result depends on the order of the handlers on the event bus.
@@ -32,7 +32,7 @@ public class AutoCraftingManager {
public void execute() {
final GuiContainer guiContainer = NEIClientUtils.getGuiContainer();
final ItemStack[] layout = snapshotLayout(guiContainer);
final List<BookmarkItem> initialItems = prepareInitialItems(math, getInventoryItems(guiContainer));
final List<BookmarkItem> initialItems = prepareInitialItems(math, ItemStackAmount.of(guiContainer));
boolean processed = false;
boolean changed = false;
@@ -43,7 +43,7 @@ public class AutoCraftingManager {
changed = false;
RecipeChainIterator iterator = new RecipeChainIterator(math, initialItems);
iterator.updateInventory(getInventoryItems(guiContainer));
iterator.updateInventory(ItemStackAmount.of(guiContainer));
while (iterator.hasNext() && !interrupted(guiContainer)) {
final Map<RecipeId, Long> recipes = iterator.next();
@@ -69,7 +69,7 @@ public class AutoCraftingManager {
if (craft) {
changed = true;
processed = true;
iterator.updateInventory(getInventoryItems(guiContainer));
iterator.updateInventory(ItemStackAmount.of(guiContainer));
}
}
@@ -138,18 +138,6 @@ public class AutoCraftingManager {
return AutoCraftingManager.math != null && !task.interrupted();
}
public static ItemStackAmount getInventoryItems(GuiContainer guiContainer) {
final ItemStackAmount inventory = new ItemStackAmount();
for (Slot slot : guiContainer.inventorySlots.inventorySlots) {
if (slot.getHasStack() && !(slot instanceof SlotCrafting) && slot.canTakeStack(guiContainer.mc.thePlayer)) {
inventory.add(slot.getStack());
}
}
return inventory;
}
private static ItemStack[] snapshotLayout(GuiContainer guiContainer) {
final List<Slot> slots = guiContainer.inventorySlots.inventorySlots;
final ItemStack[] layout = new ItemStack[slots.size()];
@@ -11,8 +11,6 @@ import java.util.Set;
import net.minecraft.client.Minecraft;
import net.minecraft.item.ItemStack;
import org.lwjgl.opengl.GL11;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.BookmarkPanel.BookmarkViewMode;
import codechicken.nei.FavoriteRecipes;
@@ -24,28 +22,18 @@ import codechicken.nei.LayoutManager;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.bookmark.tree.GuiCraftingTree;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.recipe.Recipe.RecipeIngredient;
import codechicken.nei.theme.UIRecipeTexture;
import codechicken.nei.util.NEIMouseUtils;
public class GuiFavoriteButton extends GuiRecipeButton {
private static final int BUTTON_ID_START = 14;
protected static final DrawableResource ICON_STATE_OFF = new DrawableBuilder(
"nei:textures/nei_sprites.png",
10,
76,
9,
10).build();
protected static final DrawableResource ICON_STATE_ON = new DrawableBuilder(
"nei:textures/nei_sprites.png",
19,
76,
9,
10).build();
protected static final DrawableResource ICON_STATE_OFF = UIRecipeTexture.ICON_FAVORITE_OFF;
protected static final DrawableResource ICON_STATE_ON = UIRecipeTexture.ICON_FAVORITE_ON;
protected final Recipe recipe;
protected boolean favorite = false;
@@ -94,17 +82,13 @@ public class GuiFavoriteButton extends GuiRecipeButton {
}
@Override
protected void drawContent(Minecraft minecraft, int y, int x, boolean mouseOver) {
final DrawableResource icon = isFavorite() ? ICON_STATE_ON : ICON_STATE_OFF;
final int iconX = this.xPosition + (this.width - icon.width - 1) / 2;
final int iconY = this.yPosition + (this.height - icon.height) / 2;
protected DrawableResource getIcon() {
return isFavorite() ? ICON_STATE_ON : ICON_STATE_OFF;
}
GL11.glColor4f(1, 1, 1, this.enabled ? 1 : 0.5f);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
icon.draw(iconX, iconY);
GL11.glDisable(GL11.GL_BLEND);
GL11.glColor4f(1, 1, 1, 1);
@Override
protected void drawContent(Minecraft minecraft, int mouseX, int mouseY, boolean mouseOver) {
super.drawContent(minecraft, mouseX, mouseY, mouseOver);
if (!mouseOver) {
this.selectedResult = null;
@@ -5,13 +5,10 @@ import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import org.lwjgl.opengl.GL11;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.ItemPanels;
import codechicken.nei.ItemsTooltipLineHandler;
@@ -23,20 +20,14 @@ import codechicken.nei.PositionedStack;
import codechicken.nei.api.IOverlayHandler;
import codechicken.nei.bookmark.BookmarkGrid;
import codechicken.nei.bookmark.BookmarkPayload;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.theme.UIRecipeTexture;
import codechicken.nei.util.NEIMouseUtils;
public class GuiOverlayButton extends GuiRecipeButton {
protected static DrawableResource notPresent = new DrawableBuilder(
"nei:textures/nei_tabbed_sprites.png",
0,
40,
8,
8).build();
protected static DrawableResource present = new DrawableBuilder("nei:textures/nei_tabbed_sprites.png", 8, 40, 8, 8)
.build();
protected static DrawableResource notPresent = UIRecipeTexture.ITEM_MISSING;
protected static DrawableResource present = UIRecipeTexture.ITEM_PRESENT;
public enum ItemOverlayFormat {
@@ -87,24 +78,9 @@ public class GuiOverlayButton extends GuiRecipeButton {
}
}
protected static final DrawableResource ICON_FILL = new DrawableBuilder(
"nei:textures/nei_sprites.png",
28,
76,
9,
10).build();
protected static final DrawableResource ICON_FILL_ERROR = new DrawableBuilder(
"nei:textures/nei_sprites.png",
37,
76,
9,
10).build();
protected static final DrawableResource ICON_OVERLAY = new DrawableBuilder(
"nei:textures/nei_sprites.png",
46,
76,
9,
10).build();
protected static final DrawableResource ICON_FILL = UIRecipeTexture.ICON_OVERLAY_FILL;
protected static final DrawableResource ICON_FILL_ERROR = UIRecipeTexture.ICON_OVERLAY_FILL_ERROR;
protected static final DrawableResource ICON_OVERLAY = UIRecipeTexture.ICON_OVERLAY;
protected static final int BUTTON_ID_SHIFT = 4;
public final GuiContainer firstGui;
@@ -217,22 +193,12 @@ public class GuiOverlayButton extends GuiRecipeButton {
}
@Override
protected void drawContent(Minecraft minecraft, int y, int x, boolean mouseOver) {
DrawableResource icon = ICON_OVERLAY;
protected DrawableResource getIcon() {
if (this.canFillCraftingGrid && (!requireShiftForOverlayRecipe() || NEIClientUtils.shiftKey())) {
icon = this.missedMaterialsTooltipLineHandler == null ? ICON_FILL : ICON_FILL_ERROR;
return this.missedMaterialsTooltipLineHandler == null ? ICON_FILL : ICON_FILL_ERROR;
}
final int iconX = this.xPosition + (this.width - icon.width - 1) / 2;
final int iconY = this.yPosition + (this.height - icon.height) / 2;
GL11.glColor4f(1, 1, 1, this.enabled ? 1 : 0.5f);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
icon.draw(iconX, iconY);
GL11.glDisable(GL11.GL_BLEND);
GL11.glColor4f(1, 1, 1, 1);
return ICON_OVERLAY;
}
@Override
File diff suppressed because it is too large. Load diff
@@ -13,11 +13,10 @@ import codechicken.nei.NEIServerUtils;
import codechicken.nei.PositionedStack;
import codechicken.nei.Widget;
import codechicken.nei.api.ShortcutInputHandler;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.scroll.ScrollBar;
import codechicken.nei.scroll.ScrollContainer;
import codechicken.nei.theme.UIRecipeTexture;
import codechicken.nei.theme.UIWidgetTexture;
public class GuiRecipeCatalyst extends ScrollContainer {
@@ -51,26 +50,11 @@ public class GuiRecipeCatalyst extends ScrollContainer {
private static final int SLOT_SIZE = 16;
private static final int BORDER_PADDING = 6;
private static final int TRANSPARENCY_BORDER = 4;
private static final DrawableResource BG_TEXTURE = new DrawableBuilder(
"nei:textures/catalyst_tab.png",
0,
0,
28 + TRANSPARENCY_BORDER * 2,
28 + TRANSPARENCY_BORDER * 2)
.setTextureSize(28 + TRANSPARENCY_BORDER * 2, 28 + TRANSPARENCY_BORDER * 2)
.setSlices(
BORDER_PADDING + TRANSPARENCY_BORDER,
BORDER_PADDING + TRANSPARENCY_BORDER,
BORDER_PADDING + TRANSPARENCY_BORDER,
BORDER_PADDING + TRANSPARENCY_BORDER)
.build();
private static final DrawableResource FG_TEXTURE = new DrawableBuilder("nei:textures/slot.png", 0, 0, 18, 18)
.setTextureSize(18, 18).setSlices(1, 1, 1, 1).build();
private static final int COLUMNS_BOTTOM_INSET = 5;
private static final ScrollBar VERTICAL_SCROLLBAR = UIWidgetTexture.verticalScrollBar()
.setOverflowType(ScrollBar.OverflowType.AUTO).setTrackPadding(0, BORDER_PADDING, -13, BORDER_PADDING)
.setOverflowType(ScrollBar.OverflowType.AUTO)
.setTrackPadding(0, BORDER_PADDING - 1, -13, BORDER_PADDING - 1)
.setScrollPlace(ScrollBar.ScrollPlace.START);
private List<PositionedStack> items = Collections.emptyList();
@@ -79,7 +63,7 @@ public class GuiRecipeCatalyst extends ScrollContainer {
private int style = -1;
public GuiRecipeCatalyst() {
setPaddingBlock(BORDER_PADDING + 1, BORDER_PADDING + 1);
setPaddingBlock(BORDER_PADDING, BORDER_PADDING);
}
public void setCatalysts(List<PositionedStack> items) {
@@ -98,13 +82,15 @@ public class GuiRecipeCatalyst extends ScrollContainer {
return this.availableHeight;
}
public boolean isShowWidget() {
return this.showWidget;
@Override
public boolean isVisible() {
return this.showWidget && NEIClientConfig.getJEIStyleRecipeCatalysts() != 0;
}
public int getColumnCount() {
if (NEIClientConfig.getJEIStyleRecipeCatalysts() == 1) {
final int maxItemsPerColumn = Math.max(0, this.availableHeight - 2 - BORDER_PADDING * 2) / SLOT_SIZE;
final int maxItemsPerColumn = Math
.max(0, this.availableHeight - COLUMNS_BOTTOM_INSET - 2 - BORDER_PADDING * 2) / SLOT_SIZE;
return maxItemsPerColumn > 0 ? NEIServerUtils.divideCeil(this.items.size(), maxItemsPerColumn) : 0;
}
return 1;
@@ -120,7 +106,7 @@ public class GuiRecipeCatalyst extends ScrollContainer {
final int rows = getRowCount();
setVerticalScroll(null);
setPaddingInline(BORDER_PADDING + 1, BORDER_PADDING - 3);
setPaddingInline(BORDER_PADDING, BORDER_PADDING - 3);
this.style = NEIClientConfig.getJEIStyleRecipeCatalysts();
this.h = rows * SLOT_SIZE + this.paddingBlockStart + this.paddingBlockEnd;
@@ -132,7 +118,7 @@ public class GuiRecipeCatalyst extends ScrollContainer {
this.w += VERTICAL_SCROLLBAR.getTrackWidth();
setVerticalScroll(VERTICAL_SCROLLBAR);
setPaddingInline(BORDER_PADDING + 1 + VERTICAL_SCROLLBAR.getTrackWidth(), this.paddingInlineEnd);
setPaddingInline(this.paddingInlineStart + VERTICAL_SCROLLBAR.getTrackWidth(), this.paddingInlineEnd);
}
this.showWidget = rows * columns > 0;
@@ -162,12 +148,14 @@ public class GuiRecipeCatalyst extends ScrollContainer {
if (!this.showWidget) return;
GL11.glColor4f(1, 1, 1, 1);
BG_TEXTURE.draw(
this.x - TRANSPARENCY_BORDER,
this.y - TRANSPARENCY_BORDER,
this.w + TRANSPARENCY_BORDER * 2,
this.h + TRANSPARENCY_BORDER * 2);
FG_TEXTURE.draw(
if (this.h < this.availableHeight) {
UIRecipeTexture.CATALYST_TAB_JOINED.draw(this.x, this.y, this.w, this.h);
} else {
UIRecipeTexture.CATALYST_TAB.draw(this.x, this.y, this.w, this.h);
}
UIRecipeTexture.CATALYST_SLOT.draw(
this.x + this.paddingInlineStart - 1,
this.y + this.paddingBlockStart - 1,
this.w - this.paddingInlineStart - this.paddingInlineEnd + 2,
@@ -10,7 +10,6 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import net.minecraftforge.common.MinecraftForge;
@@ -26,11 +25,11 @@ import codechicken.nei.ColorUtils;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.Widget;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.event.NEIRegisterHandlerInfosEvent;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.recipe.debug.DebugHandlerWidget;
import codechicken.nei.theme.UIRecipeTexture;
import cpw.mods.fml.common.Loader;
public abstract class GuiRecipeTab extends Widget {
@@ -44,29 +43,14 @@ public abstract class GuiRecipeTab extends Widget {
protected final String handlerName;
protected final String handlerID;
public static final int TAB_WIDTH = 24;
public static final int TAB_HEIGHT = 24;
private static final DrawableResource selectedTabImage = new DrawableBuilder(
"nei:textures/nei_tabbed_sprites.png",
0,
16,
24,
24).build();
private static final DrawableResource unselectedTabImage = new DrawableBuilder(
"nei:textures/nei_tabbed_sprites.png",
24,
16,
24,
24).build();
private boolean selected;
public GuiRecipeTab(IRecipeHandler handler, int x, int y) {
super();
this.x = x;
this.y = y;
this.w = TAB_WIDTH;
this.h = TAB_HEIGHT;
this.w = UIRecipeTexture.TAB_UNSELECTED.getWidth();
this.h = UIRecipeTexture.TAB_UNSELECTED.getHeight();
this.handler = handler;
this.handlerName = handler.getHandlerId();
this.selected = false;
@@ -84,21 +68,20 @@ public abstract class GuiRecipeTab extends Widget {
drawForeground(mouseX, mouseY);
}
public void drawBackground(int mouseX, int mouseY) {
private void drawBackground(int mouseX, int mouseY) {
final DrawableResource image = this.selected ? UIRecipeTexture.TAB_SELECTED : UIRecipeTexture.TAB_UNSELECTED;
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glColor4f(1, 1, 1, 1);
final DrawableResource image = this.selected ? selectedTabImage : unselectedTabImage;
image.draw(this.x, this.y);
image.draw(this.x, this.y, this.w, this.h);
}
public void drawForeground(int mouseX, int mouseY) {
final int iconX = this.x + 4;
final int iconY = this.y + 4;
final FontRenderer fontRenderer = GuiDraw.fontRenderer;
private void drawForeground(int mouseX, int mouseY) {
final HandlerInfo handlerInfo = getHandlerInfo(this.handlerName, this.handlerID);
final DrawableResource icon = handlerInfo != null ? handlerInfo.getImage() : null;
final ItemStack itemStack = handlerInfo != null ? handlerInfo.getItemStack() : null;
final int iconX = this.x + (this.w - 16) / 2;
final int iconY = this.y + this.h - 16 - 6;
if (icon != null) {
icon.draw(iconX + 1, iconY + 1);
@@ -111,24 +94,17 @@ public abstract class GuiRecipeTab extends Widget {
if (!isEnabled) GL11.glDisable(GL12.GL_RESCALE_NORMAL);
} else {
// Text fallback
final int color = this.selected ? ColorUtils.buttonLabelHover.getColor()
: ColorUtils.buttonLabelNormal.getColor();
String text = this.handler.getRecipeName();
if (text != null && text.length() > 0) {
if (text.length() > 2) {
text = text.substring(0, 2);
}
} else {
if (text == null || text.length() == 0) {
text = "??";
} else if (text.length() > 2) {
text = text.substring(0, 2);
}
int textCenterX = this.x + (int) (this.w / 2f);
int textCenterY = this.y + (int) (this.h / 2f) - 3;
int color = this.selected ? ColorUtils.buttonLabelHover.getColor()
: ColorUtils.buttonLabelNormal.getColor();
fontRenderer.drawStringWithShadow(
text,
textCenterX - (int) (fontRenderer.getStringWidth(text) / 2f),
textCenterY,
color);
GuiDraw.drawStringC(text, iconX + 8, iconY + 4, color);
GL11.glColor4f(1, 1, 1, 1);
}
}
@@ -2,19 +2,23 @@ package codechicken.nei.recipe;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.BooleanSupplier;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.Button;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.theme.UIRecipeTexture;
import codechicken.nei.theme.UIWidgetTexture;
public class GuiRecipeTabs {
private final List<GuiRecipeTab> tabs = new ArrayList<>();
private final List<Button> buttons = new ArrayList<>();
private final Rectangle area = new Rectangle();
private List<? extends IRecipeHandler> currenthandlers;
private List<? extends IRecipeHandler> currenthandlers = Collections.emptyList();
private int pageCount = 1;
private int pageNumber = 0;
@@ -22,56 +26,78 @@ public class GuiRecipeTabs {
private int numHandlers = 1;
private int recipetype;
private final Button prevTab = new Button("<") {
private static class TabArrowButton extends Button {
private final DrawableResource icon;
private final BooleanSupplier action;
private TabArrowButton(DrawableResource icon, BooleanSupplier action) {
this.icon = icon;
this.action = action;
this.w = 8;
this.h = 20;
}
@Override
public boolean onButtonPress(boolean rightClick) {
if (!rightClick) {
NEIClientUtils.playClickSound();
return previousPage();
} else return false;
return !rightClick && this.action.getAsBoolean();
}
};
private final Button nextTab = new Button(">") {
@Override
public boolean onButtonPress(boolean rightclick) {
if (!rightclick) {
NEIClientUtils.playClickSound();
return nextPage();
} else return false;
public void draw(int mouseX, int mouseY) {
UIWidgetTexture.BUTTON
.draw(this.x, this.y, this.w, this.h, this.icon, true, false, contains(mouseX, mouseY));
}
}
};
private final Button prevTab = new TabArrowButton(UIRecipeTexture.ICON_PREV, this::previousPage);
private final Button nextTab = new TabArrowButton(UIRecipeTexture.ICON_NEXT, this::nextPage);
public static int getTabWidth() {
return GuiRecipeTab.TAB_WIDTH;
return UIRecipeTexture.TAB_UNSELECTED.getWidth() - 1;
}
public static int getTabHeight() {
return GuiRecipeTab.TAB_HEIGHT;
return UIRecipeTexture.TAB_UNSELECTED.getHeight();
}
public void update(GuiRecipe<?> guiRecipe) {
public void place(int navLeft, int navWidth, int guiTop) {
final int tabWidth = getTabWidth();
final int tabHeight = getTabHeight();
final int perPage = (navWidth - 4) / tabWidth;
this.recipetype = guiRecipe.recipetype;
this.currenthandlers = guiRecipe.currenthandlers;
this.area.width = perPage * tabWidth;
this.area.height = tabHeight;
this.area.x = navLeft + (navWidth - this.area.width) / 2;
this.area.y = guiTop - tabHeight + 4;
this.prevTab.y = this.nextTab.y = guiTop - this.prevTab.h + 1;
this.prevTab.x = this.area.x - this.prevTab.w + 1;
this.nextTab.x = this.area.x + this.area.width - 1;
if (this.categoriesPerPage != perPage) {
this.categoriesPerPage = perPage;
rebuild();
} else {
refreshPage();
}
}
public void update(List<? extends IRecipeHandler> handlers, int recipetype) {
this.currenthandlers = handlers;
this.recipetype = recipetype;
rebuild();
}
private void rebuild() {
this.numHandlers = this.currenthandlers.size();
this.categoriesPerPage = (guiRecipe.xSize - 4) / tabWidth;
this.pageNumber = this.recipetype / Math.max(this.categoriesPerPage, 1);
this.pageCount = (int) Math.ceil((float) this.numHandlers / this.categoriesPerPage);
this.area.width = this.categoriesPerPage * tabWidth;
this.area.height = tabHeight;
this.area.x = guiRecipe.guiLeft + 4;
this.area.y = guiRecipe.guiTop - tabHeight + 3;
refreshPage();
updateArrows(tabHeight);
refreshArrows();
}
public void refreshPage() {
@@ -97,17 +123,10 @@ public class GuiRecipeTabs {
}
}
private void updateArrows(int tabHeight) {
private void refreshArrows() {
this.buttons.clear();
if (this.numHandlers > this.categoriesPerPage) {
this.prevTab.w = this.nextTab.w = 8;
this.prevTab.h = this.nextTab.h = tabHeight - 4;
this.prevTab.y = this.nextTab.y = this.area.y + 2;
this.prevTab.x = this.area.x - this.prevTab.w + 1;
this.nextTab.x = this.area.x + this.area.width - 1;
this.buttons.add(this.prevTab);
this.buttons.add(this.nextTab);
}
@@ -144,14 +163,17 @@ public class GuiRecipeTabs {
public void handleTooltip(int mousex, int mousey, List<String> tooltips) {
if (!NEIClientConfig.areJEIStyleTabsVisible()) return;
for (GuiRecipeTab tab : this.tabs) {
if (tab.contains(mousex, mousey)) {
tab.addTooltips(tooltips);
}
}
for (Button button : this.buttons) {
if (button.contains(mousex, mousey)) {
button.addTooltips(tooltips);
return;
}
}
for (GuiRecipeTab tab : this.tabs) {
if (tab.contains(mousex, mousey)) {
tab.addTooltips(tooltips);
return;
}
}
}
@@ -161,7 +183,7 @@ public class GuiRecipeTabs {
for (Button button : this.buttons) {
if (button.contains(x, y)) {
return button.onButtonPress(mouseButton == 1);
return button.handleClick(x, y, mouseButton);
}
}
@@ -36,6 +36,9 @@ public class HandlerInfo {
private boolean allowOverflowX = true;
private boolean allowOverflowY = false;
private int windowWidth = 0;
private boolean recipeSpacing = false;
private ItemStack itemStack = null;
private DrawableResource image = null;
@@ -189,6 +192,22 @@ public class HandlerInfo {
this.allowOverflowY = allowOverflowY;
}
public int getWindowWidth() {
return this.windowWidth;
}
public void setWindowWidth(int windowWidth) {
this.windowWidth = windowWidth;
}
public boolean isRecipeSpacing() {
return this.recipeSpacing;
}
public void setRecipeSpacing(boolean recipeSpacing) {
this.recipeSpacing = recipeSpacing;
}
public static class Builder {
private final HandlerInfo info;
@@ -296,6 +315,16 @@ public class HandlerInfo {
return this;
}
public Builder setWindowWidth(int windowWidth) {
this.info.windowWidth = windowWidth;
return this;
}
public Builder setRecipeSpacing(boolean recipeSpacing) {
this.info.recipeSpacing = recipeSpacing;
return this;
}
public HandlerInfo build() {
return this.info;
}
@@ -45,6 +45,10 @@ public interface IRecipeHandler {
return getRecipeName();
}
default int getRecipeWidth(int recipe) {
return 0;
}
default int getRecipeHeight(int recipe) {
return 0;
}
@@ -0,0 +1,170 @@
package codechicken.nei.recipe;
import java.util.List;
import java.util.function.BooleanSupplier;
import net.minecraft.client.gui.FontRenderer;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.Button;
import codechicken.nei.ColorUtils;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.Widget;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.theme.UIRecipeTexture;
import codechicken.nei.theme.UIWidgetTexture;
class NavigationBar extends Widget {
protected class NavButton extends Button {
private final DrawableResource icon;
private final Runnable action;
private final BooleanSupplier isEnabled;
protected NavButton(DrawableResource icon, BooleanSupplier isEnabled, Runnable action) {
this.icon = icon;
this.action = action;
this.isEnabled = isEnabled;
this.w = BUTTON_SIZE;
this.h = BUTTON_SIZE;
}
@Override
public void draw(int mx, int my) {
final boolean enabled = this.isEnabled.getAsBoolean();
final boolean active = (this.state & 0x3) == 2;
UIWidgetTexture.BUTTON.draw(this.x, this.y, this.w, this.h, this.icon, enabled, active, contains(mx, my));
}
@Override
public boolean onButtonPress(boolean rightclick) {
if (rightclick) return false;
this.action.run();
return true;
}
}
protected static final int BUTTON_SIZE = 12;
protected static final int GAP = 2;
private final NavButton prev;
private final NavButton next;
protected boolean enabled = true;
protected String label = "";
protected int color = 0xffffff;
protected int hoverColor = 0xffffff;
protected int insetLeft;
protected Runnable labelAction;
public String labelTooltip;
private String croppedLabel;
private int croppedLabelWidth;
private String croppedLabelSource;
private int croppedLabelMaxWidth;
public NavigationBar(Runnable labelAction, Runnable onPrev, Runnable onNext) {
this.prev = new NavButton(UIRecipeTexture.ICON_PREV, () -> NavigationBar.this.enabled, onPrev);
this.next = new NavButton(UIRecipeTexture.ICON_NEXT, () -> NavigationBar.this.enabled, onNext);
this.labelAction = labelAction;
this.h = BUTTON_SIZE;
}
protected int plateX() {
return this.x + BUTTON_SIZE + GAP;
}
protected int plateWidth() {
return this.w - (BUTTON_SIZE + GAP) * 2;
}
public void place(int x, int y, int w) {
this.x = x;
this.y = y;
this.w = w;
this.prev.x = x;
this.prev.y = y;
this.next.x = x + w - BUTTON_SIZE;
this.next.y = y;
}
@Override
public void draw(int mx, int my) {
GuiDraw.drawRect(
plateX() + this.insetLeft,
this.y,
plateWidth() - this.insetLeft,
this.h,
ColorUtils.recipeTitleBG.getColor());
this.prev.draw(mx, my);
this.next.draw(mx, my);
if (!this.label.isEmpty()) {
final FontRenderer font = NEIClientUtils.mc().fontRenderer;
updateCroppedLabel(font);
font.drawStringWithShadow(
this.croppedLabel,
labelX(),
labelY(font),
isLabelHovered(mx, my) ? this.hoverColor : this.color);
}
}
private void updateCroppedLabel(FontRenderer font) {
final int maxWidth = plateWidth() - this.insetLeft;
if (!this.label.equals(this.croppedLabelSource) || maxWidth != this.croppedLabelMaxWidth) {
this.croppedLabel = NEIClientUtils.cropText(font, this.label, maxWidth - 2);
this.croppedLabelSource = this.label;
this.croppedLabelMaxWidth = maxWidth;
this.croppedLabelWidth = font.getStringWidth(this.croppedLabel);
}
}
private int labelX() {
return plateX() + this.insetLeft + (plateWidth() - this.insetLeft) / 2 - this.croppedLabelWidth / 2;
}
private int labelY(FontRenderer font) {
return this.y + (this.h - font.FONT_HEIGHT) / 2 + 1;
}
private boolean isLabelHovered(int mx, int my) {
if (this.labelAction == null || this.label.isEmpty()) return false;
final FontRenderer font = NEIClientUtils.mc().fontRenderer;
updateCroppedLabel(font);
final int textX = labelX();
final int textY = labelY(font);
return mx >= textX && mx < textX + this.croppedLabelWidth && my >= textY && my < textY + font.FONT_HEIGHT;
}
@Override
public List<String> handleTooltip(int mx, int my, List<String> tooltip) {
if (tooltip.isEmpty() && this.labelTooltip != null && isLabelHovered(mx, my)) {
tooltip.add(this.labelTooltip);
}
return tooltip;
}
@Override
public boolean handleClick(int mx, int my, int button) {
if (button == 0 && isLabelHovered(mx, my)) {
this.labelAction.run();
return true;
}
if (!this.enabled) return false;
if (this.prev.contains(mx, my)) return this.prev.handleClick(mx, my, button);
if (this.next.contains(mx, my)) return this.next.handleClick(mx, my, button);
return false;
}
}
@@ -271,7 +271,7 @@ public class RecipeItemsTooltipLineHandler extends CompositeTooltipLineHandler {
}
if (screen instanceof GuiContainer container) {
return AutoCraftingManager.getInventoryItems(container);
return ItemStackAmount.of(container);
}
return new ItemStackAmount();
@@ -125,7 +125,7 @@ public class RecipeJsonWriter {
}
private static List<Integer> filteredRecipes(IRecipeHandler handler) {
return new SearchRecipeHandler<>(handler).getFilteredRecipes();
return new SearchRecipeHandler<>(handler, GuiRecipe.getRecipeListFilter()).getFilteredRecipes();
}
private void writeFile(File file, List<? extends IRecipeHandler> handlers,
@@ -11,60 +11,100 @@ import net.minecraft.item.ItemStack;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.Widget;
import codechicken.nei.recipe.widget.RecipeWidget;
import codechicken.nei.recipe.widget.ViewStates;
import codechicken.nei.scroll.ScrollContainer;
public class RecipePageManager {
private static final int RECIPE_GAP = 4;
private static final class Page {
private final List<Widget> widgets;
private final int width;
private final boolean overflowY;
private int top;
private int gap;
private Page(List<Widget> widgets, int width, boolean overflowY, int gap) {
this.widgets = widgets;
this.width = width;
this.overflowY = overflowY;
this.gap = gap;
}
}
private SearchRecipeHandler<?> handler;
private ScrollContainer container;
private HandlerInfo handlerInfo;
private String cacheKey = "";
private int numRecipes = -1;
private int searchVersion = -1;
private int visibleHeight = -1;
private int currentPageIndex = -1;
private List<List<Widget>> pageWidgets = new ArrayList<>();
private final List<RecipeWidget> recipeWidgets = new ArrayList<>();
private final List<Page> pages = new ArrayList<>();
private final ViewStates viewStates;
private int maxRecipeWidth;
private boolean overflowY;
private final int recipeGap;
public RecipePageManager(SearchRecipeHandler<?> handler, HandlerInfo handlerInfo, ScrollContainer container) {
public RecipePageManager(SearchRecipeHandler<?> handler, HandlerInfo handlerInfo, ScrollContainer container,
ViewStates viewStates) {
this.handler = handler;
this.handlerInfo = handlerInfo;
this.container = container;
this.viewStates = viewStates;
this.recipeGap = handlerInfo.isRecipeSpacing() ? RECIPE_GAP : 0;
rebuildPages();
rebuildWidgets();
}
public boolean rebuildPages() {
final String cacheKey = handlerInfo.getHandlerName() + ":"
+ getNumRecipes()
+ ":"
+ this.container.getVisibleHeight()
+ ":"
+ GuiRecipe.searchField.text();
final boolean widgetsChanged = this.numRecipes != getNumRecipes()
|| this.searchVersion != this.handler.getSearchVersion();
final int visibleHeight = this.container.getVisibleHeight();
if (cacheKey.equals(this.cacheKey)) {
if (!widgetsChanged && visibleHeight == this.visibleHeight) {
return false;
}
this.cacheKey = cacheKey;
this.visibleHeight = visibleHeight;
final List<RecipeWidget> pausedWidgets = getPausedWidgets();
this.pageWidgets.clear();
if (widgetsChanged) {
rebuildWidgets();
}
final boolean allowOverflowY = this.handlerInfo.isAllowOverflowY();
final int handlerHeight = this.handlerInfo.getHeight() + this.handlerInfo.getYShift();
final boolean multipleWidgetsAllowed = !allowOverflowY && handlerInfo.isMultipleWidgetsAllowed();
final boolean infiniteScroll = !allowOverflowY
&& NEIClientConfig.getBooleanSetting("inventory.guirecipe.infiniteScroll");
this.pages.clear();
this.overflowY = false;
final int heightAvailable = this.container.getVisibleHeight();
final int width = Math.max(166, this.handlerInfo.getWidth());
buildPages();
buildSpreadGaps();
changePage(0);
return true;
}
private void rebuildWidgets() {
this.numRecipes = getNumRecipes();
this.searchVersion = this.handler.getSearchVersion();
this.recipeWidgets.clear();
for (List<Integer> group : groupRecipes()) {
this.recipeWidgets.add(
new RecipeWidget(this.handler.original, group, this.viewStates.get(this.handler.original, group)));
}
this.maxRecipeWidth = this.recipeWidgets.stream().mapToInt(widget -> widget.w).max()
.orElse(this.handlerInfo.getWidth());
}
private List<List<Integer>> groupRecipes() {
final List<Integer> searchRecipes = this.handler.getFilteredRecipes();
final int numRecipes = searchRecipes.size();
final List<List<Integer>> groupedRecipes = new ArrayList<>();
final Map<Object, Integer> groupEndIndices = new HashMap<>();
List<Widget> widgets = new ArrayList<>();
int shiftY = 0;
for (int i = 0; i < numRecipes; i++) {
final int recipeIndex = searchRecipes.get(i);
for (int recipeIndex : searchRecipes) {
final Object groupId = this.handler.original.getRecipeGroupId(recipeIndex);
final int groupIndex = groupId != null
? groupEndIndices.computeIfAbsent(groupId, k -> groupedRecipes.size())
@@ -77,42 +117,121 @@ public class RecipePageManager {
groupedRecipes.get(groupIndex).add(recipeIndex);
}
for (int groupIndex = 0; groupIndex < groupedRecipes.size(); groupIndex++) {
final RecipeWidget widget = new RecipeWidget(this.handler.original, groupedRecipes.get(groupIndex));
return groupedRecipes;
}
// keep the pause of the rebuilt widgets
for (RecipeWidget paused : pausedWidgets) {
final int pausedIndex = paused.getRecipeHandlerRef().recipeIndex;
private void buildPages() {
final boolean multipleWidgetsAllowed = isMultipleWidgetsAllowed();
final boolean infiniteScroll = isInfiniteScroll();
final int heightAvailable = this.container.getVisibleHeight();
List<Widget> widgets = new ArrayList<>();
int shiftY = 0;
if (widget.containsRecipeIndex(pausedIndex)) {
widget.pinRecipe(pausedIndex, paused.getPinnedIngredients());
}
for (RecipeWidget widget : this.recipeWidgets) {
if (this.handlerInfo.isAllowOverflowY()) {
widget.setHeight(Math.min(widget.getContentHeight(), heightAvailable));
}
widget.w = width;
if (allowOverflowY) {
widget.h = Math.min(handlerHeight, heightAvailable);
}
if (!widgets.isEmpty()
&& (!multipleWidgetsAllowed || !infiniteScroll && shiftY + widget.h > heightAvailable)) {
this.pageWidgets.add(widgets);
if (!widgets.isEmpty() && (!multipleWidgetsAllowed
|| !infiniteScroll && shiftY + this.recipeGap + widget.h > heightAvailable)) {
addPage(widgets);
widgets = new ArrayList<>();
shiftY = 0;
}
if (!widgets.isEmpty()) {
shiftY += this.recipeGap;
}
widgets.add(widget);
shiftY += widget.h;
}
if (!widgets.isEmpty()) {
this.pageWidgets.add(widgets);
addPage(widgets);
}
}
private void addPage(List<Widget> widgets) {
final int pageWidth = widgets.stream().mapToInt(widget -> widget.w).max().orElse(0);
final int pageHeight = widgets.stream().mapToInt(widget -> widget.h).sum()
+ this.recipeGap * (widgets.size() - 1);
final boolean pageOverflowsY = pageHeight > this.container.getVisibleHeight();
this.overflowY |= pageOverflowsY;
this.pages.add(new Page(widgets, pageWidth, pageOverflowsY, this.recipeGap));
}
public boolean needsVerticalScroll() {
return this.overflowY;
}
private Page getCurrentPage() {
return this.currentPageIndex >= 0 && this.currentPageIndex < this.pages.size()
? this.pages.get(this.currentPageIndex)
: null;
}
public boolean currentPageNeedsVerticalScroll() {
final Page page = getCurrentPage();
return page != null && page.overflowY;
}
private void buildSpreadGaps() {
if (!isMultipleWidgetsAllowed() || isInfiniteScroll()
|| !NEIClientConfig.getBooleanSetting("inventory.guirecipe.evenRecipeSpacing")) {
return;
}
changePage(0);
final int heightAvailable = this.container.getVisibleHeight();
int maxHeight = 0;
return true;
for (Page page : this.pages) {
for (Widget widget : page.widgets) {
maxHeight = Math.max(maxHeight, widget.h);
}
}
final int slots = maxHeight > 0 ? (heightAvailable + this.recipeGap) / (maxHeight + this.recipeGap) : 0;
// a page that fits a single recipe has nothing to spread
if (slots <= 1) {
return;
}
for (int index = 0; index < this.pages.size(); index++) {
final Page page = this.pages.get(index);
int totalHeight = 0;
for (Widget widget : page.widgets) {
totalHeight += widget.h;
}
int spreadGap = (heightAvailable - totalHeight) / (page.widgets.size() + 1);
if (index == this.pages.size() - 1) {
final int fullPageGap;
if (index > 0) {
fullPageGap = this.pages.get(index - 1).top;
} else {
fullPageGap = (heightAvailable - slots * maxHeight) / (slots + 1);
}
spreadGap = Math.min(spreadGap, fullPageGap);
}
if (spreadGap >= this.recipeGap) {
page.top = spreadGap;
page.gap = spreadGap;
}
}
}
private boolean isInfiniteScroll() {
return !this.handlerInfo.isAllowOverflowY()
&& NEIClientConfig.getBooleanSetting("inventory.guirecipe.infiniteScroll");
}
public boolean isMultipleWidgetsAllowed() {
@@ -128,7 +247,16 @@ public class RecipePageManager {
}
public int getNumPages() {
return this.pageWidgets.size();
return this.pages.size();
}
public int getMaxRecipeWidth() {
return this.maxRecipeWidth;
}
public int getCurrentPageWidth() {
final Page page = getCurrentPage();
return page != null ? page.width : 0;
}
public void changePage(int delta) {
@@ -145,8 +273,8 @@ public class RecipePageManager {
public boolean gotoRecipeIndex(int recipeIndex) {
for (int page = 0; page < this.pageWidgets.size(); page++) {
for (Widget widget : this.pageWidgets.get(page)) {
for (int page = 0; page < this.pages.size(); page++) {
for (Widget widget : this.pages.get(page).widgets) {
if (widget instanceof RecipeWidget recipeWidget && recipeWidget.containsRecipeIndex(recipeIndex)) {
changePage(page - this.currentPageIndex);
return true;
@@ -157,24 +285,10 @@ public class RecipePageManager {
return false;
}
private List<RecipeWidget> getPausedWidgets() {
final List<RecipeWidget> paused = new ArrayList<>();
for (List<Widget> 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<ItemStack> ingredients) {
for (List<Widget> widgets : this.pageWidgets) {
for (Widget widget : widgets) {
for (Page page : this.pages) {
for (Widget widget : page.widgets) {
if (widget instanceof RecipeWidget recipeWidget && recipeWidget.containsRecipeIndex(recipeIndex)) {
return recipeWidget.pinRecipe(recipeIndex, ingredients);
}
@@ -185,32 +299,35 @@ public class RecipePageManager {
}
public List<Widget> getCurrentPageWidgets() {
if (this.pageWidgets.isEmpty()) {
if (this.pages.isEmpty()) {
return Collections.emptyList();
}
List<Widget> currentWidgets = this.pageWidgets.get(this.currentPageIndex);
int shiftY = 0;
final Page page = this.pages.get(this.currentPageIndex);
final int placeWidth = Math.max(this.container.w, page.width);
int shiftY = page.top;
for (Widget widget : currentWidgets) {
for (Widget widget : page.widgets) {
if (widget instanceof RecipeWidget recipeWidget) {
recipeWidget.setLocation(2, shiftY);
final int offsetX = (placeWidth - widget.w) / 2;
recipeWidget.setLocation(offsetX, shiftY, placeWidth - widget.w - offsetX);
}
shiftY += widget.h;
shiftY += widget.h + page.gap;
}
return currentWidgets;
return page.widgets;
}
public List<Integer> getRecipeIndices() {
if (this.pageWidgets.isEmpty()) {
if (this.pages.isEmpty()) {
return Collections.emptyList();
}
final List<Integer> recipeIndices = new ArrayList<>();
for (Widget widget : this.pageWidgets.get(this.currentPageIndex)) {
for (Widget widget : this.pages.get(this.currentPageIndex).widgets) {
if (widget instanceof RecipeWidget recipeWidget) {
recipeIndices.add(recipeWidget.getRecipeHandlerRef().recipeIndex);
}
@@ -0,0 +1,327 @@
package codechicken.nei.recipe;
import java.util.List;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.item.ItemStack;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.RecipeSearchField;
import codechicken.nei.RestartableTask;
import codechicken.nei.SearchField;
import codechicken.nei.SearchTokenParser.ISearchParserProvider;
import codechicken.nei.SearchTokenParser.SearchMode;
import codechicken.nei.api.IRecipeFilter;
import codechicken.nei.api.ItemFilter;
import codechicken.nei.search.SearchExpressionUtils;
import codechicken.nei.theme.UIRecipeTexture;
class RecipeSearchBar extends NavigationBar {
private static final int FIELD_MARGIN = 40;
private final RestartableTask updateFilter = new RestartableTask("NEI Recipe Filtering") {
@Override
public void execute() {
if (!(NEIClientUtils.mc().currentScreen instanceof GuiRecipe<?>guiRecipe)) return;
final SearchRecipeHandler<?> searchHandler = guiRecipe.getSearchHandler();
if (searchHandler == null) return;
final IRecipeFilter filter = getRecipeFilter();
final List<Integer> found = filter != null ? searchHandler.getSearchResult(filter) : null;
if (interrupted() || filter != null && found == null) return;
searchHandler.setSearchIndices(found);
}
};
private final RecipeSearchField field = new RecipeSearchField("") {
@Override
protected boolean noResults() {
final GuiScreen currentScreen = NEIClientUtils.mc().currentScreen;
return !(currentScreen instanceof GuiRecipe<?>guiRecipe) || guiRecipe.getNumRecipes() > 0;
}
@Override
public void onTextChange(String oldText) {
if (!text().equals(oldText)) {
RecipeSearchBar.this.updateFilter.restart();
}
}
};
private final NavButton toggle = new NavButton(UIRecipeTexture.ICON_SEARCH, () -> true, this::toggleField) {
@Override
public void addTooltips(List<String> tooltip) {
tooltip.add(NEIClientUtils.translate("recipe.search.tooltip.name") + GuiDraw.TOOLTIP_LINESPACE);
if (NEIClientUtils.shiftKey()) {
tooltip.add(
NEIClientUtils.translate(
"recipe.search.tooltip.input",
SearchExpressionUtils.HIGHLIGHTS.RECIPE + "<"));
tooltip.add(
NEIClientUtils.translate(
"recipe.search.tooltip.output",
SearchExpressionUtils.HIGHLIGHTS.RECIPE + ">"));
tooltip.add(
NEIClientUtils.translate(
"recipe.search.tooltip.text",
SearchExpressionUtils.HIGHLIGHTS.RECIPE + "~"));
final int patternMode = NEIClientConfig.getIntSetting("inventory.search.patternMode");
if (patternMode != 2) {
tooltip.add(
NEIClientUtils.translate(
"recipe.search.tooltip.auxiliary",
SearchExpressionUtils.HIGHLIGHTS.RECIPE + "^"));
}
if (patternMode == 3) {
tooltip.add(
NEIClientUtils.translate(
"recipe.search.tooltip.all",
SearchExpressionUtils.HIGHLIGHTS.RECIPE + "<&"));
}
for (ISearchParserProvider provider : SearchField.searchParser.getProviders()) {
if (provider.getSearchMode() == SearchMode.PREFIX) {
addPrefixTooltip(tooltip, provider);
}
}
tooltip.add(
NEIClientUtils.translate(
"recipe.search.tooltip.exclude",
SearchExpressionUtils.HIGHLIGHTS.NEGATE + "-"));
tooltip.add(
NEIClientUtils.translate(
"recipe.search.tooltip.exclude_recipe",
SearchExpressionUtils.HIGHLIGHTS.NEGATE + "!"));
tooltip.add(
NEIClientUtils
.translate("recipe.search.tooltip.or", SearchExpressionUtils.HIGHLIGHTS.OR.f + "|"));
tooltip.add(
NEIClientUtils.translate(
"recipe.search.tooltip.exact",
SearchExpressionUtils.HIGHLIGHTS.QUOTED + "\"",
SearchExpressionUtils.HIGHLIGHTS.QUOTED + "\""));
if (patternMode == 1 || patternMode == 3) {
tooltip.add(
NEIClientUtils.translate(
"recipe.search.tooltip.regex",
SearchExpressionUtils.HIGHLIGHTS.REGEX + "r/",
SearchExpressionUtils.HIGHLIGHTS.REGEX + "/"));
}
} else {
tooltip.add(NEIClientUtils.translate("recipe.search.tooltip.shift"));
}
}
private void addPrefixTooltip(List<String> tooltip, ISearchParserProvider provider) {
final char prefix = SearchField.searchParser.getRedefinedPrefix(provider.getPrefix());
final String modeName = NEIClientUtils.translate("recipe.search.tooltip.prefix." + provider.getName());
tooltip.add(
NEIClientUtils.translate(
"recipe.search.tooltip.prefix",
provider.getHighlightedColor() + String.valueOf(prefix),
modeName));
}
};
private boolean available = false;
private String pageInfo = "";
private String pageCounter = "";
private boolean pageInfoCropped;
private String pageLabel = "";
public RecipeSearchBar(Runnable onPrev, Runnable onNext) {
super(null, onPrev, onNext);
}
public void setPages(int current, int total) {
this.pageInfo = current + "/" + total;
this.pageLabel = NEIClientUtils.translate("recipe.page", current, total);
updateCounter();
updateLabel();
}
private void updateCounter() {
this.pageCounter = NEIClientUtils.cropText(GuiDraw.fontRenderer, this.pageInfo, FIELD_MARGIN - GAP);
this.pageInfoCropped = !this.pageCounter.equals(this.pageInfo);
}
private void updateLabel() {
this.label = this.field.isVisible() ? "" : this.pageLabel;
}
private void toggleField() {
if (this.field.isVisible()) {
this.field.setText("");
this.field.setFocus(false);
this.field.setVisible(false);
this.toggle.state = 0;
} else {
this.field.setVisible(true);
this.field.setFocus(true);
this.toggle.state = 2;
}
updateLabel();
}
public void setAvailable(boolean available) {
this.available = available;
this.insetLeft = available ? this.toggle.w + GAP : 0;
}
public void place(int x, int y, int w) {
super.place(x, y, w);
this.toggle.x = plateX();
this.toggle.y = y;
this.field.x = this.toggle.x + this.toggle.w + 1;
this.field.y = y - 1;
this.field.w = plateWidth() - this.toggle.w - FIELD_MARGIN;
this.field.h = 14;
updateCounter();
}
public ItemFilter getFilter() {
return this.field.getFilter();
}
public IRecipeFilter getRecipeFilter() {
return this.field.text().isEmpty() ? null : this.field.getRecipeFilter();
}
public RecipeSearchField getSearchField() {
return this.field;
}
public void updateFilter() {
this.updateFilter.restart();
}
public void reset() {
this.field.setText("");
this.field.setVisible(false);
this.toggle.state = 0;
updateLabel();
updateFilter();
}
public boolean overSearch(int px, int py) {
return this.available && this.toggle.contains(px, py) || this.field.isVisible() && this.field.contains(px, py);
}
@Override
public boolean contains(int px, int py) {
return super.contains(px, py) || overSearch(px, py);
}
@Override
public void draw(int mx, int my) {
super.draw(mx, my);
if (this.available) {
this.toggle.draw(mx, my);
}
if (this.field.isVisible()) {
this.field.draw(mx, my);
final FontRenderer font = GuiDraw.fontRenderer;
final int textY = this.y + (this.h - font.FONT_HEIGHT) / 2 + 1;
GuiDraw.drawStringC(this.pageCounter, this.field.x + this.field.w + FIELD_MARGIN / 2, textY, 0xffffff);
}
}
@Override
public boolean handleClick(int mx, int my, int button) {
if (this.available) {
if (this.toggle.contains(mx, my)) {
return this.toggle.handleClick(mx, my, button);
} else if (this.field.isVisible() && this.field.contains(mx, my)) {
return this.field.handleClick(mx, my, button);
}
this.field.onGuiClick(mx, my);
}
return super.handleClick(mx, my, button);
}
@Override
public boolean handleKeyPress(int keyID, char keyChar) {
return isFocused() && this.field.handleKeyPress(keyID, keyChar);
}
@Override
public boolean isFocused() {
return this.field.isVisible() && this.field.focused();
}
@Override
public void loseFocus() {
this.field.setFocus(false);
}
@Override
public void lastKeyTyped(int keyID, char keyChar) {
if (isFocused()) {
this.field.lastKeyTyped(keyID, keyChar);
}
}
@Override
public boolean onHotkeyPressed() {
return this.field.isVisible() && this.field.onHotkeyPressed();
}
@Override
public List<String> handleTooltip(int mx, int my, List<String> tooltip) {
if (this.available) {
tooltip = this.toggle.handleTooltip(mx, my, tooltip);
}
if (tooltip.isEmpty() && this.field.isVisible()
&& mx >= this.field.x + this.field.w
&& mx < plateX() + plateWidth()
&& my >= this.y
&& my < this.y + this.h
&& this.pageInfoCropped) {
tooltip.add(this.pageInfo);
}
return tooltip;
}
public boolean handleDragNDrop(int mx, int my, ItemStack draggedStack) {
if (this.field.isVisible() && this.field.contains(mx, my)) {
this.field.setText(SearchField.getEscapedSearchText(draggedStack));
return true;
}
return false;
}
}
@@ -8,30 +8,17 @@ import org.lwjgl.opengl.GL11;
import codechicken.lib.gui.GuiDraw;
import codechicken.lib.gui.GuiDraw.ITooltipLineHandler;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.ColorUtils;
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.theme.UIRecipeTexture;
import codechicken.nei.util.ReadableNumberConverter;
public class RecipeTooltipLineHandler implements ITooltipLineHandler {
private static final int BG_PADDING = 5;
private static final int TRANSPARENCY_BORDER = 4;
private final DrawableResource BG_TEXTURE = new DrawableBuilder(
"nei:textures/gui/recipebg.png",
0,
0,
176 + TRANSPARENCY_BORDER * 2,
166 + TRANSPARENCY_BORDER * 2)
.setSlices(
BG_PADDING + TRANSPARENCY_BORDER,
BG_PADDING + TRANSPARENCY_BORDER,
BG_PADDING + TRANSPARENCY_BORDER,
BG_PADDING + TRANSPARENCY_BORDER)
.build();
protected long lastUpdate = System.currentTimeMillis();
protected String recipeName = "";
@@ -80,12 +67,16 @@ public class RecipeTooltipLineHandler implements ITooltipLineHandler {
}
if (this.widget != null) {
return new Dimension(this.widget.w + BG_PADDING * 2, this.widget.h + BG_PADDING * 2 + 12);
return new Dimension(getContentWidth() + BG_PADDING * 2, this.widget.h + BG_PADDING * 2 + 12);
}
return new Dimension(0, 0);
}
private int getContentWidth() {
return Math.max(this.widget.w, GuiDraw.getStringWidth(this.recipeName));
}
@Override
public void draw(int x, int y) {
if (this.widget == null) return;
@@ -106,25 +97,24 @@ public class RecipeTooltipLineHandler implements ITooltipLineHandler {
GuiContainerManager.enable2DRender();
GL11.glColor4f(1, 1, 1, 1);
BG_TEXTURE.draw(
-TRANSPARENCY_BORDER,
-TRANSPARENCY_BORDER,
size.width + TRANSPARENCY_BORDER * 2,
size.height + TRANSPARENCY_BORDER * 2);
UIRecipeTexture.WIDGET.draw(0, 0, size.width, size.height);
GL11.glEnable(GL11.GL_ALPHA_TEST);
GuiDraw.drawRect(BG_PADDING, BG_PADDING, size.width - BG_PADDING * 2, 12, 0x30000000);
GuiDraw.drawStringC(this.recipeName, this.widget.w / 2, BG_PADDING + 2, 0xffffff);
final int titleColor = ColorUtils.recipeTitle.getColor();
GuiDraw.drawRect(BG_PADDING, BG_PADDING, size.width - BG_PADDING * 2, 12, ColorUtils.recipeTitleBG.getColor());
GuiDraw.drawStringC(this.recipeName, size.width / 2, BG_PADDING + 2, titleColor);
if (this.multiplier > 0) {
GuiDraw.drawString(
"x" + ReadableNumberConverter.INSTANCE.toWideReadableForm(this.multiplier),
BG_PADDING + 2,
BG_PADDING + 2,
0xffffff);
titleColor);
}
this.widget.x = BG_PADDING + (getContentWidth() - this.widget.w) / 2;
GuiHelper.useScissor(
this.widget.x,
this.widget.y,
@@ -3,6 +3,7 @@ package codechicken.nei.recipe;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.function.IntPredicate;
import java.util.stream.Collectors;
@@ -18,18 +19,19 @@ class SearchRecipeHandler<H extends IRecipeHandler> {
private List<Integer> filteredRecipes;
private List<Integer> searchRecipes;
private volatile List<Integer> searchRecipes;
public SearchRecipeHandler(H handler) {
private volatile int searchVersion;
public SearchRecipeHandler(H handler, IRecipeFilter filter) {
this.original = handler;
if (this.original.numRecipes() == 0) {
this.filteredRecipes = Collections.emptyList();
} else {
final Stream<Integer> items = IntStream.range(0, this.original.numRecipes()).boxed();
final IRecipeFilter filter = this.searchingAvailable() ? GuiRecipe.getRecipeListFilter() : null;
if (filter == null) {
if (filter == null || !this.searchingAvailable()) {
this.filteredRecipes = items.collect(Collectors.toList());
} else {
this.filteredRecipes = items.filter(recipe -> mathRecipe(this.original, recipe, filter))
@@ -64,39 +66,43 @@ class SearchRecipeHandler<H extends IRecipeHandler> {
public List<Integer> getSearchResult(IRecipeFilter filter) {
if (filteredRecipes.isEmpty() || !this.searchingAvailable()) {
if (this.filteredRecipes.isEmpty() || !this.searchingAvailable()) {
return null;
}
List<Integer> filtered = null;
final List<Integer> recipes = IntStream.range(0, filteredRecipes.size()).boxed().collect(Collectors.toList());
final List<Integer> positions = IntStream.range(0, this.filteredRecipes.size()).boxed()
.collect(Collectors.toList());
try {
filtered = ItemList.forkJoinPool.submit(
() -> recipes.parallelStream()
.filter(recipe -> mathRecipe(this.original, filteredRecipes.get(recipe), filter))
return ItemList.forkJoinPool.submit(
() -> positions.parallelStream()
.filter(position -> mathRecipe(this.original, this.filteredRecipes.get(position), filter))
.collect(Collectors.toList()))
.get();
filtered.sort((a, b) -> a - b);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return filtered;
return null;
}
public void setSearchIndices(List<Integer> searchRecipes) {
if (Objects.equals(this.searchRecipes, searchRecipes)) return;
this.searchRecipes = searchRecipes;
this.searchVersion++;
}
public int getSearchVersion() {
return this.searchVersion;
}
public List<Integer> getFilteredRecipes() {
final List<Integer> search = this.searchRecipes;
if (this.searchRecipes == null) {
if (search == null) {
return this.filteredRecipes;
}
final List<Integer> search = this.searchRecipes;
final List<Integer> resolved = new ArrayList<>(search.size());
for (int idx : search) {
@@ -107,21 +113,18 @@ class SearchRecipeHandler<H extends IRecipeHandler> {
}
public int ref(int index) {
final List<Integer> search = this.searchRecipes;
if (searchRecipes != null) {
index = searchRecipes.get(index);
if (search != null) {
index = search.get(index);
}
return filteredRecipes.get(index);
return this.filteredRecipes.get(index);
}
public int numRecipes() {
if (searchRecipes != null) {
return searchRecipes.size();
}
return filteredRecipes.size();
final List<Integer> search = this.searchRecipes;
return search != null ? search.size() : this.filteredRecipes.size();
}
}
@@ -27,7 +27,6 @@ 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;
@@ -137,7 +136,7 @@ public class RecipeChainTooltipLineHandler extends CompositeTooltipLineHandler {
final GuiContainer currentGui = NEIClientUtils.getGuiContainer();
if (this.lastShiftKey && currentGui != null && !(currentGui instanceof GuiRecipe<?>)) {
inventory.putAll(AutoCraftingManager.getInventoryItems(currentGui));
inventory.putAll(ItemStackAmount.of(currentGui));
}
if (!this.outputRecipes.isEmpty()) {
@@ -64,6 +64,8 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
public boolean showFavorites;
public boolean showOverlay;
public boolean showBadge;
public int windowWidth;
public boolean recipeSpacing;
private String csvLine;
@@ -80,6 +82,8 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
this.showFavorites = info.getShowFavoritesButton();
this.showOverlay = info.getShowOverlayButton();
this.showBadge = info.getShowBadge();
this.windowWidth = info.getWindowWidth();
this.recipeSpacing = info.isRecipeSpacing();
this.csvLine = toCsvLine();
}
@@ -92,6 +96,8 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
this.info.setShowFavoritesButton(this.showFavorites);
this.info.setShowOverlayButton(this.showOverlay);
this.info.setShowBadge(this.showBadge);
this.info.setWindowWidth(this.windowWidth);
this.info.setRecipeSpacing(this.recipeSpacing);
NEIClientConfig.handlerOrdering.put(this.handlerKey, this.order);
}
@@ -108,6 +114,8 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
this.showFavorites = intOrDefault(parts[8], this.showFavorites ? 1 : 0) == 1;
this.showOverlay = intOrDefault(parts[9], this.showOverlay ? 1 : 0) == 1;
this.showBadge = intOrDefault(parts[10], this.showBadge ? 1 : 0) == 1;
this.windowWidth = intOrDefault(parts[11], this.windowWidth);
this.recipeSpacing = intOrDefault(parts[12], this.recipeSpacing ? 1 : 0) == 1;
apply();
}
@@ -125,7 +133,9 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
String.valueOf(this.allowOverflowY ? 1 : 0),
String.valueOf(this.showFavorites ? 1 : 0),
String.valueOf(this.showOverlay ? 1 : 0),
String.valueOf(this.showBadge ? 1 : 0));
String.valueOf(this.showBadge ? 1 : 0),
String.valueOf(this.windowWidth),
String.valueOf(this.recipeSpacing ? 1 : 0));
}
public boolean isUnmodified() {
@@ -148,7 +158,7 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
private static final int LABEL_WIDTH = 50;
private static final String TOOLTIP_PREFIX = "debug.RecipeHandler.";
private static final String HEADER = "HandlerId,YShift,Height,Width,MultiWidgets,Order,AllowOverflowX,AllowOverflowY,ShowFavorites,ShowOverlay,ShowBadge";
private static final String HEADER = "HandlerId,YShift,Height,Width,MultiWidgets,Order,AllowOverflowX,AllowOverflowY,ShowFavorites,ShowOverlay,ShowBadge,WindowWidth,RecipeSpacing";
private final int[] COLORS = new int[] { 0x2200FF00, 0x22FF0000, 0x220000FF, 0x2200FFFF, 0x22FF00FF, 0x22FFFF00 };
public static DebugHandlerWidget instance = new DebugHandlerWidget();
@@ -217,6 +227,11 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
saveHandlerInfoPatch();
}, y);
y = addCheckboxWidget("RecipeSpacing", button -> {
record.recipeSpacing = button.value;
saveHandlerInfoPatch();
}, y);
final LabelWidget readonly = new LabelWidget(0xffffff, true);
readonly.y = y;
@@ -232,7 +247,12 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
y = addTextFieldWidget("Width", HandlerInfo.DEFAULT_WIDTH, (field, oldText) -> {
record.width = field.getInteger();
saveHandlerInfoPatch();
}, newValue -> newValue >= HandlerInfo.DEFAULT_WIDTH, y);
}, newValue -> newValue > 0, y);
y = addTextFieldWidget("WindowWidth", 0, (field, oldText) -> {
record.windowWidth = field.getInteger();
saveHandlerInfoPatch();
}, newValue -> newValue >= 0, y);
y = addCheckboxWidget("AllowOverflowX", button -> {
record.allowOverflowX = button.value;
@@ -474,6 +494,8 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
this.values.get("height").updateValue(String.valueOf(this.record.height));
this.values.get("height_readonly").updateValue(String.valueOf(this.record.height));
this.values.get("width").updateValue(String.valueOf(this.record.width));
this.values.get("windowwidth").updateValue(String.valueOf(this.record.windowWidth));
this.values.get("recipespacing").updateValue(String.valueOf(this.record.recipeSpacing));
this.values.get("multiwidgets").updateValue(String.valueOf(this.record.multiWidgets));
this.values.get("allowoverflowx").updateValue(String.valueOf(this.record.allowOverflowX));
@@ -745,7 +767,8 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
ClientHandler.loadSettingsFile("handlers.patch", lines -> {
final List<String> linesList = lines.collect(Collectors.toCollection(ArrayList::new));
if (linesList.isEmpty() || !HEADER.equals(linesList.get(0))) {
// files saved before new columns were appended have a prefix of the current header
if (linesList.isEmpty() || linesList.get(0).isEmpty() || !HEADER.startsWith(linesList.get(0))) {
return;
}
@@ -759,7 +782,7 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
key -> new HandlerInfoRecord(
key,
GuiRecipeTab.handlerMap.getOrDefault(key, GuiRecipeTab.DEFAULT_HANDLER_INFO)));
record.apply((line + ",null,null,null,null,null,null,null,null,null,null"));
record.apply((line + ",null,null,null,null,null,null,null,null,null,null,null,null"));
}
});
@@ -29,7 +29,6 @@ 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;
@@ -44,39 +43,41 @@ import codechicken.nei.recipe.IRecipeHandler;
import codechicken.nei.recipe.RecipeHandlerRef;
import codechicken.nei.recipe.StackInfo;
import codechicken.nei.recipe.debug.DebugHandlerWidget;
import codechicken.nei.theme.UIRecipeTexture;
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 DrawableResource PAUSE_MARKER = UIRecipeTexture.ICON_PAUSE;
protected static final int PAUSE_MARKER_OFFSET = 1;
protected static final int BUTTON_GAP = 2;
protected static final int BUTTON_SPACING = 2;
protected static final int BUTTON_BOTTOM_OFFSET = 6;
protected final RecipeGroup group;
protected final IRecipeHandler handler;
protected final HandlerInfo handlerInfo;
protected final Map<PositionedStack, List<Badge>> badgeCache = new WeakHashMap<>();
protected final Map<Integer, List<GuiRecipeButton>> buttonCache = new HashMap<>();
protected final Map<Integer, List<GuiRecipeButton>> layoutCache = new HashMap<>();
protected AcceptsFollowingTooltipLineHandler acceptsTooltip;
protected int recipeHeight = 0;
protected int spaceRight = 0;
protected final ViewState state;
protected int activeMember = 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<ItemStack> pinnedIngredients = null;
protected Map<Point, ItemStack> pinnedSlots = Collections.emptyMap();
public RecipeWidget(RecipeHandlerRef handlerRef) {
@@ -84,14 +85,24 @@ public class RecipeWidget extends Widget {
}
public RecipeWidget(IRecipeHandler handler, List<Integer> recipeIndices) {
this(new RecipeGroup(handler, recipeIndices));
this(handler, recipeIndices, null);
}
public RecipeWidget(IRecipeHandler handler, List<Integer> recipeIndices, ViewState state) {
this(new RecipeGroup(handler, recipeIndices), state);
}
public RecipeWidget(RecipeGroup group) {
this(group, null);
}
public RecipeWidget(RecipeGroup group, ViewState state) {
this.group = group;
this.handler = group.getHandler();
this.handlerInfo = group.getHandlerInfo();
this.state = state != null ? state : new ViewState();
update();
restore();
}
public RecipeHandlerRef getRecipeHandlerRef() {
@@ -106,33 +117,81 @@ public class RecipeWidget extends Widget {
return this.group.contains(recipeIndex);
}
// the state may come from a group with other members, then its cycle no longer fits
private void restore() {
final int member = this.group.indexOf(this.state.recipeIndex);
if (member < 0 || this.state.groupSize != this.group.size()) {
this.state.cycle = 0;
}
this.state.groupSize = this.group.size();
// a pause on a recipe hidden by the search stays in the state until the recipe is shown again
if (this.state.pausedRecipeIndex >= 0
&& pinRecipe(this.state.pausedRecipeIndex, this.state.pinnedIngredients)) {
return;
}
setActiveMember(Math.max(member, 0));
syncCycle();
}
public HandlerInfo getHandlerInfo() {
return this.handlerInfo;
}
public void setLocation(int x, int y) {
public void setLocation(int x, int y, int spaceRight) {
this.x = x;
this.y = y;
if (this.spaceRight != spaceRight) {
this.spaceRight = spaceRight;
relayoutButtons();
}
}
public void setHeight(int h) {
if (this.h != h) {
this.h = h;
relayoutButtons();
}
}
public void showAsWidget(boolean show) {
this.showAsWidget = show;
}
@Override
public boolean contains(int px, int py) {
return super.contains(px, py) || isOverButton(px, py);
}
private boolean isOverButton(int px, int py) {
for (GuiRecipeButton button : getRecipeButtonsIfInit()) {
if (button.contains(px - this.x, py - this.y)) {
return true;
}
}
return false;
}
public boolean isPaused() {
return this.paused;
}
public List<ItemStack> getPinnedIngredients() {
return this.pinnedIngredients;
return this.state.pinnedIngredients;
}
public void setPaused(boolean paused) {
final boolean wasPaused = this.paused;
this.paused = paused && this.group.canCycle();
this.state.pausedRecipeIndex = this.paused ? this.state.recipeIndex : -1;
if (!this.paused) {
this.pinnedIngredients = null;
this.state.pinnedIngredients = null;
this.pinnedSlots = Collections.emptyMap();
if (wasPaused) {
@@ -160,9 +219,10 @@ public class RecipeWidget extends Widget {
return false;
}
this.pinnedIngredients = ingredients;
this.state.pinnedIngredients = ingredients;
this.pinnedSlots = slots;
this.paused = true;
this.state.pausedRecipeIndex = recipeIndex;
setActiveMember(member);
updatePermutations();
@@ -219,25 +279,39 @@ public class RecipeWidget extends Widget {
@Override
public void update() {
final int prevW = this.w;
final int prevH = this.h;
int recipeWidth = 0;
this.recipeHeight = 0;
for (int member = 0; member < this.group.size(); member++) {
final int recipe = this.group.getRecipeIndex(member);
recipeWidth = Math.max(recipeWidth, this.handler.getRecipeWidth(recipe));
this.recipeHeight = Math.max(this.recipeHeight, this.handler.getRecipeHeight(recipe));
}
this.w = recipeWidth > 0 ? recipeWidth : this.handlerInfo.getWidth();
if (this.showAsWidget || !this.handlerInfo.isAllowOverflowY()) {
int maxHeight = 0;
this.h = getContentHeight();
}
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();
if (this.w != prevW || this.h != prevH) {
relayoutButtons();
}
this.update = true;
}
public int getContentHeight() {
return (this.recipeHeight > 0 ? this.recipeHeight : this.handlerInfo.getHeight())
+ this.handlerInfo.getYShift();
}
private boolean showFavoritesButton() {
return NEIClientConfig.favoritesEnabled() && this.handlerInfo.getShowFavoritesButton();
}
public List<GuiRecipeButton> getRecipeButtons() {
return this.buttonCache.computeIfAbsent(this.activeMember, this::createButtons);
}
@@ -252,8 +326,55 @@ public class RecipeWidget extends Widget {
return Collections.emptyList();
}
return Collections
.unmodifiableList(initButtons(RecipeHandlerRef.of(this.handler, this.group.getRecipeIndex(member))));
final List<GuiRecipeButton> buttons = initButtons(
RecipeHandlerRef.of(this.handler, this.group.getRecipeIndex(member)));
final List<GuiRecipeButton> unplaced = new ArrayList<>();
// NEI creates its buttons at (0, 0), so anything else was placed by a mod and keeps its position.
for (GuiRecipeButton button : buttons) {
if (button.xPosition == 0 && button.yPosition == 0) {
unplaced.add(button);
}
}
this.layoutCache.put(member, unplaced);
layoutButtons(unplaced);
return Collections.unmodifiableList(buttons);
}
private void relayoutButtons() {
for (List<GuiRecipeButton> buttons : this.layoutCache.values()) {
layoutButtons(buttons);
}
}
private void layoutButtons(List<GuiRecipeButton> buttons) {
final int top = this.handlerInfo.getYShift();
final int bottom = this.h - BUTTON_BOTTOM_OFFSET;
int columnX = 0;
int columnWidth = 0;
int y = bottom;
for (GuiRecipeButton button : buttons) {
if (y != bottom && y - button.height < top) {
columnX += columnWidth + BUTTON_SPACING;
columnWidth = 0;
y = bottom;
}
y -= button.height;
button.xPosition = columnX;
button.yPosition = y;
y -= BUTTON_SPACING;
columnWidth = Math.max(columnWidth, button.width);
}
final int left = this.w + Math.min(BUTTON_GAP, this.spaceRight - columnX - columnWidth);
for (GuiRecipeButton button : buttons) {
button.xPosition += left;
}
}
private List<GuiRecipeButton> initButtons(RecipeHandlerRef ref) {
@@ -289,22 +410,17 @@ public class RecipeWidget extends Widget {
private List<GuiRecipeButton> getDefaultButtons(RecipeHandlerRef ref) {
GuiContainer guiContainer = NEIClientUtils.getGuiContainer();
final List<GuiRecipeButton> buttons = new ArrayList<>();
final boolean showFavorites = NEIClientConfig.favoritesEnabled() && handlerInfo.getShowFavoritesButton();
final boolean showOverlay = handlerInfo.getShowOverlayButton();
final int x = Math.min(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 (this.handlerInfo.getShowOverlayButton()) {
buttons.add(new GuiOverlayButton(guiContainer, ref, 0, 0));
}
if (showFavorites) {
buttons.add(new GuiFavoriteButton(ref, x, y));
if (showFavoritesButton()) {
buttons.add(new GuiFavoriteButton(ref, 0, 0));
}
return buttons;
@@ -318,10 +434,10 @@ public class RecipeWidget extends Widget {
this.update = false;
if (this.lastcycle == -1) {
this.lastcycle = 0;
this.lastcycle = this.state.cycleticks / TICKS_PER_CYCLE;
applyCycle();
} else if (tickCycle() && !isCycleFrozen(mouseX, mouseY)) {
this.cycle++;
this.state.cycle++;
applyCycle();
} else if (this.favoriteRevision != FavoriteRecipes.getRevision()) {
this.favoriteRevision = FavoriteRecipes.getRevision();
@@ -733,8 +849,8 @@ public class RecipeWidget extends Widget {
private boolean tickCycle() {
if ((this.cycleticks++ / TICKS_PER_CYCLE) != this.lastcycle) {
this.lastcycle = this.cycleticks / TICKS_PER_CYCLE;
if ((this.state.cycleticks++ / TICKS_PER_CYCLE) != this.lastcycle) {
this.lastcycle = this.state.cycleticks / TICKS_PER_CYCLE;
return true;
}
@@ -749,15 +865,14 @@ public class RecipeWidget extends Widget {
return NEIClientConfig.freezeCycleOnHover() && !this.showAsWidget
&& contains(mouseX, mouseY)
&& (getPositionedStackMouseOver(mouseX, mouseY) != null
|| forEachButtons(button -> button.contains(mouseX, mouseY) ? true : null, false));
&& (getPositionedStackMouseOver(mouseX, mouseY) != null || isOverButton(mouseX, mouseY));
}
private void applyCycle() {
if (!this.paused) {
final List<Integer> allowed = this.group.getAllowedMembers();
setActiveMember(allowed.get(this.cycle % allowed.size()));
setActiveMember(allowed.get(this.state.cycle % allowed.size()));
}
this.group.refresh(this.activeMember);
@@ -765,7 +880,7 @@ public class RecipeWidget extends Widget {
}
private int getPermutationIndex() {
return this.cycle / this.group.getAllowedMembers().size();
return this.state.cycle / this.group.getAllowedMembers().size();
}
// keep the permutation index, move the member part of the counter to the active member
@@ -774,7 +889,7 @@ public class RecipeWidget extends Widget {
final int allowedIndex = allowed.indexOf(this.activeMember);
if (allowedIndex >= 0) {
this.cycle = this.cycle / allowed.size() * allowed.size() + allowedIndex;
this.state.cycle = this.state.cycle / allowed.size() * allowed.size() + allowedIndex;
}
}
@@ -823,6 +938,7 @@ public class RecipeWidget extends Widget {
}
}
this.state.recipeIndex = this.group.getRecipeIndex(member);
}
private boolean containsStack(PositionedStack pStack, ItemStack stack) {
@@ -0,0 +1,17 @@
package codechicken.nei.recipe.widget;
import java.util.List;
import net.minecraft.item.ItemStack;
public final class ViewState {
public int recipeIndex = -1;
public int groupSize = 0;
// single state counter: member = allowed[cycle % size], permutation index = cycle / size
public int cycle = 0;
public int cycleticks = 0;
public int pausedRecipeIndex = -1;
public List<ItemStack> pinnedIngredients = null;
}
@@ -0,0 +1,22 @@
package codechicken.nei.recipe.widget;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import codechicken.nei.recipe.IRecipeHandler;
public final class ViewStates {
private final Map<Object, ViewState> groupStates = new HashMap<>();
private final Map<Integer, ViewState> recipeStates = new HashMap<>();
// a group keeps its state while a search hides some of its recipes, a search can't split or merge groups
public ViewState get(IRecipeHandler handler, List<Integer> group) {
final int firstRecipe = group.get(0);
final Object groupId = handler.getRecipeGroupId(firstRecipe);
return groupId != null ? this.groupStates.computeIfAbsent(groupId, k -> new ViewState())
: this.recipeStates.computeIfAbsent(firstRecipe, k -> new ViewState());
}
}
@@ -3,6 +3,7 @@ package codechicken.nei.scroll;
import java.awt.Point;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
@@ -80,6 +81,16 @@ public class ScrollContainer extends WidgetContainer {
getVisibleHeight());
}
@Override
public void setWidgets(List<Widget> widgets) {
for (Widget widget : widgets) {
this.relativePosition.remove(widget);
}
super.setWidgets(widgets);
}
@Override
public void clear() {
@@ -0,0 +1,47 @@
package codechicken.nei.theme;
import codechicken.nei.drawable.DrawableResource;
public final class UIRecipeTexture {
public static final DrawableResource WINDOW = UISprite
.of("recipe/window", 176, 109, new int[] { 6, 6, 6, 6 }, new int[] { 5, 33, 5, 5 });
public static final DrawableResource WIDGET = UISprite
.of("recipe/widget", 176, 95, new int[] { 6, 6, 6, 6 }, new int[] { 5, 19, 5, 5 });
private static final DrawableResource[] TAB = UISprite.frames("recipe/tab", 24, 27, 2);
private static final DrawableResource[] NAV = UISprite.frames("recipe/icon_nav", 12, 12, 2);
private static final DrawableResource[] FAVORITE = UISprite.frames("recipe/icon_favorite", 12, 12, 2);
private static final DrawableResource[] OVERLAY = UISprite.frames("recipe/icon_overlay", 12, 12, 3);
private static final DrawableResource[] ITEM_STATUS = UISprite.frames("recipe/item_status", 12, 12, 2);
public static final DrawableResource TAB_SELECTED = TAB[0];
public static final DrawableResource TAB_UNSELECTED = TAB[1];
private static final DrawableResource[] CATALYST = UISprite
.frames("recipe/catalyst_tab", 23, 28, 2, new int[] { 6, 6, 0, 6 }, new int[] { 5, 5, 5, 5 });
public static final DrawableResource CATALYST_TAB = CATALYST[0];
public static final DrawableResource CATALYST_TAB_JOINED = CATALYST[1];
public static final DrawableResource CATALYST_SLOT = UISprite
.of("recipe/catalyst_slot", 18, 18, UISprite.DEFAULT_SPACE, new int[] { 1, 1, 1, 1 });
public static final DrawableResource ICON_PREV = NAV[0];
public static final DrawableResource ICON_NEXT = NAV[1];
public static final DrawableResource ICON_SEARCH = UISprite.of("recipe/icon_search", 12, 12);
public static final DrawableResource ICON_PAUSE = UISprite.of("recipe/icon_pause", 12, 12);
public static final DrawableResource ICON_FAVORITE_OFF = FAVORITE[0];
public static final DrawableResource ICON_FAVORITE_ON = FAVORITE[1];
public static final DrawableResource ICON_OVERLAY = OVERLAY[0];
public static final DrawableResource ICON_OVERLAY_FILL = OVERLAY[1];
public static final DrawableResource ICON_OVERLAY_FILL_ERROR = OVERLAY[2];
public static final DrawableResource ITEM_MISSING = ITEM_STATUS[0];
public static final DrawableResource ITEM_PRESENT = ITEM_STATUS[1];
private UIRecipeTexture() {}
}
@@ -346,10 +346,10 @@ moze_intel.projecte.integration.NEI.NEIAlchBagHandler,ProjectE,ProjectE:item.pe_
de.katzenpapst.amunra.nei.recipehandler.ARCircuitFab,Pra's Galacticraft Mod,GalacticraftCore:tile.machine2:4,,GalacticraftAmunRa,TRUE,,,,,,,,,,,,
de.katzenpapst.amunra.nei.recipehandler.ARNasaWorkbenchShuttle,Pra's Galacticraft Mod,GalacticraftAmunRa:item.itemShuttle,,GalacticraftAmunRa,TRUE,,,130,168,16,,,,,,,
vazkii.botania.client.integration.nei.recipe.RecipeHandlerFloatingFlowers,Botania,Botania:miniIsland,,Botania,TRUE,,,,,5,,,,,,,
vazkii.botania.client.integration.nei.recipe.RecipeHandlerPetalApothecary,Botania,Botania:altar,,Botania,TRUE,,,102,137,4,,,,,,,
vazkii.botania.client.integration.nei.recipe.RecipeHandlerRunicAltar,Botania,Botania:runeAltar,,Botania,TRUE,,,122,137,4,,,,,,,
vazkii.botania.client.integration.nei.recipe.RecipeHandlerManaPool,Botania,Botania:pool,,Botania,TRUE,,,90,137,4,,,,,,,
vazkii.botania.client.integration.nei.recipe.RecipeHandlerElvenTrade,Botania,Botania:alfheimPortal,,Botania,TRUE,,,90,130,4,,,,,,,
vazkii.botania.client.integration.nei.recipe.RecipeHandlerPetalApothecary,Botania,Botania:altar,,Botania,TRUE,,,102,166,4,,,,,,,
vazkii.botania.client.integration.nei.recipe.RecipeHandlerRunicAltar,Botania,Botania:runeAltar,,Botania,TRUE,,,122,166,4,,,,,,,
vazkii.botania.client.integration.nei.recipe.RecipeHandlerManaPool,Botania,Botania:pool,,Botania,TRUE,,,90,166,4,,,,,,,
vazkii.botania.client.integration.nei.recipe.RecipeHandlerElvenTrade,Botania,Botania:alfheimPortal,,Botania,TRUE,,,90,166,4,,,,,,,
vazkii.botania.client.integration.nei.recipe.RecipeHandlerBrewery,Botania,Botania:brewery,,Botania,TRUE,,,,,4,,,,,,,
vazkii.botania.client.integration.nei.recipe.RecipeHandlerPureDaisy,Botania,Botania:specialFlower,"{type:puredaisy}",Botania,TRUE,,,,,4,,,,,,,
vazkii.botania.client.integration.nei.recipe.RecipeHandlerLexicaBotania,Botania,Botania:lexicon,,Botania,TRUE,,,,,,,,,,,,
@@ -523,10 +523,10 @@ de.ellpeck.actuallyadditions.mod.nei.NEICompostRecipe,Actually Additions,Actuall
de.ellpeck.actuallyadditions.mod.nei.NEIReconstructorRecipe,Actually Additions,ActuallyAdditions:blockAtomicReconstructor,,ActuallyAdditions,TRUE,,,,,,,,,,,,
de.ellpeck.actuallyadditions.mod.nei.NEITreasureChestRecipe,Actually Additions,ActuallyAdditions:blockTreasureChest,,ActuallyAdditions,TRUE,,,,,,,,,,,,
vazkii.botania.client.integration.nei.RecipeHandlerFloatingFlowers,Botania,Botania:miniIsland,,Botania,TRUE,,,,,5,,,,,,,
vazkii.botania.client.integration.nei.RecipeHandlerPetalApothecary,Botania,Botania:altar,,Botania,TRUE,,,102,137,4,,,,,,,
vazkii.botania.client.integration.nei.RecipeHandlerRunicAltar,Botania,Botania:runeAltar,,Botania,TRUE,,,122,137,4,,,,,,,
vazkii.botania.client.integration.nei.RecipeHandlerManaPool,Botania,Botania:pool,,Botania,TRUE,,,90,137,4,,,,,,,
vazkii.botania.client.integration.nei.RecipeHandlerElvenTrade,Botania,Botania:alfheimPortal,,Botania,TRUE,,,90,130,4,,,,,,,
vazkii.botania.client.integration.nei.RecipeHandlerPetalApothecary,Botania,Botania:altar,,Botania,TRUE,,,102,166,4,,,,,,,
vazkii.botania.client.integration.nei.RecipeHandlerRunicAltar,Botania,Botania:runeAltar,,Botania,TRUE,,,122,166,4,,,,,,,
vazkii.botania.client.integration.nei.RecipeHandlerManaPool,Botania,Botania:pool,,Botania,TRUE,,,90,166,4,,,,,,,
vazkii.botania.client.integration.nei.RecipeHandlerElvenTrade,Botania,Botania:alfheimPortal,,Botania,TRUE,,,90,166,4,,,,,,,
vazkii.botania.client.integration.nei.RecipeHandlerBrewery,Botania,Botania:brewery,,Botania,TRUE,,,,,4,,,,,,,
vazkii.botania.client.integration.nei.RecipeHandlerPureDaisy,Botania,Botania:specialFlower,"{type:puredaisy}",Botania,TRUE,,,,,4,,,,,,,
vazkii.botania.client.integration.nei.RecipeHandlerLexicaBotania,Botania,Botania:lexicon,,Botania,TRUE,,,,,,,,,,,,
1 handler modName itemName nbtInfo modId modRequired excludedModId yShift handlerHeight handlerWidth maxRecipesPerPage imageResource imageX imageY imageWidth imageHeight itemNotes useCustomScroll
346 de.katzenpapst.amunra.nei.recipehandler.ARCircuitFab Pra's Galacticraft Mod GalacticraftCore:tile.machine2:4 GalacticraftAmunRa TRUE
347 de.katzenpapst.amunra.nei.recipehandler.ARNasaWorkbenchShuttle Pra's Galacticraft Mod GalacticraftAmunRa:item.itemShuttle GalacticraftAmunRa TRUE 130 168 16
348 vazkii.botania.client.integration.nei.recipe.RecipeHandlerFloatingFlowers Botania Botania:miniIsland Botania TRUE 5
349 vazkii.botania.client.integration.nei.recipe.RecipeHandlerPetalApothecary Botania Botania:altar Botania TRUE 102 137 166 4
350 vazkii.botania.client.integration.nei.recipe.RecipeHandlerRunicAltar Botania Botania:runeAltar Botania TRUE 122 137 166 4
351 vazkii.botania.client.integration.nei.recipe.RecipeHandlerManaPool Botania Botania:pool Botania TRUE 90 137 166 4
352 vazkii.botania.client.integration.nei.recipe.RecipeHandlerElvenTrade Botania Botania:alfheimPortal Botania TRUE 90 130 166 4
353 vazkii.botania.client.integration.nei.recipe.RecipeHandlerBrewery Botania Botania:brewery Botania TRUE 4
354 vazkii.botania.client.integration.nei.recipe.RecipeHandlerPureDaisy Botania Botania:specialFlower {type:puredaisy} Botania TRUE 4
355 vazkii.botania.client.integration.nei.recipe.RecipeHandlerLexicaBotania Botania Botania:lexicon Botania TRUE
523 de.ellpeck.actuallyadditions.mod.nei.NEIReconstructorRecipe Actually Additions ActuallyAdditions:blockAtomicReconstructor ActuallyAdditions TRUE
524 de.ellpeck.actuallyadditions.mod.nei.NEITreasureChestRecipe Actually Additions ActuallyAdditions:blockTreasureChest ActuallyAdditions TRUE
525 vazkii.botania.client.integration.nei.RecipeHandlerFloatingFlowers Botania Botania:miniIsland Botania TRUE 5
526 vazkii.botania.client.integration.nei.RecipeHandlerPetalApothecary Botania Botania:altar Botania TRUE 102 137 166 4
527 vazkii.botania.client.integration.nei.RecipeHandlerRunicAltar Botania Botania:runeAltar Botania TRUE 122 137 166 4
528 vazkii.botania.client.integration.nei.RecipeHandlerManaPool Botania Botania:pool Botania TRUE 90 137 166 4
529 vazkii.botania.client.integration.nei.RecipeHandlerElvenTrade Botania Botania:alfheimPortal Botania TRUE 90 130 166 4
530 vazkii.botania.client.integration.nei.RecipeHandlerBrewery Botania Botania:brewery Botania TRUE 4
531 vazkii.botania.client.integration.nei.RecipeHandlerPureDaisy Botania Botania:specialFlower {type:puredaisy} Botania TRUE 4
532 vazkii.botania.client.integration.nei.RecipeHandlerLexicaBotania Botania Botania:lexicon Botania TRUE
@@ -343,6 +343,9 @@ nei.options.inventory.guirecipe.slotHighlightPresent.false=No
nei.options.inventory.guirecipe.infiniteScroll=Use Infinite Scroll
nei.options.inventory.guirecipe.infiniteScroll.true=Yes
nei.options.inventory.guirecipe.infiniteScroll.false=No
nei.options.inventory.guirecipe.evenRecipeSpacing=Spread Recipes Evenly
nei.options.inventory.guirecipe.evenRecipeSpacing.true=Yes
nei.options.inventory.guirecipe.evenRecipeSpacing.false=No
nei.options.inventory.guirecipe.jeiStyleRecipeCatalyst=JEI Style Recipe Catalysts
nei.options.inventory.guirecipe.jeiStyleRecipeCatalyst.0=None
nei.options.inventory.guirecipe.jeiStyleRecipeCatalyst.1=Grid
@@ -360,6 +363,8 @@ nei.options.inventory.guirecipe.scrollPages.true=Enabled
nei.options.inventory.guirecipe.scrollPages.false=Disabled
nei.options.inventory.guirecipe.maxHeight=Max Height
nei.options.inventory.guirecipe.minWidth=Minimum Recipe Screen Width
nei.options.inventory.guirecipe.topMargin=Recipe Screen Top Margin
nei.options.inventory.showItemQuantityWidget=Show Item Quantity Widget
nei.options.inventory.showItemQuantityWidget.true=Yes
nei.options.inventory.showItemQuantityWidget.false=No
@@ -630,6 +635,8 @@ nei.debug.RecipeHandler.yShift=yShift
nei.debug.RecipeHandler.MultiWidgets=Multi Widgets
nei.debug.RecipeHandler.Height=Height
nei.debug.RecipeHandler.Width=Width
nei.debug.RecipeHandler.WindowWidth=Window Width
nei.debug.RecipeHandler.RecipeSpacing=Recipe Spacing
nei.debug.RecipeHandler.ShowFavorites=Show Favorites
nei.debug.RecipeHandler.ShowOverlay=Show Overlays
nei.debug.RecipeHandler.ShowBadge=Show Badge
@@ -213,6 +213,8 @@ nei.options.inventory.guirecipe.jeiStyleRecipeCatalyst.2=Скролл
nei.options.inventory.guirecipe.cycledIngredientsTooltip=Подсказка циклических ингредиентов
nei.options.inventory.guirecipe.cycledIngredientsTooltip.true=Показывать
nei.options.inventory.guirecipe.cycledIngredientsTooltip.false=Скрыть
nei.options.inventory.guirecipe.minWidth=Минимальная ширина окна рецептов
nei.options.inventory.guirecipe.topMargin=Верхний отступ окна рецептов
nei.options.inventory.showItemQuantityWidget=Показывать виджет количества предметов
nei.options.inventory.showItemQuantityWidget.true=Да
nei.options.inventory.showItemQuantityWidget.false=Нет
@@ -257,6 +259,9 @@ nei.options.inventory.guirecipe.shiftOverlayRecipe.false=Нет
nei.options.inventory.guirecipe.freezeCycleOnHover=Останавливать перелистывание рецепта при наведении на предмет или кнопку
nei.options.inventory.guirecipe.freezeCycleOnHover.true=Да
nei.options.inventory.guirecipe.freezeCycleOnHover.false=Нет
nei.options.inventory.guirecipe.evenRecipeSpacing=Равномерно распределять рецепты по высоте
nei.options.inventory.guirecipe.evenRecipeSpacing.true=Да
nei.options.inventory.guirecipe.evenRecipeSpacing.false=Нет
nei.options.inventory.widgetsenabled.true=NEI включен
nei.options.inventory.widgetsenabled.false=NEI выключен
nei.options.inventory.cheatmode.0=Режим рецептов
Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 186 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 172 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 157 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 194 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 110 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 146 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 206 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 202 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 312 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 319 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 KiB

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 554 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 103 B