Compare commits

...
23 Commits
Author SHA1 Message Date
slprime a02d293d44 Fix Recipe Page Area (#932) 2026-05-11 18:47:36 +03:00
sisyphussy 1265113390 Fix mui2 screen capture (#930) 2026-05-07 20:30:52 +03:00
slprime 4ffd614017 GuiRecipe: Add scrollPages Option (#929) 2026-05-07 18:57:15 +03:00
slprime 41554f4c5b Options: fix memory leaks (#928) 2026-05-06 22:36:07 +02:00
slprime 2104184077 GuiInfo: fix memory leaks (#927) 2026-05-06 20:18:35 +02:00
slprime d5f25a4be8 Prevent ConcurrentModificationException while searching for fuels in ItemList (#926) 2026-05-06 19:43:50 +03:00
slprime ccbf94790a Add Horizontal Scroll to Recipe GUI (#924) 2026-05-06 19:31:00 +03:00
slprime 2f4f72a2d6 Fix Filter Loading (#925) 2026-05-06 07:55:49 +03:00
danyadevandslprime f8cec9a78c Much faster recipe dumper (#920)
Co-authored-by: slprime <[email protected]>
2026-04-25 14:58:50 +03:00
Lucaandslprime fb43a662eb Fix StringIndexOutOfBoundsException in FormattedTextField (#922)
Co-authored-by: slprime <[email protected]>
2026-04-25 10:30:32 +00:00
Luca b2e0b8878a Fix bookmark recipe item order being inconsistent (#921) 2026-04-25 13:21:46 +03:00
slprime 374f019103 Fix Autocrafting NPE (#917) 2026-04-14 01:29:26 +03:00
slprime 5dfcff6f30 Rollback PR#913 (#916) 2026-04-13 20:39:15 +03:00
slprime bd17301cb9 Fix Collapsed Recipes in Bookmarks (#915) 2026-04-13 15:41:30 +03:00
lc-1337 96ccd4e109 fix client -> server sync in creative gui (#913) 2026-04-12 14:47:27 +03:00
Kogepan229 b30ca57e68 Don't block slot click if canCheatItem is false (#912) 2026-04-08 18:35:08 +03:00
slprime 8f949bc1d1 Refactor recipe profiler (#911) 2026-04-07 13:10:39 +03:00
slprime d25365942a Fix Repair Handler with broken ItemStack (#910) 2026-04-06 21:35:47 +03:00
slprime eb58e1dabc Improve Recipe Badge (#909) 2026-04-06 20:39:41 +03:00
slprime f4601e7eed Disable badge by default (#907) 2026-04-04 21:12:05 +03:00
slprime ba48806667 Chance tooltip (#906) 2026-04-04 00:03:15 +03:00
Martin Robertz 70c332796a update+deps 2026-04-03 16:34:57 +02:00
slprime bcc25d4369 Fix Collapsed Recipes in Bookmarks (#905) 2026-03-31 20:47:23 +03:00
48 changed files with 954 additions and 362 deletions

No files matched your search

+2 -2
View File
@@ -1,8 +1,8 @@
// Add your dependencies here
dependencies {
api('com.github.GTNewHorizons:CodeChickenCore:1.4.10:dev')
devOnlyNonPublishable('com.github.GTNewHorizons:GTNHLib:0.9.13:dev')
api('com.github.GTNewHorizons:CodeChickenCore:1.4.12:dev')
devOnlyNonPublishable('com.github.GTNewHorizons:GTNHLib:0.9.47:dev')
shadowImplementation('org.apache.commons:commons-csv:1.10.0')
+8 -8
View File
@@ -1,12 +1,12 @@
#This file is generated by updateDaemonJvm
toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/c5ee947fbfb70bc347d8d531e3a578c4/redirect
toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/5ee463876563a46fff651cce1bc53a4c/redirect
toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/c5ee947fbfb70bc347d8d531e3a578c4/redirect
toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/5ee463876563a46fff651cce1bc53a4c/redirect
toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/e1118b4c7c2858d28154d086dbff010e/redirect
toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/1630f7ebef05444cb27a2709ea0249b3/redirect
toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/cd495626d2ee49a75447e3fdc6afb287/redirect
toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/1630f7ebef05444cb27a2709ea0249b3/redirect
toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/cd495626d2ee49a75447e3fdc6afb287/redirect
toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/d4fd992c9557644e637ebe98263e0ae7/redirect
toolchainUrl.MAC_OS.X86_64=https\://api.foojay.io/disco/v3.0/ids/faa12903720d410b387cc69ccafb1a74/redirect
toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/c5ee947fbfb70bc347d8d531e3a578c4/redirect
toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/5ee463876563a46fff651cce1bc53a4c/redirect
toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/1630f7ebef05444cb27a2709ea0249b3/redirect
toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/cd495626d2ee49a75447e3fdc6afb287/redirect
toolchainUrl.WINDOWS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/a4c09dd2e2d7079373d30e524bbc2829/redirect
toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/b96cb7670c095245220e7d01d5927b58/redirect
toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/8e1d9ee5d0f13e442218f6884a306da1/redirect
toolchainVersion=25
@@ -942,12 +942,14 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
if (slot != null) {
if (slot.getBookmarkItem().chance != PositionedStack.CHANCE_FULL) {
final String chanceText = NEIClientUtils
.formatChance(slot.getBookmarkItem().chance / (float) PositionedStack.CHANCE_FULL);
currenttip.add(
1,
EnumChatFormatting.DARK_GRAY + NEIClientUtils.translate(
"recipe.chance",
NEIClientUtils.formatNumber(
slot.getBookmarkItem().chance * 100f / PositionedStack.CHANCE_FULL)));
EnumChatFormatting.GRAY + NEIClientUtils.translate(
slot.getType() == BookmarkItemType.INGREDIENT ? "recipe.badge.chance.consume"
: "recipe.badge.chance.output",
chanceText));
}
if (slot.getType() == BookmarkItemType.INGREDIENT && slot.getRecipeId() != null
@@ -45,6 +45,7 @@ import codechicken.core.ClassDiscoverer;
import codechicken.core.ClientUtils;
import codechicken.lib.packet.PacketCustom;
import codechicken.nei.api.API;
import codechicken.nei.api.GuiInfo;
import codechicken.nei.api.IConfigureNEI;
import codechicken.nei.api.ItemInfo;
import codechicken.nei.guihook.GuiContainerManager;
@@ -374,6 +375,7 @@ public class ClientHandler {
} else if (event.gui == null) {
/* prevent WorldClient reference being held in the Gui */
NEIController.manager = null;
GuiInfo.clearGuiHandlers();
}
}
@@ -296,15 +296,26 @@ public class FormattedTextField extends GuiTextField {
int shift = 0;
for (int i = 0; i < position; i++) {
while (this.formattedText.length() > i + shift && this.formattedText.charAt(i + shift) == '\u00a7') {
while (this.formattedText.length() > i + shift + 1 && this.formattedText.charAt(i + shift) == '\u00a7'
&& isFormattingCode(this.formattedText.charAt(i + shift + 1))) {
shift += 2;
}
}
return position + shift;
return Math.min(position + shift, this.formattedText.length());
}
private static boolean isFormattingCode(char c) {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')
|| (c >= 'k' && c <= 'o')
|| c == 'r'
|| (c >= 'A' && c <= 'F')
|| (c >= 'K' && c <= 'O')
|| c == 'R';
}
private String getPreviousColor(int position) {
position = Math.min(position, this.formattedText.length() - 1);
while (position >= 0) {
if (this.formattedText.charAt(position) == '\u00a7') {
return this.formattedText.substring(position, position + 2);
@@ -73,6 +73,7 @@ public class IMCForNEI {
API.registerRecipeHandler(new ProfilerRecipeHandler(true));
API.registerUsageHandler(new ProfilerRecipeHandler(false));
sendProfilerRecipeHandler();
}
private static void sendHandler(String aName, String aBlock) {
@@ -136,6 +137,19 @@ public class IMCForNEI {
FMLInterModComms.sendMessage("NotEnoughItems", "registerHandlerInfo", aNBT);
}
private static void sendProfilerRecipeHandler() {
NBTTagCompound aNBT = new NBTTagCompound();
aNBT.setString("handler", "codechicken.nei.recipe.ProfilerRecipeHandler");
aNBT.setString("modName", "Not Enough Items");
aNBT.setString("modId", "nei");
aNBT.setString("itemName", "minecraft:clock");
aNBT.setInteger("handlerHeight", 16);
aNBT.setInteger("handlerWidth", 166);
aNBT.setBoolean("multipleWidgetsAllowed", true);
aNBT.setInteger("yShift", 0);
FMLInterModComms.sendMessage("NotEnoughItems", "registerHandlerInfo", aNBT);
}
private static void sendCatalyst(String aName, String aStack) {
NBTTagCompound aNBT = new NBTTagCompound();
aNBT.setString("handlerID", aName);
+3 -1
View File
@@ -251,7 +251,6 @@ public class ItemList {
private void updateOrdering(List<ItemStack> items) {
final Map<ItemStack, Integer> newOrdering = new HashMap<>();
ItemSorter.sort(items);
if (!CollapsibleItems.isEmpty()) {
final HashMap<Integer, Integer> groups = new HashMap<>();
@@ -424,6 +423,9 @@ public class ItemList {
}
}
if (interrupted()) return;
ItemSorter.sort(items);
if (interrupted()) return;
ItemList.items = items;
ItemList.itemMap = itemMap;
+18 -2
View File
@@ -15,6 +15,7 @@ import net.minecraft.client.shader.Framebuffer;
import net.minecraft.item.ItemStack;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL30;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.api.GuiInfo;
@@ -27,7 +28,7 @@ public abstract class ItemsGrid<T extends ItemsGrid.ItemsGridSlot, M extends Ite
protected static class ScreenCapture {
private long nextCacheRefresh = 0;
private Framebuffer framebuffer;
private final Framebuffer framebuffer;
public ScreenCapture() {
this.framebuffer = new Framebuffer(1, 1, true);
@@ -51,7 +52,7 @@ public abstract class ItemsGrid<T extends ItemsGrid.ItemsGridSlot, M extends Ite
}
public void captureScreen(Runnable callback, int mode) {
GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_LIGHTING_BIT);
GL11.glPushAttrib(GL11.GL_ENABLE_BIT);
resetFramebuffer();
this.framebuffer.bindFramebuffer(false);
@@ -84,6 +85,21 @@ public abstract class ItemsGrid<T extends ItemsGrid.ItemsGridSlot, M extends Ite
} else {
this.framebuffer.framebufferClear();
}
// Copy stencil values (required by mui2)
OpenGlHelper.func_153171_g(GL30.GL_READ_FRAMEBUFFER, minecraft.getFramebuffer().framebufferObject);
OpenGlHelper.func_153171_g(GL30.GL_DRAW_FRAMEBUFFER, this.framebuffer.framebufferObject);
GL30.glBlitFramebuffer(
0,
0,
minecraft.displayWidth,
minecraft.displayHeight,
0,
0,
minecraft.displayWidth,
minecraft.displayHeight,
GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_STENCIL_BUFFER_BIT,
GL11.GL_NEAREST);
}
public void renderCapturedScreen() {
@@ -263,12 +263,13 @@ public class NEIClientConfig {
.setComment("Require holding shift to move items when overlaying recipe").getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.guirecipe.shiftOverlayRecipe", true));
tag.getTag("inventory.guirecipe.scrollPages").setComment("Disable page scroll when overlaying recipe")
.getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.guirecipe.scrollPages", true));
tag.getTag("inventory.guirecipe.profile").getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.guirecipe.profile", true));
tag.getTag("inventory.guirecipe.chance").getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.guirecipe.chance", true));
tag.getTag("inventory.guirecipe.handlerInfo").setComment("ADVANCED: Handler Info Widget")
.getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.guirecipe.handlerInfo", true));
@@ -1143,10 +1144,6 @@ public class NEIClientConfig {
return getBooleanSetting("inventory.guirecipe.shiftOverlayRecipe");
}
public static boolean showRecipeItemChances() {
return getBooleanSetting("inventory.guirecipe.chance");
}
public static boolean isEnabled() {
return enabledOverride && getBooleanSetting("inventory.widgetsenabled");
}
@@ -95,6 +95,7 @@ public class NEIClientUtils extends NEIServerUtils {
/** Formats a number with group separator and at most 2 fraction digits. */
private static final Map<Locale, DecimalFormat> decimalFormatters = new HashMap<>();
private static final DecimalFormat CHANCE_FORMAT = new DecimalFormat("##0.##%");
public static final int ALT_HASH = NEIKeyboardUtils.ALT_HASH;
public static final int SHIFT_HASH = NEIKeyboardUtils.SHIFT_HASH;
@@ -144,6 +145,10 @@ public class NEIClientUtils extends NEIServerUtils {
return getDecimalFormat().format(aNumber) + " L";
}
public static String formatChance(float chance) {
return CHANCE_FORMAT.format(chance);
}
public static void deleteHeldItem() {
deleteSlotStack(-999);
}
@@ -1,6 +1,7 @@
package codechicken.nei;
import static codechicken.lib.gui.GuiDraw.getMousePosition;
import static codechicken.nei.NEIClientConfig.canCheatItem;
import java.awt.Point;
import java.util.LinkedList;
@@ -151,6 +152,8 @@ public class NEIController implements IContainerSlotClickHandler, IContainerInpu
&& slot != null
&& slot.getStack() != null
&& slot.isItemValid(slot.getStack())) {
if (!canCheatItem(slot.getStack())) return false;
NEIClientUtils.cheatItem(slot.getStack(), button, 1);
return true;
}
@@ -13,6 +13,7 @@ import net.minecraftforge.oredict.OreDictionary;
import codechicken.nei.api.ItemFilter;
import codechicken.nei.api.ItemInfo;
import codechicken.nei.recipe.Badge;
import codechicken.nei.recipe.GuiRecipe;
import codechicken.nei.recipe.StackInfo;
@@ -86,10 +87,18 @@ public class PositionedStack {
for (ItemStack item : items) if (item.stackSize > i) item.stackSize = i;
}
public List<Badge> getBadges() {
return null;
}
public int getChance() {
return this.chance;
}
public void setChance(int chance) {
this.chance = chance;
}
public PositionedStack copy() {
PositionedStack pStack = new PositionedStack(
Arrays.stream(this.items).map(ItemStack::copy).toArray(ItemStack[]::new),
@@ -97,7 +106,7 @@ public class PositionedStack {
rely,
false);
pStack.permutated = this.permutated;
pStack.chance = getChance();
pStack.chance = this.chance;
return pStack;
}
@@ -111,7 +111,7 @@ public class SearchTokenParser {
clearCache();
}
public void clearCache() {
public synchronized void clearCache() {
this.providersCache.clear();
this.filtersCache.clear();
this.recipesCache.clear();
@@ -5,6 +5,7 @@ import java.util.LinkedList;
import net.minecraft.world.World;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.config.GuiOptionList;
import codechicken.nei.config.OptionCycled;
public class NEIInfo {
@@ -13,7 +14,8 @@ public class NEIInfo {
public static void load(World world) {
OptionCycled modeOption = (OptionCycled) NEIClientConfig.getOptionList().getOption("inventory.cheatmode");
modeOption.parent.synthesizeEnvironment(false);
// kept alive so the WeakReference in Option.slotRef isn't GC'd before copyGlobals/cycle use it
GuiOptionList env = modeOption.parent.synthesizeEnvironment(false);
if (!modeOption.optionValid(modeOption.value())) {
modeOption.copyGlobals();
modeOption.cycle();
@@ -632,7 +632,8 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
&& group.crafting.calculatedItems.containsKey(itemIndex)
&& recipeId.equals(item.recipeId)) {
chainItems.add(
item.copyWithAmount(group.crafting.calculatedItems.get(itemIndex).getCalculatedAmount()));
item.copyWithMultiplier(
group.crafting.calculatedItems.get(itemIndex).getCalculatedMultiplier()));
} else {
chainItems.add(item.copy());
}
@@ -897,25 +898,35 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
}
public void addRecipe(Recipe recipe, int multiplier, int groupId) {
final ItemStackSet results = new ItemStackSet();
final ItemStackSet ingredients = new ItemStackSet();
final ItemStackSet seenResults = new ItemStackSet();
final ItemStackSet seenIngredients = new ItemStackSet();
final List<ItemStack> results = new ArrayList<>();
final List<ItemStack> ingredients = new ArrayList<>();
for (RecipeIngredient result : recipe.getResults()) {
results.add(result.getItemStack());
ItemStack stack = result.getItemStack();
if (!seenResults.contains(stack)) {
seenResults.add(stack);
results.add(stack);
}
}
for (RecipeIngredient ingr : recipe.getIngredients()) {
ingredients.add(ingr.getItemStack());
ItemStack stack = ingr.getItemStack();
if (!seenIngredients.contains(stack)) {
seenIngredients.add(stack);
ingredients.add(stack);
}
}
for (ItemStack stack : results.values()) {
for (ItemStack stack : results) {
this.addItem(
BookmarkItem.builder(groupId, stack, recipe, BookmarkItemType.RESULT).multiplier(multiplier)
.build(),
true);
}
for (ItemStack stack : ingredients.values()) {
for (ItemStack stack : ingredients) {
this.addItem(
BookmarkItem.builder(groupId, stack, recipe, BookmarkItemType.INGREDIENT).multiplier(multiplier)
.build(),
@@ -66,10 +66,14 @@ public class BookmarkGridGenerator {
while (itemIndex < size && absoluteSlotIndex != -1) {
final BookmarkItem bookmarkItem = this.grid.getBookmarkItem(itemIndex);
final BookmarkGroup group = this.grid.getGroup(bookmarkItem.groupId);
final boolean isCollapsedRecipeAnchor = group.crafting != null && bookmarkItem.recipeId != null
&& bookmarkItem.type != BookmarkItemType.INGREDIENT
&& group.collapsedRecipes.contains(bookmarkItem.recipeId);
if (group.crafting != null && (!group.crafting.calculatedItems.containsKey(itemIndex)
|| bookmarkItem.recipeId != null && !bookmarkItem.recipeId
.equals(group.crafting.itemToRecipe.getOrDefault(itemIndex, bookmarkItem.recipeId)))) {
if (group.crafting != null && !isCollapsedRecipeAnchor
&& (!group.crafting.calculatedItems.containsKey(itemIndex)
|| bookmarkItem.recipeId != null && !bookmarkItem.recipeId.equals(
group.crafting.itemToRecipe.getOrDefault(itemIndex, bookmarkItem.recipeId)))) {
itemIndex++;
} else if (group.collapsed) {
final List<Integer> results = getGroupResults(bookmarkItem.groupId, itemIndex, size);
@@ -318,7 +322,7 @@ public class BookmarkGridGenerator {
return group.crafting.calculatedItems.get(itemIndex);
} else {
BookmarkChainItem item = BookmarkChainItem.of(this.grid.getBookmarkItem(itemIndex));
item.setRealAmount(item.getShiftAmount());
item.setRealMultiplier(item.getCalculatedMultiplier());
return item;
}
}
@@ -331,7 +335,7 @@ public class BookmarkGridGenerator {
return new BookmarksGridSlot(
slotIndex,
itemIndex,
chainItem.getRealAmount(),
chainItem.getRealMultiplier(),
0,
0,
chainItem.getItem(),
@@ -341,9 +345,9 @@ public class BookmarkGridGenerator {
return new BookmarksGridSlot(
slotIndex,
itemIndex,
chainItem.getRealAmount(),
chainItem.getRealMultiplier(),
chainItem.getShiftAmount(),
chainItem.getCalculatedAmount(),
chainItem.getCalculatedMultiplier(),
chainItem.getItem(),
chainItem.calculatedType,
group);
@@ -80,6 +80,7 @@ public class BookmarkItem {
public BookmarkItem build() {
final Map<String, ItemStack> perms;
long multiplier = 0;
if (this.permutations != null) {
perms = this.permutations;
@@ -97,9 +98,15 @@ public class BookmarkItem {
perms = Builder.generatePermutations(this.stack);
}
if (this.multiplier >= 0) {
multiplier = this.multiplier;
} else if (this.factor > 0) {
multiplier = StackInfo.getAmount(this.stack) / this.factor;
}
return new BookmarkItem(
this.groupId,
this.multiplier >= 0 ? this.multiplier : StackInfo.getAmount(this.stack) / this.factor,
multiplier,
this.factor,
this.chance,
this.stack,
@@ -221,7 +228,7 @@ public class BookmarkItem {
for (RecipeIngredient res : items) {
if (res.contains(stack)) {
amount += res.getAmount() * res.getChance();
amount += 1L * res.getAmount() * res.getChance();
}
}
@@ -64,18 +64,18 @@ public class BookmarksGridSlot extends ItemsGridSlot {
protected final boolean isFirstOutput;
protected final int rowIndex;
public BookmarksGridSlot(int slotIndex, int itemIndex, long realAmount, long shiftAmount, long calculatedAmount,
BookmarkItem bookmarkItem, CalculatedType calculatedType, BookmarkGroup group) {
public BookmarksGridSlot(int slotIndex, int itemIndex, long realMultiplier, long shiftAmount,
long calculatedMultiplier, BookmarkItem bookmarkItem, CalculatedType calculatedType, BookmarkGroup group) {
super(
slotIndex,
itemIndex,
calculatedType != null ? bookmarkItem.getItemStack(calculatedAmount)
: bookmarkItem.getItemStack(realAmount));
calculatedType != null ? bookmarkItem.getItemStack(bookmarkItem.getAmount(calculatedMultiplier))
: bookmarkItem.getItemStack(bookmarkItem.getAmount(realMultiplier)));
this.emptyItemStack = bookmarkItem.getItemStack(0);
this.realAmount = realAmount;
this.realAmount = bookmarkItem.getAmount(realMultiplier);
this.shiftAmount = shiftAmount;
this.calculatedAmount = calculatedAmount;
this.calculatedAmount = calculatedType != null ? bookmarkItem.getAmount(calculatedMultiplier) : this.realAmount;
this.group = group;
this.calculatedType = calculatedType;
@@ -84,8 +84,8 @@ public class BookmarksGridSlot extends ItemsGridSlot {
this.isOutputRecipe = group.crafting != null && group.crafting.outputRecipes.contains(bookmarkItem.recipeId);
this.isFluidDisplay = StackInfo.itemStackToNBT(bookmarkItem.itemStack).hasKey("gtFluidName");
this.realMultiplier = bookmarkItem.getMultiplierFromAmount(realAmount);
this.calculatedMultiplier = bookmarkItem.getMultiplierFromAmount(calculatedAmount);
this.realMultiplier = realMultiplier;
this.calculatedMultiplier = calculatedMultiplier;
if (this.group.crafting != null && this.group.crafting.calculatedItems.containsKey(this.itemIndex)) {
this.realType = this.group.crafting.calculatedItems.get(this.itemIndex).calculatedType
@@ -348,15 +348,19 @@ public class BookmarksGridSlot extends ItemsGridSlot {
}
protected void drawStackSize(Rectangle4i rect, ShownItemType shownItemType) {
boolean drawChance = this.calculatedMultiplier > 0;
long amount = this.calculatedAmount;
if (shownItemType == null || shownItemType == ShownItemType.REAL || this.calculatedType == null) {
amount = this.realAmount;
drawChance = this.realMultiplier > 0;
} else if (shownItemType == ShownItemType.SHIFT) {
amount = this.shiftAmount;
drawChance = false;
}
if (amount > 0 || shownItemType == ShownItemType.REAL && !this.bookmarkItem.emptyFactor()) {
if (amount > 0 || this.bookmarkItem.chance != PositionedStack.CHANCE_FULL && drawChance
|| shownItemType == ShownItemType.REAL && !this.bookmarkItem.emptyFactor()) {
final float panelFactor = (rect.w - 2) / (DEFAULT_SLOT_SIZE - 2);
final long stackSize = this.bookmarkItem.getStackSize(amount);
int color = 0xFFFFFF;
@@ -42,27 +42,27 @@ public class RecipeChainDetails {
private final BookmarkItem item;
private long realAmount = 0L;
private long realMultiplier = 0L;
private long shiftAmount = 0L;
private long calculatedAmount = 0L;
private long calculatedMultiplier = 0L;
public CalculatedType calculatedType;
protected BookmarkChainItem(BookmarkItem item, long shiftItem, long calculatedItem,
protected BookmarkChainItem(BookmarkItem item, long shiftItem, long calculatedMultiplier,
CalculatedType calculatedType) {
this.item = item.copy();
this.shiftAmount = shiftItem;
this.calculatedAmount = calculatedItem;
this.calculatedMultiplier = calculatedMultiplier;
this.calculatedType = calculatedType;
}
public static BookmarkChainItem of(BookmarkItem item, long shiftItem, long calculatedAmount,
public static BookmarkChainItem of(BookmarkItem item, long shiftItem, long calculatedMultiplier,
CalculatedType calculatedType) {
return new BookmarkChainItem(item, shiftItem, calculatedAmount, calculatedType);
return new BookmarkChainItem(item, shiftItem, calculatedMultiplier, calculatedType);
}
public static BookmarkChainItem of(BookmarkItem item, long shiftItem, CalculatedType calculatedType) {
return new BookmarkChainItem(item, shiftItem, item.getAmount(), calculatedType);
return new BookmarkChainItem(item, shiftItem, item.getMultiplier(), calculatedType);
}
public static BookmarkChainItem of(BookmarkItem item) {
@@ -70,7 +70,7 @@ public class RecipeChainDetails {
return new BookmarkChainItem(
item,
amount,
amount,
item.getMultiplier(),
item.type == BookmarkItemType.INGREDIENT ? CalculatedType.INGREDIENT : CalculatedType.RESULT);
}
@@ -78,30 +78,34 @@ public class RecipeChainDetails {
return this.item.getItemStack(amount);
}
public void setRealAmount(long amount) {
this.realAmount = amount;
public void setRealMultiplier(long multiplier) {
this.realMultiplier = multiplier;
}
public long getRealAmount() {
return this.realAmount;
public long getRealMultiplier() {
return this.realMultiplier;
}
public void setCalculatedMultiplier(long multiplier) {
this.calculatedMultiplier = multiplier;
}
public long getCalculatedMultiplier() {
return this.calculatedMultiplier;
}
public long getShiftAmount() {
return this.shiftAmount;
}
public long getCalculatedAmount() {
return this.calculatedAmount;
}
public BookmarkItem getItem() {
return this.item;
}
public void append(long amount, long calculatedAmount) {
this.shiftAmount += amount;
this.calculatedAmount += calculatedAmount;
this.item.multiplier = this.item.getMultiplierFromAmount(this.calculatedAmount);
this.calculatedMultiplier += this.item.getMultiplierFromAmount(calculatedAmount);
this.item.multiplier = this.calculatedMultiplier;
}
}
@@ -181,10 +185,9 @@ public class RecipeChainDetails {
if (itemIndex >= 0 && this.calculatedItems.containsKey(itemIndex)) {
final BookmarkItem item = entry.getValue();
if (this.recipeInMiddle.contains(item.recipeId)) {
this.calculatedItems.get(itemIndex)
.setRealAmount(Math.max(0, item.getAmount(item.getMultiplier() - 1)));
this.calculatedItems.get(itemIndex).setRealMultiplier(Math.max(0, item.getMultiplier() - 1));
} else {
this.calculatedItems.get(itemIndex).setRealAmount(item.getAmount());
this.calculatedItems.get(itemIndex).setRealMultiplier(item.getMultiplier());
}
}
}
@@ -259,7 +262,8 @@ public class RecipeChainDetails {
}
if (this.calculatedItems.containsKey(itemIndex)) {
this.calculatedItems.get(itemIndex).setRealAmount(value.getShiftAmount());
this.calculatedItems.get(itemIndex)
.setRealMultiplier(value.getItem().getMultiplierFromAmount(value.getShiftAmount()));
}
}
@@ -284,7 +288,8 @@ public class RecipeChainDetails {
} else if (amount > 0) {
items.computeIfAbsent(
StackInfo.getItemStackGUID(item.itemStack),
is -> BookmarkChainItem.of(item, 0, 0, CalculatedType.RESULT)).append(amount, amount);
is -> BookmarkChainItem.of(item, 0, 0, CalculatedType.RESULT))
.append(amount, item.getAmount());
}
}
}
@@ -8,13 +8,15 @@ import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import net.minecraft.command.CommandBase;
@@ -39,6 +41,7 @@ import codechicken.nei.recipe.GuiRecipeTab;
import codechicken.nei.recipe.ICraftingHandler;
import codechicken.nei.recipe.Recipe;
import codechicken.nei.recipe.RecipeHandlerQuery;
import codechicken.nei.recipe.TemplateRecipeHandler;
import codechicken.nei.util.NBTJson;
public class CommandRecipeId extends CommandBase {
@@ -125,12 +128,16 @@ public class CommandRecipeId extends CommandBase {
private ArrayList<ICraftingHandler> craftinghandlers = new ArrayList<>();
private ArrayList<ICraftingHandler> serialCraftingHandlers = new ArrayList<>();
protected final ICommandSender sender;
protected final File currFile;
protected final boolean fastDump;
public ProcessDumpThread(ICommandSender sender, File currFile) {
public ProcessDumpThread(ICommandSender sender, File currFile, boolean fastDump) {
this.sender = sender;
this.currFile = currFile;
this.fastDump = fastDump;
ClientHandler.loadSettingsFile("recipeidblacklist.cfg", lines -> {
final Set<String> names = lines.collect(Collectors.toSet());
@@ -150,38 +157,10 @@ public class CommandRecipeId extends CommandBase {
sendChatInfoMessage(sender, "nei.chat.recipeid.dump.start");
try (BufferedWriter writer = Files.newBufferedWriter(currFile.toPath(), StandardCharsets.UTF_8)) {
int total = ItemList.items.size();
int count = 0;
for (ItemStack stack : ItemList.items) {
if (count % 1000 == 0) {
NEIClientConfig.logger.info(
"({}/{}). Processing {} crafting recipes...",
count,
total,
stack.getDisplayName());
}
count++;
for (ICraftingHandler handler : getCraftingHandlers(stack)) {
for (int index = 0, num = handler.numRecipes(); index < num; index++) {
try {
final Recipe recipe = Recipe.of(handler, index);
if (!recipe.getIngredients().isEmpty() && !recipe.getResults().isEmpty()) {
writer.write(NBTJson.toJson(recipe.getRecipeId().toJsonObject()));
writer.newLine();
}
} catch (Exception ex) {
NEIClientConfig.logger.error(
"Found Broken RecipeId {}:{}",
GuiRecipeTab.getHandlerInfo(handler).getHandlerName(),
stack,
ex);
}
}
}
if (fastDump) {
processFastDump(writer);
} else {
processDump(writer);
}
} catch (Exception e) {
@@ -192,15 +171,118 @@ public class CommandRecipeId extends CommandBase {
sendChatInfoMessage(sender, "nei.chat.recipeid.dump.finish");
}
/**
* + technically more reliable and supports some weird handlers
* <p>
* - very very very slow, took 1 hour to get a dump in GTNH on M1 in background
* <p>
* - generates a lot of duplicates, up to 75% of file size is duplicates (and it's 300mb out of 400mb...)
*/
private void processDump(BufferedWriter writer) throws IOException {
final int total = ItemList.items.size();
int count = 0;
for (ItemStack stack : ItemList.items) {
if (count % 1000 == 0) {
NEIClientConfig.logger
.info("({}/{}). Processing {} crafting recipes...", count, total, stack.getDisplayName());
}
count++;
for (ICraftingHandler handler : getCraftingHandlers(stack)) {
writeLines(writer, collectRecipeLines(handler, stack.toString()));
}
}
}
/**
* - may skip some handlers if they're not TemplateRecipeHandler / just weird ones (like gendustry handlers)
* <p>
* + but in terms of GT recipes everything is dumped, and surprisingly it catches even more GT recipes than the
* regular dumper (in particular, it has a lot of new hammer, extruder, blast furnace, etc. recipes)
* <p>
* + way faster, took like 2.5 minutes
* <p>
* + doesn't have nearly as many duplicates, but something can still slip in, for example from
* FuelRecipeHandler. The dump has a size of only 100 MB instead of 400 MB from the regular dumper
*/
private void processFastDump(BufferedWriter writer) throws IOException {
final ArrayList<ICraftingHandler> handlers = getCraftingHandlers();
final int total = handlers.size();
final AtomicInteger count = new AtomicInteger();
try {
final List<List<String>> linesByHandler = ItemList.forkJoinPool.submit(() -> {
return handlers.parallelStream().map(handler -> {
final String handlerName = GuiRecipeTab.getHandlerInfo(handler).getHandlerName();
final List<String> lines = collectRecipeLines(handler, handlerName);
final int current = count.incrementAndGet();
NEIClientConfig.logger
.info("({}/{}). Processed {} handler recipes.", current, total, handlerName);
return lines;
}).collect(Collectors.toList());
}).get();
for (List<String> lines : linesByHandler) {
writeLines(writer, lines);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("Interrupted while dumping RecipeId", e);
} catch (ExecutionException e) {
throw new IOException("Error while dumping RecipeId", e);
}
}
private List<String> collectRecipeLines(ICraftingHandler handler, String context) {
final List<String> lines = new ArrayList<>(handler.numRecipes());
for (int index = 0, num = handler.numRecipes(); index < num; index++) {
try {
final Recipe recipe = Recipe.of(handler, index);
if (!recipe.getIngredients().isEmpty() && !recipe.getResults().isEmpty()) {
lines.add(NBTJson.toJson(recipe.getRecipeId().toJsonObject()));
}
} catch (Exception ex) {
NEIClientConfig.logger.error(
"Found Broken RecipeId {}:{}",
GuiRecipeTab.getHandlerInfo(handler).getHandlerName(),
context,
ex);
}
}
return lines;
}
private void writeLines(BufferedWriter writer, List<String> lines) throws IOException {
for (String line : lines) {
writer.write(line);
writer.newLine();
}
}
private ArrayList<ICraftingHandler> getCraftingHandlers(Object... results) {
return new RecipeHandlerQuery<>(
h -> h.getRecipeHandler("item", results),
handler -> handler.getRecipeHandler("item", results),
this.craftinghandlers,
this.serialCraftingHandlers,
"Error while looking up crafting recipe",
"outputId: item",
"results: " + Arrays.toString(results))
.runWithProfiling(NEIClientUtils.translate("recipe.concurrent.crafting"));
"outputId: item").runWithProfiling(NEIClientUtils.translate("recipe.concurrent.crafting"));
}
private ArrayList<ICraftingHandler> getCraftingHandlers() {
return new RecipeHandlerQuery<>(handler -> {
if (handler instanceof TemplateRecipeHandler templateHandler) {
return templateHandler.getAllRecipeHandler();
}
return handler.getRecipeHandler("all");
},
this.craftinghandlers,
this.serialCraftingHandlers,
"Error while looking up crafting recipe",
"outputId: all").runWithProfiling(NEIClientUtils.translate("recipe.concurrent.crafting"));
}
}
@@ -212,7 +294,7 @@ public class CommandRecipeId extends CommandBase {
@Override
public String getCommandUsage(ICommandSender sender) {
return "/recipeid dump <filename> OR /recipeid diff <prev-filename> <curr-filename> [subset name]";
return "/recipeid [dump|fast-dump] <filename> OR /recipeid diff <prev-filename> <curr-filename> <subset name>";
}
@Override
@@ -220,12 +302,27 @@ public class CommandRecipeId extends CommandBase {
return 0;
}
@Override
public List<String> addTabCompletionOptions(ICommandSender sender, String[] args) {
if (args.length == 1) {
return getListOfStringsMatchingLastWord(args, "dump", "fast-dump", "diff");
}
if ("diff".equals(args[0]) && (args.length == 2 || args.length == 3)) {
return getListOfStringsMatchingLastWord(args, getRecipeIdFilenames());
}
return Collections.emptyList();
}
@Override
public void processCommand(ICommandSender sender, String[] args) {
final String command = args.length == 0 ? null : args[0];
if ("dump".equals(command)) {
processDumpCommand(sender, args);
processDumpCommand(sender, args, false);
} else if ("fast-dump".equals(command)) {
processDumpCommand(sender, args, true);
} else if ("diff".equals(command)) {
processDiffCommand(sender, args);
} else {
@@ -263,7 +360,7 @@ public class CommandRecipeId extends CommandBase {
(new ProcessDiffThread(sender, prevFilename, currFilename, diffFilename)).start();
}
protected void processDumpCommand(ICommandSender sender, String[] args) {
protected void processDumpCommand(ICommandSender sender, String[] args, boolean fastDump) {
if (args.length > 2) {
sendChatErrorMessage(sender, "nei.chat.recipeid.many_params", getCommandUsage(sender));
@@ -274,13 +371,30 @@ public class CommandRecipeId extends CommandBase {
final String currFilename = args.length == 2 ? args[1] : "recipeId";
if (!dir.exists()) dir.mkdirs();
(new ProcessDumpThread(sender, getFile(currFilename))).start();
(new ProcessDumpThread(sender, getFile(currFilename), fastDump)).start();
}
private static File getFile(String filename) {
return new File(CommonUtils.getMinecraftDir(), "recipeid/" + filename + ".json");
}
private static String[] getRecipeIdFilenames() {
final File dir = new File(CommonUtils.getMinecraftDir(), "recipeid");
final File[] files = dir.listFiles((currentDir, name) -> name.endsWith(".json"));
if (files == null || files.length == 0) {
return new String[] {};
}
final String[] names = new String[files.length];
for (int i = 0; i < files.length; i++) {
final String name = files[i].getName();
names[i] = name.substring(0, name.length() - ".json".length());
}
return names;
}
private static void sendChatInfoMessage(ICommandSender sender, String translationKey, Object... args) {
sender.addChatMessage(
new ChatComponentTranslation(translationKey, args)
@@ -93,7 +93,7 @@ public abstract class DataDumper extends Option {
public Rectangle4i dumpButtonSize() {
int width = 80;
return new Rectangle4i(slot.slotWidth() - width, 0, width, 20);
return new Rectangle4i(getSlot().slotWidth() - width, 0, width, 20);
}
public Rectangle4i modeButtonSize() {
@@ -64,7 +64,7 @@ public class GuiHighlightTips extends GuiScreenWidget {
@Override
public void keyTyped(char c, int keycode) {
if (keycode == Keyboard.KEY_ESCAPE || keycode == Keyboard.KEY_BACK) {
Minecraft.getMinecraft().displayGuiScreen(opt.slot.getGui());
Minecraft.getMinecraft().displayGuiScreen(opt.getSlot().getGui());
return;
}
super.keyTyped(c, keycode);
@@ -62,7 +62,7 @@ public class GuiItemIconDumper extends GuiScreen {
}
private void returnScreen(IChatComponent msg) {
Minecraft.getMinecraft().displayGuiScreen(opt.slot.getGui());
Minecraft.getMinecraft().displayGuiScreen(opt.getSlot().getGui());
NEIClientUtils.printChatMessage(msg);
}
@@ -98,7 +98,7 @@ public class GuiItemSorter extends GuiOptionPane {
@Override
public GuiScreen getParentScreen() {
return opt.slot.getGui();
return opt.getSlot().getGui();
}
@Override
@@ -247,7 +247,7 @@ public class GuiPanelSettings extends GuiScreenWidget {
public void keyTyped(char c, int keycode) {
if (keycode == Keyboard.KEY_ESCAPE || keycode == Keyboard.KEY_BACK) {
Minecraft.getMinecraft().displayGuiScreen(opt.slot.getGui());
Minecraft.getMinecraft().displayGuiScreen(opt.getSlot().getGui());
return;
}
@@ -99,10 +99,12 @@ public class IMCHandler {
NEIClientConfig.logger.info("Error setting handler dimensions for {}", handler);
}
// true if not set to false
info.setUseCustomScroll(tag.hasKey("useCustomScroll") && tag.getBoolean("useCustomScroll"));
final boolean allowOverflow = tag.hasKey("useCustomScroll") && tag.getBoolean("useCustomScroll");
info.setAllowOverflowX(tag.hasKey("allowOverflowX") ? tag.getBoolean("allowOverflowX") : true);
info.setAllowOverflowY(tag.hasKey("allowOverflowY") ? tag.getBoolean("allowOverflowY") : allowOverflow);
info.setShowFavoritesButton(!tag.hasKey("showFavoritesButton") || tag.getBoolean("showFavoritesButton"));
info.setShowOverlayButton(!tag.hasKey("showOverlayButton") || tag.getBoolean("showOverlayButton"));
info.setShowBadge(tag.hasKey("showBadge") && tag.getBoolean("showBadge"));
GuiRecipeTab.handlerAdderFromIMC.remove(handler);
GuiRecipeTab.handlerAdderFromIMC.put(handler, info);
@@ -1,5 +1,6 @@
package codechicken.nei.config;
import java.lang.ref.WeakReference;
import java.util.List;
import net.minecraft.client.Minecraft;
@@ -17,7 +18,11 @@ public abstract class Option {
.playSound(PositionedSoundRecord.func_147674_a(new ResourceLocation("gui.button.press"), 1.0F));
}
public OptionScrollSlot slot;
private WeakReference<OptionScrollSlot> slotRef;
public OptionScrollSlot getSlot() {
return slotRef != null ? slotRef.get() : null;
}
public String namespace = null;
public final String name;
@@ -134,7 +139,7 @@ public abstract class Option {
* @return true if the gui is in world config mode
*/
public boolean worldConfig() {
return slot.getGui().worldConfig();
return getSlot().getGui().worldConfig();
}
/**
@@ -189,7 +194,7 @@ public abstract class Option {
}
public void onAdded(OptionScrollSlot slot) {
this.slot = slot;
this.slotRef = new WeakReference<>(slot);
}
public void onAdded(OptionList list) {
@@ -57,10 +57,10 @@ public abstract class OptionButton extends Option {
}
public Rectangle buttonSize() {
if (getPrefix() == null) return new Rectangle(0, 0, slot.slotWidth(), 20);
if (getPrefix() == null) return new Rectangle(0, 0, getSlot().slotWidth(), 20);
int width = Math.max(60, getStringWidth(getButtonText()) + 8);
return new Rectangle(slot.slotWidth() - width, 0, width, 20);
return new Rectangle(getSlot().slotWidth() - width, 0, width, 20);
}
public String getPrefix() {
@@ -85,7 +85,7 @@ public class OptionKeyBind extends OptionButton {
return false;
}
for (Option o : slot.options) {
for (Option o : getSlot().options) {
if (o instanceof OptionKeyBind && o != this && ((OptionKeyBind) o).getValue() == keyboard) {
return true;
}
@@ -131,13 +131,15 @@ public class OptionList extends OptionButton {
/**
* Adds this option to a temporary slot and gui for internal setting manipulation.
*/
public void synthesizeEnvironment(boolean world) {
getGui(null, this, world).addWidgets();
public GuiOptionList synthesizeEnvironment(boolean world) {
GuiOptionList gui = getGui(null, this, world);
gui.addWidgets();
return gui;
}
@Override
public boolean onClick(int button) {
openGui(slot.getGui(), slot.getGui().worldConfig());
openGui(getSlot().getGui(), getSlot().getGui().worldConfig());
return true;
}
@@ -131,6 +131,6 @@ public abstract class OptionStringSet extends Option {
}
public int buttonX() {
return slot.slotWidth() - (24 * options.size() - 4);
return getSlot().slotWidth() - (24 * options.size() - 4);
}
}
@@ -53,7 +53,7 @@ public class OptionTextField extends Option {
}
protected int getMaxInputWidth() {
return slot.slotWidth();
return getSlot().slotWidth();
}
public boolean isEnabled() {
@@ -64,9 +64,10 @@ public class OptionTextField extends Option {
public void draw(int mousex, int mousey, float frame) {
GuiDraw.drawString(getPrefix(), 10, 6, -1);
textField.w = Math
.max(60, Math.min(getMaxInputWidth(), slot.slotWidth() - GuiDraw.getStringWidth(getPrefix())) - 16);
textField.x = slot.slotWidth() - textField.w;
textField.w = Math.max(
60,
Math.min(getMaxInputWidth(), getSlot().slotWidth() - GuiDraw.getStringWidth(getPrefix())) - 16);
textField.x = getSlot().slotWidth() - textField.w;
textField.draw(mousex, mousey);
}
@@ -253,7 +253,7 @@ public class GuiPresetList extends GuiOptionPane {
@Override
public GuiScreen getParentScreen() {
return opt.slot.getGui();
return opt.getSlot().getGui();
}
@Override
@@ -0,0 +1,98 @@
package codechicken.nei.recipe;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import net.minecraft.util.EnumChatFormatting;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.NEIClientUtils.Alignment;
public class Badge {
protected final String text;
protected final List<String> tooltip;
protected int badgeTextColor = 0xFDD835;
protected boolean shadow = false;
protected Alignment alignment = Alignment.TopLeft;
public Badge(String text, String... tooltip) {
this.text = text;
this.tooltip = Arrays.stream(tooltip).map(t -> EnumChatFormatting.GRAY + t).collect(Collectors.toList());
this.badgeTextColor = getHexValue(
NEIClientUtils.getTextColorOrDefault("recipe.badge.color", "0xFDD835"),
0xFDD835);
}
public String getText() {
return this.text;
}
public List<String> getTooltip() {
return this.tooltip;
}
public Badge setColor(int color) {
this.badgeTextColor = color;
return this;
}
public int getColor() {
return this.badgeTextColor;
}
public Badge setShadow(boolean shadow) {
this.shadow = shadow;
return this;
}
public boolean hasShadow() {
return this.shadow;
}
public Badge setAlignment(Alignment alignment) {
this.alignment = alignment;
return this;
}
public Alignment getAlignment() {
return this.alignment;
}
private static int getHexValue(String color, int defaultValue) {
try {
return (int) Long.parseLong(color.replace("0x", ""), 16);
} catch (NumberFormatException e) {
return defaultValue;
}
}
public void draw(Rectangle4i rect) {
NEIClientUtils.drawNEIOverlayText(getText(), rect, 0.5f, getColor(), hasShadow(), getAlignment());
}
public static Badge notConsumed() {
return new Badge(
NEIClientUtils.translate("recipe.badge.nc"),
NEIClientUtils.translate("recipe.badge.nc.tooltip"));
}
public static Badge notConsumedParallel() {
return new Badge(
NEIClientUtils.translate("recipe.badge.ncp"),
NEIClientUtils.translate("recipe.badge.ncp.tooltip"));
}
public static Badge consumeChance(float chance) {
final String chanceText = NEIClientUtils.formatChance(chance);
return new Badge(chanceText, NEIClientUtils.translate("recipe.badge.chance.consume", chanceText));
}
public static Badge outputChance(float chance) {
final String chanceText = NEIClientUtils.formatChance(chance);
return new Badge(chanceText, NEIClientUtils.translate("recipe.badge.chance.output", chanceText));
}
}
@@ -21,7 +21,6 @@ import codechicken.nei.NEIClientUtils;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.bookmark.BookmarksGridSlot;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.recipe.TemplateRecipeHandler.RecipeTransferRect;
public class GuiCraftingRecipe extends GuiRecipe<ICraftingHandler> {
@@ -103,18 +102,7 @@ public class GuiCraftingRecipe extends GuiRecipe<ICraftingHandler> {
private static ICraftingHandler buildAllRecipesHandler(ICraftingHandler handler) {
if (handler instanceof TemplateRecipeHandler templateHandler) {
TemplateRecipeHandler allHandler = templateHandler.newInstance();
if (allHandler.transferRects.isEmpty()) {
allHandler.loadCraftingRecipes("all");
return allHandler;
}
for (RecipeTransferRect rect : allHandler.transferRects) {
if (allHandler.specifyTransferRect() == null
|| allHandler.specifyTransferRect().equals(rect.outputId)) {
allHandler.loadCraftingRecipes(rect.outputId, rect.results);
return allHandler;
}
}
return templateHandler.getAllRecipeHandler();
}
return handler.getRecipeHandler("all");
}
@@ -92,6 +92,9 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
private GuiButton prevtype;
private GuiButton nexttype;
private Rectangle typeArea = new Rectangle();
private Rectangle pageArea = new Rectangle();
private int lastPage = -1;
private final GuiRecipeTabs recipeTabs;
private final GuiRecipeCatalyst recipeCatalyst;
@@ -308,7 +311,7 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
@Override
public Widget getWidgetUnderMouse(int mousex, int mousey) {
if (handlerInfo.getUseCustomScroll() && !this.widgets.isEmpty()) {
if (handlerInfo.isAllowOverflowY() && !this.widgets.isEmpty()) {
return this.widgets.get(0);
}
@@ -346,7 +349,7 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
this.container.x = this.guiLeft + 3;
this.container.y = this.guiTop + 32;
this.container.h = this.ySize - 32 - 5;
this.container.h = this.ySize - 32 - 4;
GuiRecipe.toggleSearch.icon = new DrawableBuilder("nei:textures/nei_sprites.png", 0, 76, 10, 10).build();
GuiRecipe.toggleSearch.w = GuiRecipe.toggleSearch.h = 12;
@@ -358,8 +361,18 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
GuiRecipe.searchField.w = this.xSize - (BORDER_PADDING + BUTTON_WIDTH) * 2 + 1 - GuiRecipe.toggleSearch.w - 45;
GuiRecipe.searchField.h = 14;
this.buttonList.addAll(Arrays.asList(this.prevtype, this.nexttype, this.prevpage, this.nextpage));
this.typeArea.setBounds(
this.prevtype.xPosition + BUTTON_WIDTH,
this.prevtype.yPosition,
this.nexttype.xPosition - this.prevtype.xPosition - BUTTON_WIDTH - 1,
BUTTON_HEIGHT);
this.pageArea.setBounds(
this.prevpage.xPosition + BUTTON_WIDTH,
this.prevpage.yPosition,
this.nextpage.xPosition - this.prevpage.xPosition - BUTTON_WIDTH - 1,
BUTTON_HEIGHT);
this.buttonList.addAll(Arrays.asList(this.prevtype, this.nexttype, this.prevpage, this.nextpage));
if (this.currenthandlers.size() == 1) {
this.prevtype.visible = false;
this.nexttype.visible = false;
@@ -372,9 +385,19 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
if (this.handlerPages.rebuildPages() || this.lastPage != this.handlerPages.getCurrentPageIndex()) {
this.lastPage = this.handlerPages.getCurrentPageIndex();
updateContainerSize();
this.container.setWidgets(this.handlerPages.getCurrentPageWidgets());
if (this.handlerInfo.getUseCustomScroll()) {
if (!this.handlerInfo.isAllowOverflowX() && this.handlerInfo.getWidth() > this.xSize - 6) {
this.container.setPaddingInline(0, 2);
this.container.setHorizontalScroll(ScrollBar.defaultHorizontalBar().setTrackPadding(1, 0, 1, 0));
} else {
this.container.setPaddingInline(0, 0);
this.container.setHorizontalScroll(null);
}
if (this.handlerInfo.isAllowOverflowY()) {
this.container.setVerticalScroll(null);
} else if (this.container.w == this.xSize - 6) {
this.container.setVerticalScroll(VERTICAL_SCROLLBAR);
@@ -416,7 +439,7 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
this.recipetype = (this.currenthandlers.size() + idx) % this.currenthandlers.size();
this.handler = new SearchRecipeHandler<>(this.currenthandlers.get(this.recipetype));
this.handlerInfo = GuiRecipeTab.getHandlerInfo(this.handler.original);
this.container.w = Math.max(this.xSize - 6, this.handlerInfo.getWidth());
updateContainerSize();
this.handlerPages = new RecipePageManager(this.handler, this.handlerInfo, this.container);
this.prevpage.enabled = this.nextpage.enabled = this.handlerPages.getNumPages() > 1;
this.lastPage = -1;
@@ -426,9 +449,21 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
GuiRecipe.toggleSearch.state = 0;
this.container.setVerticalScrollOffset(0);
this.container.setHorizontalScrollOffset(0);
this.recipeTabs.update(this);
}
private void updateContainerSize() {
final int width = this.xSize - 6;
this.container.w = Math.max(width, this.handlerInfo.getWidth());
this.container.h = this.ySize - 32 - 4;
if (!this.handlerInfo.isAllowOverflowX() && this.handlerInfo.getWidth() > width) {
this.container.w = width;
this.container.h -= 8;
}
}
public int openTargetRecipe(RecipeId recipeId) {
int refIndex = -1;
int recipetype = 0;
@@ -671,7 +706,7 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
// If shift is held, try switching to the next recipe handler. Replicates the
// GuiRecipeTabs.mouseScrolled()
// without the checking for the cursor being inside the tabbar.
if (NEIClientUtils.shiftKey()) {
if (NEIClientUtils.shiftKey() || this.typeArea.contains(mouse)) {
if (scroll < 0) {
nextType();
} else {
@@ -683,7 +718,12 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
// Finally, if nothing else has handled scrolling, try changing to the next
// recipe page.
if (new Rectangle(this.guiLeft, this.guiTop, this.xSize, this.ySize).contains(mouse)) {
if (NEIClientConfig.getBooleanSetting("inventory.guirecipe.scrollPages")
&& this.container.boundsInside().contains(mouse.x, mouse.y)
|| this.pageArea.contains(mouse)
&& (!this.handler.searchingAvailable() || !GuiRecipe.toggleSearch.contains(mouse.x, mouse.y))
&& (!GuiRecipe.searchField.isVisible() || !GuiRecipe.searchField.contains(mouse.x, mouse.y))) {
if (scroll > 0) {
prevPage();
} else {
@@ -825,16 +865,16 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
final int textMiddle = (BUTTON_WIDTH - this.fontRendererObj.FONT_HEIGHT) / 2;
drawRect(
this.prevtype.xPosition + BUTTON_WIDTH - 1,
this.prevtype.yPosition,
this.nexttype.xPosition,
this.prevtype.yPosition + BUTTON_HEIGHT,
this.typeArea.x,
this.typeArea.y,
this.typeArea.x + this.typeArea.width,
this.typeArea.y + this.typeArea.height,
0x30000000);
drawRect(
this.prevpage.xPosition + BUTTON_WIDTH - 1,
this.prevpage.yPosition,
this.nextpage.xPosition,
this.prevpage.yPosition + BUTTON_HEIGHT,
this.pageArea.x,
this.pageArea.y,
this.pageArea.x + this.pageArea.width,
this.pageArea.y + this.pageArea.height,
0x30000000);
final String handlerTitle = this.handler.original.getRecipeName().trim();
@@ -843,7 +883,7 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
this.fontRendererObj,
titleColorCode + handlerTitle + EnumChatFormatting.RESET,
this.guiLeft + this.xSize / 2,
this.prevtype.yPosition + textMiddle,
this.typeArea.y + textMiddle,
0xffffff);
if (this.handler.searchingAvailable()) {
@@ -866,7 +906,7 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
this.fontRendererObj,
recipePage,
GuiRecipe.searchField.x + GuiRecipe.searchField.w + 22,
this.prevpage.yPosition + textMiddle,
this.pageArea.y + textMiddle,
0xffffff);
} else {
final String recipePage = NEIClientUtils.translate(
@@ -877,7 +917,7 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
this.fontRendererObj,
recipePage,
this.guiLeft + this.xSize / 2,
this.prevpage.yPosition + textMiddle,
this.pageArea.y + textMiddle,
0xffffff);
}
@@ -23,12 +23,12 @@ import net.minecraftforge.common.MinecraftForge;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.Widget;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.event.NEIRegisterHandlerInfosEvent;
@@ -139,18 +139,16 @@ public abstract class GuiRecipeTab extends Widget {
public void addTooltips(List<String> tooltip) {
tooltip.add(handler.getRecipeTabName().trim());
String handlerMod = getHandlerMod(handlerName, handlerID);
tooltip.add(EnumChatFormatting.BLUE + handlerMod);
boolean shiftHeld = Keyboard.getEventKeyState()
&& (Keyboard.getEventKey() == Keyboard.KEY_LSHIFT || Keyboard.getEventKey() == Keyboard.KEY_RSHIFT);
if (handlerMod.equals("Unknown") || shiftHeld) {
if (handlerMod.equals("Unknown") || NEIClientUtils.shiftKey()) {
tooltip.add("");
tooltip.add("HandlerName: " + handlerName);
tooltip.add("HandlerID: " + handlerID);
tooltip.add("HandlerOrder: " + NEIClientConfig.getHandlerOrder(handler));
tooltip.add(EnumChatFormatting.GRAY + "HandlerName: " + handlerName);
tooltip.add(EnumChatFormatting.GRAY + "HandlerID: " + handlerID);
tooltip.add(EnumChatFormatting.GRAY + "HandlerOrder: " + NEIClientConfig.getHandlerOrder(handler));
}
tooltip.add(EnumChatFormatting.BLUE + handlerMod);
}
public abstract boolean onButtonPress(boolean rightclick);
@@ -265,8 +263,13 @@ public abstract class GuiRecipeTab extends Widget {
NEIClientConfig.logger.info("Error setting handler dimensions for " + handler);
}
info.setUseCustomScroll(
record.isSet("useCustomScroll") ? Boolean.parseBoolean(record.get("useCustomScroll")) : false);
final boolean allowOverflow = record.isSet("useCustomScroll")
&& Boolean.parseBoolean(record.get("useCustomScroll"));
info.setAllowOverflowX(
record.isSet("allowOverflowX") ? Boolean.parseBoolean(record.get("allowOverflowX")) : true);
info.setAllowOverflowY(
record.isSet("allowOverflowY") ? Boolean.parseBoolean(record.get("allowOverflowY"))
: allowOverflow);
handlerMap.put(handler, info);
NEIClientConfig.logger.info("Loaded " + handler);
}
@@ -30,7 +30,10 @@ public class HandlerInfo {
private boolean multipleWidgetsAllowed = false;
private boolean showFavoritesButton = true;
private boolean showOverlayButton = true;
private boolean useCustomScroll = false;
private boolean showBadge = false;
private boolean allowOverflowX = true;
private boolean allowOverflowY = false;
private ItemStack itemStack = null;
private DrawableResource image = null;
@@ -142,12 +145,34 @@ public class HandlerInfo {
this.showOverlayButton = showOverlayButton;
}
public boolean getUseCustomScroll() {
return this.useCustomScroll;
public boolean getShowBadge() {
return this.showBadge;
}
public void setShowBadge(boolean showBadge) {
this.showBadge = showBadge;
}
@Deprecated
public void setUseCustomScroll(boolean useCustomScroll) {
this.useCustomScroll = useCustomScroll;
this.allowOverflowX = useCustomScroll;
this.allowOverflowY = useCustomScroll;
}
public boolean isAllowOverflowX() {
return this.allowOverflowX;
}
public void setAllowOverflowX(boolean allowOverflowX) {
this.allowOverflowX = allowOverflowX;
}
public boolean isAllowOverflowY() {
return this.allowOverflowY;
}
public void setAllowOverflowY(boolean allowOverflowY) {
this.allowOverflowY = allowOverflowY;
}
public static class Builder {
@@ -186,6 +211,7 @@ public class HandlerInfo {
return this;
}
@Deprecated
public Builder setUseCustomScroll(boolean useCustomScroll) {
this.info.setUseCustomScroll(useCustomScroll);
return this;
@@ -216,6 +242,11 @@ public class HandlerInfo {
return this;
}
public Builder setShowBadge(boolean showBadge) {
this.info.showBadge = showBadge;
return this;
}
@Deprecated
public Builder setMaxRecipesPerPage(int maxRecipesPerPage) {
this.info.multipleWidgetsAllowed = maxRecipesPerPage > 1;
@@ -227,6 +258,16 @@ public class HandlerInfo {
return this;
}
public Builder setAllowOverflowX(boolean allowOverflowX) {
this.info.allowOverflowX = allowOverflowX;
return this;
}
public Builder setAllowOverflowY(boolean allowOverflowY) {
this.info.allowOverflowY = allowOverflowY;
return this;
}
public HandlerInfo build() {
return this.info;
}
@@ -1,7 +1,6 @@
package codechicken.nei.recipe;
import java.awt.Point;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -26,7 +25,6 @@ import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.FavoriteRecipes;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.NEIClientUtils.Alignment;
import codechicken.nei.NEIServerUtils;
import codechicken.nei.PositionedStack;
import codechicken.nei.Widget;
@@ -40,12 +38,10 @@ import codechicken.nei.util.NEIMouseUtils;
public class NEIRecipeWidget extends Widget {
private static final DecimalFormat chanceFormat = new DecimalFormat("##0.##%");
protected AcceptsFollowingTooltipLineHandler acceptsFollowingTooltipLineHandler;
protected final Map<PositionedStack, Integer> favoriteIndexes = new WeakHashMap<>();
protected final Map<PositionedStack, List<ItemStack>> permutations = new WeakHashMap<>();
protected final Map<PositionedStack, String> chances = new WeakHashMap<>();
protected int chanceColor = 0xFDD835;
protected final Map<PositionedStack, List<Badge>> badgeCache = new WeakHashMap<>();
protected int favoriteRevision = -1;
protected boolean update = true;
protected int cycleticks = 0;
@@ -60,20 +56,9 @@ public class NEIRecipeWidget extends Widget {
public NEIRecipeWidget(RecipeHandlerRef handlerRef) {
this.handlerRef = handlerRef;
this.handlerInfo = GuiRecipeTab.getHandlerInfo(this.handlerRef.handler);
this.chanceColor = getHexValue(
NEIClientUtils.getTextColorOrDefault("recipe.overlay.chance", "0xFDD835"),
this.chanceColor);
update();
}
private int getHexValue(String color, int defaultValue) {
try {
return (int) Long.parseLong(color.replace("0x", ""), 16);
} catch (NumberFormatException e) {
return defaultValue;
}
}
public void setLocation(int x, int y) {
this.x = x;
this.y = y;
@@ -81,7 +66,7 @@ public class NEIRecipeWidget extends Widget {
public void update() {
if (this.showAsWidget || !this.handlerInfo.getUseCustomScroll()) {
if (this.showAsWidget || !this.handlerInfo.isAllowOverflowY()) {
final int recipeHeight = this.handlerRef.handler.getRecipeHeight(this.handlerRef.recipeIndex);
this.w = Math.max(166, this.handlerInfo.getWidth());
this.h = recipeHeight > 0 ? recipeHeight : this.handlerInfo.getHeight();
@@ -160,7 +145,7 @@ public class NEIRecipeWidget extends Widget {
final List<GuiRecipeButton> buttons = new ArrayList<>();
final boolean showFavorites = NEIClientConfig.favoritesEnabled() && handlerInfo.getShowFavoritesButton();
final boolean showOverlay = handlerInfo.getShowOverlayButton();
final int x = Math.min(168, this.w) - GuiRecipeButton.BUTTON_WIDTH;
final int x = Math.min(166, this.w) - GuiRecipeButton.BUTTON_WIDTH;
int y = this.h - GuiRecipeButton.BUTTON_HEIGHT - 6;
if (guiContainer instanceof IGuiContainerOverlay overlay) {
@@ -213,7 +198,7 @@ public class NEIRecipeWidget extends Widget {
updatePermutationsFor(pStack);
}
drawItem(pStack, mouseX, mouseY, yShift);
drawItem(pStack, mouseX, mouseY, yShift, true);
}
for (PositionedStack pStack : getCatalysts()) {
@@ -222,11 +207,11 @@ public class NEIRecipeWidget extends Widget {
updatePermutationsFor(pStack);
}
drawItem(pStack, mouseX, mouseY, yShift);
drawItem(pStack, mouseX, mouseY, yShift, true);
}
for (PositionedStack pStack : getOutputs()) {
drawItem(pStack, mouseX, mouseY, yShift);
drawItem(pStack, mouseX, mouseY, yShift, false);
}
GuiContainerManager.disableMatrixStackLogging();
@@ -260,21 +245,11 @@ public class NEIRecipeWidget extends Widget {
DebugHandlerWidget.instance.drawGuiPlaceholder(this);
}
protected void drawItem(PositionedStack pStack, int mouseX, int mouseY, int yShift) {
protected void drawItem(PositionedStack pStack, int mouseX, int mouseY, int yShift, boolean input) {
GuiContainerManager.drawItem(pStack.relx, pStack.rely, pStack.item);
if (NEIClientConfig.showRecipeItemChances()) {
final String chanceText = this.chances.computeIfAbsent(pStack, k -> getChanceText(k));
if (!chanceText.isEmpty()) {
NEIClientUtils.drawNEIOverlayText(
chanceText,
new Rectangle4i(pStack.relx, pStack.rely, 16, 16),
0.5f,
this.chanceColor,
true,
Alignment.TopLeft);
}
if (this.handlerInfo.getShowBadge()) {
drawBadge(pStack, input);
}
if (pStack.contains(mouseX - this.x, mouseY - this.y - yShift)) {
@@ -282,17 +257,41 @@ public class NEIRecipeWidget extends Widget {
}
}
protected String getChanceText(PositionedStack pStack) {
protected List<Badge> getBadges(PositionedStack pStack, boolean input) {
if (StackInfo.getAmount(pStack.item) == 0) { // not consumed
return NEIClientUtils.translate("recipe.chance.nc");
} else if (pStack.getChance() == 0) { // not consumed parallel
return NEIClientUtils.translate("recipe.chance.ncp");
} else if (pStack.getChance() != PositionedStack.CHANCE_FULL) { // chance based
return chanceFormat.format(pStack.getChance() / (float) PositionedStack.CHANCE_FULL);
return this.badgeCache.computeIfAbsent(pStack, k -> {
final List<Badge> badges = k.getBadges();
if (badges == null) {
if (input) {
if (StackInfo.getAmount(pStack.item) == 0) {
return Collections.singletonList(Badge.notConsumed());
} else if (pStack.getChance() == 0) {
return Collections.singletonList(Badge.notConsumedParallel());
} else if (pStack.getChance() != PositionedStack.CHANCE_FULL) {
return Collections.singletonList(
Badge.consumeChance(pStack.getChance() / (float) PositionedStack.CHANCE_FULL));
}
} else if (pStack.getChance() != PositionedStack.CHANCE_FULL) {
return Collections.singletonList(
Badge.outputChance(pStack.getChance() / (float) PositionedStack.CHANCE_FULL));
}
return Collections.emptyList();
}
return badges;
});
}
protected void drawBadge(PositionedStack pStack, boolean input) {
final List<Badge> badges = getBadges(pStack, input);
for (Badge badge : badges) {
badge.draw(new Rectangle4i(pStack.relx, pStack.rely, 16, 16));
}
return "";
}
@Override
@@ -406,27 +405,22 @@ public class NEIRecipeWidget extends Widget {
tooltip = this.handlerRef.handler.handleItemTooltip(guiRecipe, itemstack, tooltip, this.handlerRef.recipeIndex);
if (NEIClientConfig.showCycledIngredientsTooltip() && itemstack != null) {
final int yShift = this.handlerInfo.getYShift();
PositionedStack hovered = null;
if (itemstack != null) {
final PositionedStack hovered = getPositionedStackMouseOver(mousex, mousey);
for (PositionedStack pStack : getInputs()) {
if (pStack.contains(mousex - this.x, mousey - this.y - yShift)) {
hovered = pStack;
break;
}
}
if (hovered != null && this.handlerInfo.getShowBadge()) {
final List<Badge> badges = getBadges(hovered, getOutputs().indexOf(hovered) == -1);
if (hovered == null) {
for (PositionedStack pStack : getCatalysts()) {
if (pStack.contains(mousex - this.x, mousey - this.y - yShift)) {
hovered = pStack;
break;
for (Badge badge : badges) {
if (badge.getTooltip() != null && !badge.getTooltip().isEmpty()) {
tooltip.addAll(badge.getTooltip());
}
}
}
if (hovered == null || this.permutations.getOrDefault(hovered, Collections.emptyList()).size() <= 1) {
if (hovered == null || !NEIClientConfig.showCycledIngredientsTooltip()
|| this.permutations.getOrDefault(hovered, Collections.emptyList()).size() <= 1
|| getOutputs().indexOf(hovered) != -1) {
this.acceptsFollowingTooltipLineHandler = null;
} else if (this.acceptsFollowingTooltipLineHandler == null
|| this.acceptsFollowingTooltipLineHandler.tooltipGUID != hovered) {
@@ -608,6 +602,7 @@ public class NEIRecipeWidget extends Widget {
this.acceptsFollowingTooltipLineHandler = null;
this.favoriteIndexes.clear();
this.permutations.clear();
this.badgeCache.clear();
}
for (PositionedStack pStack : getInputs()) {
@@ -1,16 +1,24 @@
package codechicken.nei.recipe;
import static codechicken.lib.gui.GuiDraw.drawString;
import static codechicken.lib.gui.GuiDraw.getStringWidth;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.inventory.Container;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import codechicken.core.TaskProfiler.ProfilerResult;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.PositionedStack;
@@ -20,12 +28,104 @@ import codechicken.nei.util.AsyncTaskProfiler;
public class ProfilerRecipeHandler implements ICraftingHandler, IUsageHandler {
private static final AsyncTaskProfiler profiler = new AsyncTaskProfiler();
public static class RecipeProfiler {
private final AsyncTaskProfiler profiler = new AsyncTaskProfiler();
private final Map<String, IRecipeHandler> handlerMap = new ConcurrentHashMap<>();
private final AtomicInteger idCounter = new AtomicInteger(0);
private boolean isProfiling = false;
public <T extends IRecipeHandler> ArrayList<T> start(String profilerSection, Supplier<ArrayList<T>> callback) {
profilerInfos.clear();
this.handlerMap.clear();
this.idCounter.set(0);
if (NEIClientConfig.isProfileRecipeEnabled()) {
this.profiler.clear();
this.profiler.start(EnumChatFormatting.getTextWithoutFormattingCodes(profilerSection));
this.isProfiling = true;
try {
return callback.get();
} finally {
this.profiler.end();
this.isProfiling = false;
final List<ProfilerResult> results = this.profiler.getResults();
results.sort(
Comparator.comparingLong((ProfilerResult profilerResult) -> profilerResult.time)
.reversed());
for (ProfilerResult profilerResult : results) {
profilerInfos.add(new ProfilerInfo(handlerMap.get(profilerResult.name), profilerResult));
}
}
} else {
return callback.get();
}
}
public <T extends IRecipeHandler> T profile(T handler, Supplier<T> callback) {
if (this.isProfiling && !(handler instanceof ProfilerRecipeHandler)) {
final String id = String.valueOf(idCounter.incrementAndGet());
this.handlerMap.put(id, handler);
this.profiler.clearCurrent();
this.profiler.start(id);
try {
T result = callback.get();
if (result != null) {
this.handlerMap.put(id, result);
}
return result;
} finally {
this.profiler.end();
}
} else {
return callback.get();
}
}
public static AsyncTaskProfiler getProfiler() {
return profiler;
}
protected static class ProfilerInfo {
public final String modName;
public final IRecipeHandler handler;
public final List<String> tooltip = new ArrayList<>();
public final String title;
public final String time;
public ProfilerInfo(IRecipeHandler handler, ProfilerResult result) {
this.handler = handler;
this.time = (result.time < 1_000_000 ? (result.time / 1_000) + "us" : (result.time / 1_000_000) + "ms");
if (handler == null) {
this.title = result.name;
this.modName = "Unknown";
} else {
final HandlerInfo handlerInfo = GuiRecipeTab.getHandlerInfo(handler);
final String handlerName = handlerInfo != null ? handlerInfo.getHandlerName() : "Unknown";
this.title = EnumChatFormatting.getTextWithoutFormattingCodes(handler.getRecipeName());
this.modName = handlerInfo != null ? handlerInfo.getModName() : "Unknown";
this.tooltip.add(EnumChatFormatting.GRAY + "HandlerName: " + handlerName);
this.tooltip.add(EnumChatFormatting.GRAY + "HandlerID: " + handler.getOverlayIdentifier());
this.tooltip.add(EnumChatFormatting.GRAY + "HandlerOrder: " + NEIClientConfig.getHandlerOrder(handler));
}
}
}
public static final RecipeProfiler recipeProfiler = new RecipeProfiler();
protected static final List<ProfilerInfo> profilerInfos = new ArrayList<>();
private static final int WIDTH = 166;
private final boolean crafting;
public ProfilerRecipeHandler(boolean crafting) {
@@ -39,11 +139,7 @@ public class ProfilerRecipeHandler implements ICraftingHandler, IUsageHandler {
@Override
public int numRecipes() {
if (!NEIClientConfig.isProfileRecipeEnabled()) return 0;
return (int) Math.ceil(
((crafting ? GuiCraftingRecipe.craftinghandlers.size() : GuiUsageRecipe.usagehandlers.size()) - 1)
/ 6D);
return NEIClientConfig.isProfileRecipeEnabled() ? Math.max(1, profilerInfos.size()) : 0;
}
@Override
@@ -51,21 +147,32 @@ public class ProfilerRecipeHandler implements ICraftingHandler, IUsageHandler {
@Override
public void drawForeground(int recipe) {
List<ProfilerResult> results = profiler.getResults();
results.removeIf(profilerResult -> getRecipeName().equals(profilerResult.name));
if (recipe >= profilerInfos.size()) return;
results.sort((o1, o2) -> o1.time < o2.time ? 1 : -1);
final ProfilerInfo info = profilerInfos.get(recipe);
final int valueWidth = getStringWidth(info.time);
final IRecipeHandler handler = info.handler;
final boolean hovered = handler != null && handler.numRecipes() > 0
&& isHandlerTitleHovered(recipe, GuiDraw.getMousePosition());
for (int i = recipe * 6; i < results.size() && i < (recipe + 1) * 6; i++) {
ProfilerResult r = results.get(i);
int y = (i % 6) * 20 + 6;
drawString(r.name, 8, y, 0xFF808080, false);
GuiDraw.drawString(
NEIClientUtils.cropText(GuiDraw.fontRenderer, info.title, WIDTH - valueWidth - 2),
0,
3,
hovered ? 0xFFFFDD00 : 0xFF808080,
false);
GuiDraw.drawString(info.time, WIDTH - valueWidth, 3, 0xFF404040, false);
}
String s;
if (r.time < 1000000L) s = (r.time / 1000) + "us";
else s = (r.time / 1000000) + "ms";
private boolean isHandlerTitleHovered(int recipe, Point mouse) {
final GuiContainer guiContainer = NEIClientUtils.getGuiContainer();
drawString(s, 156 - getStringWidth(s), y + 10, 0xFF404040, false);
if (guiContainer instanceof GuiRecipe guiRecipe) {
final Point recipePosition = guiRecipe.getRecipePosition(recipe);
return new Rectangle(recipePosition.x, recipePosition.y, WIDTH, 16)
.contains(mouse.x - guiContainer.guiLeft, mouse.y - guiContainer.guiTop);
} else {
return false;
}
}
@@ -104,6 +211,22 @@ public class ProfilerRecipeHandler implements ICraftingHandler, IUsageHandler {
@Override
public List<String> handleTooltip(GuiRecipe<?> gui, List<String> currenttip, int recipe) {
if (recipe >= profilerInfos.size()) return currenttip;
final ProfilerInfo r = profilerInfos.get(recipe);
currenttip.add(r.title + ": " + r.time);
if (r.handler != null) {
currenttip.add(EnumChatFormatting.GRAY + "Recipes: " + r.handler.numRecipes() + GuiDraw.TOOLTIP_LINESPACE);
if (NEIClientUtils.shiftKey()) {
currenttip.addAll(r.tooltip);
}
currenttip.add(EnumChatFormatting.BLUE + r.modName);
}
return currenttip;
}
@@ -119,6 +242,23 @@ public class ProfilerRecipeHandler implements ICraftingHandler, IUsageHandler {
@Override
public boolean mouseClicked(GuiRecipe<?> gui, int button, int recipe) {
if (recipe >= profilerInfos.size()) return false;
final ProfilerInfo r = profilerInfos.get(recipe);
if (r.handler != null) {
final GuiContainer guiContainer = NEIClientUtils.getGuiContainer();
if (guiContainer instanceof GuiRecipe guiRecipe) {
int index = guiRecipe.currenthandlers.indexOf(r.handler);
if (index != -1) {
guiRecipe.setRecipePage(index);
return true;
}
}
}
return false;
}
@@ -12,10 +12,8 @@ import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.IChatComponent;
import codechicken.core.TaskProfiler;
import codechicken.nei.ItemList;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.util.AsyncTaskProfiler;
public class RecipeHandlerQuery<T extends IRecipeHandler> {
@@ -34,30 +32,22 @@ public class RecipeHandlerQuery<T extends IRecipeHandler> {
}
public ArrayList<T> runWithProfiling(String profilerSection) {
TaskProfiler profiler = ProfilerRecipeHandler.getProfiler();
return ProfilerRecipeHandler.recipeProfiler.start(profilerSection, () -> {
// Save the current config state here, as it may be altered
// if getRecipeHandlesParallel took so long and player accidentally changed config.
boolean profileRecipes = NEIClientConfig.isProfileRecipeEnabled();
if (profileRecipes) {
profiler.clear();
profiler.start(profilerSection);
}
try {
ArrayList<T> handlers = getRecipeHandlersParallel();
try {
ArrayList<T> handlers = getRecipeHandlersParallel();
if (error) {
if (error) {
displayRecipeLookupError();
}
return handlers;
} catch (InterruptedException | ExecutionException e) {
printLog(e);
displayRecipeLookupError();
return new ArrayList<>(0);
}
return handlers;
} catch (InterruptedException | ExecutionException e) {
printLog(e);
displayRecipeLookupError();
return new ArrayList<>(0);
} finally {
if (profileRecipes) profiler.end();
}
});
}
private ArrayList<T> getRecipeHandlersParallel() throws InterruptedException, ExecutionException {
@@ -77,40 +67,42 @@ public class RecipeHandlerQuery<T extends IRecipeHandler> {
private ArrayList<T> getSerialHandlersWithRecipes() {
return serialRecipeHandlers.stream().map(handler -> {
AsyncTaskProfiler profiler = ProfilerRecipeHandler.getProfiler();
profiler.clearCurrent();
profiler.start(handler.getRecipeName());
try {
return isHidden(handler) ? null : recipeHandlerFunction.apply(handler);
} catch (Throwable t) {
printLog(t);
error = true;
return null;
} finally {
profiler.end();
}
}).filter(h -> h != null && h.numRecipes() > 0 && SearchRecipeHandler.findFirst(h, (recipeIndex) -> true) != -1)
return serialRecipeHandlers.stream()
.map(handler -> ProfilerRecipeHandler.recipeProfiler.profile(handler, () -> {
try {
return isHidden(handler) ? null : recipeHandlerFunction.apply(handler);
} catch (Throwable t) {
printLog(t);
error = true;
return null;
}
}))
.filter(
h -> h != null && h.numRecipes() > 0
&& SearchRecipeHandler.findFirst(h, (recipeIndex) -> true) != -1)
.collect(Collectors.toCollection(ArrayList::new));
}
private ArrayList<T> getHandlersWithRecipes() throws InterruptedException, ExecutionException {
return ItemList.forkJoinPool.submit(() -> recipeHandlers.parallelStream().map(handler -> {
AsyncTaskProfiler profiler = ProfilerRecipeHandler.getProfiler();
profiler.clearCurrent();
profiler.start(handler.getRecipeName());
try {
return isHidden(handler) ? null : recipeHandlerFunction.apply(handler);
} catch (Throwable t) {
printLog(t);
error = true;
return null;
} finally {
profiler.end();
}
}).filter(h -> h != null && h.numRecipes() > 0 && SearchRecipeHandler.findFirst(h, (recipeIndex) -> true) != -1)
.collect(Collectors.toCollection(ArrayList::new))).get();
return ItemList.forkJoinPool.submit(
() -> recipeHandlers.parallelStream()
.map(handler -> ProfilerRecipeHandler.recipeProfiler.profile(handler, () -> {
try {
return isHidden(handler) ? null : recipeHandlerFunction.apply(handler);
} catch (Throwable t) {
printLog(t);
error = true;
return null;
}
}))
.filter(
h -> h != null && h.numRecipes() > 0
&& SearchRecipeHandler.findFirst(h, (recipeIndex) -> true) != -1)
.collect(Collectors.toCollection(ArrayList::new)))
.get();
}
private boolean isHidden(T handler) {
@@ -42,10 +42,10 @@ public class RecipePageManager {
this.cacheKey = cacheKey;
this.pageWidgets.clear();
final boolean useCustomScroll = this.handlerInfo.getUseCustomScroll();
final boolean allowOverflowY = this.handlerInfo.isAllowOverflowY();
final int handlerHeight = this.handlerInfo.getHeight() + this.handlerInfo.getYShift();
final boolean multipleWidgetsAllowed = !useCustomScroll && handlerInfo.isMultipleWidgetsAllowed();
final boolean infiniteScroll = !useCustomScroll
final boolean multipleWidgetsAllowed = !allowOverflowY && handlerInfo.isMultipleWidgetsAllowed();
final boolean infiniteScroll = !allowOverflowY
&& NEIClientConfig.getBooleanSetting("inventory.guirecipe.infiniteScroll");
final int heightAvailable = this.container.getVisibleHeight();
@@ -59,7 +59,7 @@ public class RecipePageManager {
final NEIRecipeWidget widget = RecipeHandlerRef.of(this.handler.original, recipeIndex).getRecipeWidget();
widget.w = width;
if (useCustomScroll) {
if (allowOverflowY) {
widget.h = Math.min(handlerHeight, heightAvailable);
}
@@ -84,7 +84,7 @@ public class RecipePageManager {
}
public boolean isMultipleWidgetsAllowed() {
return !this.handlerInfo.getUseCustomScroll() && this.handlerInfo.isMultipleWidgetsAllowed();
return !this.handlerInfo.isAllowOverflowY() && this.handlerInfo.isMultipleWidgetsAllowed();
}
public int getNumRecipes() {
@@ -120,10 +120,14 @@ public class RepairRecipeHandler extends TemplateRecipeHandler {
final List<ItemStack> permutations = new ArrayList<>();
for (ItemStack itemstack2 : ItemList.items) {
if (itemstack1.getItem().getIsRepairable(itemstack1, itemstack2)) {
final ItemStack right = itemstack2.copy();
right.stackSize = 4;
permutations.add(right);
try {
if (itemstack1.getItem().getIsRepairable(itemstack1, itemstack2)) {
final ItemStack right = itemstack2.copy();
right.stackSize = 4;
permutations.add(right);
}
} catch (Exception e) {
// Catch exceptions from mods that don't properly implement getIsRepairable
}
}
@@ -84,12 +84,13 @@ public abstract class TemplateRecipeHandler implements ICraftingHandler, IUsageH
efuels.add(Item.getItemFromBlock(Blocks.wooden_door));
efuels.add(Item.getItemFromBlock(Blocks.trapped_chest));
Stopwatch stopwatch = Stopwatch.createStarted();
final Stopwatch stopwatch = Stopwatch.createStarted();
final List<ItemStack> itemsSnapshot = new ArrayList<>(ItemList.items);
if (parallel) {
try {
FurnaceRecipeHandler.afuels = ItemList.forkJoinPool
.submit(
() -> ItemList.items.parallelStream().map(TemplateRecipeHandler::identifyFuel)
() -> itemsSnapshot.parallelStream().map(TemplateRecipeHandler::identifyFuel)
.filter(Objects::nonNull).collect(Collectors.toCollection(ArrayList::new)))
.get();
} catch (InterruptedException | ExecutionException e) {
@@ -97,7 +98,7 @@ public abstract class TemplateRecipeHandler implements ICraftingHandler, IUsageH
e.printStackTrace();
}
} else {
FurnaceRecipeHandler.afuels = ItemList.items.stream().map(TemplateRecipeHandler::identifyFuel)
FurnaceRecipeHandler.afuels = itemsSnapshot.stream().map(TemplateRecipeHandler::identifyFuel)
.filter(Objects::nonNull).collect(Collectors.toCollection(ArrayList::new));
}
@@ -535,6 +536,24 @@ public abstract class TemplateRecipeHandler implements ICraftingHandler, IUsageH
}
}
public ICraftingHandler getAllRecipeHandler() {
TemplateRecipeHandler handler = newInstance();
if (handler.transferRects.isEmpty()) {
handler.loadCraftingRecipes("all");
return handler;
}
final String transferRectId = handler.specifyTransferRect();
for (RecipeTransferRect rect : handler.transferRects) {
if (transferRectId == null || transferRectId.equals(rect.outputId)) {
handler.loadCraftingRecipes(rect.outputId, rect.results);
return handler;
}
}
return handler.getRecipeHandler("all");
}
public ICraftingHandler getRecipeHandler(String outputId, Object... results) {
TemplateRecipeHandler handler = newInstance();
handler.loadCraftingRecipes(outputId, results);
@@ -371,8 +371,8 @@ public class RecipeChainMath {
addRequiredAmount(prefItem, ingrAmount, Long.MAX_VALUE);
} else {
addRequiredAmount(prefItem, ingrAmount, Long.MAX_VALUE);
final long multiplier = prefItem
.getMultiplierFromAmount(this.requiredAmount.get(prefItem) - prefItem.getAmount());
final long multiplier = Math
.max(0, prefItem.getMultiplierFromAmount(this.requiredAmount.get(prefItem)) - prefItem.multiplier);
if (multiplier > 0) {
addShift(prefItem.recipeId, multiplier);
@@ -7,12 +7,12 @@ import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.IntPredicate;
import java.util.regex.Matcher;
import java.util.stream.Collectors;
@@ -53,9 +53,11 @@ public class DebugHandlerWidget extends Widget {
public int height;
public boolean multiWidgets;
public int order;
public boolean useCustomScroll;
public boolean allowOverflowX;
public boolean allowOverflowY;
public boolean showFavorites;
public boolean showOverlay;
public boolean showBadge;
private String csvLine;
@@ -67,9 +69,11 @@ public class DebugHandlerWidget extends Widget {
this.height = info.getHeight();
this.multiWidgets = info.isMultipleWidgetsAllowed();
this.order = NEIClientConfig.handlerOrdering.getOrDefault(handlerKey, 0);
this.useCustomScroll = info.getUseCustomScroll();
this.allowOverflowX = info.isAllowOverflowX();
this.allowOverflowY = info.isAllowOverflowY();
this.showFavorites = info.getShowFavoritesButton();
this.showOverlay = info.getShowOverlayButton();
this.showBadge = info.getShowBadge();
this.csvLine = toCsvLine();
}
@@ -77,9 +81,11 @@ public class DebugHandlerWidget extends Widget {
this.info.setYShift(this.yShift);
this.info.setHandlerDimensions(this.width, this.height);
this.info.setMultipleWidgetsAllowed(this.multiWidgets);
this.info.setUseCustomScroll(this.useCustomScroll);
this.info.setAllowOverflowX(this.allowOverflowX);
this.info.setAllowOverflowY(this.allowOverflowY);
this.info.setShowFavoritesButton(this.showFavorites);
this.info.setShowOverlayButton(this.showOverlay);
this.info.setShowBadge(this.showBadge);
NEIClientConfig.handlerOrdering.put(this.handlerKey, this.order);
}
@@ -91,9 +97,11 @@ public class DebugHandlerWidget extends Widget {
this.width = intOrDefault(parts[3], this.width);
this.multiWidgets = intOrDefault(parts[4], this.multiWidgets ? 1 : 0) == 1;
this.order = intOrDefault(parts[5], this.order);
this.useCustomScroll = intOrDefault(parts[6], this.useCustomScroll ? 1 : 0) == 1;
this.showFavorites = intOrDefault(parts[7], this.showFavorites ? 1 : 0) == 1;
this.showOverlay = intOrDefault(parts[8], this.showOverlay ? 1 : 0) == 1;
this.allowOverflowX = intOrDefault(parts[6], this.allowOverflowX ? 1 : 0) == 1;
this.allowOverflowY = intOrDefault(parts[7], this.allowOverflowY ? 1 : 0) == 1;
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;
apply();
}
@@ -107,9 +115,11 @@ public class DebugHandlerWidget extends Widget {
String.valueOf(this.width),
String.valueOf(this.multiWidgets ? 1 : 0),
String.valueOf(this.order),
String.valueOf(this.useCustomScroll ? 1 : 0),
String.valueOf(this.allowOverflowX ? 1 : 0),
String.valueOf(this.allowOverflowY ? 1 : 0),
String.valueOf(this.showFavorites ? 1 : 0),
String.valueOf(this.showOverlay ? 1 : 0));
String.valueOf(this.showOverlay ? 1 : 0),
String.valueOf(this.showBadge ? 1 : 0));
}
public boolean isUnmodified() {
@@ -132,7 +142,7 @@ public class DebugHandlerWidget extends Widget {
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,UseCustomScroll,ShowFavorites,ShowOverlay";
private static final String HEADER = "HandlerId,YShift,Height,Width,MultiWidgets,Order,AllowOverflowX,AllowOverflowY,ShowFavorites,ShowOverlay,ShowBadge";
private final int[] COLORS = new int[] { 0x2200FF00, 0x22FF0000, 0x220000FF, 0x2200FFFF, 0x22FF00FF, 0x22FFFF00 };
public static DebugHandlerWidget instance = new DebugHandlerWidget();
@@ -178,12 +188,12 @@ public class DebugHandlerWidget extends Widget {
y = addTextFieldWidget("Order", 0, (field, oldText) -> {
record.order = field.getInteger();
saveHandlerInfoPatch();
}, y);
}, null, y);
y = addTextFieldWidget("yShift", 0, (field, oldText) -> {
record.yShift = field.getInteger();
saveHandlerInfoPatch();
}, y);
}, null, y);
y = addCheckboxWidget("MultiWidgets", button -> {
record.multiWidgets = button.value;
@@ -200,15 +210,20 @@ public class DebugHandlerWidget extends Widget {
y = addTextFieldWidget("Height", HandlerInfo.DEFAULT_HEIGHT, (field, oldText) -> {
record.height = field.getInteger();
saveHandlerInfoPatch();
}, y);
}, newValue -> newValue > 0, y);
y = addTextFieldWidget("Width", HandlerInfo.DEFAULT_WIDTH, (field, oldText) -> {
record.width = field.getInteger();
saveHandlerInfoPatch();
}, newValue -> newValue >= HandlerInfo.DEFAULT_WIDTH, y);
y = addCheckboxWidget("AllowOverflowX", button -> {
record.allowOverflowX = button.value;
saveHandlerInfoPatch();
}, y);
y = addCheckboxWidget("UseCustomScroll", button -> {
record.useCustomScroll = button.value;
y = addCheckboxWidget("AllowOverflowY", button -> {
record.allowOverflowY = button.value;
saveHandlerInfoPatch();
}, y);
@@ -222,6 +237,11 @@ public class DebugHandlerWidget extends Widget {
saveHandlerInfoPatch();
}, y);
y = addCheckboxWidget("ShowBadge", button -> {
record.showBadge = button.value;
saveHandlerInfoPatch();
}, y);
this.h = 10 + LINE_HEIGHT + y;
this.container.h = this.h - INLINE_PADDING * 2 - LINE_HEIGHT;
}
@@ -244,9 +264,10 @@ public class DebugHandlerWidget extends Widget {
return y + value.h + 1;
}
private int addTextFieldWidget(String key, int defaultValue, BiConsumer<IntegerField, String> onChange, int y) {
private int addTextFieldWidget(String key, int defaultValue, BiConsumer<IntegerField, String> onChange,
IntPredicate validator, int y) {
final LabelWidget label = new LabelWidget(0x888888, false);
final IntegerField value = new IntegerField(key, onChange, defaultValue);
final IntegerField value = new IntegerField(key, onChange, validator, defaultValue);
label.y = value.y = y;
value.w = 60;
@@ -387,10 +408,12 @@ public class DebugHandlerWidget extends Widget {
this.values.get("width").updateValue(String.valueOf(this.record.width));
this.values.get("multiwidgets").updateValue(String.valueOf(this.record.multiWidgets));
this.values.get("usecustomscroll").updateValue(String.valueOf(this.record.useCustomScroll));
this.values.get("allowoverflowx").updateValue(String.valueOf(this.record.allowOverflowX));
this.values.get("allowoverflowy").updateValue(String.valueOf(this.record.allowOverflowY));
this.values.get("showfavorites").updateValue(String.valueOf(this.record.showFavorites));
this.values.get("showoverlay").updateValue(String.valueOf(this.record.showOverlay));
this.values.get("showbadge").updateValue(String.valueOf(this.record.showBadge));
updateOverride();
@@ -578,17 +601,23 @@ public class DebugHandlerWidget extends Widget {
public void loadHandlerInfoPatch() {
ClientHandler.loadSettingsFile("handlers.patch", lines -> {
final List<String> linesList = lines.collect(Collectors.toCollection(ArrayList::new));
for (String line : lines.collect(Collectors.toCollection(HashSet::new))) {
if (HEADER.equals(line)) continue;
final String[] parts = (line).split(",");
if (linesList.isEmpty() || !HEADER.equals(linesList.get(0))) {
return;
}
linesList.remove(0);
for (String line : linesList) {
final String[] parts = line.split(",");
final String handlerKey = parts[0];
if (GuiRecipeTab.handlerMap.containsKey(handlerKey)) {
final HandlerInfoRecord record = patches.computeIfAbsent(
handlerKey,
key -> new HandlerInfoRecord(key, GuiRecipeTab.handlerMap.get(key)));
record.apply((line + ",null,null,null,null,null,null,null,null"));
record.apply((line + ",null,null,null,null,null,null,null,null,null,null"));
}
}
@@ -1,6 +1,7 @@
package codechicken.nei.recipe.debug;
import java.util.function.BiConsumer;
import java.util.function.IntPredicate;
import net.minecraft.client.Minecraft;
@@ -13,10 +14,13 @@ public class IntegerField extends TextField implements IUpdatableWidget {
protected int defaultValue = 0;
protected BiConsumer<IntegerField, String> onChange;
protected IntPredicate validator;
public IntegerField(String ident, BiConsumer<IntegerField, String> onChange, int defaultValue) {
public IntegerField(String ident, BiConsumer<IntegerField, String> onChange, IntPredicate validator,
int defaultValue) {
super(ident);
this.onChange = onChange;
this.validator = validator;
this.defaultValue = defaultValue;
this.h = 16;
this.z = 2;
@@ -68,8 +72,12 @@ public class IntegerField extends TextField implements IUpdatableWidget {
}
protected int getInteger() {
return getInteger(text());
}
protected int getInteger(String text) {
try {
return Integer.parseInt(text());
return Integer.parseInt(text);
} catch (NumberFormatException nfe) {
return this.defaultValue;
}
@@ -78,10 +86,17 @@ public class IntegerField extends TextField implements IUpdatableWidget {
@Override
public boolean onMouseWheel(int i, int mx, int my) {
if (!contains(mx, my)) return false;
setText(Integer.toString(getInteger() + i));
setText(Integer.toString(getInteger() - i));
return true;
}
@Override
public void setText(String newValue) {
if (validator == null || validator.test(getInteger(newValue))) {
super.setText(newValue);
}
}
public void updateValue(String newValue) {
setText(newValue);
}
+17 -7
View File
@@ -301,10 +301,12 @@ nei.options.inventory.guirecipe.handlerInfo=Handler Info Widget
nei.options.inventory.guirecipe.handlerInfo.tip=Use shift+d while in the Recipes GUI
nei.options.inventory.guirecipe.handlerInfo.true=Enabled
nei.options.inventory.guirecipe.handlerInfo.false=Disabled
nei.options.inventory.guirecipe.scrollPages=Scroll Pages
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.chance=Show Change
nei.options.inventory.guirecipe.chance.true=Yes
nei.options.inventory.guirecipe.chance.false=No
nei.options.inventory.showItemQuantityWidget=Show Item Quantity Widget
nei.options.inventory.showItemQuantityWidget.true=Yes
nei.options.inventory.showItemQuantityWidget.false=No
@@ -544,7 +546,9 @@ nei.debug.RecipeHandler.Height=Height
nei.debug.RecipeHandler.Width=Width
nei.debug.RecipeHandler.ShowFavorites=Show Favorites
nei.debug.RecipeHandler.ShowOverlay=Show Overlays
nei.debug.RecipeHandler.UseCustomScroll=Use Custom Scroll
nei.debug.RecipeHandler.ShowBadge=Show Badge
nei.debug.RecipeHandler.AllowOverflowY=Allow Overflow Y
nei.debug.RecipeHandler.AllowOverflowX=Allow Overflow X
nei.debug.RecipeHandler.Override=Override
nei.debug.RecipeHandler.checkbox.on=On
nei.debug.RecipeHandler.checkbox.off=Off
@@ -560,9 +564,15 @@ nei.recipe.shapeless=Shapeless Crafting
nei.recipe.furnace=Smelting
nei.recipe.fuel=Fuel
nei.recipe.fuel.smeltCount=Smelts %s items
nei.recipe.chance=Chance: %s%%
nei.recipe.chance.nc=NC
nei.recipe.chance.ncp=NC(P)
nei.recipe.badge.nc=NC
nei.recipe.badge.nc.tooltip=Does not get consumed in the process
nei.recipe.badge.ncp=NC(P)
nei.recipe.badge.ncp.tooltip=Considered in parallel calculation, but not get consumed
nei.recipe.badge.chance.consume=Consume Chance: %s
nei.recipe.badge.chance.output=Output Chance: %s
# Deprecated
nei.recipe.fuel.required=%s required