Compare commits

..
Author SHA1 Message Date
June Awesome 4058f23490 testing if this works 2026-03-22 18:53:26 -04:00
144 changed files with 1943 additions and 4375 deletions

No files matched your search

+2 -19
View File
@@ -1,17 +1,12 @@
// Add your dependencies here
configurations.create('gtnhlibEmbed') {
canBeConsumed = false
canBeResolved = true
}
dependencies {
api('com.github.GTNewHorizons:CodeChickenCore:1.4.17:dev')
devOnlyNonPublishable('com.github.GTNewHorizons:GTNHLib:0.11.37:dev')
api('com.github.GTNewHorizons:CodeChickenCore:1.4.10:dev')
devOnlyNonPublishable('com.github.GTNewHorizons:GTNHLib:0.9.13:dev')
shadowImplementation('org.apache.commons:commons-csv:1.10.0')
compileOnly('maven.modrinth:forge-essentials:7.5.1')
compileOnly('com.cardinalstar.cubicchunks:CubicChunks1710:v0.1.14-alpha:dev')
antlr('org.antlr:antlr4:4.13.2')
shadowImplementation('org.antlr:antlr4-runtime:4.13.2')
@@ -22,16 +17,4 @@ dependencies {
testRuntimeOnly('org.junit.platform:junit-platform-launcher')
testRuntimeOnly("org.lwjgl.lwjgl:lwjgl:2.9.3");
compileOnly("com.github.GTNewHorizons:GTNHLib:0.11.37") { transitive = false }
gtnhlibEmbed("com.github.GTNewHorizons:GTNHLib:0.11.37") { transitive = false }
}
[tasks.jar, tasks.shadowJar].each {
it.configure {
from({ project.configurations.getByName('gtnhlibEmbed').collect { zipTree(it) } }) {
include 'com/gtnewhorizon/gtnhlib/color/ColorResource.class'
include 'com/gtnewhorizon/gtnhlib/color/ColorResource$*.class'
}
}
}
+10 -10
View File
@@ -1,12 +1,12 @@
#This file is generated by updateDaemonJvm
toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/97d46b5ff4df0bf61e95652a190a5567/redirect
toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/9ef54a08e06b0754cee9fc95ed3a3134/redirect
toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/97d46b5ff4df0bf61e95652a190a5567/redirect
toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/9ef54a08e06b0754cee9fc95ed3a3134/redirect
toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/1df82b76031285ef2e6a4f59ffe9299d/redirect
toolchainUrl.MAC_OS.X86_64=https\://api.foojay.io/disco/v3.0/ids/c7d5be6a02945ac2e045048ee54a7d32/redirect
toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/97d46b5ff4df0bf61e95652a190a5567/redirect
toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/9ef54a08e06b0754cee9fc95ed3a3134/redirect
toolchainUrl.WINDOWS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/643f404f769811f5f265fd66f7af5d89/redirect
toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/38256085a73e137cb4937ea9c4807fec/redirect
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.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.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
toolchainVersion=25
+1 -1
View File
@@ -17,7 +17,7 @@ pluginManagement {
}
plugins {
id 'com.gtnewhorizons.gtnhsettingsconvention' version '2.0.29'
id 'com.gtnewhorizons.gtnhsettingsconvention' version '2.0.24'
}
@@ -19,7 +19,6 @@ import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumChatFormatting;
import org.apache.commons.io.IOUtils;
@@ -185,33 +184,27 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
if (itemStack != null && this.grid.indexOf(groupId, itemStack, recipeId, false) == -1) {
final boolean existsRecipe = recipeId != null
&& this.grid.existsRecipe(recipeId, BookmarkGrid.DEFAULT_GROUP_ID);
final Recipe recipe = Recipe.of(recipeId);
final BookmarkItem.Builder builder;
if (recipe != null) {
builder = BookmarkItem.builder(groupId, itemStack, recipe, BookmarkItemType.RESULT).multiplier(1);
} else if (recipeId != null) {
builder = BookmarkItem.builder(groupId, itemStack).recipeId(recipeId)
.factor(StackInfo.getAmount(itemStack)).multiplier(1);
} else {
builder = BookmarkItem.builder(groupId, itemStack).factor(1).multiplier(StackInfo.getAmount(itemStack));
}
final NBTTagCompound nbTag = StackInfo.itemStackToNBT(itemStack);
long count = nbTag.getInteger("Count");
long factor = existsRecipe ? Math.max(count, 1) : 1;
if (existsRecipe) {
builder.type(BookmarkItemType.RESULT);
for (int i = 0; i < this.grid.size(); i++) {
if (this.grid.getBookmarkItem(i).equalsRecipe(recipeId, groupId)) {
builder.multiplier(this.grid.getBookmarkItem(i).getMultiplier());
count *= this.grid.getBookmarkItem(i).getMultiplier();
break;
}
}
} else {
builder.type(BookmarkItemType.ITEM);
}
this.grid.addItem(builder.build(), true);
this.grid.addItem(
BookmarkItem.of(
groupId,
StackInfo.withAmount(itemStack, count),
factor,
recipeId,
existsRecipe ? BookmarkItemType.RESULT : BookmarkItemType.ITEM),
true);
return true;
}
@@ -219,11 +212,9 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
}
public boolean addRecipe(Recipe recipe, int multiplier, int groupId) {
if (recipe == null) return false;
final RecipeId recipeId = recipe.getRecipeId();
if (this.grid.getGroup(groupId) != null && !this.grid.existsRecipe(recipeId, groupId)) {
if (recipe != null && this.grid.getGroup(groupId) != null && !this.grid.existsRecipe(recipeId, groupId)) {
this.grid.addRecipe(recipe, multiplier, groupId);
return true;
}
@@ -254,22 +245,15 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
ItemStack stack = recipeId.getResult();
if (stack != null && uniqueRecipe.add(recipeId)) {
final Recipe recipe = Recipe.of(recipeId);
final BookmarkItem.Builder builder;
if (recipe != null) {
builder = BookmarkItem.builder(groupId, stack, recipe, BookmarkItemType.RESULT);
} else {
builder = BookmarkItem.builder(groupId, stack).recipeId(recipeId)
.factor(StackInfo.getAmount(stack));
}
this.grid.addItem(builder.multiplier(1).type(BookmarkItemType.ITEM).build(), true);
this.grid.addItem(
BookmarkItem
.of(groupId, stack, StackInfo.getAmount(stack), recipeId, BookmarkItemType.ITEM),
true);
uniqueStack.add(stack);
}
} else {
final ItemStack stack = extractItem(item);
ItemStack stack = extractItem(item);
if (stack != null && !uniqueStack.contains(stack)) {
this.grid.addItem(BookmarkItem.of(groupId, stack), true);
@@ -799,15 +783,15 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
NEIMouseUtils.getKeyName(NEIMouseUtils.MOUSE_BTN_RMB),
NEIClientUtils.translate("bookmark.group.toggle_crafting_chain"));
hotkeys.put(
KeyManager.getKeyName("bookmark.remove_recipe", NEIClientUtils.SHIFT_HASH),
NEIClientConfig.getKeyName("gui.remove_recipe"),
NEIClientUtils.translate("bookmark.group.remove_recipe"));
if (BookmarkContainerInfo.getBookmarkContainerHandler(NEIClientUtils.getGuiContainer()) != null) {
hotkeys.put(
KeyManager.getKeyName("bookmark.pull_items"),
NEIClientConfig.getKeyName("gui.bookmark_pull_items"),
NEIClientUtils.translate("bookmark.group.pull_items"));
hotkeys.put(
KeyManager.getKeyName("bookmark.pull_items", NEIClientUtils.SHIFT_HASH),
NEIClientConfig.getKeyName("gui.bookmark_pull_items", NEIClientUtils.SHIFT_HASH),
NEIClientUtils.translate("bookmark.group.pull_items_shift"));
}
@@ -913,7 +897,9 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
this.grid.createRecipeChainMath(groupId));
}
currenttip.add(GuiDraw.TOOLTIP_HANDLER + GuiDraw.getTipLineId(this.recipeChainTooltipLineHandler));
if (this.recipeChainTooltipLineHandler != null) {
currenttip.add(GuiDraw.TOOLTIP_HANDLER + GuiDraw.getTipLineId(this.recipeChainTooltipLineHandler));
}
return currenttip;
}
@@ -939,17 +925,6 @@ 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.GRAY + NEIClientUtils.translate(
slot.getType() == BookmarkItemType.INGREDIENT ? "recipe.badge.chance.consume"
: "recipe.badge.chance.output",
chanceText));
}
if (slot.getType() == BookmarkItemType.INGREDIENT && slot.getRecipeId() != null
&& slot.getBookmarkItem().permutations.size() > 1) {
RecipeId recipeId = slot.getRecipeId();
@@ -1094,13 +1069,10 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
}
activeStack = items.get((items.size() - shift + stackIndex) % items.size());
this.acceptsFollowingTooltipLineHandler.setActiveStack(activeStack);
final int targetItemIndex = Math.abs(itemIndex);
final BookmarkItem oldItem = this.grid.getBookmarkItem(targetItemIndex);
final BookmarkItem newItem = oldItem.copyWithPerm(activeStack);
this.grid.replaceBookmarkItem(targetItemIndex, newItem);
this.grid.getBookmarkItem(Math.abs(itemIndex)).itemStack = activeStack;
this.grid.onItemsChanged();
}
return true;
@@ -1147,7 +1119,7 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
for (BookmarkItem item : math.initialItems) {
final long invStackSize = inventory.getOrDefault(item.itemStack, 0L);
final long amount = item.getAmount() - invStackSize * item.fluidCellAmount;
final long amount = item.amount - invStackSize * item.fluidCellAmount;
if (amount > 0) {
pullItemStacks.add(item.getItemStack(amount));
}
@@ -1161,7 +1133,7 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
for (BookmarkItem item : math.initialItems) {
final long invStackSize = inventory.getOrDefault(item.itemStack, 0L);
final long strStackSize = containerStorage.getOrDefault(item.itemStack, 0L);
final long amount = item.getAmount() - invStackSize * item.fluidCellAmount
final long amount = item.amount - invStackSize * item.fluidCellAmount
- strStackSize * item.fluidCellAmount;
if (amount > 0) {
@@ -1295,7 +1267,7 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
public BookmarkRecipeId getBookmarkRecipeId(int itemIndex) {
BookmarkItem item = this.grid.getCalculatedItem(itemIndex);
return item == null || item.type == BookmarkItemType.INGREDIENT || item.recipeId == null ? null
: new BookmarkRecipeId(item.recipeId.getHandlerName(), item.recipeId.getIngredients());
: new BookmarkRecipeId(item.recipeId.getHandleName(), item.recipeId.getIngredients());
}
@Deprecated
@@ -57,10 +57,6 @@ public abstract class Button extends Widget {
return label;
}
public int getRenderLabelColor() {
return 0;
}
public final String label;
public Image icon;
@@ -45,7 +45,6 @@ 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;
@@ -375,7 +374,6 @@ public class ClientHandler {
} else if (event.gui == null) {
/* prevent WorldClient reference being held in the Gui */
NEIController.manager = null;
GuiInfo.clearGuiHandlers();
}
}
@@ -112,7 +112,7 @@ public class CollapsibleItems {
group.setFilter(itemStr);
}
if (group.filter != null) {
if (group != null && group.filter != null) {
addGroup(group);
group = new GroupItem();
}
@@ -1,22 +0,0 @@
package codechicken.nei;
import com.gtnewhorizon.gtnhlib.color.ColorResource;
public class ColorUtils {
private static final ColorResource.Factory color = new ColorResource.Factory("nei");
public static final ColorResource
// spotless:off
textGray = color.rgb("textGray", "0x404040"),
textLightGray = color.rgb("textLightGray", "0x606060"),
recipeTitle = color.rgb("recipeTitle", "0xFFFFFF"),
recipeTitleHover = color.rgb("recipeTitleHover", "0xFFFF55"),
subsetWidget = color.rgb("subsetWidget", "0xAA00AA"),
recipeBadge = color.rgb("recipeBadge", "0xFDD835"),
buttonLabelNormal = color.rgb("buttonLabelNormal", "0xE0E0E0"),
buttonLabelHover = color.rgb("buttonLabelHover", "0xFFFFA0"),
buttonLabelDisabled = color.rgb("buttonLabelDisabled", "0x601010"),
buttonLabelInactive = color.rgb("buttonLabelInactive", "0xA0A0A0");
// spotless:on
}
@@ -79,13 +79,14 @@ public class ContainerCreativeInv extends Container {
@Override
public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int slotIndex) {
ItemStack transferredStack = null;
Slot slot = inventorySlots.get(slotIndex);
Slot slot = (Slot) inventorySlots.get(slotIndex);
if (slot != null && slot.getHasStack()) {
ItemStack stack = slot.getStack();
transferredStack = stack.copy();
if (stack.getItem() instanceof ItemArmor armor) {
if (stack.getItem() instanceof ItemArmor) {
ItemArmor armor = (ItemArmor) stack.getItem();
if (!getSlot(90 + armor.armorType).getHasStack()) {
getSlot(90 + armor.armorType).putStack(transferredStack);
slot.putStack(null);
@@ -8,6 +8,7 @@ import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.ContainerEnchantment;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagList;
@@ -163,14 +164,14 @@ public class ContainerEnchantmentModifier extends ContainerEnchantment {
public boolean addEnchantment(int e, int level) {
if (e < Enchantment.enchantmentsList.length && Enchantment.enchantmentsList[e] != null) {
inventorySlots.get(0).getStack().addEnchantment(Enchantment.enchantmentsList[e], level);
((Slot) inventorySlots.get(0)).getStack().addEnchantment(Enchantment.enchantmentsList[e], level);
return true;
}
return false;
}
public void removeEnchantment(int e) {
ItemStack stack = inventorySlots.get(0).getStack();
ItemStack stack = ((Slot) inventorySlots.get(0)).getStack();
NBTTagList nbttaglist = stack.getEnchantmentTagList();
if (nbttaglist != null) {
for (int i = 0; i < nbttaglist.tagCount(); i++) {
@@ -20,7 +20,7 @@ public class DefaultHighlightHandler implements IHighlightHandler {
String name = null;
try {
String s = GuiContainerManager.itemDisplayNameShort(stack);
if (!s.endsWith("Unnamed")) name = s;
if (s != null && !s.endsWith("Unnamed")) name = s;
if (name != null) currenttip.add(name);
} catch (Exception ignored) {}
@@ -91,7 +91,7 @@ public class FastTransferManager {
public static void clearSlots(Container container) {
for (int slotNo = 0; slotNo < container.inventorySlots.size(); slotNo++)
container.inventorySlots.get(slotNo).putStack(null);
((Slot) container.inventorySlots.get(slotNo)).putStack(null);
}
public void performMassTransfer(GuiContainer window, int fromSlot, int toSlot, ItemStack heldStack) {
@@ -289,7 +289,7 @@ public class FastTransferManager {
if (held == null) return -1;
for (int i = 0; i < window.inventorySlots.inventorySlots.size(); i++) {
for (int i = 0; held != null && i < window.inventorySlots.inventorySlots.size(); i++) {
final Slot slot = window.inventorySlots.inventorySlots.get(i);
if (slot.inventory instanceof InventoryPlayer && !slot.getHasStack() && slot.isItemValid(held)) {
@@ -225,7 +225,7 @@ public class FavoriteRecipes {
continue;
}
if (FAVORITE_ITEM.equals(recipeId.getHandlerName()) || RecipeHandlerRef.of(recipeId) != null) {
if (FAVORITE_ITEM.equals(recipeId.getHandleName()) || RecipeHandlerRef.of(recipeId) != null) {
manualFavorites.add(stack, recipeId);
} else {
hasErrors = true;
@@ -296,26 +296,15 @@ public class FormattedTextField extends GuiTextField {
int shift = 0;
for (int i = 0; i < position; i++) {
while (this.formattedText.length() > i + shift + 1 && this.formattedText.charAt(i + shift) == '\u00a7'
&& isFormattingCode(this.formattedText.charAt(i + shift + 1))) {
while (this.formattedText.length() > i + shift && this.formattedText.charAt(i + shift) == '\u00a7') {
shift += 2;
}
}
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';
return position + shift;
}
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);
@@ -24,8 +24,8 @@ public class GuiEnchantmentModifier extends GuiContainer {
@Override
protected void drawGuiContainerForegroundLayer(int par1, int par2) {
fontRendererObj.drawString(translate("enchant"), 12, 6, ColorUtils.textGray.getColor());
fontRendererObj.drawString(translate("enchant.level"), 19, 20, ColorUtils.textGray.getColor());
fontRendererObj.drawString(translate("enchant"), 12, 6, 0x404040);
fontRendererObj.drawString(translate("enchant.level"), 19, 20, 0x404040);
}
protected void drawGuiContainerBackgroundLayer(float f, int i, int j) {
@@ -39,11 +39,7 @@ public class GuiEnchantmentModifier extends GuiContainer {
container.drawScrollBar(this);
String levelstring = "" + container.level;
fontRendererObj.drawString(
levelstring,
33 - fontRendererObj.getStringWidth(levelstring) / 2,
34,
ColorUtils.textLightGray.getColor());
fontRendererObj.drawString(levelstring, 33 - fontRendererObj.getStringWidth(levelstring) / 2, 34, 0xFF606060);
GL11.glTranslatef(-guiLeft, -guiTop, 0);
}
@@ -82,8 +78,8 @@ public class GuiEnchantmentModifier extends GuiContainer {
private void changeLevel(int i) {
container.level += i;
buttonList.get(0).enabled = container.level != 1;
buttonList.get(1).enabled = container.level != 10;
((GuiButton) buttonList.get(0)).enabled = container.level != 1;
((GuiButton) buttonList.get(1)).enabled = container.level != 10;
}
protected void mouseClicked(int i, int j, int k) {
@@ -45,14 +45,15 @@ public class GuiNEIButton extends GuiButton {
}
protected int getTextColour(boolean mouseOver) {
int color = 0xe0e0e0;
if (!enabled) {
return ColorUtils.buttonLabelInactive.getColor();
color = 0xffa0a0a0;
} else if (mouseOver) {
return ColorUtils.buttonLabelHover.getColor();
color = 0xffffa0;
}
return ColorUtils.buttonLabelNormal.getColor();
return color;
}
protected void drawContent(Minecraft minecraft, int y, int x, boolean mouseOver) {
@@ -289,10 +289,10 @@ public class GuiPotionCreator extends GuiContainerWidget {
CCRenderState.changeTexture("nei:textures/gui/potion.png");
drawTexturedModalRect(0, 0, 0, 0, xSize, ySize);
FontUtils.drawCenteredString(translate("potion.favourite"), xSize / 2, 4, ColorUtils.textGray.getColor());
fontRendererObj.drawString(translate("potion.duration"), 12, 40, ColorUtils.textGray.getColor());
fontRendererObj.drawString(translate("potion.level"), 19, 73, ColorUtils.textGray.getColor());
FontUtils.drawCenteredString(translateAmplifier(amplifier), 33, 86, ColorUtils.textGray.getColor());
FontUtils.drawCenteredString(translate("potion.favourite"), xSize / 2, 4, 0x404040);
fontRendererObj.drawString(translate("potion.duration"), 12, 40, 0x404040);
fontRendererObj.drawString(translate("potion.level"), 19, 73, 0x404040);
FontUtils.drawCenteredString(translateAmplifier(amplifier), 33, 86, 0xFF606060);
}
@Override
@@ -28,7 +28,7 @@ public class HUDRenderer implements IKeyStateTracker {
@Override
public void tickKeyStates() {
if (KeyManager.isPressed("world.highlight_tips")) {
if (KeyManager.keyStates.get("world.highlight_tips").down) {
ConfigTag tag = NEIClientConfig.getSetting("world.highlight_tips");
tag.setBooleanValue(!tag.getBooleanValue());
}
@@ -73,7 +73,6 @@ public class IMCForNEI {
API.registerRecipeHandler(new ProfilerRecipeHandler(true));
API.registerUsageHandler(new ProfilerRecipeHandler(false));
sendProfilerRecipeHandler();
}
private static void sendHandler(String aName, String aBlock) {
@@ -137,19 +136,6 @@ 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);
@@ -30,7 +30,14 @@ public class InfiniteStackSizeHandler implements IInfiniteItemHandler {
@Override
public void replenishInfiniteStack(InventoryPlayer inv, int slotNo) {
inv.getStackInSlot(slotNo).stackSize = 111;
ItemStack stack = inv.getStackInSlot(slotNo);
stack.stackSize = 111;
for (int i = 0; i < inv.getSizeInventory(); i++) {
if (i == slotNo) continue;
if (NEIServerUtils.areStacksSameType(stack, inv.getStackInSlot(i))) inv.setInventorySlotContents(i, null);
}
}
@Override
@@ -241,7 +241,7 @@ public class ItemCraftablesPanel
private GuiContainer getGuiContainer() {
final GuiContainer firstGui = NEIClientUtils.getGuiContainer();
return (firstGui instanceof GuiRecipe<?>gui) ? gui.firstGui : firstGui;
return (firstGui instanceof GuiRecipe gui) ? gui.firstGui : firstGui;
}
private Map<ItemStack, RecipeId> generateCraftables(GuiContainer firstGui) {
+273 -13
View File
@@ -2,23 +2,40 @@ package codechicken.nei;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinWorkerThread;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import net.minecraft.client.Minecraft;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.IIcon;
import net.minecraftforge.fluids.IFluidContainerItem;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import codechicken.nei.ThreadOperationTimer.TimeoutException;
import codechicken.nei.api.ItemFilter;
import codechicken.nei.api.ItemFilter.ItemFilterProvider;
import codechicken.nei.api.ItemInfo;
import codechicken.nei.recipe.InformationHandler;
import codechicken.nei.recipe.RecipeHandlerRef;
import codechicken.nei.recipe.RepairRecipeHandler;
import codechicken.nei.search.TooltipFilter;
import codechicken.nei.util.ItemUntranslator;
import cpw.mods.fml.common.FMLLog;
public class ItemList {
@@ -36,6 +53,9 @@ public class ItemList {
public static final List<ItemFilterProvider> itemFilterers = new LinkedList<>();
public static final List<ItemsLoadedCallback> loadCallbacks = new LinkedList<>();
private static final HashSet<Item> erroredItems = new HashSet<>();
private static final HashSet<String> stackTraces = new HashSet<>();
private static Map<ItemStack, Integer> ordering = new HashMap<>();
/**
* Unlike {@link LayoutManager#itemsLoaded}, this indicates whether item loading is actually finished or not.
*/
@@ -97,15 +117,7 @@ public class ItemList {
displayName = EnumChatFormatting
.getTextWithoutFormattingCodes(item.getItem().getItemStackDisplayName(item));
if (displayName != null && !displayName.isEmpty() && this.pattern.matcher(displayName).find()) {
return true;
}
}
for (String alias : ItemInfo.getAliases(item)) {
if (this.pattern.matcher(alias).find()) {
return true;
}
return displayName != null && !displayName.isEmpty() && this.pattern.matcher(displayName).find();
}
return false;
@@ -206,6 +218,231 @@ public class ItemList {
return filters;
}
public static final RestartableTask loadItems = new RestartableTask("NEI Item Loading") {
private void damageSearch(Item item, List<ItemStack> permutations) {
HashSet<String> damageIconSet = new HashSet<>();
for (int damage = 0; damage < 16; damage++) try {
ItemStack itemstack = new ItemStack(item, 1, damage);
IIcon icon = item.getIconIndex(itemstack);
String name = getTooltip(itemstack);
String s = name + "@" + (icon == null ? 0 : icon.hashCode());
if (damageIconSet.add(s)) {
permutations.add(itemstack);
}
} catch (TimeoutException t) {
throw t;
} catch (Throwable t) {
NEIServerUtils.logOnce(
t,
stackTraces,
"Ommiting " + item + ":" + damage + " " + item.getClass().getSimpleName(),
item.toString());
}
}
private String getTooltip(ItemStack stack) {
try {
return String.join("\n", stack.getTooltip(Minecraft.getMinecraft().thePlayer, false));
} catch (Throwable ignored) {}
return "";
}
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<>();
int orderIndex = 0;
for (ItemStack stack : items) {
final int groupIndex = CollapsibleItems.getGroupIndex(stack);
if (groupIndex == -1) {
newOrdering.put(stack, orderIndex++);
} else {
if (!groups.containsKey(groupIndex)) {
groups.put(groupIndex, orderIndex++);
}
newOrdering.put(stack, groups.get(groupIndex));
}
}
} else {
int orderIndex = 0;
for (ItemStack stack : items) {
newOrdering.put(stack, orderIndex++);
}
}
ItemList.ordering = newOrdering;
}
private List<ItemStack> getPermutations(Item item) {
final List<ItemStack> permutations = new LinkedList<>(ItemInfo.itemOverrides.get(item));
if (permutations.isEmpty()) {
item.getSubItems(item, null, permutations);
}
if (permutations.isEmpty()) {
damageSearch(item, permutations);
}
permutations.addAll(ItemInfo.itemVariants.get(item));
return permutations.stream()
.filter(
stack -> stack.getItem() != null && stack.getItem().delegate.name() != null
&& !ItemInfo.isHidden(stack))
.collect(Collectors.toList());
}
private void runChecked(ItemStack stack, Runnable action, String reason) {
int hashOld = 0;
if (stack.hasTagCompound()) {
hashOld = stack.stackTagCompound.hashCode();
}
action.run();
if (stack.hasTagCompound() && hashOld != stack.stackTagCompound.hashCode()) {
FMLLog.warning(
"NEI: Forced tag update with reason (" + reason
+ ") for "
+ stack
+ "("
+ stack.getItem()
+ ")");
}
}
private void forceTagCompoundInitialization(ItemStack stack) {
Item item = stack.getItem();
if (item == null) {
return;
}
if (item instanceof IFluidContainerItem) {
IFluidContainerItem fluidItem = (IFluidContainerItem) item;
runChecked(stack, () -> fluidItem.getFluid(stack), "getFluid");
}
runChecked(stack, () -> item.isDamaged(stack), "isDamaged");
runChecked(stack, () -> item.getDamage(stack), "getDamage");
runChecked(stack, () -> item.showDurabilityBar(stack), "showDurabilityBar");
runChecked(stack, () -> item.getAttributeModifiers(stack), "getAttributeModifiers");
runChecked(stack, () -> item.getDurabilityForDisplay(stack), "getDurabilityForDisplay");
runChecked(stack, () -> item.getItemStackLimit(stack), "getItemStackLimit");
runChecked(stack, () -> item.getToolClasses(stack), "getToolClasses");
runChecked(stack, () -> item.getUnlocalizedNameInefficiently(stack), "getUnlocalizedNameInefficiently");
runChecked(stack, () -> item.hasEffect(stack), "hasEffect");
runChecked(stack, () -> item.getDigSpeed(stack, Blocks.stone, 0), "getDigSpeed");
/*
* unused... for now runChecked(stack, () -> GameRegistry.getFuelValue(stack), "getFuelValue");
* runChecked(stack, () -> item.getUnlocalizedName(stack), "getUnlocalizedName"); runChecked(stack, () ->
* item.doesContainerItemLeaveCraftingGrid(stack), "doesContainerItemLeaveCraftingGrid"); runChecked(stack,
* () -> item.getItemUseAction(stack), "getItemUseAction"); runChecked(stack, () ->
* item.getMaxItemUseDuration(stack), "getMaxItemUseDuration"); runChecked(stack, () ->
* item.getPotionEffect(stack), "getPotionEffect"); runChecked(stack, () -> item.isPotionIngredient(stack),
* "isPotionIngredient"); runChecked(stack, () -> item.getRarity(stack), "getRarity"); runChecked(stack, ()
* -> item.hasCustomEntity(stack), "hasCustomEntity"); runChecked(stack, () ->
* item.getSmeltingExperience(stack), "getSmeltingExperience"); runChecked(stack, () ->
* item.getMaxDamage(stack), "getMaxDamage"); runChecked(stack, () -> item.getDamage(stack), "getDamage");
* runChecked(stack, stack::isItemDamaged, "isItemDamaged"); runChecked(stack, () -> item.hasEffect(stack,
* 0), "hasEffect"); runChecked(stack, () -> item.getItemEnchantability(stack), "getItemEnchantability");
* runChecked(stack, () -> item.isBeaconPayment(stack), "isBeaconPayment"); runChecked(stack, () ->
* item.getDamage(stack), "getDamage"); runChecked(stack, () -> item.getDamage(stack), "getDamage");
* runChecked(stack, () -> item.getDamage(stack), "getDamage");
*/
}
// Generate itemlist, permutations, orders, collapsibleitems, and informationhandler stacks
@Override
@SuppressWarnings("unchecked")
public void execute() {
if (!NEIClientConfig.isEnabled() || NEIClientUtils.mc().thePlayer == null) return;
ThreadOperationTimer timer = getTimer(NEIClientConfig.getItemLoadingTimeout());
LayoutManager.itemsLoaded = true;
loadFinished = false;
SearchField.searchParser.clearCache();
ItemSorter.instance.ordering.clear();
CollapsibleItems.clearCache();
TooltipFilter.clearCache();
InformationHandler.clearCache();
List<ItemStack> items = new ArrayList<>();
ListMultimap<Item, ItemStack> itemMap = ArrayListMultimap.create();
ItemStackSet unique = new ItemStackSet();
StreamSupport.stream(((Iterable<Item>) Item.itemRegistry).spliterator(), true).forEach(item -> {
if (item == null || item.delegate.name() == null || erroredItems.contains(item)) return;
try {
timer.reset(item);
List<ItemStack> permutations = getPermutations(item);
timer.reset();
for (ItemStack stack : permutations) {
if (!unique.contains(stack)) {
synchronized (unique) {
unique.add(stack);
}
synchronized (items) {
items.add(stack);
}
forceTagCompoundInitialization(stack);
CollapsibleItems.putItem(stack);
TooltipFilter.getSearchTooltip(stack);
InformationHandler.populateStacks(stack);
}
}
synchronized (itemMap) {
itemMap.putAll(item, permutations);
}
} catch (Throwable t) {
NEIServerConfig.logger.error("Removing item: {} from list.", item, t);
erroredItems.add(item);
}
});
int index = 0;
for (Item item : (Iterable<Item>) Item.itemRegistry) {
for (ItemStack stack : itemMap.get(item)) {
ItemSorter.instance.ordering.put(stack, index++);
}
}
if (interrupted()) return;
ItemList.items = items;
ItemList.itemMap = itemMap;
for (ItemsLoadedCallback callback : loadCallbacks) callback.itemsLoaded();
if (interrupted()) return;
updateOrdering(ItemList.items);
loadFinished = true;
RepairRecipeHandler.findRepairRecipesOnceParallel();
RecipeHandlerRef.clearCache();
FavoriteRecipes.reload();
SubsetWidget.updateHiddenItems();
ItemPanels.bookmarkPanel.load();
updateFilter.restart();
}
};
public static ForkJoinPool forkJoinPool;
static {
@@ -225,12 +462,35 @@ public class ItemList {
forkJoinPool = new ForkJoinPool(poolSize, factory, null, false);
}
// The item list pipeline lives in ItemListLoader; these references are kept for backward compatibility.
public static final RestartableTask loadItems = ItemListLoader.loadItems;
public static final RestartableTask updateFilter = new RestartableTask("NEI Item Filtering") {
public static final RestartableTask refreshItems = ItemListLoader.refreshItems;
@Override
public void execute() {
public static final RestartableTask updateFilter = ItemListLoader.updateFilter;
if (!loadFinished) return;
ItemFilter filter = getItemListFilter();
ArrayList<ItemStack> filtered;
try {
filtered = ItemList.forkJoinPool.submit(
() -> items.parallelStream().filter(filter::matches)
.collect(Collectors.toCollection(ArrayList::new)))
.get();
} catch (InterruptedException | ExecutionException e) {
filtered = new ArrayList<>();
e.printStackTrace();
stop();
}
if (interrupted()) return;
filtered.sort(Comparator.comparingInt(ItemList.ordering::get));
if (interrupted()) return;
ItemPanel.updateItemList(filtered);
}
};
/**
* @deprecated Use updateFilter.restart()
@@ -1,375 +0,0 @@
package codechicken.nei;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import net.minecraftforge.fluids.IFluidContainerItem;
import com.google.common.base.Throwables;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import codechicken.nei.ItemList.ItemsLoadedCallback;
import codechicken.nei.ThreadOperationTimer.TimeoutException;
import codechicken.nei.api.ItemFilter;
import codechicken.nei.api.ItemInfo;
import codechicken.nei.recipe.InformationHandler;
import codechicken.nei.recipe.RecipeHandlerRef;
import codechicken.nei.recipe.RepairRecipeHandler;
import codechicken.nei.search.TooltipFilter;
import cpw.mods.fml.common.FMLLog;
public class ItemListLoader {
private static final HashSet<Item> erroredItems = new HashSet<>();
private static final HashSet<String> stackTraces = new HashSet<>();
private static Map<ItemStack, Integer> ordering = new HashMap<>();
private ItemListLoader() {}
private static void damageSearch(Item item, List<ItemStack> permutations) {
final Set<String> damageIconSet = new HashSet<>();
final EntityPlayer player = Minecraft.getMinecraft().thePlayer;
for (int damage = 0; damage < 16; damage++) {
try {
final ItemStack itemstack = new ItemStack(item, 1, damage);
final IIcon icon = item.getIconIndex(itemstack);
final String key = itemstack.getDisplayName() + "@"
+ (icon == null ? 0 : icon.hashCode())
+ "@"
+ getInformation(itemstack, player);
if (damageIconSet.add(key)) {
permutations.add(itemstack);
}
} catch (TimeoutException t) {
throw t;
} catch (Throwable t) {
NEIServerUtils.logOnce(
t,
stackTraces,
"Ommiting " + item + ":" + damage + " " + item.getClass().getSimpleName(),
item.toString());
}
}
}
private static String getInformation(ItemStack stack, EntityPlayer player) {
try {
final List<String> tooltip = new ArrayList<>();
stack.getItem().addInformation(stack, player, tooltip, false);
return String.join("\n", tooltip);
} catch (Throwable ignored) {}
return "";
}
private static void updateOrdering(List<ItemStack> items) {
final Map<ItemStack, Integer> newOrdering = new HashMap<>();
if (!CollapsibleItems.isEmpty()) {
final HashMap<Integer, Integer> groups = new HashMap<>();
int orderIndex = 0;
for (ItemStack stack : items) {
final int groupIndex = CollapsibleItems.getGroupIndex(stack);
if (groupIndex == -1) {
newOrdering.put(stack, orderIndex++);
} else {
if (!groups.containsKey(groupIndex)) {
groups.put(groupIndex, orderIndex++);
}
newOrdering.put(stack, groups.get(groupIndex));
}
}
} else {
int orderIndex = 0;
for (ItemStack stack : items) {
newOrdering.put(stack, orderIndex++);
}
}
ordering = newOrdering;
}
private static List<ItemStack> getPermutations(Item item) {
final List<ItemStack> permutations = new LinkedList<>(ItemInfo.itemOverrides.get(item));
if (permutations.isEmpty()) {
item.getSubItems(item, null, permutations);
}
if (permutations.isEmpty()) {
damageSearch(item, permutations);
}
permutations.addAll(ItemInfo.itemVariants.get(item));
return permutations.stream()
.filter(
stack -> stack.getItem() != null && stack.getItem().delegate.name() != null
&& !ItemInfo.isHidden(stack))
.collect(Collectors.toList());
}
private static void runChecked(ItemStack stack, Runnable action, String reason) {
int hashOld = 0;
if (stack.hasTagCompound()) {
hashOld = stack.stackTagCompound.hashCode();
}
action.run();
if (stack.hasTagCompound() && hashOld != stack.stackTagCompound.hashCode()) {
FMLLog.warning(
"NEI: Forced tag update with reason (" + reason + ") for " + stack + "(" + stack.getItem() + ")");
}
}
private static void forceTagCompoundInitialization(ItemStack stack) {
Item item = stack.getItem();
if (item == null) {
return;
}
if (item instanceof IFluidContainerItem fluidItem) {
runChecked(stack, () -> fluidItem.getFluid(stack), "getFluid");
}
runChecked(stack, () -> item.isDamaged(stack), "isDamaged");
runChecked(stack, () -> item.getDamage(stack), "getDamage");
runChecked(stack, () -> item.showDurabilityBar(stack), "showDurabilityBar");
runChecked(stack, () -> item.getAttributeModifiers(stack), "getAttributeModifiers");
runChecked(stack, () -> item.getDurabilityForDisplay(stack), "getDurabilityForDisplay");
runChecked(stack, () -> item.getItemStackLimit(stack), "getItemStackLimit");
runChecked(stack, () -> item.getToolClasses(stack), "getToolClasses");
runChecked(stack, () -> item.getUnlocalizedNameInefficiently(stack), "getUnlocalizedNameInefficiently");
runChecked(stack, () -> item.hasEffect(stack), "hasEffect");
runChecked(stack, () -> item.getDigSpeed(stack, Blocks.stone, 0), "getDigSpeed");
/*
* unused... for now runChecked(stack, () -> GameRegistry.getFuelValue(stack), "getFuelValue");
* runChecked(stack, () -> item.getUnlocalizedName(stack), "getUnlocalizedName"); runChecked(stack, () ->
* item.doesContainerItemLeaveCraftingGrid(stack), "doesContainerItemLeaveCraftingGrid"); runChecked(stack, ()
* -> item.getItemUseAction(stack), "getItemUseAction"); runChecked(stack, () ->
* item.getMaxItemUseDuration(stack), "getMaxItemUseDuration"); runChecked(stack, () ->
* item.getPotionEffect(stack), "getPotionEffect"); runChecked(stack, () -> item.isPotionIngredient(stack),
* "isPotionIngredient"); runChecked(stack, () -> item.getRarity(stack), "getRarity"); runChecked(stack, () ->
* item.hasCustomEntity(stack), "hasCustomEntity"); runChecked(stack, () -> item.getSmeltingExperience(stack),
* "getSmeltingExperience"); runChecked(stack, () -> item.getMaxDamage(stack), "getMaxDamage");
* runChecked(stack, () -> item.getDamage(stack), "getDamage"); runChecked(stack, stack::isItemDamaged,
* "isItemDamaged"); runChecked(stack, () -> item.hasEffect(stack, 0), "hasEffect"); runChecked(stack, () ->
* item.getItemEnchantability(stack), "getItemEnchantability"); runChecked(stack, () ->
* item.isBeaconPayment(stack), "isBeaconPayment"); runChecked(stack, () -> item.getDamage(stack), "getDamage");
* runChecked(stack, () -> item.getDamage(stack), "getDamage"); runChecked(stack, () -> item.getDamage(stack),
* "getDamage");
*/
}
@SuppressWarnings("unchecked")
private static List<ItemStack> gatherItems(ThreadOperationTimer timer) {
ItemSorter.instance.ordering.clear();
List<ItemStack> items = new ArrayList<>();
ListMultimap<Item, ItemStack> itemMap = ArrayListMultimap.create();
ItemStackSet unique = new ItemStackSet();
final List<Item> registryItems = new ArrayList<>();
for (Item item : (Iterable<Item>) Item.itemRegistry) registryItems.add(item);
registryItems.parallelStream().forEach(item -> {
if (item == null || item.delegate.name() == null || erroredItems.contains(item)) return;
try {
timer.reset(item);
List<ItemStack> permutations = getPermutations(item);
timer.reset();
synchronized (itemMap) {
itemMap.putAll(item, permutations);
}
} catch (Throwable t) {
NEIServerConfig.logger.error(
"Removing item: {} from list.\n{}: {}",
item,
t.getMessage(),
Throwables.getStackTraceAsString(t));
erroredItems.add(item);
}
});
int index = 0;
for (Item item : (Iterable<Item>) Item.itemRegistry) {
for (ItemStack stack : itemMap.get(item)) {
ItemSorter.instance.ordering.put(stack, index++);
if (!unique.contains(stack)) {
unique.add(stack);
items.add(stack);
}
}
}
ItemList.itemMap = itemMap;
return items;
}
private static void buildItemCaches(List<ItemStack> items) {
SearchField.searchParser.clearCache();
TooltipFilter.clearCache();
InformationHandler.clearCache();
items.parallelStream().forEach(stack -> {
try {
forceTagCompoundInitialization(stack);
InformationHandler.populateStacks(stack);
} catch (Throwable t) {
NEIServerConfig.logger.error(
"Failed to build caches for: {}\n{}: {}",
stack,
t.getMessage(),
Throwables.getStackTraceAsString(t));
}
});
}
private static void indexCollapsibleItems(List<ItemStack> items) {
CollapsibleItems.clearCache();
items.parallelStream().forEach(CollapsibleItems::putItem);
}
public static final RestartableTask loadItems = new RestartableTask("NEI Item Loading") {
@Override
public void execute() {
if (!NEIClientConfig.isEnabled() || NEIClientUtils.mc().thePlayer == null) return;
final ThreadOperationTimer timer = getTimer(NEIClientConfig.getItemLoadingTimeout());
LayoutManager.itemsLoaded = true;
ItemList.loadFinished = false;
warmTooltips.stop();
List<ItemStack> items = gatherItems(timer);
if (interrupted()) return;
buildItemCaches(items);
indexCollapsibleItems(items);
if (interrupted()) return;
ItemSorter.sort(items);
if (interrupted()) return;
ItemList.items = items;
for (ItemsLoadedCallback callback : ItemList.loadCallbacks) callback.itemsLoaded();
if (interrupted()) return;
updateOrdering(ItemList.items);
ItemList.loadFinished = true;
RepairRecipeHandler.findRepairRecipesOnceParallel();
RecipeHandlerRef.clearCache();
FavoriteRecipes.reload();
SubsetWidget.updateHiddenItems();
updateFilter.restart();
warmTooltips.restart();
loadBookmarks.restart();
}
};
public static final RestartableTask warmTooltips = new RestartableTask("NEI Tooltip Caching") {
@Override
public void execute() {
if (!ItemList.loadFinished) return;
// Use the common pool, not ItemList.forkJoinPool, so it does not queue behind updateFilter.
ItemList.items.parallelStream().forEach(stack -> {
if (interrupted()) return;
try {
TooltipFilter.getSearchTooltip(stack);
} catch (Throwable ignored) {}
});
}
};
public static final RestartableTask loadBookmarks = new RestartableTask("NEI Bookmark Loading") {
@Override
public void execute() {
ItemPanels.bookmarkPanel.load();
}
};
public static final RestartableTask refreshItems = new RestartableTask("NEI Item Reordering") {
@Override
public void execute() {
if (!ItemList.loadFinished) return;
final List<ItemStack> items = new ArrayList<>(ItemList.items);
indexCollapsibleItems(items);
if (interrupted()) return;
ItemSorter.sort(items);
if (interrupted()) return;
ItemList.items = items;
updateOrdering(ItemList.items);
FavoriteRecipes.reload();
SubsetWidget.updateHiddenItems();
updateFilter.restart();
loadBookmarks.restart();
}
};
public static final RestartableTask updateFilter = new RestartableTask("NEI Item Filtering") {
@Override
public void execute() {
if (!ItemList.loadFinished) return;
ItemFilter filter = ItemList.getItemListFilter();
ArrayList<ItemStack> filtered;
try {
filtered = ItemList.forkJoinPool.submit(
() -> ItemList.items.parallelStream().filter(filter::matches)
.collect(Collectors.toCollection(ArrayList::new)))
.get();
} catch (InterruptedException | ExecutionException e) {
filtered = new ArrayList<>();
e.printStackTrace();
stop();
}
if (interrupted()) return;
filtered.sort(Comparator.comparingInt(ordering::get));
if (interrupted()) return;
ItemPanel.updateItemList(filtered);
}
};
}
@@ -23,7 +23,6 @@ import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
import net.minecraftforge.client.MinecraftForgeClient;
import net.minecraftforge.common.util.ForgeDirection;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@@ -66,41 +65,27 @@ public class ItemMobSpawner extends ItemBlock {
@Override
public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, int x, int y, int z, int side,
float hitX, float hitY, float hitZ) {
int targetX = x;
int targetY = y;
int targetZ = z;
if (!world.getBlock(x, y, z).isReplaceable(world, x, y, z)) {
ForgeDirection direction = ForgeDirection.getOrientation(side);
targetX += direction.offsetX;
targetY += direction.offsetY;
targetZ += direction.offsetZ;
}
placedX = targetX;
placedY = targetY;
placedZ = targetZ;
String mobType = getMobTypeFromItemStack(itemstack);
placedX = x;
placedY = y;
placedZ = z;
boolean placed = super.onItemUse(itemstack, entityplayer, world, x, y, z, side, hitX, hitY, hitZ);
if (placed) {
TileEntity tileEntity = world.getTileEntity(targetX, targetY, targetZ);
if (tileEntity instanceof TileEntityMobSpawner spawner && mobType != null) {
spawner.func_145881_a().setEntityName(mobType);
if (!world.isRemote) {
world.markBlockForUpdate(targetX, targetY, targetZ);
NEICPH.sendMobSpawnerID(targetX, targetY, targetZ, mobType);
if (placed && !world.isRemote) {
TileEntity tileEntity = world.getTileEntity(x, y, z);
if (tileEntity instanceof TileEntityMobSpawner) {
TileEntityMobSpawner spawner = (TileEntityMobSpawner) tileEntity;
String mobType = getMobTypeFromItemStack(itemstack);
if (mobType != null) {
spawner.func_145881_a().setEntityName(mobType);
world.markBlockForUpdate(x, y, z);
NEICPH.sendMobSpawnerID(x, y, z, mobType);
}
}
return true;
}
return false;
return placed;
}
private String getMobTypeFromItemStack(ItemStack stack) {
@@ -238,6 +223,7 @@ public class ItemMobSpawner extends ItemBlock {
NEIClientConfig.logger.debug("Cleared all entity references from cache");
}
@SuppressWarnings("unchecked")
public static void loadSpawners() {
if (loaded) {
return;
@@ -245,7 +231,8 @@ public class ItemMobSpawner extends ItemBlock {
synchronized (ItemMobSpawner.class) {
try {
for (Map.Entry<Class<? extends Entity>, String> entry : EntityList.classToStringMapping.entrySet()) {
for (Map.Entry<Class<? extends Entity>, String> entry : ((Map<Class<? extends Entity>, String>) EntityList.classToStringMapping)
.entrySet()) {
Class<? extends Entity> clazz = entry.getKey();
String name = entry.getValue();
@@ -321,7 +308,7 @@ public class ItemMobSpawner extends ItemBlock {
String name = ENTITY_CLASS_TO_NAME_CACHE.get(entityClass);
if (name == null) {
name = EntityList.classToStringMapping.get(entityClass);
name = (String) EntityList.classToStringMapping.get(entityClass);
}
return name != null && shouldRegisterEntity(entityClass, name);
@@ -46,7 +46,8 @@ public class ItemStackMap<T> {
}
public boolean equals(Object o) {
if (!(o instanceof StackMetaKey t)) return false;
if (!(o instanceof StackMetaKey)) return false;
StackMetaKey t = (StackMetaKey) o;
return damage == t.damage && Objects.equal(tag, t.tag);
}
}
@@ -217,7 +218,8 @@ public class ItemStackMap<T> {
public void put(ItemStack key, T value) {
if (key == null || key.getItem() == null) return;
DetailMap map = itemMap.computeIfAbsent(key.getItem(), k -> new DetailMap());
DetailMap map = itemMap.get(key.getItem());
if (map == null) itemMap.put(key.getItem(), map = new DetailMap());
map.put(key, value);
}
+6 -6
View File
@@ -42,7 +42,7 @@ public class ItemZoom extends Widget implements IContainerInputHandler {
if (this.stack != null && this.availableAreaWidth >= SLOT_SIZE * 2
&& (NEIClientConfig.getBooleanSetting("inventory.itemzoom.enabled")
|| KeyManager.isKeyDown("itemzoom.hold"))
|| NEIClientConfig.isKeyHashDown("gui.itemzoom_hold"))
&& GuiContainerManager.shouldShowTooltip(NEIClientUtils.getGuiContainer())) {
final float inverseScaleFactor = 1.0f / this.scale;
final float screenScale = getScreenScale();
@@ -74,7 +74,7 @@ public class ItemZoom extends Widget implements IContainerInputHandler {
if (NEIClientConfig.getBooleanSetting("inventory.itemzoom.enabled")
&& NEIClientConfig.getBooleanSetting("inventory.itemzoom.helpText")) {
String keyName = KeyManager.getKeyName("itemzoom.toggle", NEIClientUtils.SHIFT_HASH);
String keyName = NEIClientConfig.getKeyName("gui.itemzoom_toggle");
if (keyName != null) {
String helpText = NEIClientUtils.translate("itemzoom.toggle", keyName);
@@ -198,24 +198,24 @@ public class ItemZoom extends Widget implements IContainerInputHandler {
@Override
public boolean lastKeyTyped(GuiContainer gui, char keyChar, int keyID) {
if (KeyManager.isHashDown("itemzoom.toggle", NEIClientUtils.SHIFT_HASH)) {
if (NEIClientConfig.isKeyHashDown("gui.itemzoom_toggle")) {
NEIClientConfig.getSetting("inventory.itemzoom.enabled")
.setBooleanValue(!NEIClientConfig.getBooleanSetting("inventory.itemzoom.enabled"));
return true;
}
if (this.stack != null && KeyManager.isKeyDown("itemzoom.hold")) {
if (this.stack != null && NEIClientConfig.isKeyHashDown("gui.itemzoom_hold")) {
return true;
}
if (this.stack != null && KeyManager.isKeyDown("itemzoom.zoom_in")) {
if (this.stack != null && NEIClientConfig.isKeyHashDown("gui.itemzoom_zoom_in")) {
increaseZoom(gui);
previousKeyboardRepeatEnabled = Keyboard.areRepeatEventsEnabled();
Keyboard.enableRepeatEvents(true);
return true;
}
if (this.stack != null && KeyManager.isKeyDown("itemzoom.zoom_out")) {
if (this.stack != null && NEIClientConfig.isKeyHashDown("gui.itemzoom_zoom_out")) {
decreaseZoom(gui);
previousKeyboardRepeatEnabled = Keyboard.areRepeatEventsEnabled();
Keyboard.enableRepeatEvents(true);
+2 -18
View File
@@ -15,7 +15,6 @@ 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;
@@ -28,7 +27,7 @@ public abstract class ItemsGrid<T extends ItemsGrid.ItemsGridSlot, M extends Ite
protected static class ScreenCapture {
private long nextCacheRefresh = 0;
private final Framebuffer framebuffer;
private Framebuffer framebuffer;
public ScreenCapture() {
this.framebuffer = new Framebuffer(1, 1, true);
@@ -52,7 +51,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.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_LIGHTING_BIT);
resetFramebuffer();
this.framebuffer.bindFramebuffer(false);
@@ -85,21 +84,6 @@ 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() {
@@ -92,11 +92,6 @@ public class ItemsTooltipLineHandler implements ITooltipLineHandler {
this.labelColor = color;
}
public void setLabel(String label) {
this.label = label;
this.size.width = Math.max(this.columns * SLOT_SIZE, fontRenderer.getStringWidth(this.label) + 15);
}
@Override
public void draw(int x, int y) {
if (this.length == 0) return;
+23 -131
View File
@@ -2,21 +2,14 @@ package codechicken.nei;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.StringJoiner;
import net.minecraft.client.Minecraft;
import net.minecraft.client.settings.KeyBinding;
import java.util.Map.Entry;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import codechicken.nei.util.NEIKeyboardUtils;
import codechicken.nei.util.NEIMouseUtils;
import cpw.mods.fml.client.registry.ClientRegistry;
/**
* Registers NEI key bindings as vanilla {@link KeyBinding}s and exposes their state to the rest of NEI.
* Good old down/held/up keystate tracker
*/
public class KeyManager {
@@ -25,132 +18,31 @@ public class KeyManager {
public void tickKeyStates();
}
public static class KeyState {
public boolean down;
public boolean held;
public boolean up;
}
public static HashMap<String, KeyState> keyStates = new HashMap<>();
public static LinkedList<IKeyStateTracker> trackers = new LinkedList<>();
private static final Map<String, KeyBinding> keyBindings = new HashMap<>();
private static final Map<String, String> keyAliases = new HashMap<>();
private static volatile boolean pendingOptionsReload = false;
static {
// Aliases for legacy keybinds
keyAliases.put("gui.recipe", "recipe.recipe");
keyAliases.put("gui.usage", "recipe.usage");
keyAliases.put("gui.hide_bookmarks", "bookmark.hide");
}
public static KeyBinding registerKeyBinding(String ident, int defaultKey) {
return keyBindings.computeIfAbsent(ident, id -> {
final KeyBinding binding = new KeyBinding(
"nei.options.keys." + id,
NEIKeyboardUtils.unhash(defaultKey),
categoryFor(id));
ClientRegistry.registerKeyBinding(binding);
return binding;
});
}
public static KeyBinding getKeyBinding(String ident) {
return keyBindings.get(keyAliases.getOrDefault(ident, ident));
}
public static boolean isRegistered(String description) {
for (KeyBinding binding : keyBindings.values()) {
if (binding.getKeyDescription().equals(description)) {
return true;
}
}
return false;
}
public static int getKeyCode(String ident) {
final KeyBinding binding = getKeyBinding(ident);
return binding == null ? Keyboard.KEY_NONE : binding.getKeyCode();
}
public static boolean isKeyDown(String ident) {
final KeyBinding binding = getKeyBinding(ident);
if (binding != null) {
final int keyCode = binding.getKeyCode();
if (keyCode < 0) {
return Mouse.isButtonDown(keyCode + 100);
} else if (keyCode > Keyboard.KEY_NONE && keyCode < Keyboard.KEYBOARD_SIZE) {
return Keyboard.isKeyDown(keyCode);
}
}
return false;
}
public static boolean isHashDown(String ident) {
return isHashDown(ident, 0);
}
public static boolean isHashDown(String ident, int modifierMask) {
if (!isKeyDown(ident)) {
return false;
}
if (NEIKeyboardUtils.isHashKey(getKeyCode(ident))) {
return true;
}
return ((modifierMask & NEIKeyboardUtils.CTRL_HASH) != 0) == NEIClientUtils.controlKey()
&& ((modifierMask & NEIKeyboardUtils.SHIFT_HASH) != 0) == NEIClientUtils.shiftKey()
&& ((modifierMask & NEIKeyboardUtils.ALT_HASH) != 0) == NEIClientUtils.altKey();
}
public static String getKeyName(String ident) {
return getKeyName(ident, 0);
}
public static String getKeyName(String ident, int meta) {
final int keyCode = getKeyCode(ident);
return keyCode == Keyboard.KEY_NONE ? null : NEIKeyboardUtils.getKeyName(keyCode + meta);
}
public static String getKeyName(String ident, int meta, int mouseBind) {
final int keyCode = getKeyCode(ident);
return keyCode == Keyboard.KEY_NONE && mouseBind == NEIMouseUtils.MOUSE_BTN_NONE ? null
: getKeyName(keyCode + meta, mouseBind);
}
public static String getKeyName(int keyBind, int mouseBind) {
StringJoiner keyText = new StringJoiner(" + ");
String keyHash = keyBind == Keyboard.KEY_NONE ? "" : NEIKeyboardUtils.getKeyName(keyBind);
String mouseHash = mouseBind == NEIMouseUtils.MOUSE_BTN_NONE ? "" : NEIMouseUtils.getKeyName(mouseBind);
if (!keyHash.isEmpty()) {
keyText.add(keyHash);
}
if (!mouseHash.isEmpty()) {
keyText.add(mouseHash);
}
return keyText.toString();
}
public static boolean isPressed(String ident) {
final KeyBinding binding = getKeyBinding(ident);
return binding != null && binding.isPressed();
}
private static String categoryFor(String ident) {
final int dot = ident.indexOf('.');
return dot < 0 ? "nei.options.keys" : "nei.options.keys." + ident.substring(0, dot);
}
public static void requestOptionsReload() {
pendingOptionsReload = true;
}
public static void tickKeyStates() {
for (Entry<String, KeyState> entry : keyStates.entrySet()) {
final int keyCode = NEIKeyboardUtils.unhash(NEIClientConfig.getKeyBinding(entry.getKey()));
final boolean down = keyCode > 0 && keyCode < Keyboard.KEYBOARD_SIZE && Keyboard.isKeyDown(keyCode);
final KeyState state = entry.getValue();
if (pendingOptionsReload) {
pendingOptionsReload = false;
Minecraft.getMinecraft().gameSettings.loadOptions();
if (down) {
state.down = !state.held;
state.up = false;
} else {
state.up = state.held;
state.down = false;
}
state.held = down;
}
for (IKeyStateTracker tracker : trackers) tracker.tickKeyStates();
@@ -224,17 +224,17 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
@Override
public boolean lastKeyTyped(GuiContainer gui, char keyChar, int keyID) {
if (KeyManager.isKeyDown("gui.hide")) {
if (NEIClientConfig.isKeyHashDown("gui.hide")) {
toggleBooleanSetting("inventory.hidden");
return true;
}
if (KeyManager.isKeyDown("bookmark.hide")) {
if (NEIClientConfig.isKeyHashDown("gui.hide_bookmarks")) {
toggleBooleanSetting("inventory.bookmarks.enabled");
return true;
}
if (KeyManager.isKeyDown("gui.next_tooltip") && GuiContainerManager.incrementTooltipPage()) {
if (NEIClientConfig.isKeyHashDown("gui.next_tooltip") && GuiContainerManager.incrementTooltipPage()) {
return true;
}
@@ -941,12 +941,12 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
public void tickKeyStates() {
if (Minecraft.getMinecraft().currentScreen != null) return;
if (KeyManager.isPressed("world.dawn")) timeButtons[0].onButtonPress(false);
if (KeyManager.isPressed("world.noon")) timeButtons[1].onButtonPress(false);
if (KeyManager.isPressed("world.dusk")) timeButtons[2].onButtonPress(false);
if (KeyManager.isPressed("world.midnight")) timeButtons[3].onButtonPress(false);
if (KeyManager.isPressed("world.rain")) rain.onButtonPress(false);
if (KeyManager.isPressed("world.heal")) heal.onButtonPress(false);
if (KeyManager.isPressed("world.creative")) gamemode.onButtonPress(false);
if (KeyManager.keyStates.get("world.dawn").down) timeButtons[0].onButtonPress(false);
if (KeyManager.keyStates.get("world.noon").down) timeButtons[1].onButtonPress(false);
if (KeyManager.keyStates.get("world.dusk").down) timeButtons[2].onButtonPress(false);
if (KeyManager.keyStates.get("world.midnight").down) timeButtons[3].onButtonPress(false);
if (KeyManager.keyStates.get("world.rain").down) rain.onButtonPress(false);
if (KeyManager.keyStates.get("world.heal").down) heal.onButtonPress(false);
if (KeyManager.keyStates.get("world.creative").down) gamemode.onButtonPress(false);
}
}
@@ -244,11 +244,7 @@ public class LayoutStyleMinecraft extends LayoutStyle {
Image icon = b.getRenderIcon();
if (icon == null) {
int labelColor = b.getRenderLabelColor();
int colour = labelColor != 0 ? labelColor
: tex == 2 ? ColorUtils.buttonLabelHover.getColor()
: tex == 0 ? ColorUtils.buttonLabelDisabled.getColor()
: ColorUtils.buttonLabelNormal.getColor();
int colour = tex == 2 ? 0xffffa0 : tex == 0 ? 0x601010 : 0xe0e0e0;
drawStringC(b.getRenderLabel(), b.x + b.w / 2, b.y + (b.h - 8) / 2, colour);
} else {
@@ -54,7 +54,6 @@ public class NEIActions {
addAction("magnet", true);
addAction("enchant", true);
addAction("potion", true);
addAction("autocraft");
canDisable.add("dawn");
canDisable.add("noon");
+2 -16
View File
@@ -6,7 +6,6 @@ import static codechicken.nei.PacketIDs.S2C;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.play.INetHandlerPlayClient;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.world.World;
@@ -15,7 +14,6 @@ import codechicken.core.ClientUtils;
import codechicken.lib.inventory.InventoryUtils;
import codechicken.lib.packet.PacketCustom;
import codechicken.lib.packet.PacketCustom.IClientPacketHandler;
import codechicken.nei.commands.CommandBookmarkAdd;
import cpw.mods.fml.relauncher.Side;
public class NEICPH implements IClientPacketHandler {
@@ -58,18 +56,6 @@ public class NEICPH implements IClientPacketHandler {
case S2C.OPEN_POTION_GUI:
ClientUtils.openSMPGui(packet.readUByte(), new GuiPotionCreator(mc.thePlayer.inventory));
break;
case S2C.CACHE_BOOKMARK_DATA:
handleCacheBookmarkData(packet);
break;
}
}
private void handleCacheBookmarkData(PacketCustom packet) {
final String payloadId = packet.readString();
final NBTTagCompound payloadTag = packet.readNBTTagCompound();
if (payloadTag != null) {
CommandBookmarkAdd.cachePayload(payloadId, payloadTag);
}
}
@@ -200,9 +186,9 @@ public class NEICPH implements IClientPacketHandler {
packet.sendToServer();
}
public static void sendChatLink(NBTTagCompound payloadTag) {
public static void sendChatLink(ItemStack stackover) {
PacketCustom packet = new PacketCustom(channel, C2S.SEND_CHAT_ITEM_LINK);
packet.writeNBTTagCompound(payloadTag);
packet.writeItemStack(stackover);
packet.sendToServer();
}
@@ -61,6 +61,7 @@ import codechicken.nei.recipe.IRecipeHandler;
import codechicken.nei.recipe.InformationHandler;
import codechicken.nei.recipe.RecipeCatalysts;
import codechicken.nei.util.ItemUntranslator;
import codechicken.nei.util.NEIKeyboardUtils;
import codechicken.obfuscator.ObfuscationRun;
public class NEIClientConfig {
@@ -262,10 +263,6 @@ 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));
@@ -310,7 +307,7 @@ public class NEIClientConfig {
super.onClick(button);
CollapsibleItems.saveStates();
CollapsibleItems.load();
ItemList.refreshItems.restart();
LayoutManager.markItemsDirty();
return true;
}
});
@@ -814,38 +811,35 @@ public class NEIClientConfig {
}
private static void setDefaultKeyBindings() {
API.addKeyBind("gui.enchant", Keyboard.KEY_X);
API.addKeyBind("gui.potion", Keyboard.KEY_P);
API.addHashBind("gui.recipe", Keyboard.KEY_R);
API.addHashBind("gui.usage", Keyboard.KEY_U);
API.addKeyBind("gui.back", Keyboard.KEY_BACK);
API.addHashBind("gui.enchant", Keyboard.KEY_X);
API.addHashBind("gui.potion", Keyboard.KEY_P);
API.addKeyBind("gui.prev", Keyboard.KEY_PRIOR);
API.addKeyBind("gui.next", Keyboard.KEY_NEXT);
API.addKeyBind("gui.hide", Keyboard.KEY_O);
API.addKeyBind("gui.search", Keyboard.KEY_F);
API.addKeyBind("gui.prev_machine", Keyboard.KEY_UP);
API.addKeyBind("gui.next_machine", Keyboard.KEY_DOWN);
API.addKeyBind("gui.prev_recipe", Keyboard.KEY_LEFT);
API.addKeyBind("gui.next_recipe", Keyboard.KEY_RIGHT);
API.addHashBind("gui.hide", Keyboard.KEY_O);
API.addHashBind("gui.search", Keyboard.KEY_F);
API.addKeyBind("gui.bookmark", Keyboard.KEY_A);
API.addHashBind("gui.favorite", Keyboard.KEY_F + NEIClientUtils.SHIFT_HASH);
API.addKeyBind("gui.favorite_item", Keyboard.KEY_F);
API.addHashBind("gui.remove_recipe", Keyboard.KEY_A + NEIClientUtils.SHIFT_HASH);
API.addKeyBind("gui.bookmark_pull_items", Keyboard.KEY_V);
API.addKeyBind("gui.overlay", Keyboard.KEY_S);
API.addKeyBind("gui.craft_items", Keyboard.KEY_C);
API.addHashBind("gui.hide_bookmarks", Keyboard.KEY_B);
API.addKeyBind("gui.getprevioussearch", Keyboard.KEY_UP);
API.addKeyBind("gui.getnextsearch", Keyboard.KEY_DOWN);
API.addKeyBind("gui.next_tooltip", Keyboard.KEY_Z);
API.addKeyBind("recipe.recipe", Keyboard.KEY_R);
API.addKeyBind("recipe.usage", Keyboard.KEY_U);
API.addKeyBind("recipe.back", Keyboard.KEY_BACK);
API.addKeyBind("recipe.prev_machine", Keyboard.KEY_UP);
API.addKeyBind("recipe.next_machine", Keyboard.KEY_DOWN);
API.addKeyBind("recipe.prev_recipe", Keyboard.KEY_LEFT);
API.addKeyBind("recipe.next_recipe", Keyboard.KEY_RIGHT);
API.addKeyBind("bookmark.add", Keyboard.KEY_A);
API.addKeyBind("bookmark.favorite", Keyboard.KEY_F);
API.addKeyBind("bookmark.favorite_item", Keyboard.KEY_F);
API.addKeyBind("bookmark.remove_recipe", Keyboard.KEY_A);
API.addKeyBind("bookmark.pull_items", Keyboard.KEY_V);
API.addKeyBind("bookmark.chat_link", Keyboard.KEY_L);
API.addKeyBind("bookmark.hide", Keyboard.KEY_B);
API.addKeyBind("itemzoom.toggle", Keyboard.KEY_Z);
API.addKeyBind("itemzoom.hold", 0);
API.addKeyBind("itemzoom.zoom_in", 0);
API.addKeyBind("itemzoom.zoom_out", 0);
API.addHashBind("gui.itemzoom_toggle", Keyboard.KEY_Z + NEIClientUtils.SHIFT_HASH);
API.addHashBind("gui.itemzoom_hold", 0);
API.addHashBind("gui.itemzoom_zoom_in", 0);
API.addHashBind("gui.itemzoom_zoom_out", 0);
API.addKeyBind("world.chunkoverlay", Keyboard.KEY_F9);
API.addKeyBind("world.moboverlay", Keyboard.KEY_F7);
@@ -857,10 +851,10 @@ public class NEIClientConfig {
API.addKeyBind("world.rain", 0);
API.addKeyBind("world.heal", 0);
API.addKeyBind("world.creative", 0);
API.addKeyBind("copy.name", Keyboard.KEY_C);
API.addKeyBind("copy.oredict", Keyboard.KEY_D);
API.addKeyBind("copy.identifier", Keyboard.KEY_X);
API.addHashBind("gui.copy_name", Keyboard.KEY_C + NEIClientUtils.CTRL_HASH);
API.addHashBind("gui.copy_oredict", Keyboard.KEY_D + NEIClientUtils.CTRL_HASH);
API.addHashBind("gui.copy_id", Keyboard.KEY_X + NEIClientUtils.CTRL_HASH);
API.addHashBind("gui.chat_link_item", Keyboard.KEY_L + NEIClientUtils.CTRL_HASH);
}
public static OptionList getOptionList() {
@@ -882,14 +876,9 @@ public class NEIClientConfig {
world = new ConfigSet(new File(specificDir, "NEI.dat"), new ConfigFile(new File(specificDir, "NEI.cfg")));
if (newWorld && Minecraft.getMinecraft().isSingleplayer() && getLockedMode() == -1) {
final int globalMode = global.config.getTag("inventory.cheatmode").getIntValue();
final int worldMode = Math
.min(globalMode, NEIClientUtils.mc().playerController.isInCreativeMode() ? 2 : 0);
if (worldMode != globalMode) {
world.config.getTag("inventory.cheatmode").setIntValue(worldMode);
}
if (newWorld && Minecraft.getMinecraft().isSingleplayer()) {
world.config.getTag("inventory.cheatmode")
.setIntValue(NEIClientUtils.mc().playerController.isInCreativeMode() ? 2 : 0);
}
bootNEI();
@@ -926,7 +915,9 @@ public class NEIClientConfig {
return;
}
ItemPanels.bookmarkPanel.save();
if (ItemPanels.bookmarkPanel != null) {
ItemPanels.bookmarkPanel.save();
}
SubsetWidget.saveHidden();
FavoriteRecipes.save();
@@ -934,28 +925,50 @@ public class NEIClientConfig {
world.saveNBT();
}
private static final Map<String, String> keySettings = new HashMap<>();
public static int getKeyBinding(String string) {
return KeyManager.getKeyCode(string);
final String key = keySettings.computeIfAbsent(string, s -> "keys." + s);
return getSetting(key).getIntValue(Keyboard.KEY_NONE);
}
public static void setDefaultKeyBinding(String string, int key) {
KeyManager.registerKeyBinding(string, key);
getSetting("keys." + string).getIntValue(key);
}
public static boolean isKeyHashDown(String string) {
return KeyManager.isHashDown(string);
final int hash = getKeyBinding(string);
if (hash != Keyboard.CHAR_NONE && Keyboard.getEventKeyState()) {
return KeyManager.keyStates.containsKey(string) ? Keyboard.isKeyDown(NEIKeyboardUtils.unhash(hash))
: hash == NEIClientUtils.getKeyHash();
}
return false;
}
public static String getKeyName(String keyBind) {
return KeyManager.getKeyName(keyBind);
return getKeyName(keyBind, 0);
}
public static String getKeyName(String keyBind, int meta, int mouseBind) {
return KeyManager.getKeyName(keyBind, meta, mouseBind);
final int hash = getKeyBinding(keyBind);
if (hash == Keyboard.CHAR_NONE) {
return null;
}
return NEIClientUtils.getKeyName(hash + meta, mouseBind);
}
public static String getKeyName(String keyBind, int meta) {
return KeyManager.getKeyName(keyBind, meta);
final int hash = getKeyBinding(keyBind);
if (hash == Keyboard.CHAR_NONE) {
return null;
}
return NEIKeyboardUtils.getKeyName(hash + meta);
}
public static void bootNEI() {
@@ -990,7 +1003,6 @@ public class NEIClientConfig {
}
});
KeyManager.requestOptionsReload();
RecipeCatalysts.loadCatalystInfo();
SubsetWidget.loadCustomSubsets();
SubsetWidget.loadHidden();
@@ -1009,11 +1021,7 @@ public class NEIClientConfig {
}.start();
} else {
SubsetWidget.loadHidden();
if (ItemList.loadFinished) {
ItemList.refreshItems.restart();
} else {
ItemList.loadItems.restart();
}
ItemList.loadItems.restart();
}
}
@@ -1037,9 +1045,7 @@ public class NEIClientConfig {
}
public static boolean autocraftingEnabled() {
if (!getBooleanSetting("inventory.autocrafting")) return false;
if (hasSMPCounterpart) return permissableActions.contains("autocraft");
return true;
return getBooleanSetting("inventory.autocrafting");
}
public static boolean favoritesEnabled() {
@@ -25,6 +25,7 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.StringJoiner;
import java.util.stream.Collectors;
import net.minecraft.client.Minecraft;
@@ -38,7 +39,6 @@ import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.IChatComponent;
import net.minecraft.util.ResourceLocation;
@@ -57,6 +57,7 @@ import codechicken.nei.api.GuiInfo;
import codechicken.nei.api.IInfiniteItemHandler;
import codechicken.nei.api.ItemInfo;
import codechicken.nei.util.NEIKeyboardUtils;
import codechicken.nei.util.NEIMouseUtils;
public class NEIClientUtils extends NEIServerUtils {
@@ -94,7 +95,6 @@ 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;
@@ -126,7 +126,7 @@ public class NEIClientUtils extends NEIServerUtils {
});
}
public static String formatNumber(Number aNumber) {
public static String formatNumber(long aNumber) {
if (NEIModContainer.isGTNHLibLoaded()) {
return NumberFormatUtil.formatNumber(aNumber);
@@ -135,7 +135,7 @@ public class NEIClientUtils extends NEIServerUtils {
return getDecimalFormat().format(aNumber);
}
public static String formatFluid(Number aNumber) {
public static String formatFluid(long aNumber) {
if (NEIModContainer.isGTNHLibLoaded()) {
return NumberFormatUtil.formatFluid(aNumber);
@@ -144,10 +144,6 @@ 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);
}
@@ -380,8 +376,8 @@ public class NEIClientUtils extends NEIServerUtils {
else sendCommand(getStringSetting("command.heal"), mc().thePlayer.getCommandSenderName());
}
public static void sendChatItemLink(NBTTagCompound payload) {
if (hasSMPCounterPart()) NEICPH.sendChatLink(payload);
public static void sendChatItemLink(ItemStack stackover) {
if (hasSMPCounterPart()) NEICPH.sendChatLink(stackover);
}
public static void toggleMagnetMode() {
@@ -455,8 +451,55 @@ public class NEIClientUtils extends NEIServerUtils {
return Keyboard.isKeyDown(Keyboard.KEY_LMENU) || Keyboard.isKeyDown(Keyboard.KEY_RMENU);
}
public static int getMetaHash() {
if (Keyboard.getEventKeyState()) {
int hash = 0;
if (altKey()) {
hash = hash | ALT_HASH;
}
if (shiftKey()) {
hash = hash | SHIFT_HASH;
}
if (controlKey()) {
hash = hash | CTRL_HASH;
}
return hash;
}
return 0;
}
public static int getKeyHash() {
if (Keyboard.getEventKeyState()) {
final int keycode = Keyboard.getEventKey();
if (!NEIKeyboardUtils.isHashKey(keycode)) {
return getMetaHash() + keycode;
}
}
return Keyboard.CHAR_NONE;
}
public static String getKeyName(int keyBind, int mouseBind) {
return KeyManager.getKeyName(keyBind, mouseBind);
StringJoiner keyText = new StringJoiner(" + ");
String keyHash = keyBind == Keyboard.KEY_NONE ? "" : NEIKeyboardUtils.getKeyName(keyBind);
String mouseHash = mouseBind == NEIMouseUtils.MOUSE_BTN_NONE ? "" : NEIMouseUtils.getKeyName(mouseBind);
if (!keyHash.isEmpty()) {
keyText.add(keyHash);
}
if (!mouseHash.isEmpty()) {
keyText.add(mouseHash);
}
return keyText.toString();
}
public static void playClickSound() {
@@ -1,16 +1,15 @@
package codechicken.nei;
import static codechicken.lib.gui.GuiDraw.getMousePosition;
import static codechicken.nei.NEIClientConfig.canCheatItem;
import java.awt.Point;
import java.util.LinkedList;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.gui.inventory.GuiContainerCreative;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Slot;
import net.minecraft.inventory.SlotCrafting;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.client.ClientCommandHandler;
@@ -27,7 +26,7 @@ import codechicken.nei.commands.CommandUntranslator;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.guihook.IContainerInputHandler;
import codechicken.nei.guihook.IContainerSlotClickHandler;
import codechicken.nei.util.EmptyContainer;
import codechicken.nei.recipe.GuiRecipe;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@@ -77,38 +76,29 @@ public class NEIController implements IContainerSlotClickHandler, IContainerInpu
public static void updateUnlimitedItems(InventoryPlayer inventory) {
if (!NEIClientConfig.canPerformAction("item") || !NEIClientConfig.hasSMPCounterPart()) return;
int size = inventory.getSizeInventory();
for (int i = 0; i < size; i++) {
LinkedList<ItemStack> beforeStacks = new LinkedList<>();
for (int i = 0; i < inventory.getSizeInventory(); i++)
beforeStacks.add(NEIServerUtils.copyStack(inventory.getStackInSlot(i)));
for (int i = 0; i < inventory.getSizeInventory(); i++) {
ItemStack stack = inventory.getStackInSlot(i);
if (stack == null) continue;
for (IInfiniteItemHandler handler : ItemInfo.infiniteHandlers) {
if (!handler.canHandleItem(stack) || !handler.isItemInfinite(stack)) continue;
for (IInfiniteItemHandler handler : ItemInfo.infiniteHandlers)
if (handler.canHandleItem(stack) && handler.isItemInfinite(stack))
handler.replenishInfiniteStack(inventory, i);
}
long beforeSize = packStackSize(stack.stackSize, stack.getItemDamage());
handler.replenishInfiniteStack(inventory, i);
for (int i = 0; i < inventory.getSizeInventory(); i++) {
ItemStack newstack = inventory.getStackInSlot(i);
ItemStack newstack = inventory.getStackInSlot(i);
if (!sameStack(stack, beforeSize, newstack)) {
NEIClientUtils.setSlotContents(i, newstack, false); // sends via SMP handler ;)
stack.stackSize = (int) (beforeSize >> 32);
stack.setItemDamage((int) beforeSize);
inventory.setInventorySlotContents(i, stack); // restore in case of SMP fail
}
if (!NEIServerUtils.areStacksIdentical(beforeStacks.get(i), newstack)) {
inventory.setInventorySlotContents(i, beforeStacks.get(i)); // restore in case of SMP fail
NEIClientUtils.setSlotContents(i, newstack, false); // sends via SMP handler ;)
}
}
}
private static long packStackSize(int stackSize, int itemDamage) {
return ((long) stackSize << 32) | (itemDamage & 0xFFFFFFFFL);
}
private static boolean sameStack(ItemStack before, long beforeSize, ItemStack stack) {
if (stack == null) return before == null;
return before != null && Item.getIdFromItem(before.getItem()) == Item.getIdFromItem(stack.getItem())
&& beforeSize == packStackSize(stack.stackSize, stack.getItemDamage());
}
public static void processCreativeCycling(InventoryPlayer inventory) {
if (NEIClientConfig.invCreativeMode() && NEIClientUtils.controlKey()) {
if (selectedItem != inventory.currentItem) {
@@ -161,8 +151,6 @@ 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;
}
@@ -261,7 +249,7 @@ public class NEIController implements IContainerSlotClickHandler, IContainerInpu
// slot in GuiRecipe does not contain actual stack
// and scroll should be handled by GuiRecipe, not here
if (gui.inventorySlots instanceof EmptyContainer) return false;
if (gui instanceof GuiRecipe) return false;
Point mousePos = getMousePosition();
Slot mouseover = manager.window.getSlotAtPosition(mousePos.x, mousePos.y);
@@ -43,7 +43,6 @@ public class NEIModContainer extends DummyModContainer {
private static boolean gregTech5Loaded;
private static boolean gtnhLibLoaded;
private static boolean cubicChunksLoaded;
private static ASMDataTable asmDataTable;
@@ -70,10 +69,6 @@ public class NEIModContainer extends DummyModContainer {
return gtnhLibLoaded;
}
public static boolean isCCLoaded() {
return cubicChunksLoaded;
}
@Override
public Set<ArtifactVersion> getRequirements() {
Set<ArtifactVersion> deps = new HashSet<>();
@@ -101,7 +96,6 @@ public class NEIModContainer extends DummyModContainer {
public void preInit(FMLPreInitializationEvent event) {
gregTech5Loaded = Loader.isModLoaded("gregtech") && !Loader.isModLoaded("gregapi_post");
gtnhLibLoaded = Loader.isModLoaded("gtnhlib");
cubicChunksLoaded = Loader.isModLoaded("cubicchunks");
if (CommonUtils.isClient()) ClientHandler.preInit();
asmDataTable = event.getAsmData();
}
+1 -3
View File
@@ -11,7 +11,6 @@ import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.inventory.InventoryBasic;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.play.INetHandlerPlayServer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityMobSpawner;
@@ -96,8 +95,7 @@ public class NEISPH implements IServerPacketHandler {
}
private void handleSendChatItemLink(EntityPlayerMP sender, PacketCustom packet) {
final NBTTagCompound payloadTag = packet.readNBTTagCompound();
NEIServerUtils.sendChatItemLink(sender, payloadTag);
NEIServerUtils.sendChatItemLink(sender, packet.readItemStack());
}
private void handleDummySlotSet(EntityPlayerMP sender, PacketCustom packet) {
@@ -108,7 +108,6 @@ public class NEIServerConfig {
setDefaultFeature("save-state");
setDefaultFeature("item");
setDefaultFeature("delete");
setDefaultFeature("autocraft", "ALL");
setDefaultFeature("notify-item", "CONSOLE, OP");
}
@@ -10,7 +10,6 @@ import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.zip.ZipException;
import net.minecraft.command.ICommandSender;
@@ -29,11 +28,11 @@ import net.minecraft.nbt.NBTException;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.IChatComponent;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraft.world.WorldSettings.GameType;
import net.minecraftforge.oredict.OreDictionary;
@@ -45,7 +44,6 @@ import codechicken.lib.inventory.InventoryRange;
import codechicken.lib.inventory.InventoryUtils;
import codechicken.lib.packet.PacketCustom;
import codechicken.nei.PacketIDs.S2C;
import codechicken.nei.recipe.StackInfo;
import codechicken.nei.util.NBTHelper;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.registry.GameRegistry;
@@ -75,7 +73,7 @@ public class NEIServerUtils {
public static void toggleRaining(World world, boolean notify) {
boolean raining = !world.isRaining();
if (!raining) // turn off
world.provider.resetRainAndThunder();
((WorldServer) world).provider.resetRainAndThunder();
else world.getWorldInfo().setRaining(!isRaining(world));
if (notify)
@@ -88,46 +86,16 @@ public class NEIServerUtils {
player.extinguish();
}
public static void sendChatItemLink(EntityPlayerMP sender, NBTTagCompound payload) {
if (payload == null) {
sender.addChatMessage(new ChatComponentText("Invalid bookmark payload"));
return;
}
final String linkType = payload.getString("linkType");
final String payloadId = UUID.randomUUID().toString().substring(0, 8);
final PacketCustom packet = new PacketCustom(NEISPH.channel, S2C.CACHE_BOOKMARK_DATA).writeString(payloadId)
.writeNBTTagCompound((NBTTagCompound) payload.copy());
for (EntityPlayer player : ServerUtils.getPlayers()) {
if (player instanceof EntityPlayerMP playerMP) {
packet.sendToPlayer(playerMP);
}
}
try {
final IChatComponent clickable;
if (payload.hasKey("item")) {
clickable = StackInfo.loadFromNBT(payload.getCompoundTag("item")).func_151000_E();
} else {
clickable = new ChatComponentText("[")
.appendSibling(new ChatComponentTranslation("nei.chat.item_link." + linkType + ".text"))
.appendText("]");
}
if (clickable == null) {
throw new Exception("Invalid ItemStack NBT");
}
clickable.getChatStyle()
.setChatClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/nei_bookmark " + payloadId));
ServerUtils.sendChatToAll(
new ChatComponentTranslation("nei.chat.item_link.text", sender.getDisplayName(), clickable));
} catch (Exception e) {
sender.addChatMessage(new ChatComponentText(e.toString()));
}
public static void sendChatItemLink(EntityPlayerMP sender, ItemStack stackover) {
ServerUtils.sendChatToAll(
new ChatComponentTranslation(
"nei.chat.item_link.text",
sender.getDisplayName(),
stackover.func_151000_E().setChatStyle(
stackover.func_151000_E().getChatStyle().setChatClickEvent(
new ClickEvent(
ClickEvent.Action.RUN_COMMAND,
"/nei_bookmark " + stackover.writeToNBT(new NBTTagCompound()))))));
}
public static long getTime(World world) {
@@ -261,6 +229,9 @@ public class NEIServerUtils {
/**
* GT Items don't have any NBT set for the recipe, so if either of the stacks has a NULL nbt, and the other doesn't,
* pretend they stack
*
* @param ItemStack stack
* @return
*/
public static boolean isItemTool(ItemStack stack) {
return GTMetaBaseItemHolder.gtMetaBaseItem != null
@@ -452,7 +423,7 @@ public class NEIServerUtils {
}
public static List<Integer> getRange(final int start, final int end) {
return new AbstractList<>() {
return new AbstractList<Integer>() {
@Override
public Integer get(int index) {
@@ -37,6 +37,5 @@ public final class PacketIDs {
public static final int OPEN_ENCHANTMENT_GUI = 21;
public static final int SET_CREATIVE_PLUS_MODE = 23;
public static final int OPEN_POTION_GUI = 24;
public static final int CACHE_BOOKMARK_DATA = 25;
}
}
@@ -309,12 +309,12 @@ public abstract class PanelWidget<T extends ItemsGrid<? extends ItemsGridSlot, ?
final Point mouse = GuiDraw.getMousePosition();
if (!contains(mouse.x, mouse.y)) return false;
if (KeyManager.isKeyDown("gui.next")) {
if (NEIClientConfig.isKeyHashDown("gui.next")) {
this.grid.shiftPage(1);
return true;
}
if (KeyManager.isKeyDown("gui.prev")) {
if (NEIClientConfig.isKeyHashDown("gui.prev")) {
this.grid.shiftPage(-1);
return true;
}
@@ -24,12 +24,12 @@ public class PopupInputHandler implements IContainerInputHandler {
@Override
public boolean lastKeyTyped(GuiContainer gui, char keyChar, int keyID) {
if (KeyManager.isHashDown("gui.enchant") && canPerformAction("enchant")) {
if (NEIClientConfig.isKeyHashDown("gui.enchant") && canPerformAction("enchant")) {
NEICPH.sendOpenEnchantmentWindow();
return true;
}
if (KeyManager.isHashDown("gui.potion") && canPerformAction("potion")) {
if (NEIClientConfig.isKeyHashDown("gui.potion") && canPerformAction("potion")) {
NEICPH.sendOpenPotionWindow();
return true;
}
@@ -13,33 +13,21 @@ import net.minecraftforge.oredict.OreDictionary;
import codechicken.nei.api.ItemFilter;
import codechicken.nei.api.ItemInfo;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.recipe.Badge;
import codechicken.nei.recipe.GuiRecipe;
import codechicken.nei.recipe.StackInfo;
/**
* Simply an {@link ItemStack} with position. Mainly used in the recipe handlers.
*/
public class PositionedStack implements Cloneable {
/** Maximum chance value representing 100% probability (1 unit = 0.01%). */
public static final int CHANCE_FULL = 10_000;
public class PositionedStack {
public int relx;
public int rely;
public int width = 16;
public int height = 16;
public ItemStack[] items;
// compatibility dummy
public ItemStack item;
protected int chance = CHANCE_FULL;
protected boolean permutated = false;
protected String acceptsLabel;
protected List<String> tooltip;
protected List<Badge> badges;
private boolean permutated = false;
public PositionedStack(Object object, int x, int y, boolean genPerms) {
items = NEIServerUtils.extractRecipeItems(object);
@@ -94,55 +82,14 @@ public class PositionedStack implements Cloneable {
for (ItemStack item : items) if (item.stackSize > i) item.stackSize = i;
}
public void setAcceptsLabel(String acceptsLabel) {
this.acceptsLabel = acceptsLabel;
}
public String getAcceptsLabel() {
return this.acceptsLabel;
}
public void setBadges(List<Badge> badges) {
this.badges = badges;
}
public List<Badge> getBadges() {
return this.badges;
}
public void setTooltip(List<String> tooltip) {
this.tooltip = tooltip;
}
public List<String> getTooltip() {
return this.tooltip;
}
public int getChance() {
return this.chance;
}
public void setChance(int chance) {
this.chance = chance;
}
public PositionedStack copy() {
try {
PositionedStack pStack = (PositionedStack) super.clone();
pStack.items = Arrays.stream(this.items).map(ItemStack::copy).toArray(ItemStack[]::new);
pStack.item = this.item == null ? null : this.item.copy();
pStack.tooltip = this.tooltip == null ? null : new ArrayList<>(this.tooltip);
pStack.badges = this.badges == null ? null : new ArrayList<>(this.badges);
return pStack;
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
public void draw(int mousex, int mousey) {
final int x = this.relx + (this.width - 16) / 2;
final int y = this.rely + (this.height - 16) / 2;
GuiContainerManager.drawItem(x, y, this.item);
PositionedStack pStack = new PositionedStack(
Arrays.stream(this.items).map(ItemStack::copy).toArray(ItemStack[]::new),
relx,
rely,
false);
pStack.permutated = this.permutated;
return pStack;
}
public List<ItemStack> getFilteredPermutations() {
@@ -199,9 +146,7 @@ public class PositionedStack implements Cloneable {
}
public boolean contains(int mx, int my) {
return mx >= this.relx - 1 && mx < this.relx + this.width + 1
&& my >= this.rely - 1
&& my < this.rely + this.height + 1;
return mx >= this.relx - 1 && mx < this.relx + 17 && my >= this.rely - 1 && my < this.rely + 17;
}
public boolean contains(ItemStack ingredient) {
@@ -229,21 +174,4 @@ public class PositionedStack implements Cloneable {
public String toString() {
return "PositionedStack(output='" + item.toString() + "')";
}
/**
* A {@link PositionedStack} that keeps its items but never draws them.
*/
public static class Placeholder extends PositionedStack {
public Placeholder(Object object, int x, int y, boolean genPerms) {
super(object, x, y, genPerms);
}
public Placeholder(Object object, int x, int y) {
this(object, x, y, true);
}
@Override
public void draw(int mousex, int mousey) {}
}
}
@@ -163,7 +163,9 @@ public class PresetsList {
public static void load() {
final File presetsFile = new File(CommonUtils.getMinecraftDir(), "saves/NEI/global/presets.ini");
if (!presetsFile.exists()) return;
if (presetsFile == null || !presetsFile.exists()) {
return;
}
List<String> itemStrings;
try (FileInputStream reader = new FileInputStream(presetsFile)) {
@@ -249,7 +251,7 @@ public class PresetsList {
updateSubsets();
CollapsibleItems.saveStates();
CollapsibleItems.load();
ItemList.refreshItems.restart();
LayoutManager.markItemsDirty();
}
private static void updateSubsets() {
@@ -50,11 +50,11 @@ public abstract class RecipeSearchField extends TextField implements ItemFilterP
@Override
public void lastKeyTyped(int keyID, char keyChar) {
if (focused() && KeyManager.isKeyDown("gui.getprevioussearch")) {
if (focused() && NEIClientConfig.isKeyHashDown("gui.getprevioussearch")) {
handleNavigateHistory(TextHistory.Direction.PREVIOUS);
}
if (focused() && KeyManager.isKeyDown("gui.getnextsearch")) {
if (focused() && NEIClientConfig.isKeyHashDown("gui.getnextsearch")) {
handleNavigateHistory(TextHistory.Direction.NEXT);
}
}
@@ -15,6 +15,7 @@ import net.minecraftforge.fluids.FluidStack;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.ItemList.NothingItemFilter;
import codechicken.nei.SearchTokenParser.ISearchParserProvider;
import codechicken.nei.SearchTokenParser.SearchMode;
import codechicken.nei.api.IRecipeFilter;
import codechicken.nei.api.IRecipeFilter.IRecipeFilterProvider;
import codechicken.nei.api.ItemFilter;
@@ -84,8 +85,8 @@ public class SearchField extends TextField implements ItemFilterProvider {
}
@Override
public String getName() {
return this.name;
public SearchMode getSearchMode() {
return SearchMode.fromInt(NEIClientConfig.getIntSetting("inventory.search." + this.name + "SearchMode"));
}
}
@@ -229,14 +230,14 @@ public class SearchField extends TextField implements ItemFilterProvider {
@Override
public void lastKeyTyped(int keyID, char keyChar) {
if (isVisible() && KeyManager.isHashDown("gui.search")) {
if (isVisible() && NEIClientConfig.isKeyHashDown("gui.search")) {
setFocus(true);
}
if (focused() && KeyManager.isKeyDown("gui.getprevioussearch")) {
if (focused() && NEIClientConfig.isKeyHashDown("gui.getprevioussearch")) {
handleNavigateHistory(TextHistory.Direction.PREVIOUS);
}
if (focused() && KeyManager.isKeyDown("gui.getnextsearch")) {
if (focused() && NEIClientConfig.isKeyHashDown("gui.getnextsearch")) {
handleNavigateHistory(TextHistory.Direction.NEXT);
}
}
@@ -59,13 +59,7 @@ public class SearchTokenParser {
public EnumChatFormatting getHighlightedColor();
default SearchMode getSearchMode() {
return SearchMode.fromInt(NEIClientConfig.getIntSetting("inventory.search." + getName() + "SearchMode"));
}
default String getName() {
return String.valueOf(getPrefix());
}
public SearchMode getSearchMode();
}
private static class ProvidersCache {
@@ -117,7 +111,7 @@ public class SearchTokenParser {
clearCache();
}
public synchronized void clearCache() {
public void clearCache() {
this.providersCache.clear();
this.filtersCache.clear();
this.recipesCache.clear();
@@ -185,7 +179,7 @@ public class SearchTokenParser {
public synchronized ItemFilter getFilter(String rawText, boolean skipRecipeTokens) {
final String filterText = EnumChatFormatting.getTextWithoutFormattingCodes(rawText).toLowerCase();
if (filterText.isEmpty()) {
if (filterText == null || filterText.isEmpty()) {
return new EverythingItemFilter();
}
@@ -259,7 +253,7 @@ public class SearchTokenParser {
public synchronized IRecipeFilter getRecipeFilter(String filterText) {
filterText = EnumChatFormatting.getTextWithoutFormattingCodes(filterText).toLowerCase();
if (filterText.isEmpty()) {
if (filterText == null || filterText.isEmpty()) {
return new RecipeFilter(FilterContext.ANY, true, new EverythingItemFilter());
}
@@ -46,7 +46,8 @@ public class ServerHandler {
@SubscribeEvent
public void tickEvent(TickEvent.PlayerTickEvent event) {
if (event.phase == Phase.START && event.player instanceof EntityPlayerMP player) {
if (event.phase == Phase.START && event.player instanceof EntityPlayerMP) {
EntityPlayerMP player = (EntityPlayerMP) event.player;
PlayerSave save = NEIServerConfig.forPlayer(player.getCommandSenderName());
if (save == null) return;
updateMagneticPlayer(player, save);
+26 -44
View File
@@ -6,6 +6,7 @@ import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -18,7 +19,6 @@ import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTTagString;
import net.minecraft.util.EnumChatFormatting;
import org.lwjgl.opengl.GL11;
@@ -399,8 +399,8 @@ public class SubsetWidget extends Button implements ItemFilterProvider {
}
@Override
public String getName() {
return "subsets";
public SearchMode getSearchMode() {
return SearchMode.fromInt(NEIClientConfig.getIntSetting("inventory.search.subsetsSearchMode"));
}
private boolean matches(String name, String searchText, Pattern pattern) {
@@ -413,10 +413,9 @@ public class SubsetWidget extends Button implements ItemFilterProvider {
}
/**
* Canonical {@link StackInfo#getItemStackGUID(ItemStack)} of every hidden item, stored by GUID so the state
* survives world reloads. All operations should be synchronised.
* All operations on this variable should be synchronised.
*/
private static final Set<String> hiddenItems = new HashSet<>();
private static final ItemStackSet hiddenItems = new ItemStackSet();
private static final Map<String, SubsetTag> tags = new HashMap<>();
private static final SubsetTag root = new SubsetTag("");
@@ -457,16 +456,11 @@ public class SubsetWidget extends Button implements ItemFilterProvider {
}
public static boolean isHidden(ItemStack item) {
final String guid = StackInfo.getItemStackGUID(item);
synchronized (hiddenLock) {
return hiddenItems.contains(guid);
return hiddenItems.contains(item);
}
}
private static List<String> toGUIDs(List<ItemStack> items) {
return items.stream().map(StackInfo::getItemStackGUID).collect(Collectors.toList());
}
private static List<ItemStack> getItems(SubsetTag tag, List<ItemStack> items) {
items.addAll(tag.items);
@@ -478,22 +472,19 @@ public class SubsetWidget extends Button implements ItemFilterProvider {
}
public static void showOnly(SubsetTag tag) {
final List<String> allItems = toGUIDs(getItems(root, new ArrayList<>()));
final List<String> tagItems = toGUIDs(getItems(tag, new ArrayList<>()));
synchronized (hiddenLock) {
hiddenItems.clear();
hiddenItems.addAll(allItems);
hiddenItems.removeAll(tagItems);
hiddenItems.addAll(getItems(root, new ArrayList<>()));
hiddenItems.removeAll(getItems(tag, new ArrayList<>()));
}
calculateVisibility();
}
public static void setHidden(SubsetTag tag, boolean hidden) {
final List<String> tagItems = toGUIDs(getItems(tag, new ArrayList<>()));
synchronized (hiddenLock) {
final List<ItemStack> tagItems = getItems(tag, new ArrayList<>());
if (hidden) {
hiddenItems.addAll(tagItems);
} else {
@@ -505,13 +496,11 @@ public class SubsetWidget extends Button implements ItemFilterProvider {
}
public static void setHidden(ItemStack item, boolean hidden) {
final String guid = StackInfo.getItemStackGUID(item);
synchronized (hiddenLock) {
if (hidden) {
hiddenItems.add(guid);
hiddenItems.add(item);
} else {
hiddenItems.remove(guid);
hiddenItems.remove(item);
}
}
calculateVisibility();
@@ -593,23 +582,13 @@ public class SubsetWidget extends Button implements ItemFilterProvider {
}
public static void loadHidden() {
final Set<String> guids = new HashSet<>();
final List<ItemStack> itemList = new LinkedList<>();
try {
final NBTTagList guidList = NEIClientConfig.world.nbt.getTagList("hiddenItems", 8);
for (int i = 0; i < guidList.tagCount(); i++) {
guids.add(guidList.getStringTagAt(i));
}
final NBTTagList list = NEIClientConfig.world.nbt.getTagList("hiddenItems", 10);
for (int i = 0; i < list.tagCount(); i++) {
final ItemStack stack = ItemStack.loadItemStackFromNBT(list.getCompoundTagAt(i));
if (stack != null) {
guids.add(StackInfo.getItemStackGUID(stack));
}
itemList.add(ItemStack.loadItemStackFromNBT(list.getCompoundTagAt(i)));
}
} catch (Exception e) {
NEIClientConfig.logger.error("Error loading hiddenItems", e);
@@ -618,7 +597,7 @@ public class SubsetWidget extends Button implements ItemFilterProvider {
synchronized (hiddenLock) {
hiddenItems.clear();
hiddenItems.addAll(guids);
hiddenItems.addAll(itemList);
}
}
@@ -627,8 +606,8 @@ public class SubsetWidget extends Button implements ItemFilterProvider {
final NBTTagList list = new NBTTagList();
synchronized (hiddenLock) {
for (String guid : hiddenItems) {
list.appendTag(new NBTTagString(guid));
for (ItemStack stack : hiddenItems.values()) {
list.appendTag(stack.writeToNBT(new NBTTagCompound()));
}
}
@@ -709,18 +688,21 @@ public class SubsetWidget extends Button implements ItemFilterProvider {
this.z = 1;
}
@Override
public int getRenderLabelColor() {
return NEIClientConfig.subsetWidgetOnTop() ? 0 : ColorUtils.subsetWidget.getColor();
}
@Override
public String getRenderLabel() {
if (NEIClientConfig.subsetWidgetOnTop()) {
return NEIClientUtils.translate("inventory.item_subsets");
} else {
return String.valueOf(SearchField.searchParser.getRedefinedPrefix(PREFIX));
final String translated = NEIClientUtils.translate("gui.button.label.subset");
if (!translated.startsWith("nei.")) { // Optional localization string for resource packs
return translated;
}
return EnumChatFormatting.DARK_PURPLE + String.valueOf(SearchField.searchParser.getRedefinedPrefix(PREFIX))
+ EnumChatFormatting.RESET;
}
}
@Override
@@ -1,11 +1,5 @@
package codechicken.nei;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;
import net.minecraft.block.Block;
import net.minecraft.block.BlockSnow;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.Entity;
@@ -21,8 +15,6 @@ import net.minecraft.world.chunk.Chunk;
import org.lwjgl.opengl.GL11;
import com.cardinalstar.cubicchunks.world.api.IMinMaxHeight;
import codechicken.lib.math.MathHelper;
import codechicken.nei.KeyManager.IKeyStateTracker;
import cpw.mods.fml.relauncher.ReflectionHelper;
@@ -34,23 +26,24 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
public static int mobOverlay = 0;
private static byte[] mobSpawnCache;
private static long mobOverlayUpdateTime;
private static String oregenPatternName;
public static void reset() {
mobOverlay = 0;
chunkOverlay = 0;
oregenPatternName = null;
}
@Override
public void tickKeyStates() {
if (Minecraft.getMinecraft().currentScreen != null) return;
if (KeyManager.isPressed("world.moboverlay")) {
if (KeyManager.keyStates.get("world.moboverlay").down) {
mobOverlay = (mobOverlay + 1) % 2;
NEIClientUtils
.printChatMessage(new ChatComponentText(NEIClientUtils.translate("chat.moboverlay." + mobOverlay)));
}
if (KeyManager.isPressed("world.chunkoverlay")) {
if (KeyManager.keyStates.get("world.chunkoverlay").down) {
chunkOverlay = (chunkOverlay + 1) % (NEIModContainer.isGT5Loaded() ? 4 : 3);
// 0-2 (or 3 with gt)
NEIClientUtils.printChatMessage(
@@ -60,7 +53,6 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
}
public static void render(float frame) {
GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_LINE_BIT);
GL11.glPushMatrix();
Entity entity = Minecraft.getMinecraft().renderViewEntity;
@@ -74,12 +66,9 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
GL11.glTranslated(-interpPosX + intOffsetX, -interpPosY + intOffsetY, -interpPosZ + intOffsetZ);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glDepthFunc(GL11.GL_LEQUAL);
renderChunkBounds(entity, intOffsetX, intOffsetY, intOffsetZ);
renderMobSpawnOverlay(entity, intOffsetX, intOffsetY, intOffsetZ);
GL11.glPopMatrix();
GL11.glPopAttrib();
}
private static void buildMobSpawnOverlay(Entity entity) {
@@ -127,15 +116,6 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
}
}
private static double getOverlayYOffset(World world, int x, int y, int z) {
Block block = world.getBlock(x, y, z);
if (block instanceof BlockSnow) {
int meta = world.getBlockMetadata(x, y, z) & 7;
return (1 + meta) / 8.0 + 0.02;
}
return 0.02;
}
private static void renderMobSpawnOverlay(Entity entity, int intOffsetX, int intOffsetY, int intOffsetZ) {
if (mobOverlay == 0) {
if (mobSpawnCache != null) {
@@ -191,12 +171,10 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
curSpawnMode = spawnMode;
}
double yOff = getOverlayYOffset(world, x + intOffsetX, y + intOffsetY, z + intOffsetZ);
tess.addVertex(x, y + yOff, z);
tess.addVertex(x + 1, y + yOff, z + 1);
tess.addVertex(x + 1, y + yOff, z);
tess.addVertex(x, y + yOff, z + 1);
tess.addVertex(x, y + 0.02, z);
tess.addVertex(x + 1, y + 0.02, z + 1);
tess.addVertex(x + 1, y + 0.02, z);
tess.addVertex(x, y + 0.02, z + 1);
}
}
}
@@ -237,9 +215,6 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
private static void renderChunkBounds(Entity entity, int intOffsetX, int intOffsetY, int intOffsetZ) {
if (chunkOverlay == 0) return;
int worldMinY = worldMinHeight(entity.worldObj);
int worldMaxY = worldMaxHeight(entity.worldObj);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
@@ -258,13 +233,14 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
double dy = 128;
double y1 = Math.floor(entity.posY - dy / 2);
double y2 = y1 + dy;
if (y1 < worldMinY) {
y1 = worldMinY;
y2 = worldMinY + dy;
if (y1 < 0) {
y1 = 0;
y2 = dy;
}
if (y2 > worldMaxY) {
y2 = worldMaxY;
y1 = Math.max(worldMaxY - dy, worldMinY);
if (y1 > entity.worldObj.getHeight()) {
y2 = entity.worldObj.getHeight();
y1 = y2 - dy;
}
y1 -= intOffsetY;
@@ -290,34 +266,19 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
tess.addVertex(x1, y2, z1);
}
if (NEIModContainer.isCCLoaded()) {
tess.setColorRGBA_F(0, 0.5F, 0.9F, (float) dist * 0.5F);
int cubeBase = (int) Math.floor((y1 + intOffsetY) / 16.0) * 16;
for (int cubeY = cubeBase; cubeY <= y2 + intOffsetY; cubeY += 16) {
double ry = cubeY - intOffsetY;
tess.addVertex(x1, ry, z1);
tess.addVertex(x2, ry, z1);
tess.addVertex(x1, ry, z2);
tess.addVertex(x2, ry, z2);
tess.addVertex(x1, ry, z1);
tess.addVertex(x1, ry, z2);
tess.addVertex(x2, ry, z1);
tess.addVertex(x2, ry, z2);
}
}
if (cx == 0 && cz == 0) {
if (chunkOverlay == 2) {
dy = 32;
y1 = Math.floor(entity.posY - dy / 2);
y2 = y1 + dy;
if (y1 < worldMinY) {
y1 = worldMinY;
y2 = worldMinY + dy;
if (y1 < 0) {
y1 = 0;
y2 = dy;
}
if (y2 > worldMaxY) {
y2 = worldMaxY;
y1 = Math.max(worldMaxY - dy, worldMinY);
if (y1 > entity.worldObj.getHeight()) {
y2 = entity.worldObj.getHeight();
y1 = y2 - dy;
}
y1 -= intOffsetY;
@@ -416,55 +377,20 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
GL11.glDisable(GL11.GL_BLEND);
}
private static int worldMinHeight(World world) {
if (NEIModContainer.isCCLoaded() && world instanceof IMinMaxHeight worldHeights) {
return worldHeights.getMinHeight();
} else {
return 0;
}
}
private static int worldMaxHeight(World world) {
if (NEIModContainer.isCCLoaded() && world instanceof IMinMaxHeight worldHeights) {
return worldHeights.getMaxHeight();
} else {
return world.getHeight();
}
}
private static Callable<String> oregenPatternReader;
private static String getOregenPatternName() {
if (oregenPatternReader == null) {
oregenPatternReader = resolveOregenPatternReader();
}
try {
return oregenPatternReader.call();
} catch (Exception ignored) {
return "AXISSYMMETRICAL";
}
}
private static Callable<String> resolveOregenPatternReader() {
try {
final Class<?> gtWorldGenerator = ReflectionHelper.getClass(
WorldOverlayRenderer.class.getClassLoader(),
"gregtech.common.GTWorldgenerator",
"gregtech.common.GT_Worldgenerator");
if (oregenPatternName == null) {
try {
// GT5-Unofficial >= 5.09.54.29 support
final Method accessor = gtWorldGenerator.getMethod("getOregenPattern");
return () -> ((Enum<?>) accessor.invoke(null)).name();
} catch (NoSuchMethodException legacy) {
// Older GT
final Field oregenPattern = gtWorldGenerator.getDeclaredField("oregenPattern");
oregenPattern.setAccessible(true);
return () -> ((Enum<?>) oregenPattern.get(null)).name();
final ClassLoader loader = WorldOverlayRenderer.class.getClassLoader();
final Class<?> gtWorldGenerator = ReflectionHelper
.getClass(loader, "gregtech.common.GTWorldgenerator", "gregtech.common.GT_Worldgenerator");
oregenPatternName = ((Enum<?>) gtWorldGenerator.getDeclaredField("oregenPattern").get(null)).name();
} catch (Exception ignored) {
oregenPatternName = "AXISSYMMETRICAL";
}
} catch (Exception ignored) {
return () -> "AXISSYMMETRICAL";
}
return oregenPatternName;
}
public static void load() {
+13 -20
View File
@@ -1,11 +1,9 @@
package codechicken.nei.api;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import net.minecraft.block.Block;
import net.minecraft.client.gui.inventory.GuiContainer;
@@ -22,6 +20,7 @@ import codechicken.nei.ItemList;
import codechicken.nei.ItemSorter;
import codechicken.nei.ItemStackSet;
import codechicken.nei.KeyManager;
import codechicken.nei.KeyManager.KeyState;
import codechicken.nei.LayoutManager;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.OffsetPositioner;
@@ -33,6 +32,7 @@ import codechicken.nei.SubsetWidget.SubsetTag;
import codechicken.nei.api.IRecipeFilter.IRecipeFilterProvider;
import codechicken.nei.api.ItemFilter.ItemFilterProvider;
import codechicken.nei.config.Option;
import codechicken.nei.config.OptionKeyBind;
import codechicken.nei.recipe.CatalystInfo;
import codechicken.nei.recipe.GuiCraftingRecipe;
import codechicken.nei.recipe.GuiRecipe;
@@ -176,21 +176,6 @@ public class API {
}
}
/**
* Add an alias name that this item can be found by in the search field, in addition to its display name.
*/
public static void setAliases(ItemStack item, String... aliases) {
final List<String> list = Arrays.asList(aliases).stream().filter(Objects::nonNull).map(String::trim)
.filter(s -> !s.isEmpty()).collect(Collectors.toList());
if (list.isEmpty()) {
ItemInfo.itemAliases.remove(item);
} else {
ItemInfo.itemAliases.put(item, list);
}
}
/**
* Adds an item to the item panel. Any items added using this function will override the default search pattern.
*
@@ -221,12 +206,20 @@ public class API {
* @param defaultKey The default value, commonly obtained from {@link Keyboard}
*/
public static void addKeyBind(String ident, int defaultKey) {
KeyManager.registerKeyBinding(ident, defaultKey);
NEIClientConfig.setDefaultKeyBinding(ident, defaultKey);
KeyManager.keyStates.put(ident, new KeyState());
addOption(new OptionKeyBind(ident));
}
@Deprecated
/**
* Add a custom KeyBinding to be configured in the Controls menu.
*
* @param ident An identifier for your key, eg "shoot"
* @param defaultKey The default value, commonly obtained from {@link Keyboard}
*/
public static void addHashBind(String ident, int defaultKey) {
KeyManager.registerKeyBinding(ident, defaultKey);
NEIClientConfig.setDefaultKeyBinding(ident, defaultKey);
addOption(new OptionKeyBind(ident, true));
}
public static void addOption(Option option) {
@@ -8,7 +8,6 @@ import java.util.stream.Collectors;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.item.ItemStack;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.PositionedStack;
import codechicken.nei.recipe.GuiOverlayButton.ItemOverlayState;
import codechicken.nei.recipe.IRecipeHandler;
@@ -33,10 +32,6 @@ public interface IOverlayHandler {
return false;
}
default boolean requireShiftForOverlayRecipe() {
return NEIClientConfig.requireShiftForOverlayRecipe();
}
default List<ItemOverlayState> presenceOverlay(GuiContainer firstGui, IRecipeHandler recipe, int recipeIndex) {
final List<ItemOverlayState> itemPresenceSlots = new ArrayList<>();
final List<PositionedStack> ingredients = recipe.getIngredientStacks(recipeIndex);
@@ -1,7 +1,6 @@
package codechicken.nei.api;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
@@ -77,18 +76,14 @@ import cpw.mods.fml.common.registry.GameRegistry.UniqueIdentifier;
*/
public class ItemInfo {
public enum Layout {
public static enum Layout {
HEADER,
BODY,
FOOTER;
public static final Layout[] VALUES = values();
FOOTER
}
public static final ArrayListMultimap<Layout, IHighlightHandler> highlightHandlers = ArrayListMultimap.create();
public static final ItemStackMap<String> nameOverrides = new ItemStackMap<>();
public static final ItemStackMap<List<String>> itemAliases = new ItemStackMap<>();
public static final ItemStackSet hiddenItems = new ItemStackSet();
public static final AnyMultiItemFilter hiddenItemsRules = new AnyMultiItemFilter();
public static final ItemStackSet finiteItems = new ItemStackSet();
@@ -114,11 +109,6 @@ public class ItemInfo {
return nameOverrides.get(stack);
}
public static List<String> getAliases(ItemStack stack) {
final List<String> aliases = itemAliases.get(stack);
return aliases != null ? aliases : Collections.emptyList();
}
public static boolean canBeInfinite(ItemStack stack) {
return !finiteItems.contains(stack);
}
@@ -475,7 +465,7 @@ public class ItemInfo {
MovingObjectPosition mop) {
List<String> retString = new ArrayList<>();
for (ItemInfo.Layout layout : Layout.VALUES)
for (ItemInfo.Layout layout : ItemInfo.Layout.values())
for (IHighlightHandler handler : ItemInfo.highlightHandlers.get(layout))
retString = handler.handleTextData(itemStack, world, player, mop, retString, layout);
@@ -5,7 +5,6 @@ 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 {
@@ -14,9 +13,7 @@ public class NEIInfo {
public static void load(World world) {
OptionCycled modeOption = (OptionCycled) NEIClientConfig.getOptionList().getOption("inventory.cheatmode");
final boolean worldConfig = NEIClientConfig.isWorldSpecific("inventory.cheatmode");
// kept alive so the WeakReference in Option.slotRef isn't GC'd before copyGlobals/cycle use it
GuiOptionList env = modeOption.parent.synthesizeEnvironment(worldConfig);
modeOption.parent.synthesizeEnvironment(false);
if (!modeOption.optionValid(modeOption.value())) {
modeOption.copyGlobals();
modeOption.cycle();
@@ -20,17 +20,14 @@ import codechicken.nei.FavoriteRecipes;
import codechicken.nei.ItemPanels;
import codechicken.nei.ItemQuantityField;
import codechicken.nei.ItemsGrid.ItemsGridSlot;
import codechicken.nei.KeyManager;
import codechicken.nei.LayoutManager;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.PositionedStack;
import codechicken.nei.SearchField;
import codechicken.nei.bookmark.BookmarkGrid;
import codechicken.nei.bookmark.BookmarkGroup;
import codechicken.nei.bookmark.BookmarkItem;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.bookmark.BookmarkPayload;
import codechicken.nei.bookmark.BookmarksGridSlot;
import codechicken.nei.recipe.AutoCraftingManager;
import codechicken.nei.recipe.GuiCraftingRecipe;
@@ -77,7 +74,8 @@ public abstract class ShortcutInputHandler {
return false;
}
if (KeyManager.isKeyDown("gui.overlay") && stackover == null && LayoutManager.overlayRenderer != null) {
if (NEIClientConfig.isKeyHashDown("gui.overlay") && stackover == null
&& LayoutManager.overlayRenderer != null) {
LayoutManager.overlayRenderer = null;
return true;
}
@@ -87,21 +85,16 @@ public abstract class ShortcutInputHandler {
if (groupId != -1) {
if (KeyManager.isHashDown("bookmark.remove_recipe", NEIClientUtils.SHIFT_HASH)) {
if (NEIClientConfig.isKeyHashDown("gui.remove_recipe")) {
ItemPanels.bookmarkPanel.removeGroup(groupId);
return true;
}
if (KeyManager.isKeyDown("bookmark.pull_items")) {
if (NEIClientConfig.isKeyHashDown("gui.bookmark_pull_items")) {
return ItemPanels.bookmarkPanel.pullBookmarkItems(groupId, NEIClientUtils.shiftKey());
}
if (KeyManager.isKeyDown("bookmark.chat_link") && NEIClientUtils.controlKey()) {
NEIClientUtils.sendChatItemLink(BookmarkPayload.of(groupId).toNBT());
return true;
}
if (NEIClientConfig.autocraftingEnabled() && KeyManager.isKeyDown("gui.craft_items")
if (NEIClientConfig.autocraftingEnabled() && NEIClientConfig.isKeyHashDown("gui.craft_items")
&& NEIClientUtils.shiftKey()
&& ItemPanels.bookmarkPanel.getGrid().isCraftingMode(groupId)) {
final RecipeChainMath math = ItemPanels.bookmarkPanel.getGrid().createRecipeChainMath(groupId);
@@ -124,47 +117,46 @@ public abstract class ShortcutInputHandler {
stackover = stackover.copy();
if (KeyManager.isKeyDown("gui.overlay")) {
if (NEIClientConfig.isKeyHashDown("gui.overlay")) {
return openOverlayRecipe(stackover);
}
if (KeyManager.isHashDown("copy.name", NEIClientUtils.CTRL_HASH)) {
if (NEIClientConfig.isKeyHashDown("gui.copy_name")) {
return copyItemStackName(stackover);
}
if (KeyManager.isHashDown("copy.identifier", NEIClientUtils.CTRL_HASH)) {
if (NEIClientConfig.isKeyHashDown("gui.copy_id")) {
return copyItemStackID(stackover);
}
if (KeyManager.isHashDown("copy.oredict", NEIClientUtils.CTRL_HASH)) {
if (NEIClientConfig.isKeyHashDown("gui.copy_oredict")) {
return copyItemStackOreDictionary(stackover);
}
if (KeyManager.isKeyDown("bookmark.chat_link") && NEIClientUtils.controlKey()) {
return sendRecipeInChatLink(stackover, NEIClientUtils.shiftKey());
if (NEIClientConfig.isKeyHashDown("gui.chat_link_item")) {
return sendItemStackChatLink(stackover);
}
if (KeyManager.isKeyDown("recipe.recipe")) {
if (NEIClientConfig.isKeyHashDown("gui.recipe")) {
return GuiCraftingRecipe.openRecipeGui("item", stackover);
}
if (KeyManager.isKeyDown("recipe.usage")) {
if (NEIClientConfig.isKeyHashDown("gui.usage")) {
return GuiUsageRecipe.openRecipeGui("item", stackover);
}
if (KeyManager.isHashDown("bookmark.favorite", NEIClientUtils.SHIFT_HASH)) {
if (NEIClientConfig.isKeyHashDown("gui.favorite")) {
return saveFavoriteTree(stackover);
}
if (KeyManager.isKeyDown("bookmark.add")) {
if (NEIClientConfig.isKeyHashDown("gui.bookmark")) {
return saveRecipeInBookmark(stackover, NEIClientUtils.shiftKey(), NEIClientUtils.controlKey());
}
if (KeyManager.isKeyDown("bookmark.pull_items")) {
if (NEIClientConfig.isKeyHashDown("gui.bookmark_pull_items")) {
return pullRecipeItems(stackover, NEIClientUtils.shiftKey());
}
if (NEIClientConfig.autocraftingEnabled() && KeyManager.isKeyDown("gui.craft_items")
if (NEIClientConfig.autocraftingEnabled() && NEIClientConfig.isKeyHashDown("gui.craft_items")
&& NEIClientUtils.shiftKey()) {
return runAutoCrafting(stackover, !NEIClientUtils.controlKey());
}
@@ -204,37 +196,10 @@ public abstract class ShortcutInputHandler {
return true;
}
private static boolean sendRecipeInChatLink(ItemStack stackover, boolean saveIngredients) {
final Point mousePos = GuiDraw.getMousePosition();
final BookmarksGridSlot slot = ItemPanels.bookmarkPanel.getSlotMouseOver(mousePos.x, mousePos.y);
private static boolean sendItemStackChatLink(ItemStack stackover) {
if (stackover == null) return false;
if (slot != null && saveIngredients && slot.getType() == BookmarkItemType.RESULT) {
NEIClientUtils.sendChatItemLink(BookmarkPayload.of(slot.getBookmarkItem()).toNBT());
return true;
}
final Recipe recipe = getFocusedRecipe(stackover, mousePos.x, mousePos.y, saveIngredients);
if (recipe != null && saveIngredients) {
NEIClientUtils.sendChatItemLink(BookmarkPayload.of(recipe).toNBT());
return true;
}
final RecipeId recipeId;
if (slot != null) {
recipeId = slot.getType() == BookmarkItemType.INGREDIENT ? null : slot.getRecipeId();
} else {
recipeId = recipe != null ? recipe.getRecipeId() : null;
}
final boolean existsRecipe = NEIClientConfig.getBooleanSetting("inventory.bookmarks.bookmarkItemsWithRecipe");
if (ItemPanels.itemPanel.containsWithSubpanels(mousePos.x, mousePos.y)) {
stackover = ItemQuantityField.prepareStackWithQuantity(stackover, 0);
}
NEIClientUtils.sendChatItemLink(BookmarkPayload.of(stackover, existsRecipe ? recipeId : null).toNBT());
NEIClientUtils.sendChatItemLink(stackover); // I wish clients could just send formatted messages
return true;
}
@@ -274,7 +239,7 @@ public abstract class ShortcutInputHandler {
if (slot.getGroup().crafting == null) {
final Recipe recipe = Recipe.of(slot.getRecipeId());
if (recipe != null) {
math = RecipeChainMath.of(recipe, Math.max(1, slot.getMultiplier()));
math = RecipeChainMath.of(recipe, Math.max(1, slot != null ? slot.getMultiplier() : 1));
}
} else {
math = ItemPanels.bookmarkPanel.getGrid()
@@ -441,7 +406,7 @@ public abstract class ShortcutInputHandler {
}
}
if (gui instanceof GuiRecipe<?>guiRecipe) {
if (gui instanceof GuiRecipe guiRecipe) {
recipe = guiRecipe.getFocusedRecipe();
}
@@ -479,19 +444,15 @@ public abstract class ShortcutInputHandler {
if (groupId != -1) {
hotkeys.put(
KeyManager.getKeyName("bookmark.remove_recipe", NEIClientUtils.SHIFT_HASH),
NEIClientConfig.getKeyName("gui.remove_recipe"),
NEIClientUtils.translate("bookmark.group.remove_recipe"));
hotkeys.put(
KeyManager.getKeyName("bookmark.chat_link", NEIClientUtils.CTRL_HASH),
NEIClientUtils.translate("bookmark.group.chat_link"));
if (BookmarkContainerInfo.getBookmarkContainerHandler(gui) != null) {
hotkeys.put(
KeyManager.getKeyName("bookmark.pull_items"),
NEIClientConfig.getKeyName("gui.bookmark_pull_items"),
NEIClientUtils.translate("bookmark.group.pull_items"));
hotkeys.put(
KeyManager.getKeyName("bookmark.pull_items", NEIClientUtils.SHIFT_HASH),
NEIClientConfig.getKeyName("gui.bookmark_pull_items", NEIClientUtils.SHIFT_HASH),
NEIClientUtils.translate("bookmark.group.pull_items_shift"));
}
@@ -501,7 +462,7 @@ public abstract class ShortcutInputHandler {
.getKeyName("gui.craft_items", NEIClientUtils.SHIFT_HASH + NEIClientUtils.CTRL_HASH),
NEIClientUtils.translate("bookmark.group.craft_missing"));
hotkeys.put(
KeyManager.getKeyName("gui.craft_items", NEIClientUtils.SHIFT_HASH),
NEIClientConfig.getKeyName("gui.craft_items", NEIClientUtils.SHIFT_HASH),
NEIClientUtils.translate("bookmark.group.craft_all"));
}
@@ -522,28 +483,30 @@ public abstract class ShortcutInputHandler {
if (group.crafting != null && group.collapsed) {
hotkeys.put(
KeyManager.getKeyName("bookmark.add", NEIClientUtils.SHIFT_HASH),
NEIClientConfig.getKeyName("gui.bookmark", NEIClientUtils.SHIFT_HASH),
NEIClientUtils.translate("bookmark.group.remove_recipe"));
} else if (slot.getRecipeId() == null || slot.getType() == BookmarkItemType.ITEM) {
hotkeys.put(KeyManager.getKeyName("bookmark.add"), NEIClientUtils.translate("bookmark.remove_item"));
hotkeys.put(
NEIClientConfig.getKeyName("gui.bookmark"),
NEIClientUtils.translate("bookmark.remove_item"));
} else if (group.crafting != null && group.crafting.recipeRelations.entrySet().stream().anyMatch(
entry -> entry.getKey().equals(slot.getRecipeId())
|| entry.getValue().contains(slot.getRecipeId()))) {
hotkeys.put(
KeyManager.getKeyName("bookmark.add", NEIClientUtils.SHIFT_HASH),
NEIClientConfig.getKeyName("gui.bookmark", NEIClientUtils.SHIFT_HASH),
NEIClientUtils.translate("bookmark.remove_recipe"));
} else {
hotkeys.put(
KeyManager.getKeyName("bookmark.add", NEIClientUtils.SHIFT_HASH),
NEIClientConfig.getKeyName("gui.bookmark", NEIClientUtils.SHIFT_HASH),
NEIClientUtils.translate("bookmark.remove_recipe"));
if (slot.getType() == BookmarkItemType.INGREDIENT) {
hotkeys.put(
KeyManager.getKeyName("bookmark.add"),
NEIClientConfig.getKeyName("gui.bookmark"),
NEIClientUtils.translate("bookmark.remove_item"));
hotkeys.put(
KeyManager.getKeyName("bookmark.add", NEIClientUtils.SHIFT_HASH),
NEIClientConfig.getKeyName("gui.bookmark", NEIClientUtils.SHIFT_HASH),
NEIClientUtils.translate("bookmark.remove_recipe"));
} else {
final BookmarkItem item = slot.getBookmarkItem();
@@ -553,14 +516,14 @@ public abstract class ShortcutInputHandler {
m -> m.type == BookmarkItemType.RESULT && !m.equals(item)
&& item.equalsRecipe(m))) {
hotkeys.put(
KeyManager.getKeyName("bookmark.add"),
NEIClientConfig.getKeyName("gui.bookmark"),
NEIClientUtils.translate("bookmark.remove_recipe"));
} else {
hotkeys.put(
KeyManager.getKeyName("bookmark.add"),
NEIClientConfig.getKeyName("gui.bookmark"),
NEIClientUtils.translate("bookmark.remove_item"));
hotkeys.put(
KeyManager.getKeyName("bookmark.add", NEIClientUtils.SHIFT_HASH),
NEIClientConfig.getKeyName("gui.bookmark", NEIClientUtils.SHIFT_HASH),
NEIClientUtils.translate("bookmark.remove_recipe"));
}
@@ -570,66 +533,60 @@ public abstract class ShortcutInputHandler {
if (BookmarkContainerInfo.getBookmarkContainerHandler(gui) != null) {
hotkeys.put(
KeyManager.getKeyName("bookmark.pull_items"),
NEIClientConfig.getKeyName("gui.bookmark_pull_items"),
NEIClientUtils.translate("bookmark.group.pull_items"));
hotkeys.put(
KeyManager.getKeyName("bookmark.pull_items", NEIClientUtils.SHIFT_HASH),
NEIClientConfig.getKeyName("gui.bookmark_pull_items", NEIClientUtils.SHIFT_HASH),
NEIClientUtils.translate("bookmark.group.pull_items_shift"));
}
} else {
hotkeys.put(KeyManager.getKeyName("bookmark.add"), NEIClientUtils.translate("bookmark.add_item"));
hotkeys.put(NEIClientConfig.getKeyName("gui.bookmark"), NEIClientUtils.translate("bookmark.add_item"));
if (StackInfo.getAmount(stack) > 0) {
hotkeys.put(
KeyManager.getKeyName("bookmark.add", NEIClientUtils.CTRL_HASH),
NEIClientConfig.getKeyName("gui.bookmark", NEIClientUtils.CTRL_HASH),
NEIClientUtils.translate("bookmark.add_item_with_count"));
}
if (recipeId != null) {
hotkeys.put(
KeyManager.getKeyName("bookmark.add", NEIClientUtils.SHIFT_HASH + NEIClientUtils.CTRL_HASH),
NEIClientConfig
.getKeyName("gui.bookmark", NEIClientUtils.SHIFT_HASH + NEIClientUtils.CTRL_HASH),
NEIClientUtils.translate("bookmark.add_item_with_recipe_and_count"));
hotkeys.put(
KeyManager.getKeyName("bookmark.add", NEIClientUtils.SHIFT_HASH),
NEIClientConfig.getKeyName("gui.bookmark", NEIClientUtils.SHIFT_HASH),
NEIClientUtils.translate("bookmark.add_item_with_recipe"));
}
if ((ItemPanels.itemPanel.contains(mousex, mousey)
|| ItemPanels.itemPanel.historyPanel.contains(mousex, mousey)) && FavoriteRecipes.contains(stack)) {
hotkeys.put(
KeyManager.getKeyName("bookmark.favorite", NEIClientUtils.SHIFT_HASH),
NEIClientConfig.getKeyName("gui.favorite"),
NEIClientUtils.translate("recipe.favorite.bookmark_recipe"));
}
}
hotkeys.put(KeyManager.getKeyName("recipe.recipe"), NEIClientUtils.translate("itempanel.open_crafting"));
hotkeys.put(KeyManager.getKeyName("recipe.usage"), NEIClientUtils.translate("itempanel.open_usage"));
hotkeys.put(NEIClientConfig.getKeyName("gui.recipe"), NEIClientUtils.translate("itempanel.open_crafting"));
hotkeys.put(NEIClientConfig.getKeyName("gui.usage"), NEIClientUtils.translate("itempanel.open_usage"));
hotkeys.put(NEIClientConfig.getKeyName("gui.copy_name"), NEIClientUtils.translate("itempanel.copy_name"));
hotkeys.put(NEIClientConfig.getKeyName("gui.copy_oredict"), NEIClientUtils.translate("itempanel.copy_oredict"));
hotkeys.put(NEIClientConfig.getKeyName("gui.copy_id"), NEIClientUtils.translate("itempanel.copy_id"));
hotkeys.put(
KeyManager.getKeyName("copy.name", NEIClientUtils.CTRL_HASH),
NEIClientUtils.translate("itempanel.copy_name"));
hotkeys.put(
KeyManager.getKeyName("copy.oredict", NEIClientUtils.CTRL_HASH),
NEIClientUtils.translate("itempanel.copy_oredict"));
hotkeys.put(
KeyManager.getKeyName("copy.identifier", NEIClientUtils.CTRL_HASH),
NEIClientUtils.translate("itempanel.copy_id"));
hotkeys.put(
KeyManager.getKeyName("bookmark.chat_link", NEIClientUtils.CTRL_HASH),
NEIClientUtils.translate("bookmark.item.chat_link"));
NEIClientConfig.getKeyName("gui.chat_link_item"),
NEIClientUtils.translate("itempanel.chat_link_item"));
if (!(gui instanceof GuiRecipe) && NEIClientConfig.canCheatItem(stack)) {
hotkeys.put(
KeyManager.getKeyName(NEIClientUtils.SHIFT_HASH, NEIMouseUtils.MOUSE_BTN_LMB),
NEIClientUtils.getKeyName(NEIClientUtils.SHIFT_HASH, NEIMouseUtils.MOUSE_BTN_LMB),
NEIClientUtils.translate("itempanel.open_crafting"));
hotkeys.put(
KeyManager.getKeyName(NEIClientUtils.SHIFT_HASH, NEIMouseUtils.MOUSE_BTN_RMB),
NEIClientUtils.getKeyName(NEIClientUtils.SHIFT_HASH, NEIMouseUtils.MOUSE_BTN_RMB),
NEIClientUtils.translate("itempanel.open_usage"));
hotkeys.put(
KeyManager.getKeyName(NEIClientUtils.CTRL_HASH, NEIMouseUtils.MOUSE_BTN_LMB),
NEIClientUtils.getKeyName(NEIClientUtils.CTRL_HASH, NEIMouseUtils.MOUSE_BTN_LMB),
NEIClientUtils.translate("itempanel.infinite_item"));
} else {
hotkeys.put(
@@ -647,18 +604,18 @@ public abstract class ShortcutInputHandler {
if (handlerRef.canUseOverlayRenderer(gui)) {
hotkeys.put(
KeyManager.getKeyName("gui.overlay"),
NEIClientConfig.getKeyName("gui.overlay"),
NEIClientUtils.translate("itempanel.overlay_recipe"));
}
if (handlerRef.canFillCraftingGrid(gui)) {
hotkeys.put(
KeyManager.getKeyName("gui.overlay", NEIClientUtils.SHIFT_HASH),
NEIClientConfig.getKeyName("gui.overlay", NEIClientUtils.SHIFT_HASH),
NEIClientUtils.translate("itempanel.fill_crafting_grid"));
if (handlerRef.allowedTransferAlghoritm(gui)) {
hotkeys.put(
KeyManager.getKeyName(
NEIClientConfig.getKeyName(
"gui.overlay",
NEIClientUtils.SHIFT_HASH + NEIClientUtils.CTRL_HASH),
NEIClientUtils.translate("itempanel.fill_crafting_grid_quantity"));
@@ -667,19 +624,16 @@ public abstract class ShortcutInputHandler {
if (NEIClientConfig.autocraftingEnabled()) {
hotkeys.put(
KeyManager.getKeyName(
NEIClientConfig.getKeyName(
"gui.craft_items",
NEIClientUtils.SHIFT_HASH + NEIClientUtils.CTRL_HASH),
NEIClientUtils.translate("itempanel.craft_missing"));
hotkeys.put(
KeyManager.getKeyName("gui.craft_items", NEIClientUtils.SHIFT_HASH),
NEIClientConfig.getKeyName("gui.craft_items", NEIClientUtils.SHIFT_HASH),
NEIClientUtils.translate("itempanel.craft_all"));
}
}
hotkeys.put(
KeyManager.getKeyName("bookmark.chat_link", NEIClientUtils.SHIFT_HASH + NEIClientUtils.CTRL_HASH),
NEIClientUtils.translate("bookmark.recipe.chat_link"));
}
hotkeysCache.update(mousex, mousey, stack, groupId, hotkeys);
@@ -692,10 +646,8 @@ public abstract class ShortcutInputHandler {
final List<ItemStack> playerInventory = AutoCraftingManager.getInventoryItems(guiContainer).values();
final RecipeId rootRecipeId = math.createMasterRoot();
for (int i = 0; i < math.recipeIngredients.size(); i++) {
final BookmarkItem item = math.recipeIngredients.get(i);
if (item.getAmount() > 0 && rootRecipeId.equals(item.recipeId)) {
for (BookmarkItem item : math.recipeIngredients) {
if (item.amount > 0 && rootRecipeId.equals(item.recipeId)) {
long amount = 0;
for (ItemStack stack : playerInventory) {
@@ -704,12 +656,8 @@ public abstract class ShortcutInputHandler {
}
}
if (amount >= item.getAmount()) {
math.recipeIngredients.set(
i,
BookmarkItem.builder(item).multiplier(1)
.factor(amount + item.getAmount() - (amount % item.getAmount()))
.chance(PositionedStack.CHANCE_FULL).build());
if (amount >= item.amount) {
item.factor = item.amount = amount + item.amount - (amount % item.amount);
}
}
}
@@ -736,7 +684,7 @@ public abstract class ShortcutInputHandler {
return itemSlot.getRecipeId();
}
if (gui instanceof GuiRecipe<?>guiRecipe) {
if (gui instanceof GuiRecipe guiRecipe) {
final Recipe focusedRecipe = guiRecipe.getFocusedRecipe();
if (focusedRecipe != null) {
@@ -1,76 +0,0 @@
package codechicken.nei.asm;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.List;
import net.minecraft.client.settings.KeyBinding;
import cpw.mods.fml.relauncher.ReflectionHelper;
public final class KeyBindingFixHooks {
private static volatile boolean initialized;
private static Field keybindArrayField;
private static Field pressedField;
private static Field pressTimeField;
private KeyBindingFixHooks() {}
public static void onTickAll(int keyCode) {
if (keyCode == 0) {
return;
}
for (KeyBinding binding : getBindings()) {
if (binding.getKeyCode() == keyCode) {
try {
pressTimeField.setInt(binding, pressTimeField.getInt(binding) + 1);
} catch (Exception ignored) {}
}
}
}
public static void setKeyBindStateAll(int keyCode, boolean pressed) {
if (keyCode == 0) {
return;
}
for (KeyBinding binding : getBindings()) {
if (binding.getKeyCode() == keyCode) {
try {
pressedField.setBoolean(binding, pressed);
} catch (Exception ignored) {}
}
}
}
@SuppressWarnings("unchecked")
private static List<KeyBinding> getBindings() {
init();
try {
return (List<KeyBinding>) keybindArrayField.get(null);
} catch (Exception ignored) {}
return Collections.emptyList();
}
private static synchronized void init() {
if (initialized) {
return;
}
keybindArrayField = ReflectionHelper.findField(KeyBinding.class, "keybindArray", "field_74516_a");
pressedField = ReflectionHelper.findField(KeyBinding.class, "pressed", "field_74513_e");
pressTimeField = ReflectionHelper.findField(KeyBinding.class, "pressTime", "field_151474_i");
initialized = true;
}
}
@@ -56,8 +56,7 @@ public class NEITransformer implements IClassTransformer {
public NEITransformer() {
if (FMLLaunchHandler.side().isClient()) {
// Generates method to set the placed position of a mob spawner for the item
// callback. More portable than
// Generates method to set the placed position of a mob spawner for the item callback. More portable than
// copying vanilla placement code
transformer.add(
new MethodWriter(
@@ -83,6 +82,7 @@ public class NEITransformer implements IClassTransformer {
asmblocks.get("commaFix"),
true));
// fix workbench container losing items on shift click output without room for the full stack
transformer.add(
new MethodTransformer(
new ObfMapping(
@@ -105,33 +105,6 @@ public class NEITransformer implements IClassTransformer {
asmblocks.get("d_glintAlphaFix"),
asmblocks.get("glintAlphaFix")));
if (FMLLaunchHandler.side().isClient()) {
transformer.add(
new MethodWriter(
ACC_PUBLIC | ACC_STATIC,
new ObfMapping("net/minecraft/client/settings/KeyBinding", "func_74507_a", "(I)V"),
asmblocks.get("m_keyBindingOnTickAll")));
transformer.add(
new MethodWriter(
ACC_PUBLIC | ACC_STATIC,
new ObfMapping("net/minecraft/client/settings/KeyBinding", "func_74510_a", "(IZ)V"),
asmblocks.get("m_keyBindingSetStateAll")));
transformer.add(
new MethodInjector(
new ObfMapping("net/minecraft/client/settings/GameSettings", "func_74303_b", "()V"),
asmblocks.get("saveOptionsHook"),
true));
transformer.add(
new MethodInjector(
new ObfMapping("net/minecraft/client/settings/GameSettings", "func_74303_b", "()V"),
asmblocks.get("n_saveOptionsSendSettings"),
asmblocks.get("saveOptionsRestoreHook"),
false));
}
String GuiContainer = "net/minecraft/client/gui/inventory/GuiContainer";
// add manager field
transformer.add(
@@ -1,78 +0,0 @@
package codechicken.nei.asm;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import codechicken.core.CommonUtils;
import codechicken.nei.KeyManager;
import codechicken.nei.NEIClientConfig;
public final class SaveOptionsFixHooks {
private static final String KEY_PREFIX = "key_nei.options.keys.";
private static List<String> pendingRestoreLines;
private SaveOptionsFixHooks() {}
public static void onBeforeSaveOptions() {
pendingRestoreLines = null;
if (NEIClientConfig.isLoaded()) {
return;
}
final File optionsFile = new File(CommonUtils.getMinecraftDir(), "options.txt");
if (!optionsFile.exists()) {
return;
}
final List<String> missing = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(optionsFile))) {
String line;
while ((line = reader.readLine()) != null) {
if (!line.startsWith(KEY_PREFIX)) continue;
final int colon = line.indexOf(':');
if (colon <= 0) continue;
final String description = line.substring(4, colon);
if (!KeyManager.isRegistered(description)) {
missing.add(line);
}
}
} catch (IOException e) {
NEIClientConfig.logger.error("Failed to read key bindings before options save", e);
return;
}
if (!missing.isEmpty()) {
pendingRestoreLines = missing;
}
}
public static void onAfterSaveOptions() {
final List<String> restore = pendingRestoreLines;
pendingRestoreLines = null;
if (restore == null) {
return;
}
final File optionsFile = new File(CommonUtils.getMinecraftDir(), "options.txt");
try (FileWriter writer = new FileWriter(optionsFile, true)) {
for (String line : restore) {
writer.write(line);
writer.write(System.lineSeparator());
}
} catch (IOException e) {
NEIClientConfig.logger.error("Failed to restore NEI key bindings after options save", e);
}
}
}
@@ -24,7 +24,7 @@ import codechicken.lib.gui.GuiDraw;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.BookmarkPanel.BookmarkViewMode;
import codechicken.nei.ItemPanels;
import codechicken.nei.ItemStackSet;
import codechicken.nei.ItemStackAmount;
import codechicken.nei.ItemsGrid;
import codechicken.nei.ItemsGrid.MouseContext;
import codechicken.nei.LayoutManager;
@@ -33,7 +33,6 @@ import codechicken.nei.NEIClientUtils;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.recipe.Recipe;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.recipe.Recipe.RecipeIngredient;
import codechicken.nei.recipe.StackInfo;
import codechicken.nei.recipe.chain.RecipeChainMath;
@@ -140,16 +139,17 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
if (group.collapsedRecipes.contains(collapsedRecipeId)) {
for (BookmarkItem item : this.bookmarkItems) {
if (item.groupId == groupId && collapsedRecipeId.equals(item.recipeId) && item.multiplier == 1) {
item.multiplier = 0;
if (item.groupId == groupId && collapsedRecipeId.equals(item.recipeId)
&& item.amount == item.factor) {
item.amount = 0;
}
}
} else {
for (BookmarkItem item : this.bookmarkItems) {
if (item.groupId == groupId && collapsedRecipeId.equals(item.recipeId) && item.multiplier == 0) {
item.multiplier = 1;
if (item.groupId == groupId && collapsedRecipeId.equals(item.recipeId) && item.amount == 0) {
item.amount = item.factor;
}
}
@@ -627,17 +627,15 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
for (int itemIndex = 0; itemIndex < this.bookmarkItems.size(); itemIndex++) {
final BookmarkItem item = this.bookmarkItems.get(itemIndex);
if (item.groupId == groupId && (recipeRelations == null || recipeRelations.contains(item.recipeId))) {
long amount = item.amount;
if (recipeId != null && group.crafting != null
&& group.crafting.calculatedItems.containsKey(itemIndex)
&& recipeId.equals(item.recipeId)) {
chainItems.add(
item.copyWithMultiplier(
group.crafting.calculatedItems.get(itemIndex).getCalculatedMultiplier()));
} else {
chainItems.add(item.copy());
amount = group.crafting.calculatedItems.get(itemIndex).getCalculatedAmount();
}
chainItems.add(item.copyWithAmount(amount));
}
}
@@ -879,16 +877,6 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
return this.bookmarkItems.get(itemIndex);
}
public void replaceBookmarkItem(int itemIndex, BookmarkItem newItem) {
if (itemIndex < 0 || itemIndex >= this.bookmarkItems.size()) {
return;
}
this.bookmarkItems.set(itemIndex, newItem);
onItemsChanged();
}
public int getAbsoluteSlotIndex(int itemIndex) {
return this.gridGenerator.itemToSlot.getOrDefault(itemIndex, -1);
}
@@ -908,38 +896,34 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
}
public void addRecipe(Recipe recipe, int multiplier, int groupId) {
final ItemStackSet seenResults = new ItemStackSet();
final ItemStackSet seenIngredients = new ItemStackSet();
final List<ItemStack> results = new ArrayList<>();
final List<ItemStack> ingredients = new ArrayList<>();
final RecipeId recipeId = recipe.getRecipeId();
final List<ItemStack> results = recipe.getResults().stream().map(res -> res.getItemStack())
.collect(Collectors.toList());
final List<ItemStack> ingredients = recipe.getIngredients().stream().map(ingr -> ingr.getItemStack())
.collect(Collectors.toList());
for (RecipeIngredient result : recipe.getResults()) {
ItemStack stack = result.getItemStack();
if (!seenResults.contains(stack)) {
seenResults.add(stack);
results.add(stack);
}
}
for (RecipeIngredient ingr : recipe.getIngredients()) {
ItemStack stack = ingr.getItemStack();
if (!seenIngredients.contains(stack)) {
seenIngredients.add(stack);
ingredients.add(stack);
}
}
for (ItemStack stack : results) {
for (ItemStack stack : ItemStackAmount.of(results).values()) {
long factor = StackInfo.getAmount(stack);
this.addItem(
BookmarkItem.builder(groupId, stack, recipe, BookmarkItemType.RESULT).multiplier(multiplier)
.build(),
BookmarkItem.of(
groupId,
StackInfo.withAmount(stack, factor * multiplier),
factor,
recipeId,
BookmarkItemType.RESULT),
true);
}
for (ItemStack stack : ingredients) {
for (ItemStack stack : ItemStackAmount.of(ingredients).values()) {
long factor = StackInfo.getAmount(stack);
this.addItem(
BookmarkItem.builder(groupId, stack, recipe, BookmarkItemType.INGREDIENT).multiplier(multiplier)
.build(),
BookmarkItem.of(
groupId,
StackInfo.withAmount(stack, factor * multiplier),
factor,
recipeId,
BookmarkItemType.INGREDIENT,
BookmarkItem.generatePermutations(stack, recipe)),
true);
}
}
@@ -1149,8 +1133,8 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
final Set<Long> sizes = new HashSet<>();
for (BookmarkItem item : this.bookmarkItems) {
if (item.groupId == targetGroupId && item.getAmount() > 0) {
sizes.add(Math.max(item.getStackSize(), item.getStackSize(item.getAmount(1))));
if (item.groupId == targetGroupId && item.amount > 0) {
sizes.add(Math.max(item.getStackSize(), item.factor / item.fluidCellAmount));
items.add(item);
}
}
@@ -1159,16 +1143,14 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
long multiplier = Integer.MAX_VALUE;
for (BookmarkItem item : items) {
final long amount = item.getAmount();
final long customFactor = (amount + gcd - 1) / gcd;
final long customMultiplier = customFactor > 0 ? ((amount + customFactor - 1) / customFactor) : 0;
long customFactor = (long) Math.ceil(item.amount / (double) gcd);
long customMultiplier = (long) (customFactor > 0 ? Math.ceil(item.amount / (double) customFactor) : 0);
multiplier = Math.min(shiftMultiplier(customMultiplier, shift, 1), multiplier);
}
for (BookmarkItem item : items) {
final long amount = item.getAmount();
final long customFactor = (amount + gcd - 1) / gcd;
item.multiplier = item.getMultiplierFromAmount(customFactor * multiplier);
long customFactor = (long) Math.ceil(item.amount / (double) gcd);
item.amount = customFactor * multiplier;
}
} else {
final Map<RecipeId, Long> recipeMultipliers = new HashMap<>();
@@ -1176,7 +1158,7 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
final List<BookmarkItem> items = new ArrayList<>();
for (BookmarkItem item : this.bookmarkItems) {
if (!item.emptyFactor()
if (item.factor > 0
&& outputRecipes.stream().anyMatch(recipeId -> item.equalsRecipe(recipeId, targetGroupId))) {
final long multiplier = recipeMultipliers.getOrDefault(item.recipeId, (long) Integer.MAX_VALUE);
final boolean recipeInMiddle = group.crafting != null
@@ -1186,7 +1168,7 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
item.recipeId,
Math.min(
shiftMultiplier(
Math.max(recipeInMiddle ? 1 : 0, item.multiplier),
Math.max(recipeInMiddle ? 1 : 0, item.getMultiplier()),
shift,
recipeInMiddle ? 1 : 0),
multiplier));
@@ -1195,7 +1177,7 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
}
for (BookmarkItem item : items) {
item.multiplier = recipeMultipliers.getOrDefault(item.recipeId, 0L);
item.amount = item.factor * recipeMultipliers.getOrDefault(item.recipeId, 0L);
}
}
@@ -1215,10 +1197,10 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
long multiplier = Integer.MAX_VALUE;
for (BookmarkItem item : this.bookmarkItems) {
if (item.equalsRecipe(recipeId, targetItem.groupId) && !item.emptyFactor()) {
if (item.equalsRecipe(recipeId, targetItem.groupId) && item.factor > 0) {
multiplier = Math.min(
shiftMultiplier(
Math.max(recipeInMiddle ? 1 : 0, item.multiplier),
Math.max(recipeInMiddle ? 1 : 0, item.getMultiplier()),
shift,
recipeInMiddle ? 1 : 0),
multiplier);
@@ -1226,8 +1208,8 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
}
for (BookmarkItem item : this.bookmarkItems) {
if (item.equalsRecipe(recipeId, targetItem.groupId) && !item.emptyFactor()) {
item.multiplier = multiplier;
if (item.equalsRecipe(recipeId, targetItem.groupId) && item.factor > 0) {
item.amount = item.factor * multiplier;
}
}
@@ -1235,7 +1217,7 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
for (BookmarkItem item : this.bookmarkItems) {
if (targetItem.equals(item)) {
item.multiplier = shiftMultiplier(item.multiplier, shift, 0);
item.amount = item.factor * shiftMultiplier(item.getMultiplier(), shift, 0);
break;
}
}
@@ -66,14 +66,10 @@ 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 && !isCollapsedRecipeAnchor
&& (!group.crafting.calculatedItems.containsKey(itemIndex)
|| bookmarkItem.recipeId != null && !bookmarkItem.recipeId.equals(
group.crafting.itemToRecipe.getOrDefault(itemIndex, bookmarkItem.recipeId)))) {
if (group.crafting != null && (!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);
@@ -193,11 +189,13 @@ public class BookmarkGridGenerator {
for (int shadowIndex : shadows) {
final boolean isIngredient = shadows.get(0) != shadowIndex
|| group.crafting.calculatedItems.get(shadowIndex).calculatedType == CalculatedType.INGREDIENT;
final BookmarkItem shadowBookmarkItem = BookmarkItem.builder(bookmarkItem.groupId, bookmarkItem.itemStack)
.multiplier(1).factor(StackInfo.getAmount(bookmarkItem.itemStack)).recipeId(bookmarkItem.recipeId)
.type(isIngredient ? BookmarkItemType.INGREDIENT : BookmarkItemType.RESULT)
.permutations(Collections.emptyMap()).build();
final BookmarkItem shadowBookmarkItem = BookmarkItem.of(
bookmarkItem.groupId,
bookmarkItem.itemStack,
1,
bookmarkItem.recipeId,
isIngredient ? BookmarkItemType.INGREDIENT : BookmarkItemType.RESULT,
Collections.emptyMap());
if ((absoluteSlotIndex = nextSlotIndex(
absoluteSlotIndex + 1,
@@ -322,7 +320,7 @@ public class BookmarkGridGenerator {
return group.crafting.calculatedItems.get(itemIndex);
} else {
BookmarkChainItem item = BookmarkChainItem.of(this.grid.getBookmarkItem(itemIndex));
item.setRealMultiplier(item.getCalculatedMultiplier());
item.setRealAmount(item.getShiftAmount());
return item;
}
}
@@ -335,7 +333,7 @@ public class BookmarkGridGenerator {
return new BookmarksGridSlot(
slotIndex,
itemIndex,
chainItem.getRealMultiplier(),
chainItem.getRealAmount(),
0,
0,
chainItem.getItem(),
@@ -345,9 +343,9 @@ public class BookmarkGridGenerator {
return new BookmarksGridSlot(
slotIndex,
itemIndex,
chainItem.getRealMultiplier(),
chainItem.getRealAmount(),
chainItem.getShiftAmount(),
chainItem.getCalculatedMultiplier(),
chainItem.getCalculatedAmount(),
chainItem.getItem(),
chainItem.calculatedType,
group);
@@ -2,7 +2,6 @@ package codechicken.nei.bookmark;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -10,160 +9,14 @@ import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fluids.FluidStack;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.PositionedStack;
import codechicken.nei.recipe.Recipe;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.recipe.Recipe.RecipeIngredient;
import codechicken.nei.recipe.StackInfo;
import codechicken.nei.util.NBTJson;
public class BookmarkItem {
public static class Builder {
private static Map<ItemStack, String> fuzzyPermutations = new HashMap<>();
private final int groupId;
private final ItemStack stack;
private long factor;
private long multiplier = -1;
private long chance = PositionedStack.CHANCE_FULL;
private RecipeId recipeId = null;
private Recipe recipe = null;
private BookmarkItemType type = BookmarkItemType.ITEM;
private Map<String, ItemStack> permutations = null;
private Builder(int groupId, ItemStack stack) {
final NBTTagCompound nbTag = StackInfo.itemStackToNBT(stack);
this.groupId = groupId;
this.stack = stack;
this.factor = nbTag.hasKey("gtFluidName") ? Math.min(144, nbTag.getInteger("Count")) : 1;
}
public Builder factor(long factor) {
this.factor = factor;
return this;
}
public Builder multiplier(long multiplier) {
this.multiplier = multiplier;
return this;
}
public Builder chance(long chance) {
this.chance = chance;
return this;
}
public Builder recipe(Recipe recipe) {
this.recipe = recipe;
this.recipeId = null;
return this;
}
public Builder recipeId(RecipeId recipeId) {
this.recipeId = recipeId;
this.recipe = null;
return this;
}
public Builder type(BookmarkItemType type) {
this.type = type;
return this;
}
public Builder permutations(Map<String, ItemStack> permutations) {
this.permutations = permutations;
return this;
}
public BookmarkItem build() {
final Map<String, ItemStack> perms;
long multiplier = 0;
if (this.permutations != null) {
perms = this.permutations;
} else if (this.type == BookmarkItemType.INGREDIENT) {
if (this.recipe != null) {
perms = Builder.generatePermutations(this.stack, this.recipe);
} else if (this.recipeId != null) {
perms = Builder.generatePermutations(this.stack, Recipe.of(this.recipeId));
} else {
perms = Builder.generatePermutations(this.stack);
}
} else {
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,
multiplier,
this.factor,
this.chance,
this.stack,
perms,
this.recipeId != null ? this.recipeId : this.recipe != null ? this.recipe.getRecipeId() : null,
this.type);
}
public static Map<String, ItemStack> generatePermutations(ItemStack stack) {
return Collections.singletonMap(getItemGUID(stack), stack);
}
public static Map<String, ItemStack> generatePermutations(ItemStack stack, Recipe recipe) {
if (recipe != null) {
final RecipeIngredient ingr = recipe.getIngredients().stream()
.filter(ingredient -> ingredient.contains(stack)).findAny().orElse(null);
if (ingr != null) {
final Map<String, ItemStack> permutations = new HashMap<>();
for (ItemStack ingrStack : ingr.getPermutations()) {
permutations.put(getItemGUID(ingrStack), ingrStack);
}
return permutations;
}
}
return generatePermutations(stack);
}
private static synchronized String getItemGUID(ItemStack stack) {
final FluidStack fluidStack = StackInfo.getFluid(stack);
if (fluidStack != null) {
return fluidStack.getFluid().getName() + ":" + fluidStack.tag;
} else {
for (Map.Entry<ItemStack, String> entry : Builder.fuzzyPermutations.entrySet()) {
if (NEIClientUtils.areStacksSameTypeCraftingWithNBT(stack, entry.getKey())) {
Builder.fuzzyPermutations.put(stack, entry.getValue());
return entry.getValue();
}
}
final String stackGUID = StackInfo.getItemStackGUID(stack);
Builder.fuzzyPermutations.put(stack, stackGUID);
return stackGUID;
}
}
}
public enum BookmarkItemType {
INGREDIENT,
@@ -179,238 +32,150 @@ public class BookmarkItem {
}
}
private static Map<ItemStack, String> fuzzyPermutations = new HashMap<>();
public int groupId;
public long amount = 0L;
public final int fluidCellAmount;
public ItemStack itemStack;
public Map<String, ItemStack> permutations;
public long factor;
public RecipeId recipeId;
public BookmarkItemType type = BookmarkItemType.ITEM;
public long multiplier = 1L;
public final long factor;
public final int fluidCellAmount;
public final long chance;
protected BookmarkItem(int groupId, long multiplier, long factor, long chance, ItemStack itemStack,
Map<String, ItemStack> permutations, RecipeId recipeId, BookmarkItemType type) {
final FluidStack fluidStack = StackInfo.getFluid(itemStack);
if (fluidStack != null) {
this.fluidCellAmount = Math.max(1, StackInfo.isFluidContainer(itemStack) ? fluidStack.amount : 1);
} else {
this.fluidCellAmount = 1;
}
protected BookmarkItem(int groupId, long amount, int fluidCellAmount, ItemStack itemStack,
Map<String, ItemStack> permutations, long factor, RecipeId recipeId, BookmarkItemType type) {
this.groupId = groupId;
this.amount = amount;
this.fluidCellAmount = fluidCellAmount;
this.itemStack = itemStack;
this.permutations = permutations;
this.factor = factor;
this.recipeId = recipeId;
this.type = type == null ? BookmarkItemType.ITEM : type;
this.multiplier = multiplier;
this.factor = factor;
this.chance = chance;
}
public static Builder builder(int groupId, ItemStack stack) {
return new Builder(groupId, stack);
}
public static BookmarkItem of(int groupId, ItemStack stack, long factor, RecipeId recipeId, BookmarkItemType type,
Map<String, ItemStack> permutations) {
final FluidStack fluidStack = StackInfo.getFluid(stack);
int fluidCellAmount = 1;
long amount;
public static Builder builder(BookmarkItem item) {
return new Builder(item.groupId, item.itemStack).factor(item.factor).multiplier(item.multiplier)
.chance(item.chance).recipeId(item.recipeId).type(item.type).permutations(item.permutations);
}
public static Builder builder(int groupId, ItemStack stack, Recipe recipe, BookmarkItemType type) {
final List<RecipeIngredient> items = type == BookmarkItemType.RESULT ? recipe.getResults()
: recipe.getIngredients();
final Builder builder = builder(groupId, stack).type(type).recipe(recipe);
final ItemStack emptyStack = StackInfo.withAmount(stack, 0);
long amount = 0;
for (RecipeIngredient res : items) {
for (ItemStack perm : res.getPermutations()) {
if (NEIClientUtils.areStacksSameTypeWithNBT(emptyStack, StackInfo.withAmount(perm, 0))) {
amount += 1L * StackInfo.getAmount(perm) * res.getChance();
break;
}
}
}
if ((amount % PositionedStack.CHANCE_FULL) == 0) {
builder.factor(amount / PositionedStack.CHANCE_FULL);
if (fluidStack != null) {
amount = fluidStack.amount * (long) Math.max(0, stack.stackSize);
fluidCellAmount = Math.max(1, StackInfo.isFluidContainer(stack) ? fluidStack.amount : 1);
} else {
builder.factor(1).chance(amount);
amount = StackInfo.getAmount(stack);
}
return builder;
return new BookmarkItem(
groupId,
amount,
fluidCellAmount,
stack,
permutations,
factor * fluidCellAmount,
recipeId,
type);
}
public static BookmarkItem of(int groupId, ItemStack stack, long factor, RecipeId recipeId, BookmarkItemType type) {
return of(
groupId,
stack,
factor,
recipeId,
type,
generatePermutations(stack, recipeId, type == BookmarkItemType.INGREDIENT));
}
public static BookmarkItem of(int groupId, ItemStack stack) {
return builder(groupId, stack).build();
final NBTTagCompound nbTag = StackInfo.itemStackToNBT(stack);
final long factor = nbTag.hasKey("gtFluidName") ? Math.min(144, nbTag.getInteger("Count")) : 1;
return BookmarkItem.of(
groupId,
stack,
factor,
null,
BookmarkItemType.ITEM,
Collections.singletonMap(getItemGUID(stack), stack));
}
public static BookmarkItem of(JsonObject jsonObject) {
final NBTTagCompound itemStackNBT = (NBTTagCompound) NBTJson.toNbt(jsonObject.get("item"));
final ItemStack itemStack = StackInfo.loadFromNBT(itemStackNBT);
if (itemStack != null) {
final int groupId = jsonObject.has("groupId") ? jsonObject.get("groupId").getAsInt()
: BookmarkGrid.DEFAULT_GROUP_ID;
final BookmarkItem.Builder builder = BookmarkItem.builder(groupId, itemStack);
if (jsonObject.has("type")) {
builder.type(BookmarkItemType.fromInt(jsonObject.get("type").getAsInt()));
} else if (jsonObject.has("ingredient") && jsonObject.get("ingredient").getAsBoolean()) {
builder.type(BookmarkItemType.INGREDIENT);
} else {
builder.type(BookmarkItemType.RESULT);
}
if (jsonObject.has("multiplier")) {
builder.multiplier(jsonObject.get("multiplier").getAsInt());
}
if (jsonObject.has("factor")) {
builder.factor(jsonObject.get("factor").getAsInt());
}
if (jsonObject.has("chance")) {
builder.chance(jsonObject.get("chance").getAsInt());
}
if (jsonObject.get("recipeId") instanceof JsonObject recipeJson) {
builder.recipeId(RecipeId.of(recipeJson));
}
return builder.build();
}
return null;
}
public BookmarkItem copyWithMultiplier(long multiplier) {
public BookmarkItem copyWithAmount(long amount) {
return new BookmarkItem(
this.groupId,
multiplier,
this.factor,
this.chance,
amount,
this.fluidCellAmount,
this.itemStack,
this.permutations,
this.factor,
this.recipeId,
this.type);
}
public BookmarkItem copyWithAmount(long amount) {
return copyWithMultiplier(getMultiplierFromAmount(amount));
}
public BookmarkItem copy() {
return copyWithMultiplier(this.multiplier);
return copyWithAmount(this.amount);
}
public BookmarkItem copyWithPerm(ItemStack stack) {
public static Map<String, ItemStack> generatePermutations(ItemStack stack, RecipeId recipeId,
boolean isIngredient) {
if (this.recipeId != null
&& !NEIClientUtils.areStacksSameTypeWithNBT(StackInfo.withAmount(stack, 0), this.getItemStack(0))) {
final ItemStack oldPerm = findPermutation(this.itemStack);
final ItemStack newPerm = findPermutation(stack);
if (isIngredient && recipeId != null) {
return generatePermutations(stack, Recipe.of(recipeId));
}
if (oldPerm != null && newPerm != null) {
final long oldAmount = StackInfo.getAmount(oldPerm);
final long amount = oldAmount > 0 ? this.factor * this.chance * StackInfo.getAmount(newPerm) / oldAmount
: 0;
final long factor = (amount % PositionedStack.CHANCE_FULL) == 0 ? amount / PositionedStack.CHANCE_FULL
: 1;
final long chance = factor == 1 ? amount : PositionedStack.CHANCE_FULL;
return Collections.singletonMap(getItemGUID(stack), stack);
}
return new BookmarkItem(
this.groupId,
this.multiplier,
factor,
chance,
newPerm,
this.permutations,
this.recipeId,
this.type);
public static Map<String, ItemStack> generatePermutations(ItemStack stack, Recipe recipe) {
if (recipe != null) {
final RecipeIngredient ingr = recipe.getIngredients().stream()
.filter(ingredient -> ingredient.contains(stack)).findAny().orElse(null);
if (ingr != null) {
final Map<String, ItemStack> permutations = new HashMap<>();
for (ItemStack ingrStack : ingr.getPermutations()) {
permutations.put(getItemGUID(ingrStack), ingrStack);
}
return permutations;
}
}
return copy();
return Collections.singletonMap(getItemGUID(stack), stack);
}
private ItemStack findPermutation(ItemStack stack) {
private static synchronized String getItemGUID(ItemStack stack) {
final FluidStack fluidStack = StackInfo.getFluid(stack);
for (ItemStack itemStack : this.permutations.values()) {
if (StackInfo.equalItemAndNBT(stack, itemStack, true)) {
return itemStack;
if (fluidStack != null) {
return fluidStack.getFluid().getName() + ":" + fluidStack.tag;
} else {
for (Map.Entry<ItemStack, String> entry : BookmarkItem.fuzzyPermutations.entrySet()) {
if (NEIClientUtils.areStacksSameTypeCraftingWithNBT(stack, entry.getKey())) {
BookmarkItem.fuzzyPermutations.put(stack, entry.getValue());
return entry.getValue();
}
}
}
return null;
final String stackGUID = StackInfo.getItemStackGUID(stack);
BookmarkItem.fuzzyPermutations.put(stack, stackGUID);
return stackGUID;
}
}
public boolean containsItems(BookmarkItem item) {
return this.permutations.keySet().stream().anyMatch(item.permutations::containsKey);
}
public long getAmount() {
return getAmount(this.multiplier);
}
public long getAmount(long multiplier, ItemStack perm) {
if (this.recipeId != null && perm != null
&& !NEIClientUtils.areStacksSameTypeWithNBT(StackInfo.withAmount(perm, 0), this.getItemStack(0))) {
final ItemStack oldPerm = findPermutation(this.itemStack);
final ItemStack newPerm = findPermutation(perm);
if (oldPerm != null && newPerm != null) {
final long oldAmount = StackInfo.getAmount(oldPerm);
final long amount = oldAmount > 0 ? this.factor * this.chance * StackInfo.getAmount(newPerm) / oldAmount
: 0;
final long factor = (amount % PositionedStack.CHANCE_FULL) == 0 ? amount / PositionedStack.CHANCE_FULL
: 1;
final long chance = factor == 1 ? amount : PositionedStack.CHANCE_FULL;
return getAmount(multiplier, factor, chance);
}
}
return getAmount(multiplier);
}
public long getAmount(long multiplier) {
return getAmount(multiplier, this.factor, this.chance);
}
protected long getAmount(long multiplier, long factor, long chance) {
long amount = factor * multiplier;
if (this.fluidCellAmount > 1) {
amount = amount * this.fluidCellAmount;
}
if (chance != PositionedStack.CHANCE_FULL) {
if (this.type == BookmarkItemType.INGREDIENT) {
// For ingredients, round up the expected amount to be conservative.
return (amount * chance + PositionedStack.CHANCE_FULL - 1) / PositionedStack.CHANCE_FULL;
} else {
// For results, round down the expected amount to be conservative.
return (amount * chance) / PositionedStack.CHANCE_FULL;
}
}
return amount;
}
public ItemStack getItemStack() {
return getItemStack(getAmount());
return getItemStack(this.amount);
}
public ItemStack getItemStack(long amount) {
@@ -418,34 +183,23 @@ public class BookmarkItem {
}
public long getStackSize() {
return getStackSize(getAmount());
return getStackSize(this.amount);
}
public long getStackSize(long amount) {
if (this.fluidCellAmount > 1) {
amount = (amount + this.fluidCellAmount - 1) / this.fluidCellAmount;
}
return amount;
}
public long getMultiplierFromAmount(long amount) {
if (this.factor <= 0 || this.chance <= 0) return 0;
if (this.fluidCellAmount > 1) {
amount = (amount + this.fluidCellAmount - 1) / this.fluidCellAmount;
}
if (this.chance == PositionedStack.CHANCE_FULL) {
return (amount + this.factor - 1) / this.factor;
}
return (amount * PositionedStack.CHANCE_FULL + this.factor * this.chance - 1) / (this.factor * this.chance);
return (long) (this.factor > 0 ? Math.ceil(amount / (double) this.fluidCellAmount) : 0);
}
public long getMultiplier() {
return this.multiplier;
return getMultiplier(this.amount);
}
public long getMultiplier(long amount) {
return (long) (this.factor > 0 ? Math.ceil(amount / (double) this.factor) : 0);
}
public long getFactor() {
return this.factor / this.fluidCellAmount;
}
public boolean equalsRecipe(BookmarkItem meta) {
@@ -456,10 +210,6 @@ public class BookmarkItem {
return groupId == this.groupId && recipeId != null && recipeId.equals(this.recipeId);
}
public boolean emptyFactor() {
return this.factor <= 0 || this.chance <= 0;
}
@Override
public int hashCode() {
return Objects.hash(this.groupId, this.fluidCellAmount, this.type.toInt(), this.recipeId);
@@ -478,27 +228,4 @@ public class BookmarkItem {
return false;
}
public JsonObject toJsonObject() {
final JsonObject jsonObject = new JsonObject();
jsonObject.add("item", NBTJson.toJsonObject(StackInfo.itemStackToNBT(getItemStack())));
jsonObject.add("multiplier", new JsonPrimitive(this.multiplier));
jsonObject.add("factor", new JsonPrimitive(this.factor));
jsonObject.add("type", new JsonPrimitive(this.type.toInt()));
if (this.groupId != BookmarkGrid.DEFAULT_GROUP_ID) {
jsonObject.add("groupId", new JsonPrimitive(this.groupId));
}
if (this.recipeId != null) {
jsonObject.add("recipeId", this.recipeId.toJsonObject());
}
if (this.chance != PositionedStack.CHANCE_FULL) {
jsonObject.add("chance", new JsonPrimitive(this.chance));
}
return jsonObject;
}
}
@@ -1,283 +0,0 @@
package codechicken.nei.bookmark;
import java.awt.Point;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import com.google.gson.JsonObject;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.BookmarkPanel.BookmarkViewMode;
import codechicken.nei.ItemPanels;
import codechicken.nei.ItemQuantityField;
import codechicken.nei.ItemStackSet;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.recipe.Recipe;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.recipe.Recipe.RecipeIngredient;
import codechicken.nei.recipe.StackInfo;
import codechicken.nei.util.NBTJson;
public class BookmarkPayload {
private String linkType;
private NBTTagCompound target;
private NBTTagCompound group;
private NBTTagList items = new NBTTagList();
private NBTTagList recipes = new NBTTagList();
private BookmarkPayload(String linkType, ItemStack stack) {
this.linkType = linkType;
this.target = stack != null ? StackInfo.itemStackToNBT(stack) : null;
}
public static BookmarkPayload of(NBTTagCompound nbt) {
final BookmarkPayload payload = new BookmarkPayload(nbt.getString("linkType"), null);
if (nbt.hasKey("item")) {
payload.target = nbt.getCompoundTag("item");
}
if (nbt.hasKey("group")) {
payload.group = nbt.getCompoundTag("group");
}
payload.items = nbt.getTagList("items", 10);
payload.recipes = nbt.getTagList("recipes", 10);
return payload;
}
public static BookmarkPayload of(BookmarkItem item) {
final BookmarkPayload payload = new BookmarkPayload("recipe", item.getItemStack());
final BookmarkGrid grid = ItemPanels.bookmarkPanel.getGrid();
final Map<RecipeId, Integer> recipesIndexes = new HashMap<>();
final RecipeId recipeId = item.recipeId;
final int groupId = item.groupId;
payload.items = new NBTTagList();
payload.recipes = new NBTTagList();
if (recipeId != null) {
for (int itemIndex = 0; itemIndex < grid.size(); itemIndex++) {
final BookmarkItem currentItem = grid.getBookmarkItem(itemIndex);
if (currentItem != null && currentItem.groupId == groupId && recipeId.equals(currentItem.recipeId)) {
addBookmarkItemToPayload(payload, currentItem, recipesIndexes);
}
}
} else {
addBookmarkItemToPayload(payload, item, recipesIndexes);
}
return payload;
}
public static BookmarkPayload of(Recipe recipe) {
final BookmarkPayload payload = new BookmarkPayload("recipe", recipe.getResult());
final Map<RecipeId, Integer> recipesIndexes = new HashMap<>();
final ItemStackSet seenIngredients = new ItemStackSet();
final ItemStackSet seenResults = new ItemStackSet();
for (RecipeIngredient result : recipe.getResults()) {
ItemStack stack = result.getItemStack();
if (!seenResults.contains(stack)) {
final BookmarkItem item = BookmarkItem.builder(-1, stack, recipe, BookmarkItemType.RESULT).build();
addBookmarkItemToPayload(payload, item, recipesIndexes);
seenResults.add(stack);
}
}
for (RecipeIngredient ingr : recipe.getIngredients()) {
ItemStack stack = ingr.getItemStack();
if (!seenIngredients.contains(stack)) {
final BookmarkItem item = BookmarkItem.builder(-1, stack, recipe, BookmarkItemType.INGREDIENT).build();
addBookmarkItemToPayload(payload, item, recipesIndexes);
seenIngredients.add(stack);
}
}
return payload;
}
public static BookmarkPayload of(int groupId) {
final BookmarkPayload payload = new BookmarkPayload("group", null);
final Map<RecipeId, Integer> recipesIndexes = new HashMap<>();
final BookmarkGrid grid = ItemPanels.bookmarkPanel.getGrid();
for (int itemIndex = 0; itemIndex < grid.size(); itemIndex++) {
final BookmarkItem item = grid.getBookmarkItem(itemIndex);
if (item != null && item.groupId == groupId) {
addBookmarkItemToPayload(payload, item, recipesIndexes);
}
}
payload.group = generateGroup(grid.getGroup(groupId));
return payload;
}
public static BookmarkPayload of(ItemStack stackover, RecipeId recipeId) {
final BookmarkPayload payload = new BookmarkPayload("item", stackover);
final Map<RecipeId, Integer> recipesIndexes = new HashMap<>();
final Point mousePos = GuiDraw.getMousePosition();
if (ItemPanels.itemPanel.containsWithSubpanels(mousePos.x, mousePos.y)) {
stackover = ItemQuantityField.prepareStackWithQuantity(stackover, 0);
}
final BookmarkItem item = BookmarkItem.builder(-1, stackover).recipeId(recipeId).type(BookmarkItemType.ITEM)
.build();
addBookmarkItemToPayload(payload, item, recipesIndexes);
return payload;
}
private static NBTTagCompound generateGroup(BookmarkGroup group) {
final NBTTagCompound groupTag = new NBTTagCompound();
final NBTTagList collapsedRecipes = new NBTTagList();
groupTag.setString("viewmode", group.viewMode.toString());
groupTag.setBoolean("crafting", group.crafting != null);
groupTag.setBoolean("collapsed", group.collapsed);
for (RecipeId recipeId : group.collapsedRecipes) {
collapsedRecipes.appendTag(NBTJson.toNbt(recipeId.toJsonObject()));
}
groupTag.setTag("collapsedRecipes", collapsedRecipes);
return groupTag;
}
private static void addBookmarkItemToPayload(BookmarkPayload payload, BookmarkItem item,
Map<RecipeId, Integer> recipesIndexes) {
final JsonObject itemTag = item.toJsonObject();
itemTag.remove("groupId");
if (item.recipeId != null) {
final int recipeIndex = recipesIndexes
.computeIfAbsent(item.recipeId, recipeId -> addRecipeToPayload(payload, recipeId, recipesIndexes));
itemTag.addProperty("recipeId", recipeIndex);
}
payload.items.appendTag(NBTJson.toNbt(itemTag));
}
private static int addRecipeToPayload(BookmarkPayload payload, RecipeId recipeId,
Map<RecipeId, Integer> recipesIndexes) {
final NBTTagCompound recipeTag = new NBTTagCompound();
final int recipeIndex = payload.recipes.tagCount();
recipeTag.setTag("recipeId", NBTJson.toNbt(recipeId.toJsonObject()));
recipeTag.setInteger("recipeIndex", recipeIndex);
payload.recipes.appendTag(recipeTag);
return recipeIndex;
}
public NBTTagCompound toNBT() {
final NBTTagCompound payloadTag = new NBTTagCompound();
payloadTag.setString("linkType", linkType);
if (target != null) {
payloadTag.setTag("item", target);
}
if (group != null) {
payloadTag.setTag("group", group);
}
payloadTag.setTag("items", items);
payloadTag.setTag("recipes", recipes);
return payloadTag;
}
public String getLinkType() {
return this.linkType;
}
public ItemStack getTargetStack() {
return this.target != null ? StackInfo.loadFromNBT(this.target) : null;
}
public BookmarkGroup getGroup() {
if (this.group == null) {
return null;
}
final boolean crafting = this.group.hasKey("crafting") && this.group.getBoolean("crafting");
final BookmarkViewMode viewMode;
if (this.group.hasKey("viewmode")) {
viewMode = BookmarkViewMode.valueOf(this.group.getString("viewmode"));
} else {
viewMode = BookmarkViewMode.TODO_LIST;
}
final BookmarkGroup group = new BookmarkGroup(viewMode, crafting);
if (this.group.hasKey("collapsed")) {
group.collapsed = this.group.getBoolean("collapsed");
}
if (this.group.hasKey("collapsedRecipes")) {
final NBTTagList collapsedRecipes = this.group.getTagList("collapsedRecipes", 10);
for (int i = 0; i < collapsedRecipes.tagCount(); i++) {
final NBTTagCompound recipeTag = collapsedRecipes.getCompoundTagAt(i);
final RecipeId recipeId = RecipeId.of((JsonObject) NBTJson.toJsonObject(recipeTag));
group.collapsedRecipes.add(recipeId);
}
}
return group;
}
public List<BookmarkItem> getBookmarkItems(int groupId) {
final List<BookmarkItem> bookmarkItems = new ArrayList<>();
final Map<Integer, RecipeId> recipesMap = new HashMap<>();
for (int i = 0; i < recipes.tagCount(); i++) {
final NBTTagCompound recipeTag = recipes.getCompoundTagAt(i);
final RecipeId recipeId = RecipeId
.of((JsonObject) NBTJson.toJsonObject(recipeTag.getCompoundTag("recipeId")));
recipesMap.put(recipeTag.getInteger("recipeIndex"), recipeId);
}
for (int i = 0; i < items.tagCount(); i++) {
final NBTTagCompound itemTag = items.getCompoundTagAt(i);
RecipeId recipeId = null;
if (itemTag.hasKey("recipeId")) {
recipeId = recipesMap.get(itemTag.getInteger("recipeId"));
itemTag.removeTag("recipeId");
}
final BookmarkItem item = BookmarkItem.of((JsonObject) NBTJson.toJsonObject(itemTag));
if (item != null) {
item.groupId = groupId;
item.recipeId = recipeId;
bookmarkItems.add(item);
}
}
return bookmarkItems;
}
}
@@ -10,6 +10,7 @@ import java.util.Collections;
import java.util.List;
import java.util.Map;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import org.apache.commons.io.IOUtils;
@@ -24,7 +25,9 @@ import com.google.gson.JsonSyntaxException;
import codechicken.nei.BookmarkPanel.BookmarkViewMode;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.recipe.StackInfo;
import codechicken.nei.util.NBTJson;
public class BookmarkStorage {
@@ -195,11 +198,7 @@ public class BookmarkStorage {
continue;
}
final BookmarkItem item = BookmarkItem.of(parser.parse(itemStr).getAsJsonObject());
if (item != null) {
grid.addItem(item, false);
} else {
if (!addItemToGrid(grid, parser.parse(itemStr).getAsJsonObject())) {
wasError = true;
NEIClientConfig.logger.warn(
"Failed to load bookmarked ItemStack from json string, the item no longer exists:\n{}",
@@ -238,6 +237,47 @@ public class BookmarkStorage {
this.bookmarkFile = bookmarkFile;
}
private boolean addItemToGrid(BookmarkGrid grid, JsonObject jsonObject) {
NBTTagCompound itemStackNBT;
if (jsonObject.get("item") != null) {
itemStackNBT = (NBTTagCompound) NBTJson.toNbt(jsonObject.get("item"));
} else { // old format
itemStackNBT = (NBTTagCompound) NBTJson.toNbt(jsonObject);
}
ItemStack itemStack = StackInfo.loadFromNBT(itemStackNBT);
if (itemStack != null) {
RecipeId recipeId = null;
boolean isFluid = itemStackNBT.hasKey("gtFluidName");
int groupId = jsonObject.has("groupId") ? jsonObject.get("groupId").getAsInt()
: BookmarkGrid.DEFAULT_GROUP_ID;
int factor = jsonObject.has("factor") ? Math.abs(jsonObject.get("factor").getAsInt()) : (isFluid ? 144 : 1);
BookmarkItemType type = jsonObject.has("type") ? BookmarkItemType.fromInt(jsonObject.get("type").getAsInt())
: null;
if (type == null) {
// old format
type = jsonObject.has("ingredient") && jsonObject.get("ingredient").getAsBoolean()
? BookmarkItemType.INGREDIENT
: BookmarkItemType.RESULT;
}
if (jsonObject.get("recipeId") instanceof JsonObject recipeJson) {
recipeId = RecipeId.of(recipeJson);
}
if (!grid.groups.containsKey(groupId)) {
groupId = BookmarkGrid.DEFAULT_GROUP_ID;
}
grid.addItem(BookmarkItem.of(groupId, itemStack, factor, recipeId, type), false);
}
return itemStack != null;
}
public void save() {
if (this.bookmarkFile == null) {
@@ -278,7 +318,21 @@ public class BookmarkStorage {
for (BookmarkItem item : grid.bookmarkItems) {
try {
strings.add(NBTJson.toJson(item.toJsonObject()));
JsonObject row = new JsonObject();
row.add("item", NBTJson.toJsonObject(StackInfo.itemStackToNBT(item.getItemStack())));
row.add("factor", new JsonPrimitive(item.getFactor()));
row.add("type", new JsonPrimitive(item.type.toInt()));
if (item.groupId != BookmarkGrid.DEFAULT_GROUP_ID) {
row.add("groupId", new JsonPrimitive(item.groupId));
}
if (item.recipeId != null) {
row.add("recipeId", item.recipeId.toJsonObject());
}
strings.add(NBTJson.toJson(row));
} catch (JsonSyntaxException e) {
NEIClientConfig.logger.error("Failed to stringify bookmarked ItemStack to json string");
}
@@ -14,7 +14,6 @@ import codechicken.nei.ItemsGrid.MouseContext;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.NEIClientUtils.Alignment;
import codechicken.nei.PositionedStack;
import codechicken.nei.bookmark.BookmarkGrid.BookmarkMouseContext;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.bookmark.RecipeChainDetails.CalculatedType;
@@ -64,18 +63,18 @@ public class BookmarksGridSlot extends ItemsGridSlot {
protected final boolean isFirstOutput;
protected final int rowIndex;
public BookmarksGridSlot(int slotIndex, int itemIndex, long realMultiplier, long shiftAmount,
long calculatedMultiplier, BookmarkItem bookmarkItem, CalculatedType calculatedType, BookmarkGroup group) {
public BookmarksGridSlot(int slotIndex, int itemIndex, long realAmount, long shiftAmount, long calculatedAmount,
BookmarkItem bookmarkItem, CalculatedType calculatedType, BookmarkGroup group) {
super(
slotIndex,
itemIndex,
calculatedType != null ? bookmarkItem.getItemStack(bookmarkItem.getAmount(calculatedMultiplier))
: bookmarkItem.getItemStack(bookmarkItem.getAmount(realMultiplier)));
calculatedType != null ? bookmarkItem.getItemStack(calculatedAmount)
: bookmarkItem.getItemStack(realAmount));
this.emptyItemStack = bookmarkItem.getItemStack(0);
this.realAmount = bookmarkItem.getAmount(realMultiplier);
this.realAmount = realAmount;
this.shiftAmount = shiftAmount;
this.calculatedAmount = calculatedType != null ? bookmarkItem.getAmount(calculatedMultiplier) : this.realAmount;
this.calculatedAmount = calculatedAmount;
this.group = group;
this.calculatedType = calculatedType;
@@ -84,8 +83,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 = realMultiplier;
this.calculatedMultiplier = calculatedMultiplier;
this.realMultiplier = bookmarkItem.getMultiplier(realAmount);
this.calculatedMultiplier = bookmarkItem.getMultiplier(calculatedAmount);
if (this.group.crafting != null && this.group.crafting.calculatedItems.containsKey(this.itemIndex)) {
this.realType = this.group.crafting.calculatedItems.get(this.itemIndex).calculatedType
@@ -193,7 +192,7 @@ public class BookmarksGridSlot extends ItemsGridSlot {
protected HandlerInfo getHandlerInfo() {
if (this.bookmarkItem.recipeId != null && this.handlerInfo == null) {
this.handlerInfo = GuiRecipeTab.getHandlerInfo(this.bookmarkItem.recipeId.getHandlerName(), null);
this.handlerInfo = GuiRecipeTab.getHandlerInfo(this.bookmarkItem.recipeId.getHandleName(), null);
}
return this.handlerInfo;
}
@@ -348,22 +347,17 @@ 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 || this.bookmarkItem.chance != PositionedStack.CHANCE_FULL && drawChance
|| shownItemType == ShownItemType.REAL && !this.bookmarkItem.emptyFactor()) {
if (amount > 0 || shownItemType == ShownItemType.REAL && this.bookmarkItem.factor > 0) {
final float panelFactor = (rect.w - 2) / (DEFAULT_SLOT_SIZE - 2);
final long stackSize = this.bookmarkItem.getStackSize(amount);
int color = 0xFFFFFF;
String amountString = "";
if (stackSize < 10_000) {
@@ -376,16 +370,11 @@ public class BookmarksGridSlot extends ItemsGridSlot {
amountString += "L";
}
if (this.bookmarkItem.chance != PositionedStack.CHANCE_FULL) {
amountString = "~" + amountString;
color = 0xFFAA00;
}
NEIClientUtils.drawNEIOverlayText(
amountString,
new Rectangle4i(rect.x + 1, rect.y + 1, rect.w - 2, rect.h - 2),
panelFactor,
color,
0xFFFFFF,
true,
this.isFluidDisplay ? Alignment.BottomLeft : Alignment.BottomRight);
}
@@ -42,35 +42,34 @@ public class RecipeChainDetails {
private final BookmarkItem item;
private long realMultiplier = 0L;
private long realAmount = 0L;
private long shiftAmount = 0L;
private long calculatedMultiplier = 0L;
private long calculatedAmount = 0L;
public CalculatedType calculatedType;
protected BookmarkChainItem(BookmarkItem item, long shiftItem, long calculatedMultiplier,
protected BookmarkChainItem(BookmarkItem item, long shiftItem, long calculatedItem,
CalculatedType calculatedType) {
this.item = item.copy();
this.shiftAmount = shiftItem;
this.calculatedMultiplier = calculatedMultiplier;
this.calculatedAmount = calculatedItem;
this.calculatedType = calculatedType;
}
public static BookmarkChainItem of(BookmarkItem item, long shiftItem, long calculatedMultiplier,
public static BookmarkChainItem of(BookmarkItem item, long shiftItem, long calculatedAmount,
CalculatedType calculatedType) {
return new BookmarkChainItem(item, shiftItem, calculatedMultiplier, calculatedType);
return new BookmarkChainItem(item, shiftItem, calculatedAmount, calculatedType);
}
public static BookmarkChainItem of(BookmarkItem item, long shiftItem, CalculatedType calculatedType) {
return new BookmarkChainItem(item, shiftItem, item.getMultiplier(), calculatedType);
return new BookmarkChainItem(item, shiftItem, item.amount, calculatedType);
}
public static BookmarkChainItem of(BookmarkItem item) {
final long amount = item.getAmount();
return new BookmarkChainItem(
item,
amount,
item.getMultiplier(),
item.amount,
item.amount,
item.type == BookmarkItemType.INGREDIENT ? CalculatedType.INGREDIENT : CalculatedType.RESULT);
}
@@ -78,34 +77,30 @@ public class RecipeChainDetails {
return this.item.getItemStack(amount);
}
public void setRealMultiplier(long multiplier) {
this.realMultiplier = multiplier;
public void setRealAmount(long amount) {
this.realAmount = amount;
}
public long getRealMultiplier() {
return this.realMultiplier;
}
public void setCalculatedMultiplier(long multiplier) {
this.calculatedMultiplier = multiplier;
}
public long getCalculatedMultiplier() {
return this.calculatedMultiplier;
public long getRealAmount() {
return this.realAmount;
}
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.calculatedMultiplier += this.item.getMultiplierFromAmount(calculatedAmount);
this.item.multiplier = this.calculatedMultiplier;
this.calculatedAmount += calculatedAmount;
this.item.amount = this.calculatedAmount;
}
}
@@ -185,9 +180,10 @@ 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).setRealMultiplier(Math.max(0, item.getMultiplier() - 1));
this.calculatedItems.get(itemIndex)
.setRealAmount(Math.max(0, item.factor * (item.getMultiplier() - 1)));
} else {
this.calculatedItems.get(itemIndex).setRealMultiplier(item.getMultiplier());
this.calculatedItems.get(itemIndex).setRealAmount(item.amount);
}
}
}
@@ -243,7 +239,7 @@ public class RecipeChainDetails {
for (BookmarkItem item : chainItems) {
if (recipeRelations.contains(item.recipeId)) {
subChainItems.add(item.copyWithMultiplier(recipeId.equals(item.recipeId) ? item.multiplier : 0));
subChainItems.add(item.copyWithAmount(recipeId.equals(item.recipeId) ? item.amount : 0));
}
}
@@ -262,8 +258,7 @@ public class RecipeChainDetails {
}
if (this.calculatedItems.containsKey(itemIndex)) {
this.calculatedItems.get(itemIndex)
.setRealMultiplier(value.getItem().getMultiplierFromAmount(value.getShiftAmount()));
this.calculatedItems.get(itemIndex).setRealAmount(value.getShiftAmount());
}
}
@@ -277,19 +272,18 @@ public class RecipeChainDetails {
for (RecipeId relRecipeId : recipeRelations) {
for (BookmarkItem item : math.recipeResults) {
if (item.recipeId.equals(relRecipeId)) {
final long amount = item.getAmount() - math.requiredAmount.getOrDefault(item, 0L);
final long amount = item.amount - math.requiredAmount.getOrDefault(item, 0L);
if (item.recipeId.equals(recipeId)) {
multiplier.put(item.recipeId, item.getMultiplier());
items.computeIfAbsent(
StackInfo.getItemStackGUID(item.itemStack),
is -> BookmarkChainItem.of(item, 0, 0, CalculatedType.RESULT))
.append(amount, item.getAmount());
.append(amount, item.amount);
} else if (amount > 0) {
items.computeIfAbsent(
StackInfo.getItemStackGUID(item.itemStack),
is -> BookmarkChainItem.of(item, 0, 0, CalculatedType.RESULT))
.append(amount, item.getAmount());
is -> BookmarkChainItem.of(item, 0, 0, CalculatedType.RESULT)).append(amount, amount);
}
}
}
@@ -298,17 +292,17 @@ public class RecipeChainDetails {
if (item.recipeId.equals(relRecipeId)) {
final BookmarkItem prefItem = math.preferredItems.get(item);
final long amount = math.requiredAmount.containsKey(prefItem) ? 0
: math.requiredAmount.getOrDefault(item, item.getAmount());
: math.requiredAmount.getOrDefault(item, item.amount);
final long refAmount = prefItem != null && !topLevelRecipes.contains(prefItem.recipeId)
? math.requiredAmount.getOrDefault(prefItem, 0L)
: 0;
if (amount != 0 || item.getAmount() > refAmount && math.requiredAmount.containsKey(prefItem)
if (amount != 0 || item.amount > refAmount && math.requiredAmount.containsKey(prefItem)
|| recipeId.equals(item.recipeId) && multiplier.get(recipeId) == 0) {
items.computeIfAbsent(
StackInfo.getItemStackGUID(item.itemStack),
is -> BookmarkChainItem.of(item, 0, 0, CalculatedType.INGREDIENT))
.append(amount, item.getAmount() - refAmount);
.append(amount, item.amount - refAmount);
}
}
}
@@ -318,7 +312,7 @@ public class RecipeChainDetails {
}
private void generateResult(RecipeChainMath math, BookmarkItem item, int itemIndex) {
final long amount = item.getAmount() - math.requiredAmount.getOrDefault(item, 0L);
final long amount = item.amount - math.requiredAmount.getOrDefault(item, 0L);
final CalculatedType calculatedType = math.outputRecipes.containsKey(item.recipeId) ? CalculatedType.RESULT
: CalculatedType.REMAINDER;
@@ -328,7 +322,7 @@ public class RecipeChainDetails {
private void generateIngredient(RecipeChainMath math, BookmarkItem item, int itemIndex) {
final BookmarkItem prefItem = math.preferredItems.get(item);
final long amount = math.requiredAmount.containsKey(prefItem) ? 0
: math.requiredAmount.getOrDefault(item, item.getAmount());
: math.requiredAmount.getOrDefault(item, item.amount);
this.calculatedItems.put(itemIndex, BookmarkChainItem.of(item, amount, CalculatedType.INGREDIENT));
}
@@ -1,7 +1,5 @@
package codechicken.nei.bookmark;
import static codechicken.nei.bookmark.BookmarkGrid.DEFAULT_GROUP_ID;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Collections;
@@ -141,11 +139,13 @@ public class SortableItem {
return;
}
if (overGroupId != DEFAULT_GROUP_ID && beforeGroupId != DEFAULT_GROUP_ID) {
beforeGroupId = DEFAULT_GROUP_ID;
if (overGroupId != BookmarkGrid.DEFAULT_GROUP_ID
&& beforeGroupId != BookmarkGrid.DEFAULT_GROUP_ID) {
beforeGroupId = BookmarkGrid.DEFAULT_GROUP_ID;
}
if (overGroupId == DEFAULT_GROUP_ID && afterGroupId != DEFAULT_GROUP_ID) {
if (overGroupId == BookmarkGrid.DEFAULT_GROUP_ID && beforeGroupId != BookmarkGrid.DEFAULT_GROUP_ID
&& afterGroupId != BookmarkGrid.DEFAULT_GROUP_ID) {
return;
}
@@ -160,11 +160,12 @@ public class SortableItem {
return;
}
if (overGroupId != DEFAULT_GROUP_ID && afterGroupId != DEFAULT_GROUP_ID) {
afterGroupId = DEFAULT_GROUP_ID;
if (overGroupId != BookmarkGrid.DEFAULT_GROUP_ID && afterGroupId != BookmarkGrid.DEFAULT_GROUP_ID) {
afterGroupId = BookmarkGrid.DEFAULT_GROUP_ID;
}
if (overGroupId == DEFAULT_GROUP_ID && beforeGroupId != DEFAULT_GROUP_ID) {
if (overGroupId == BookmarkGrid.DEFAULT_GROUP_ID && beforeGroupId != BookmarkGrid.DEFAULT_GROUP_ID
&& afterGroupId != BookmarkGrid.DEFAULT_GROUP_ID) {
return;
}
@@ -1,39 +1,18 @@
package codechicken.nei.commands;
import java.util.Arrays;
import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommandSender;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.JsonToNBT;
import net.minecraft.nbt.NBTException;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChatComponentTranslation;
import codechicken.nei.ItemPanels;
import codechicken.nei.LRUCache;
import codechicken.nei.bookmark.BookmarkGrid;
import codechicken.nei.bookmark.BookmarkGroup;
import codechicken.nei.bookmark.BookmarkPayload;
public class CommandBookmarkAdd extends CommandBase {
private static final LRUCache<String, NBTTagCompound> PAYLOAD_CACHE = new LRUCache<>(64);
public static void cachePayload(String payloadId, NBTTagCompound payload) {
if (payloadId == null || payloadId.isEmpty() || payload == null) {
return;
}
synchronized (PAYLOAD_CACHE) {
PAYLOAD_CACHE.put(payloadId, (NBTTagCompound) payload.copy());
}
}
private static NBTTagCompound getCachedPayload(String payloadId) {
synchronized (PAYLOAD_CACHE) {
return PAYLOAD_CACHE.get(payloadId);
}
}
@Override
public String getCommandName() {
return "nei_bookmark";
@@ -41,7 +20,7 @@ public class CommandBookmarkAdd extends CommandBase {
@Override
public String getCommandUsage(ICommandSender sender) {
return "/nei_bookmark <payloadId>";
return "/nei_bookmark <nbt>";
}
@Override
@@ -51,37 +30,19 @@ public class CommandBookmarkAdd extends CommandBase {
@Override
public void processCommand(ICommandSender sender, String[] args) {
if (args.length < 1) {
sender.addChatMessage(new ChatComponentText("§c/nei_bookmark <payloadId>"));
if (args.length < 1 || args[0].length() < 3) {
sender.addChatMessage(new ChatComponentText("§c/nei_bookmark <nbt>"));
return;
}
try {
final String payloadId = String.join(" ", Arrays.copyOfRange(args, 0, args.length));
final NBTTagCompound payload = getCachedPayload(payloadId);
if (payload == null) {
throw new IllegalArgumentException("Missing cached payload");
}
addBookmarkFromPayload((NBTTagCompound) payload.copy());
ItemPanels.bookmarkPanel.addItem(
ItemStack.loadItemStackFromNBT((NBTTagCompound) JsonToNBT.func_150315_a(String.join(" ", args))));
sender.addChatMessage(new ChatComponentTranslation("nei.chat.bookmark_added.text"));
} catch (Exception e) {
} catch (NBTException e) {
sender.addChatMessage(new ChatComponentText(e.toString()));
}
}
private static void addBookmarkFromPayload(NBTTagCompound nbt) {
final BookmarkPayload payload = BookmarkPayload.of(nbt);
final BookmarkGrid grid = ItemPanels.bookmarkPanel.getGrid();
final BookmarkGroup group = payload.getGroup();
int groupId = BookmarkGrid.DEFAULT_GROUP_ID;
if (group != null) {
groupId = grid.addGroup(group);
}
payload.getBookmarkItems(groupId).forEach(item -> grid.addItem(item, true));
}
}
@@ -8,15 +8,13 @@ import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Arrays;
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;
@@ -41,7 +39,6 @@ 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 {
@@ -128,16 +125,12 @@ 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, boolean fastDump) {
public ProcessDumpThread(ICommandSender sender, File currFile) {
this.sender = sender;
this.currFile = currFile;
this.fastDump = fastDump;
ClientHandler.loadSettingsFile("recipeidblacklist.cfg", lines -> {
final Set<String> names = lines.collect(Collectors.toSet());
@@ -157,10 +150,38 @@ public class CommandRecipeId extends CommandBase {
sendChatInfoMessage(sender, "nei.chat.recipeid.dump.start");
try (BufferedWriter writer = Files.newBufferedWriter(currFile.toPath(), StandardCharsets.UTF_8)) {
if (fastDump) {
processFastDump(writer);
} else {
processDump(writer);
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);
}
}
}
}
} catch (Exception e) {
@@ -171,118 +192,15 @@ 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<>(
handler -> handler.getRecipeHandler("item", results),
h -> h.getRecipeHandler("item", results),
this.craftinghandlers,
this.serialCraftingHandlers,
"Error while looking up crafting recipe",
"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"));
"outputId: item",
"results: " + Arrays.toString(results))
.runWithProfiling(NEIClientUtils.translate("recipe.concurrent.crafting"));
}
}
@@ -294,7 +212,7 @@ public class CommandRecipeId extends CommandBase {
@Override
public String getCommandUsage(ICommandSender sender) {
return "/recipeid [dump|fast-dump] <filename> OR /recipeid diff <prev-filename> <curr-filename> <subset name>";
return "/recipeid dump <filename> OR /recipeid diff <prev-filename> <curr-filename> [subset name]";
}
@Override
@@ -302,27 +220,12 @@ 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, false);
} else if ("fast-dump".equals(command)) {
processDumpCommand(sender, args, true);
processDumpCommand(sender, args);
} else if ("diff".equals(command)) {
processDiffCommand(sender, args);
} else {
@@ -360,7 +263,7 @@ public class CommandRecipeId extends CommandBase {
(new ProcessDiffThread(sender, prevFilename, currFilename, diffFilename)).start();
}
protected void processDumpCommand(ICommandSender sender, String[] args, boolean fastDump) {
protected void processDumpCommand(ICommandSender sender, String[] args) {
if (args.length > 2) {
sendChatErrorMessage(sender, "nei.chat.recipeid.many_params", getCommandUsage(sender));
@@ -371,30 +274,13 @@ public class CommandRecipeId extends CommandBase {
final String currFilename = args.length == 2 ? args[1] : "recipeId";
if (!dir.exists()) dir.mkdirs();
(new ProcessDumpThread(sender, getFile(currFilename), fastDump)).start();
(new ProcessDumpThread(sender, getFile(currFilename))).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)
@@ -92,8 +92,8 @@ public abstract class DataDumper extends Option {
}
public Rectangle4i dumpButtonSize() {
int width = 50;
return new Rectangle4i(getSlot().slotWidth() - width, 0, width, 20);
int width = 80;
return new Rectangle4i(slot.slotWidth() - width, 0, width, 20);
}
public Rectangle4i modeButtonSize() {
@@ -18,7 +18,6 @@ import org.lwjgl.input.Keyboard;
import codechicken.core.gui.GuiCCButton;
import codechicken.core.gui.GuiScreenWidget;
import codechicken.lib.config.ConfigTag;
import codechicken.lib.math.MathHelper;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.HUDRenderer;
@@ -28,16 +27,12 @@ public class GuiHighlightTips extends GuiScreenWidget {
private final String name;
private GuiCCButton toggleButton;
private final Option opt;
private final GuiOptionList parentGui;
private final boolean world;
private Point dragDown;
public GuiHighlightTips(Option opt) {
super(80, 20);
this.opt = opt;
name = opt.name;
this.parentGui = (GuiOptionList) Minecraft.getMinecraft().currentScreen;
this.world = parentGui.worldConfig();
}
@Override
@@ -53,7 +48,7 @@ public class GuiHighlightTips extends GuiScreenWidget {
@Override
public void actionPerformed(String ident, Object... params) {
if (ident.equals("show")) {
getTag(name).setBooleanValue(!show());
opt.getTag(name).setBooleanValue(!show());
updateNames();
}
}
@@ -63,21 +58,13 @@ public class GuiHighlightTips extends GuiScreenWidget {
}
private boolean show() {
return renderTag(name).getBooleanValue();
}
private ConfigTag getTag(String s) {
return (world ? opt.worldConfigSet() : opt.globalConfigSet()).config.getTag(s);
}
private ConfigTag renderTag(String s) {
return (world && opt.worldSpecific(s) ? opt.worldConfigSet() : opt.globalConfigSet()).config.getTag(s);
return opt.renderTag(name).getBooleanValue();
}
@Override
public void keyTyped(char c, int keycode) {
if (keycode == Keyboard.KEY_ESCAPE || keycode == Keyboard.KEY_BACK) {
Minecraft.getMinecraft().displayGuiScreen(parentGui);
Minecraft.getMinecraft().displayGuiScreen(opt.slot.getGui());
return;
}
super.keyTyped(c, keycode);
@@ -95,7 +82,7 @@ public class GuiHighlightTips extends GuiScreenWidget {
}
public Point getPos() {
return new Point(renderTag(name + ".x").getIntValue(), renderTag(name + ".y").getIntValue());
return new Point(opt.renderTag(name + ".x").getIntValue(), opt.renderTag(name + ".y").getIntValue());
}
public Dimension sampleSize() // copied from HUDManager when running with the sample for this gui
@@ -161,8 +148,8 @@ public class GuiHighlightTips extends GuiScreenWidget {
}
private void setPos(Point p) {
getTag(name).setBooleanValue(show()); // duplicates global tag for the option gui if in world mode
getTag(name + ".x").setIntValue(p.x);
getTag(name + ".y").setIntValue(p.y);
opt.getTag(name).setBooleanValue(show()); // duplicates global tag for the option gui if in world mode
opt.getTag(name + ".x").setIntValue(p.x);
opt.getTag(name + ".y").setIntValue(p.y);
}
}
@@ -43,7 +43,6 @@ public class GuiItemIconDumper extends GuiScreen {
}
private Option opt;
private final GuiOptionList parentGui;
private int drawIndex;
private int parseIndex;
private final File dir = new File(CommonUtils.getMinecraftDir(), "dumps/itempanel_icons");
@@ -53,7 +52,6 @@ public class GuiItemIconDumper extends GuiScreen {
public GuiItemIconDumper(Option opt, int iconSize) {
this.opt = opt;
this.parentGui = (GuiOptionList) Minecraft.getMinecraft().currentScreen;
this.iconSize = iconSize;
borderSize = iconSize / 16;
boxSize = iconSize + borderSize * 2;
@@ -64,7 +62,7 @@ public class GuiItemIconDumper extends GuiScreen {
}
private void returnScreen(IChatComponent msg) {
Minecraft.getMinecraft().displayGuiScreen(parentGui);
Minecraft.getMinecraft().displayGuiScreen(opt.slot.getGui());
NEIClientUtils.printChatMessage(msg);
}
@@ -7,14 +7,11 @@ import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import org.lwjgl.opengl.GL11;
import codechicken.lib.config.ConfigTag;
import codechicken.lib.math.MathHelper;
import codechicken.nei.ItemList;
import codechicken.nei.ItemSorter;
import codechicken.nei.ItemSorter.SortEntry;
import codechicken.nei.LayoutManager;
@@ -51,8 +48,6 @@ public class GuiItemSorter extends GuiOptionPane {
public final Option opt;
public final List<SortItem> slots = new ArrayList<>();
public final List<SortEntry> list;
private final GuiOptionList parentGui;
private final boolean world;
boolean dragging;
public SortItem dragged;
@@ -61,9 +56,7 @@ public class GuiItemSorter extends GuiOptionPane {
public GuiItemSorter(Option opt) {
this.opt = opt;
this.parentGui = (GuiOptionList) Minecraft.getMinecraft().currentScreen;
this.world = parentGui.worldConfig();
list = ItemSorter.fromSaveString(renderTag(opt.configName()).getValue());
list = ItemSorter.fromSaveString(opt.renderTag().getValue());
for (SortEntry e : list) slots.add(new SortItem(e));
}
@@ -105,7 +98,7 @@ public class GuiItemSorter extends GuiOptionPane {
@Override
public GuiScreen getParentScreen() {
return parentGui;
return opt.slot.getGui();
}
@Override
@@ -121,25 +114,16 @@ public class GuiItemSorter extends GuiOptionPane {
list.remove(dragged.e);
list.add(nslot, dragged.e);
getTag(opt.configName()).setValue(ItemSorter.getSaveString(list));
opt.getTag().setValue(ItemSorter.getSaveString(list));
LayoutManager.markItemsDirty();
if (opt.activeTag() == getTag(opt.configName())) {
if (opt.activeTag() == opt.getTag()) {
ItemSorter.list = new ArrayList<>(list);
}
ItemList.refreshItems.restart();
}
}
}
private ConfigTag getTag(String s) {
return (world ? opt.worldConfigSet() : opt.globalConfigSet()).config.getTag(s);
}
private ConfigTag renderTag(String s) {
return (world && opt.worldSpecific(s) ? opt.worldConfigSet() : opt.globalConfigSet()).config.getTag(s);
}
public SortItem itemAt(int mx, int my) {
if (!pane.windowBounds().contains(mx, my)) return null;
@@ -12,7 +12,6 @@ import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import codechicken.core.gui.GuiScreenWidget;
import codechicken.lib.config.ConfigTag;
import codechicken.lib.gui.GuiDraw;
import codechicken.lib.render.CCRenderState;
import codechicken.lib.vec.Rectangle4i;
@@ -22,7 +21,7 @@ import codechicken.nei.guihook.GuiContainerManager;
public class GuiPanelSettings extends GuiScreenWidget {
private final GuiOptionList parentGui;
private final Option opt;
private PanelPlaceholder bookmarksPanel;
private PanelPlaceholder itemsPanel;
@@ -55,7 +54,6 @@ public class GuiPanelSettings extends GuiScreenWidget {
private final Option opt;
private final String name;
private final boolean world;
private Rectangle4i margin;
private Point dragDown;
private String dragDir;
@@ -69,10 +67,9 @@ public class GuiPanelSettings extends GuiScreenWidget {
private PanelResizeButton rightButton = new PanelResizeButton(PANEL_SIZE, PANEL_SIZE * 2);
private PanelResizeButton bottomButton = new PanelResizeButton(PANEL_SIZE * 2, PANEL_SIZE);
public PanelPlaceholder(Option opt, String name, boolean world) {
public PanelPlaceholder(Option opt, String name) {
this.opt = opt;
this.name = name;
this.world = world;
}
public void resize(Rectangle4i margin) {
@@ -119,10 +116,10 @@ public class GuiPanelSettings extends GuiScreenWidget {
final int minWidth = ItemsGrid.SLOT_SIZE;
final int minHeight = ItemsGrid.SLOT_SIZE;
int paddingLeft = (int) Math.ceil(margin.w * getTag(name + ".left").getIntValue() / 100000.0);
int paddingTop = (int) Math.ceil(margin.h * getTag(name + ".top").getIntValue() / 100000.0);
int paddingRight = (int) Math.ceil(margin.w * getTag(name + ".right").getIntValue() / 100000.0);
int paddingBottom = (int) Math.ceil(margin.h * getTag(name + ".bottom").getIntValue() / 100000.0);
int paddingLeft = (int) Math.ceil(margin.w * opt.renderTag(name + ".left").getIntValue() / 100000.0);
int paddingTop = (int) Math.ceil(margin.h * opt.renderTag(name + ".top").getIntValue() / 100000.0);
int paddingRight = (int) Math.ceil(margin.w * opt.renderTag(name + ".right").getIntValue() / 100000.0);
int paddingBottom = (int) Math.ceil(margin.h * opt.renderTag(name + ".bottom").getIntValue() / 100000.0);
if (dragDir != null) {
final Point mouse = GuiDraw.getMousePosition();
@@ -162,10 +159,6 @@ public class GuiPanelSettings extends GuiScreenWidget {
return new int[] { paddingLeft, paddingTop, paddingRight, paddingBottom };
}
private ConfigTag getTag(String s) {
return (world ? opt.worldConfigSet() : opt.globalConfigSet()).config.getTag(s);
}
protected void drawItems() {
final int columns = (w - 2) / ItemsGrid.SLOT_SIZE;
final int rows = (h - (PANEL_SIZE + 2) * 2 - 2) / ItemsGrid.SLOT_SIZE;
@@ -226,10 +219,10 @@ public class GuiPanelSettings extends GuiScreenWidget {
if (button == 0 && dragDown != null) {
int[] padding = getPaddings();
getTag(name + ".left").setIntValue(padding[0] * 100000 / margin.w);
getTag(name + ".top").setIntValue(padding[1] * 100000 / margin.h);
getTag(name + ".right").setIntValue(padding[2] * 100000 / margin.w);
getTag(name + ".bottom").setIntValue(padding[3] * 100000 / margin.h);
opt.renderTag(name + ".left").setIntValue(padding[0] * 100000 / margin.w);
opt.renderTag(name + ".top").setIntValue(padding[1] * 100000 / margin.h);
opt.renderTag(name + ".right").setIntValue(padding[2] * 100000 / margin.w);
opt.renderTag(name + ".bottom").setIntValue(padding[3] * 100000 / margin.h);
dragDir = null;
dragDown = null;
@@ -239,11 +232,10 @@ public class GuiPanelSettings extends GuiScreenWidget {
public GuiPanelSettings(Option opt) {
super(176, 198);
this.parentGui = (GuiOptionList) Minecraft.getMinecraft().currentScreen;
this.opt = opt;
boolean world = parentGui.worldConfig();
bookmarksPanel = new PanelPlaceholder(opt, opt.name + ".bookmarks", world);
itemsPanel = new PanelPlaceholder(opt, opt.name + ".items", world);
bookmarksPanel = new PanelPlaceholder(opt, opt.name + ".bookmarks");
itemsPanel = new PanelPlaceholder(opt, opt.name + ".items");
}
@Override
@@ -255,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(parentGui);
Minecraft.getMinecraft().displayGuiScreen(opt.slot.getGui());
return;
}
@@ -17,6 +17,7 @@ import codechicken.nei.recipe.GuiRecipeTab;
import codechicken.nei.recipe.GuiUsageRecipe;
import codechicken.nei.recipe.HandlerInfo;
import codechicken.nei.recipe.IRecipeHandler;
import codechicken.nei.recipe.TemplateRecipeHandler;
import codechicken.nei.util.NBTJson;
public class HandlerDumper extends DataDumper {
@@ -36,7 +37,10 @@ public class HandlerDumper extends DataDumper {
LinkedList<String[]> list = new LinkedList<>();
for (IRecipeHandler handler : GuiUsageRecipe.usagehandlers) {
final String handlerName = handler.getHandlerId();
final String handlerId = Objects.firstNonNull(handler.getOverlayIdentifier(), "null");
final String handlerId = Objects.firstNonNull(
handler instanceof TemplateRecipeHandler ? ((TemplateRecipeHandler) handler).getOverlayIdentifier()
: null,
"null");
HandlerInfo info = GuiRecipeTab.getHandlerInfo(handlerName, handlerId);
list.add(
@@ -99,12 +99,10 @@ public class IMCHandler {
NEIClientConfig.logger.info("Error setting handler dimensions for {}", handler);
}
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);
// true if not set to false
info.setUseCustomScroll(tag.hasKey("useCustomScroll") && tag.getBoolean("useCustomScroll"));
info.setShowFavoritesButton(!tag.hasKey("showFavoritesButton") || tag.getBoolean("showFavoritesButton"));
info.setShowOverlayButton(!tag.hasKey("showOverlayButton") || tag.getBoolean("showOverlayButton"));
info.setShowBadge(tag.hasKey("showBadge") && tag.getBoolean("showBadge"));
GuiRecipeTab.handlerAdderFromIMC.remove(handler);
GuiRecipeTab.handlerAdderFromIMC.put(handler, info);
@@ -5,7 +5,6 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.item.Item;
@@ -24,11 +23,7 @@ import codechicken.nei.guihook.GuiContainerManager;
public class ItemPanelDumper extends DataDumper {
public static final int CSV = 0;
public static final int NBT = 1;
public static final int JSON = 2;
public static final int PNG = 3;
private static final Minecraft mc = Minecraft.getMinecraft();
private static final int[] resolutions = new int[] { 16, 32, 48, 64, 128, 256 };
public ItemPanelDumper(String name) {
super(name);
@@ -59,29 +54,19 @@ public class ItemPanelDumper extends DataDumper {
public int getRes() {
int i = renderTag(name + ".res").getIntValue(0);
int size = 16 << i;
if (size >= getSmallerScreenAxisSize() || i < 0) {
getTag(name + ".res").setIntValue(0);
size = 16;
}
return size;
}
private int getSmallerScreenAxisSize() {
int width = mc.displayWidth;
int height = mc.displayHeight;
return Math.min(width, height);
if (i >= resolutions.length || i < 0) renderTag().setIntValue(i = 0);
return resolutions[i];
}
public Rectangle4i resButtonSize() {
int width = 60;
int width = 50;
return new Rectangle4i(modeButtonSize().x - width - 6, 0, width, 20);
}
@Override
public void draw(int mousex, int mousey, float frame) {
super.draw(mousex, mousey, frame);
if (getMode() == PNG) {
if (getMode() == 3) {
int res = getRes();
drawButton(mousex, mousey, resButtonSize(), res + "x" + res);
}
@@ -89,35 +74,23 @@ public class ItemPanelDumper extends DataDumper {
@Override
public void mouseClicked(int mousex, int mousey, int button) {
if (getMode() != PNG) {
super.mouseClicked(mousex, mousey, button);
return;
}
if (resButtonSize().contains(mousex, mousey)) {
if (getMode() == 3 && resButtonSize().contains(mousex, mousey)) {
NEIClientUtils.playClickSound();
int current = renderTag(name + ".res").getIntValue(0);
int next;
// 31 - numberOfLeadingZeros(x) = floor(log2(x))
int max = 31 - Integer.numberOfLeadingZeros(getSmallerScreenAxisSize()) - 3;
if (button == 1) { // Right click to cycle backward
next = (current - 1 + max) % max;
} else { // Left click to cycle forward
next = (current + 1) % max;
}
getTag(name + ".res").setIntValue(next);
} else if (!dumpButtonSize().contains(mousex, mousey) || acknowledgedItemSizeWarning()) {
super.mouseClicked(mousex, mousey, button);
}
getTag(name + ".res").setIntValue((renderTag(name + ".res").getIntValue(0) + 1) % resolutions.length);
} else super.mouseClicked(mousex, mousey, button);
}
@Override
public String getFileExtension() {
return switch (getMode()) {
case CSV -> ".csv";
case NBT -> ".nbt";
case JSON -> ".json";
default -> null;
};
switch (getMode()) {
case 0:
return ".csv";
case 1:
return ".nbt";
case 2:
return ".json";
}
return null;
}
@Override
@@ -132,29 +105,15 @@ public class ItemPanelDumper extends DataDumper {
@Override
public void dumpFile() {
if (getMode() == PNG && acknowledgedItemSizeWarning())
mc.displayGuiScreen(new GuiItemIconDumper(this, getRes()));
if (getMode() == 3) Minecraft.getMinecraft().displayGuiScreen(new GuiItemIconDumper(this, getRes()));
else super.dumpFile();
}
private boolean acknowledgedItemSizeWarning() {
return !showItemSizeWarning() || NEIClientUtils.shiftKey();
}
private boolean showItemSizeWarning() {
int res = getRes();
// More than 4 items at 2048x2048, 16 items at 1024x1024, 64 at 512x512, etc.
int WARNING_SIZE = 16_777_216;
return ItemPanels.itemPanel.getItems().size() * res * res > WARNING_SIZE;
}
@Override
public void dumpTo(File file) throws IOException {
switch (getMode()) {
case CSV -> super.dumpTo(file);
case NBT -> dumpNBT(file);
default -> dumpJson(file);
}
if (getMode() == 0) super.dumpTo(file);
else if (getMode() == 1) dumpNBT(file);
else dumpJson(file);
}
public void dumpNBT(File file) throws IOException {
@@ -182,22 +141,4 @@ public class ItemPanelDumper extends DataDumper {
public int modeCount() {
return 4;
}
@Override
public List<String> handleTooltip(int mousex, int mousey, List<String> currenttip) {
if (getMode() == PNG && dumpButtonSize().contains(mousex, mousey) && showItemSizeWarning()) {
int res = getRes();
currenttip.add(
NEIClientUtils.translate(
"options.tools.dump.itempanel.icon.warning.1",
ItemPanels.itemPanel.getItems().size(),
res,
res));
currenttip.add(
NEIClientUtils.translate(
"options.tools.dump.itempanel.icon.warning.2",
NEIClientUtils.translate("key.shift")));
}
return currenttip;
}
}
@@ -1,6 +1,5 @@
package codechicken.nei.config;
import java.lang.ref.WeakReference;
import java.util.List;
import net.minecraft.client.Minecraft;
@@ -18,11 +17,7 @@ public abstract class Option {
.playSound(PositionedSoundRecord.func_147674_a(new ResourceLocation("gui.button.press"), 1.0F));
}
private WeakReference<OptionScrollSlot> slotRef;
public OptionScrollSlot getSlot() {
return slotRef != null ? slotRef.get() : null;
}
public OptionScrollSlot slot;
public String namespace = null;
public final String name;
@@ -139,7 +134,7 @@ public abstract class Option {
* @return true if the gui is in world config mode
*/
public boolean worldConfig() {
return getSlot().getGui().worldConfig();
return slot.getGui().worldConfig();
}
/**
@@ -194,7 +189,7 @@ public abstract class Option {
}
public void onAdded(OptionScrollSlot slot) {
this.slotRef = new WeakReference<>(slot);
this.slot = 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, getSlot().slotWidth(), 20);
if (getPrefix() == null) return new Rectangle(0, 0, slot.slotWidth(), 20);
int width = Math.max(60, getStringWidth(getButtonText()) + 8);
return new Rectangle(getSlot().slotWidth() - width, 0, width, 20);
return new Rectangle(slot.slotWidth() - width, 0, width, 20);
}
public String getPrefix() {
@@ -0,0 +1,137 @@
package codechicken.nei.config;
import static codechicken.lib.gui.GuiDraw.drawRect;
import static codechicken.lib.gui.GuiDraw.drawStringC;
import java.awt.Rectangle;
import org.lwjgl.input.Keyboard;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.util.NEIKeyboardUtils;
public class OptionKeyBind extends OptionButton {
private boolean editing = false;
private boolean useHash = false;
private int keyboard = Keyboard.CHAR_NONE;
public OptionKeyBind(String name) {
this(name, false);
}
public OptionKeyBind(final String name, final boolean useHash) {
super("keys." + name);
this.useHash = useHash;
}
@Override
public void onMouseClicked(int mousex, int mousey, int button) {
if (editing) {
resetChanges();
}
}
@Override
public void keyTyped(char c, int keycode) {
if (!editing) {
return;
}
if (keycode == Keyboard.KEY_RETURN) {
applyChanges();
return;
}
keyboard = useHash ? NEIClientUtils.getKeyHash() : keycode;
if (keyboard != Keyboard.CHAR_NONE) {
applyChanges();
}
}
@Override
public boolean onClick(int btn) {
if (editing) {
return true;
} else if (btn == 0) {
editing = true;
return true;
} else if (btn == 1) {
keyboard = Keyboard.CHAR_NONE;
applyChanges();
return true;
}
return false;
}
protected void applyChanges() {
setValue(keyboard);
resetChanges();
}
protected void resetChanges() {
editing = false;
keyboard = Keyboard.CHAR_NONE;
}
public boolean conflicted() {
final int keyboard = getValue();
if (keyboard <= 0) {
return false;
}
for (Option o : slot.options) {
if (o instanceof OptionKeyBind && o != this && ((OptionKeyBind) o).getValue() == keyboard) {
return true;
}
}
return false;
}
public void setValue(int keycode) {
getTag().setIntValue(keycode);
}
public int getValue() {
return renderTag().getIntValue();
}
@Override
public String getPrefix() {
return translateN(name);
}
@Override
public void drawButton(int mx, int my) {
if (editing) {
Rectangle b = buttonSize();
drawRect(b.x, b.y, b.width, b.height, -6250336);
drawRect(b.x + 1, b.y + 1, b.width - 2, b.height - 2, -16777216);
drawStringC(getButtonText(), b.x, b.y, b.width, b.height, getTextColour(mx, my));
} else {
super.drawButton(mx, my);
}
}
@Override
public String getButtonText() {
if (editing) {
return NEIKeyboardUtils.getHashName(NEIClientUtils.getMetaHash());
}
return NEIKeyboardUtils.getKeyName(Math.max(getValue(), 0));
}
@Override
public int getTextColour(int mousex, int mousey) {
return !editing && conflicted() ? 0xFFFF6666 : -1;
}
}
@@ -131,15 +131,13 @@ public class OptionList extends OptionButton {
/**
* Adds this option to a temporary slot and gui for internal setting manipulation.
*/
public GuiOptionList synthesizeEnvironment(boolean world) {
GuiOptionList gui = getGui(null, this, world);
gui.addWidgets();
return gui;
public void synthesizeEnvironment(boolean world) {
getGui(null, this, world).addWidgets();
}
@Override
public boolean onClick(int button) {
openGui(getSlot().getGui(), getSlot().getGui().worldConfig());
openGui(slot.getGui(), slot.getGui().worldConfig());
return true;
}
@@ -131,6 +131,6 @@ public abstract class OptionStringSet extends Option {
}
public int buttonX() {
return getSlot().slotWidth() - (24 * options.size() - 4);
return slot.slotWidth() - (24 * options.size() - 4);
}
}
@@ -53,7 +53,7 @@ public class OptionTextField extends Option {
}
protected int getMaxInputWidth() {
return getSlot().slotWidth();
return slot.slotWidth();
}
public boolean isEnabled() {
@@ -64,10 +64,9 @@ 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(), getSlot().slotWidth() - GuiDraw.getStringWidth(getPrefix())) - 16);
textField.x = getSlot().slotWidth() - textField.w;
textField.w = Math
.max(60, Math.min(getMaxInputWidth(), slot.slotWidth() - GuiDraw.getStringWidth(getPrefix())) - 16);
textField.x = slot.slotWidth() - textField.w;
textField.draw(mousex, mousey);
}
@@ -5,7 +5,6 @@ import static codechicken.lib.gui.GuiDraw.drawStringC;
import org.lwjgl.opengl.GL11;
import codechicken.nei.Button;
import codechicken.nei.ColorUtils;
import codechicken.nei.LayoutManager;
public abstract class CheckboxButton extends Button {
@@ -39,8 +38,7 @@ public abstract class CheckboxButton extends Button {
tex = 1;
}
int colour = tex == 2 ? ColorUtils.buttonLabelHover.getColor()
: tex == 0 ? ColorUtils.buttonLabelDisabled.getColor() : ColorUtils.buttonLabelNormal.getColor();
int colour = tex == 2 ? 0xffffa0 : tex == 0 ? 0x601010 : 0xe0e0e0;
LayoutManager.drawButtonBackground(x, y, w, h, true, isChecked() ? 0 : tex);
drawStringC(getRenderLabel(), x + w / 2, y + (h - 8) / 2, colour);
}
@@ -17,14 +17,12 @@ import codechicken.nei.LayoutManager;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.PresetsList;
import codechicken.nei.PresetsList.Preset;
import codechicken.nei.config.GuiOptionList;
import codechicken.nei.config.GuiOptionPane;
import codechicken.nei.config.Option;
public class GuiPresetList extends GuiOptionPane {
private final Option opt;
private final GuiOptionList parentGui;
protected static final int SLOT_HEIGHT = 24;
protected static final int BUTTON_HEIGHT = 20;
protected GuiCCButton createButton;
@@ -33,7 +31,6 @@ public class GuiPresetList extends GuiOptionPane {
public GuiPresetList(Option opt) {
this.opt = opt;
this.parentGui = (GuiOptionList) Minecraft.getMinecraft().currentScreen;
this.createButton = new GuiCCButton(0, 2, 0, 16, NEIClientUtils.translate("presets.new"))
.setActionCommand("create");
this.toggleButton = new GuiCCButton(0, 2, 0, 16, NEIClientUtils.translate("presets.toggle"))
@@ -256,7 +253,7 @@ public class GuiPresetList extends GuiOptionPane {
@Override
public GuiScreen getParentScreen() {
return parentGui;
return opt.slot.getGui();
}
@Override
@@ -21,7 +21,7 @@ import codechicken.nei.ItemList.AnyMultiItemFilter;
import codechicken.nei.ItemList.NegatedItemFilter;
import codechicken.nei.ItemsGrid;
import codechicken.nei.ItemsGrid.ItemsGridSlot;
import codechicken.nei.KeyManager;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.PresetsList;
import codechicken.nei.PresetsList.Preset;
@@ -81,15 +81,15 @@ public class RightPanel extends GuiWidget {
@Override
public void lastKeyTyped(int keyID, char keyChar) {
if (!focused() && KeyManager.isHashDown("gui.search")) {
if (!focused() && NEIClientConfig.isKeyHashDown("gui.search")) {
setFocus(true);
}
if (focused() && KeyManager.isKeyDown("gui.getprevioussearch")) {
if (focused() && NEIClientConfig.isKeyHashDown("gui.getprevioussearch")) {
handleNavigateHistory(TextHistory.Direction.PREVIOUS);
}
if (focused() && KeyManager.isKeyDown("gui.getnextsearch")) {
if (focused() && NEIClientConfig.isKeyHashDown("gui.getnextsearch")) {
handleNavigateHistory(TextHistory.Direction.NEXT);
}
}
@@ -46,7 +46,6 @@ import org.lwjgl.opengl.GL12;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.ItemList;
import codechicken.nei.ItemStackSet;
import codechicken.nei.KeyManager;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.NEIModContainer;
@@ -625,7 +624,7 @@ public class GuiContainerManager {
tooltip.set(0, tooltip.get(0) + GuiDraw.TOOLTIP_LINESPACE);
}
} else if (!tooltip.isEmpty() && !tooltip.get(0).startsWith(GuiDraw.TOOLTIP_HANDLER)) {
} else if (!tooltip.isEmpty()) {
tooltip.set(0, tooltip.get(0) + GuiDraw.TOOLTIP_LINESPACE);
}
@@ -763,7 +762,7 @@ public class GuiContainerManager {
"inventory.tooltip.page",
tooltipPage + 1,
maxTooltipPage,
KeyManager.getKeyName("gui.next_tooltip"));
NEIClientConfig.getKeyName("gui.next_tooltip"));
if (lastLine.startsWith(GuiDraw.TOOLTIP_HANDLER)) {
currentTooltip.add(lastLine);
@@ -15,7 +15,7 @@ public class AcceptsFollowingTooltipLineHandler extends ItemsTooltipLineHandler
public Object tooltipGUID;
protected AcceptsFollowingTooltipLineHandler(Object tooltipGUID, List<ItemStack> items, ItemStack activeStack,
public AcceptsFollowingTooltipLineHandler(Object tooltipGUID, List<ItemStack> items, ItemStack activeStack,
int maxRows) {
super(NEIClientUtils.translate("recipe.accepts"), items, false, maxRows);
this.tooltipGUID = tooltipGUID;
@@ -32,46 +32,43 @@ public class AutoCraftingManager {
StackInfo.pauseItemDamageSound(true);
try {
do {
changed = false;
do {
changed = false;
RecipeChainIterator iterator = new RecipeChainIterator(math, initialItems);
iterator.updateInventory(getInventoryItems(guiContainer));
RecipeChainIterator iterator = new RecipeChainIterator(math, initialItems);
iterator.updateInventory(getInventoryItems(guiContainer));
while (iterator.hasNext() && !interrupted(guiContainer)) {
final Map<RecipeId, Long> recipes = iterator.next();
boolean craft = false;
while (iterator.hasNext() && !interrupted(guiContainer)) {
final Map<RecipeId, Long> recipes = iterator.next();
boolean craft = false;
for (Map.Entry<RecipeId, Long> entry : recipes.entrySet()) {
final RecipeHandlerRef handler = RecipeHandlerRef.of(entry.getKey());
for (Map.Entry<RecipeId, Long> entry : recipes.entrySet()) {
final RecipeHandlerRef handler = RecipeHandlerRef.of(entry.getKey());
if (handler != null && handler.canCraft(guiContainer)) {
long multiplier = entry.getValue();
if (handler != null && handler.canCraft(guiContainer)) {
long multiplier = entry.getValue();
while (multiplier > 0 && !interrupted(guiContainer)
&& handler.craft(guiContainer, (int) Math.min(64, multiplier))) {
multiplier -= 64;
}
craft = craft || multiplier != entry.getValue();
while (multiplier > 0 && !interrupted(guiContainer)
&& handler.craft(guiContainer, (int) Math.min(64, multiplier))) {
multiplier -= 64;
}
if (interrupted(guiContainer)) break;
craft = multiplier != entry.getValue();
}
if (craft) {
changed = true;
processed = true;
iterator.updateInventory(getInventoryItems(guiContainer));
}
if (interrupted(guiContainer)) break;
}
} while (changed && !interrupted(guiContainer));
if (craft) {
changed = true;
processed = true;
iterator.updateInventory(getInventoryItems(guiContainer));
}
}
} finally {
StackInfo.pauseItemDamageSound(false);
}
} while (changed && !interrupted(guiContainer));
StackInfo.pauseItemDamageSound(false);
if (processed && !changed && !interrupted(guiContainer)) {
NEIClientUtils.playClickSound();
@@ -94,7 +91,7 @@ public class AutoCraftingManager {
for (BookmarkItem item : math.initialItems) {
final long invStackSize = inventory.getOrDefault(item.itemStack, 0L);
final long amount = Math.max(0, item.getAmount() - invStackSize * item.fluidCellAmount);
final long amount = Math.max(0, item.amount - invStackSize * item.fluidCellAmount);
if (amount > 0) {
initialItems.add(item.copyWithAmount(amount));
}
@@ -1,89 +0,0 @@
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.ColorUtils;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.NEIClientUtils.Alignment;
public class Badge {
protected final String text;
protected final List<String> tooltip;
protected int badgeTextColor;
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 = ColorUtils.recipeBadge.getColor();
}
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;
}
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));
}
}
@@ -64,7 +64,7 @@ public class BookmarkRecipeId {
return false;
}
short idx = 0;
Short idx = 0;
for (PositionedStack pStack : stacks) {
final NBTTagCompound tagCompoundA = StackInfo
@@ -123,7 +123,8 @@ public class BookmarkRecipeId {
return true;
}
if (anObject instanceof BookmarkRecipeId anRecipeId) {
if (anObject instanceof BookmarkRecipeId) {
final BookmarkRecipeId anRecipeId = (BookmarkRecipeId) anObject;
if (!handlerName.equals(anRecipeId.handlerName)) {
return false;
@@ -13,7 +13,7 @@ public class BrewingOverlayHandler extends DefaultOverlayHandler {
public Slot[][] mapIngredSlots(GuiContainer gui, List<PositionedStack> ingredients) {
Slot[][] map = super.mapIngredSlots(gui, ingredients);
Slot[] potSlots = new Slot[3];
for (int i = 0; i < 3; i++) potSlots[i] = gui.inventorySlots.inventorySlots.get(i);
for (int i = 0; i < 3; i++) potSlots[i] = (Slot) gui.inventorySlots.inventorySlots.get(i);
map[1] = potSlots;
return map;
}
@@ -1,4 +1,4 @@
package codechicken.nei.util;
package codechicken.nei.recipe;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
@@ -8,7 +8,7 @@ import net.minecraft.item.ItemStack;
import codechicken.nei.PositionedStack;
import codechicken.nei.api.ShortcutInputHandler;
public class EmptyContainer extends Container {
public class ContainerRecipe extends Container {
private ItemStack activeStack = null;
@@ -36,7 +36,6 @@ public class DefaultOverlayHandler implements IOverlayHandler {
public int numSlots;
public int recipeAmount;
public boolean isContainerItem = false;
public long damagePerContainerCraft;
}
public static class IngredientDistribution {
@@ -124,11 +123,6 @@ public class DefaultOverlayHandler implements IOverlayHandler {
if (craftingSlot.getHasStack() && craftingSlot.canTakeStack(firstGui.mc.thePlayer)) {
FastTransferManager.clickSlot(firstGui, craftingSlot.slotNumber, 0, 1);
if (craftingSlot.getHasStack()) {
break;
}
craft = true;
}
@@ -203,7 +197,7 @@ public class DefaultOverlayHandler implements IOverlayHandler {
return ingredSlots;
}
protected void moveIngredients(GuiContainer gui, List<IngredientDistribution> assignedIngredients, int multiplier) {
private void moveIngredients(GuiContainer gui, List<IngredientDistribution> assignedIngredients, int multiplier) {
final Slot craftingSlot = getCraftingResultSlot(gui);
for (Slot slot : gui.inventorySlots.inventorySlots) {
@@ -216,7 +210,7 @@ public class DefaultOverlayHandler implements IOverlayHandler {
for (IngredientDistribution distrib : assignedIngredients) {
if (distrib.slots.length == 0 || !slot.getHasStack() || !canStack(distrib.permutation, stack)) continue;
int transferCap = Math.min(slotTransferCap, Math.max(multiplier * distrib.permutation.stackSize, 1));
int transferCap = Math.min(slotTransferCap, multiplier * distrib.permutation.stackSize);
int stackSize = slot.getStack().stackSize;
boolean pickup = false;
@@ -255,7 +249,7 @@ public class DefaultOverlayHandler implements IOverlayHandler {
}
}
protected int calculateRecipeQuantity(List<IngredientDistribution> assignedIngredients) {
private int calculateRecipeQuantity(List<IngredientDistribution> assignedIngredients) {
int quantity = Integer.MAX_VALUE;
for (IngredientDistribution distrib : assignedIngredients) {
@@ -265,11 +259,6 @@ public class DefaultOverlayHandler implements IOverlayHandler {
final int maxStackSize = istack.stack.getMaxStackSize();
if (maxStackSize == 1 && istack.isContainerItem) {
if (istack.damagePerContainerCraft > 0) {
quantity = (int) Math.min(quantity, istack.damagePerContainerCraft);
}
// If non-stackable, fill up as much as possible of the other ingredients
continue;
}
@@ -286,7 +275,7 @@ public class DefaultOverlayHandler implements IOverlayHandler {
return quantity;
}
protected Slot[][] assignIngredSlots(GuiContainer gui, List<PositionedStack> ingredients,
private Slot[][] assignIngredSlots(GuiContainer gui, List<PositionedStack> ingredients,
List<IngredientDistribution> assignedIngredients) {
Slot[][] recipeSlots = mapIngredSlots(gui, ingredients); // setup the slot map
@@ -331,7 +320,7 @@ public class DefaultOverlayHandler implements IOverlayHandler {
return recipeSlots;
}
protected List<IngredientDistribution> assignIngredients(List<PositionedStack> ingredients,
private List<IngredientDistribution> assignIngredients(List<PositionedStack> ingredients,
List<DistributedIngred> ingredStacks) {
ArrayList<IngredientDistribution> assignedIngredients = new ArrayList<>();
for (PositionedStack posstack : ingredients) // assign what we need and have
@@ -369,7 +358,7 @@ public class DefaultOverlayHandler implements IOverlayHandler {
return assignedIngredients;
}
protected void findInventoryQuantities(GuiContainer gui, List<DistributedIngred> ingredStacks) {
private void findInventoryQuantities(GuiContainer gui, List<DistributedIngred> ingredStacks) {
for (Slot slot : gui.inventorySlots.inventorySlots) /* work out how much we have to go round */ {
if (slot.getHasStack() && canMoveFrom(slot, gui)) {
final ItemStack pstack = slot.getStack();
@@ -383,14 +372,7 @@ public class DefaultOverlayHandler implements IOverlayHandler {
final NBTTagCompound tagCompound = pstack.getTagCompound();
if (tagCompound != null && tagCompound.hasKey("GT.ToolStats")) {
final NBTTagCompound toolStats = tagCompound.getCompoundTag("GT.ToolStats");
final long damagePerContainerCraft = getGTToolDamagePerContainerCraft(pstack);
final long maxDamage = toolStats.getLong("MaxDamage");
final long damage = toolStats.getLong("Damage");
istack.isContainerItem = true;
istack.damagePerContainerCraft = (maxDamage - damage + damagePerContainerCraft - 1)
/ damagePerContainerCraft;
} else {
final boolean isPausedItemDamageSound = StackInfo.isPausedItemDamageSound();
StackInfo.pauseItemDamageSound(true);
@@ -408,20 +390,7 @@ public class DefaultOverlayHandler implements IOverlayHandler {
}
}
private int getGTToolDamagePerContainerCraft(ItemStack aStack) {
try {
final Object toolStats = aStack.getItem().getClass().getMethod("getToolStats", ItemStack.class)
.invoke(aStack.getItem(), aStack);
return (int) toolStats.getClass().getMethod("getToolDamagePerContainerCraft").invoke(toolStats);
} catch (Throwable th) {
th.printStackTrace();
}
return 0;
}
protected List<DistributedIngred> getPermutationIngredients(List<PositionedStack> ingredients) {
private List<DistributedIngred> getPermutationIngredients(List<PositionedStack> ingredients) {
ArrayList<DistributedIngred> ingredStacks = new ArrayList<>();
for (PositionedStack posstack : ingredients) /* work out what we need */ {
for (ItemStack pstack : posstack.items) {
@@ -53,7 +53,8 @@ public class FuelRecipeHandler extends FurnaceRecipeHandler {
private void loadAllSmelting() {
// Note: Not safe as written for parallelStream
final Map<ItemStack, ItemStack> smeltingRecipes = FurnaceRecipes.smelting().getSmeltingList();
final Map<ItemStack, ItemStack> smeltingRecipes = (Map<ItemStack, ItemStack>) FurnaceRecipes.smelting()
.getSmeltingList();
smeltingRecipes.entrySet().stream().map(recipe -> new SmeltingPair(recipe.getKey(), recipe.getValue()))
.collect(Collectors.toCollection(() -> mfurnace));
}
@@ -84,7 +84,7 @@ public class FurnaceRecipeHandler extends TemplateRecipeHandler {
public void loadCraftingRecipes(String outputId, Object... results) {
if (outputId.equals("smelting") && getClass() == FurnaceRecipeHandler.class) { // don't want subclasses getting
// a hold of this
Map<ItemStack, ItemStack> recipes = FurnaceRecipes.smelting().getSmeltingList();
Map<ItemStack, ItemStack> recipes = (Map<ItemStack, ItemStack>) FurnaceRecipes.smelting().getSmeltingList();
for (Entry<ItemStack, ItemStack> recipe : recipes.entrySet())
arecipes.add(new SmeltingPair(recipe.getKey(), recipe.getValue()));
} else super.loadCraftingRecipes(outputId, results);
@@ -92,7 +92,7 @@ public class FurnaceRecipeHandler extends TemplateRecipeHandler {
@Override
public void loadCraftingRecipes(ItemStack result) {
Map<ItemStack, ItemStack> recipes = FurnaceRecipes.smelting().getSmeltingList();
Map<ItemStack, ItemStack> recipes = (Map<ItemStack, ItemStack>) FurnaceRecipes.smelting().getSmeltingList();
for (Entry<ItemStack, ItemStack> recipe : recipes.entrySet())
if (NEIServerUtils.areStacksSameType(recipe.getValue(), result))
arecipes.add(new SmeltingPair(recipe.getKey(), recipe.getValue()));
@@ -108,7 +108,7 @@ public class FurnaceRecipeHandler extends TemplateRecipeHandler {
@Override
public void loadUsageRecipes(ItemStack ingredient) {
Map<ItemStack, ItemStack> recipes = FurnaceRecipes.smelting().getSmeltingList();
Map<ItemStack, ItemStack> recipes = (Map<ItemStack, ItemStack>) FurnaceRecipes.smelting().getSmeltingList();
for (Entry<ItemStack, ItemStack> recipe : recipes.entrySet())
if (NEIServerUtils.areStacksSameTypeCrafting(recipe.getKey(), ingredient)) {
SmeltingPair arecipe = new SmeltingPair(recipe.getKey(), recipe.getValue());
@@ -21,6 +21,7 @@ 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> {
@@ -82,8 +83,8 @@ public class GuiCraftingRecipe extends GuiRecipe<ICraftingHandler> {
} else if ("recipeId".equals(outputId)) {
ItemStack stack = (ItemStack) results[0];
RecipeId recipeId = (RecipeId) results[1];
craftinghandlers = filterByHandlerName(craftinghandlers, recipeId.getHandlerName());
serialCraftingHandlers = filterByHandlerName(serialCraftingHandlers, recipeId.getHandlerName());
craftinghandlers = filterByHandlerName(craftinghandlers, recipeId.getHandleName());
serialCraftingHandlers = filterByHandlerName(serialCraftingHandlers, recipeId.getHandleName());
recipeHandlerFunction = h -> h.getRecipeHandler("item", stack);
} else {
recipeHandlerFunction = h -> h.getRecipeHandler(outputId, results);
@@ -102,7 +103,18 @@ public class GuiCraftingRecipe extends GuiRecipe<ICraftingHandler> {
private static ICraftingHandler buildAllRecipesHandler(ICraftingHandler handler) {
if (handler instanceof TemplateRecipeHandler templateHandler) {
return templateHandler.getAllRecipeHandler();
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 handler.getRecipeHandler("all");
}
@@ -119,7 +131,7 @@ public class GuiCraftingRecipe extends GuiRecipe<ICraftingHandler> {
public static RecipeId getRecipeId(GuiScreen gui, ItemStack stackover) {
if (gui instanceof GuiRecipe<?>guiRecipe) {
if (gui instanceof GuiRecipe guiRecipe) {
final Recipe focusedRecipe = guiRecipe.getFocusedRecipe();
if (focusedRecipe != null) {
@@ -19,7 +19,6 @@ import codechicken.nei.FavoriteRecipes;
import codechicken.nei.Image;
import codechicken.nei.ItemPanels;
import codechicken.nei.ItemStackSet;
import codechicken.nei.KeyManager;
import codechicken.nei.LayoutManager;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
@@ -123,7 +122,7 @@ public class GuiFavoriteButton extends GuiRecipeButton {
public void lastKeyTyped(char keyChar, int keyID) {
if (KeyManager.isKeyDown("bookmark.add") && NEIClientUtils.shiftKey()) {
if (NEIClientConfig.isKeyHashDown("gui.bookmark") && NEIClientUtils.shiftKey()) {
saveRecipeInBookmark();
}
@@ -132,7 +131,7 @@ public class GuiFavoriteButton extends GuiRecipeButton {
@Override
public Map<String, String> handleHotkeys(int mousex, int mousey, Map<String, String> hotkeys) {
hotkeys.put(
KeyManager.getKeyName("bookmark.add", NEIClientUtils.SHIFT_HASH),
NEIClientConfig.getKeyName("gui.bookmark", NEIClientUtils.SHIFT_HASH),
translate("recipe.favorite.bookmark_recipe"));
if (this.recipe.getResults().size() > 1) {
@@ -155,16 +154,11 @@ public class GuiFavoriteButton extends GuiRecipeButton {
if (this.selectedResult == null) return;
NEIClientUtils.gl2DRenderContext(
() -> GuiDraw.drawRect(
this.selectedResult.relx,
this.selectedResult.rely,
this.selectedResult.width,
this.selectedResult.height,
0x66333333));
() -> GuiDraw.drawRect(this.selectedResult.relx, this.selectedResult.rely, 16, 16, 0x66333333));
final Image icon = isFavorite() ? ICON_STATE_ON : ICON_STATE_OFF;
final int iconX = this.selectedResult.relx + (this.selectedResult.width - icon.width) / 2;
final int iconY = this.selectedResult.rely + (this.selectedResult.height + 2 - icon.height) / 2;
final int iconX = this.selectedResult.relx + (16 - icon.width) / 2;
final int iconY = this.selectedResult.rely + (18 - icon.height) / 2;
LayoutManager.drawIcon(iconX, iconY, icon);
}
@@ -235,7 +229,7 @@ public class GuiFavoriteButton extends GuiRecipeButton {
}
}
if (recipeId != null && FavoriteRecipes.FAVORITE_ITEM.contains(recipeId.getHandlerName())) {
if (recipeId != null && FavoriteRecipes.FAVORITE_ITEM.contains(recipeId.getHandleName())) {
items.add(stack);
} else {
Recipe recipe = Recipe.of(recipeId);
@@ -15,14 +15,11 @@ import org.lwjgl.opengl.GL11;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.ItemPanels;
import codechicken.nei.ItemsTooltipLineHandler;
import codechicken.nei.KeyManager;
import codechicken.nei.LayoutManager;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
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.util.NEIMouseUtils;
@@ -99,18 +96,13 @@ public class GuiOverlayButton extends GuiRecipeButton {
super(handlerRef, x, y, handlerRef.recipeIndex + BUTTON_ID_SHIFT, "+");
this.firstGui = firstGui != null && firstGui.inventorySlots != null ? firstGui : null;
IOverlayHandler overlayHandler = null;
if (this.firstGui != null) {
overlayHandler = this.handlerRef.getOverlayHandler(this.firstGui);
this.canUseOverlayRenderer = this.handlerRef.getRecipeOverlayRenderer(this.firstGui) != null;
this.canFillCraftingGrid = this.handlerRef.canFillCraftingGrid(this.firstGui);
this.hasOverlay = this.canUseOverlayRenderer || overlayHandler != null;
this.hasOverlay = this.canUseOverlayRenderer || this.handlerRef.getOverlayHandler(this.firstGui) != null;
}
setRequireShiftForOverlayRecipe(
overlayHandler != null ? overlayHandler.requireShiftForOverlayRecipe()
: NEIClientConfig.requireShiftForOverlayRecipe());
setRequireShiftForOverlayRecipe(NEIClientConfig.requireShiftForOverlayRecipe());
ingredientsOverlay();
}
@@ -165,17 +157,13 @@ public class GuiOverlayButton extends GuiRecipeButton {
}
hotkeys.put(
KeyManager.getKeyName("bookmark.add", NEIClientUtils.SHIFT_HASH),
NEIClientConfig.getKeyName("gui.bookmark", NEIClientUtils.SHIFT_HASH),
NEIClientUtils.translate("recipe.overlay.bookmarkRecipe"));
hotkeys.put(
KeyManager.getKeyName("bookmark.add", NEIClientUtils.SHIFT_HASH + NEIClientUtils.CTRL_HASH),
NEIClientConfig.getKeyName("gui.bookmark", NEIClientUtils.SHIFT_HASH + NEIClientUtils.CTRL_HASH),
NEIClientUtils.translate("recipe.overlay.bookmarkRecipeAndCount"));
hotkeys.put(
KeyManager.getKeyName("bookmark.chat_link", NEIClientUtils.SHIFT_HASH + NEIClientUtils.CTRL_HASH),
NEIClientUtils.translate("recipe.overlay.sendRecipeToChat"));
return hotkeys;
}
@@ -331,13 +319,9 @@ public class GuiOverlayButton extends GuiRecipeButton {
@Override
public void lastKeyTyped(char keyChar, int keyID) {
if (KeyManager.isKeyDown("bookmark.add") && NEIClientUtils.shiftKey()) {
if (NEIClientConfig.isKeyHashDown("gui.bookmark") && NEIClientUtils.shiftKey()) {
saveRecipeInBookmark();
}
if (KeyManager.isKeyDown("bookmark.chat_link") && NEIClientUtils.controlKey() && NEIClientUtils.shiftKey()) {
sendRecipeChatLink();
}
}
public void saveRecipeInBookmark() {
@@ -352,7 +336,4 @@ public class GuiOverlayButton extends GuiRecipeButton {
}
}
private void sendRecipeChatLink() {
NEIClientUtils.sendChatItemLink(BookmarkPayload.of(getRecipe()).toNBT());
}
}
@@ -17,6 +17,7 @@ import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
@@ -24,9 +25,7 @@ import org.lwjgl.opengl.GL11;
import codechicken.lib.gui.GuiDraw;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.Button;
import codechicken.nei.ColorUtils;
import codechicken.nei.GuiNEIButton;
import codechicken.nei.KeyManager;
import codechicken.nei.NEICPH;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
@@ -34,8 +33,6 @@ import codechicken.nei.PositionedStack;
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.VisiblityData;
import codechicken.nei.Widget;
import codechicken.nei.api.IGuiContainerOverlay;
@@ -56,8 +53,6 @@ import codechicken.nei.scroll.ScrollBar;
import codechicken.nei.scroll.ScrollBar.OverflowType;
import codechicken.nei.scroll.ScrollBar.ScrollPlace;
import codechicken.nei.scroll.ScrollContainer;
import codechicken.nei.search.SearchExpressionUtils;
import codechicken.nei.util.EmptyContainer;
import codechicken.nei.util.SlotInaccessible;
public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer implements IGuiContainerOverlay,
@@ -97,9 +92,6 @@ 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;
@@ -176,59 +168,6 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
return true;
}
@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 + ">"));
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 + "\""));
} 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));
}
};
/**
@@ -238,7 +177,7 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
private boolean isHeightHackApplied = false;
protected GuiRecipe(GuiScreen prevgui) {
super(new EmptyContainer());
super(new ContainerRecipe());
this.recipeTabs = new GuiRecipeTabs() {
@Override
@@ -248,7 +187,7 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
};
this.recipeCatalyst = new GuiRecipeCatalyst();
this.slotcontainer = (EmptyContainer) this.inventorySlots;
this.slotcontainer = (ContainerRecipe) this.inventorySlots;
this.prevGui = prevgui;
this.firstGuiGeneral = prevgui;
@@ -369,7 +308,7 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
@Override
public Widget getWidgetUnderMouse(int mousex, int mousey) {
if (handlerInfo.isAllowOverflowY() && !this.widgets.isEmpty()) {
if (handlerInfo.getUseCustomScroll() && !this.widgets.isEmpty()) {
return this.widgets.get(0);
}
@@ -407,7 +346,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 - 4;
this.container.h = this.ySize - 32 - 5;
GuiRecipe.toggleSearch.icon = new DrawableBuilder("nei:textures/nei_sprites.png", 0, 76, 10, 10).build();
GuiRecipe.toggleSearch.w = GuiRecipe.toggleSearch.h = 12;
@@ -419,18 +358,8 @@ 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.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;
@@ -443,19 +372,9 @@ 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.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()) {
if (this.handlerInfo.getUseCustomScroll()) {
this.container.setVerticalScroll(null);
} else if (this.container.w == this.xSize - 6) {
this.container.setVerticalScroll(VERTICAL_SCROLLBAR);
@@ -497,7 +416,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);
updateContainerSize();
this.container.w = Math.max(this.xSize - 6, this.handlerInfo.getWidth());
this.handlerPages = new RecipePageManager(this.handler, this.handlerInfo, this.container);
this.prevpage.enabled = this.nextpage.enabled = this.handlerPages.getNumPages() > 1;
this.lastPage = -1;
@@ -507,21 +426,9 @@ 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;
@@ -533,7 +440,7 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
final H localHandler = this.currenthandlers.get(j);
final HandlerInfo localHandlerInfo = GuiRecipeTab.getHandlerInfo(localHandler);
if (localHandlerInfo.getHandlerName().equals(this.recipeId.getHandlerName())) {
if (localHandlerInfo.getHandlerName().equals(this.recipeId.getHandleName())) {
recipetype = j;
if (!this.recipeId.getIngredients().isEmpty()) {
@@ -583,7 +490,7 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
@Override
public Slot getSlotAtPosition(int mousex, int mousey) {
final Widget activeWidget = this.container.getWidgetUnderMouse(mousex, mousey);
final EmptyContainer slotcontainer = (EmptyContainer) inventorySlots;
final ContainerRecipe slotcontainer = (ContainerRecipe) inventorySlots;
slotcontainer.setActiveStack(null);
if (activeWidget instanceof NEIRecipeWidget recipeWidget) {
@@ -657,15 +564,15 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
if (i == mc.gameSettings.keyBindInventory.getKeyCode()) {
this.mc.displayGuiScreen(getFirstScreenGeneral());
NEICPH.sendRequestContainer();
} else if (KeyManager.isKeyDown("recipe.back")) {
} else if (NEIClientConfig.isKeyHashDown("gui.back")) {
this.mc.displayGuiScreen(this.prevGui);
} else if (KeyManager.isKeyDown("recipe.prev_machine")) {
} else if (NEIClientConfig.isKeyHashDown("gui.prev_machine")) {
prevType();
} else if (KeyManager.isKeyDown("recipe.next_machine")) {
} else if (NEIClientConfig.isKeyHashDown("gui.next_machine")) {
nextType();
} else if (KeyManager.isKeyDown("recipe.prev_recipe")) {
} else if (NEIClientConfig.isKeyHashDown("gui.prev_recipe")) {
prevPage();
} else if (KeyManager.isKeyDown("recipe.next_recipe")) {
} else if (NEIClientConfig.isKeyHashDown("gui.next_recipe")) {
nextPage();
}
}
@@ -764,7 +671,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() || this.typeArea.contains(mouse)) {
if (NEIClientUtils.shiftKey()) {
if (scroll < 0) {
nextType();
} else {
@@ -776,12 +683,7 @@ 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 (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 (new Rectangle(this.guiLeft, this.guiTop, this.xSize, this.ySize).contains(mouse)) {
if (scroll > 0) {
prevPage();
} else {
@@ -816,10 +718,6 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
this.recipeTabs.handleTooltip(mousex, mousey, currenttip);
if (this.handler != null && this.handler.searchingAvailable()) {
currenttip = GuiRecipe.toggleSearch.handleTooltip(mousex, mousey, currenttip);
}
if (currenttip.isEmpty() && isHandlerTitleHovered(mousex, mousey)) {
currenttip.add(NEIClientUtils.translate("recipe.tab.view_all.tooltip"));
}
@@ -886,10 +784,9 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
}
public void forceRefreshPage() {
final int currentPage = this.handlerPages.getCurrentPageIndex();
this.currenthandlers.sort(NEIClientConfig.HANDLER_COMPARATOR);
this.recipetype = this.currenthandlers.indexOf(this.handler.original);
final int currentPage = this.handlerPages.getCurrentPageIndex();
setRecipePage(this.recipetype);
this.handlerPages.changePage(currentPage);
@@ -927,26 +824,26 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
final int textMiddle = (BUTTON_WIDTH - this.fontRendererObj.FONT_HEIGHT) / 2;
drawRect(
this.typeArea.x,
this.typeArea.y,
this.typeArea.x + this.typeArea.width,
this.typeArea.y + this.typeArea.height,
this.prevtype.xPosition + BUTTON_WIDTH - 1,
this.prevtype.yPosition,
this.nexttype.xPosition,
this.prevtype.yPosition + BUTTON_HEIGHT,
0x30000000);
drawRect(
this.pageArea.x,
this.pageArea.y,
this.pageArea.x + this.pageArea.width,
this.pageArea.y + this.pageArea.height,
this.prevpage.xPosition + BUTTON_WIDTH - 1,
this.prevpage.yPosition,
this.nextpage.xPosition,
this.prevpage.yPosition + BUTTON_HEIGHT,
0x30000000);
final String handlerTitle = this.handler.original.getRecipeName().trim();
final int titleColor = getHandlerTitleColor(isHandlerTitleHovered(mouseX, mouseY));
final String titleColorCode = getHandlerTitleColorCode(isHandlerTitleHovered(mouseX, mouseY));
drawCenteredString(
this.fontRendererObj,
handlerTitle,
titleColorCode + handlerTitle + EnumChatFormatting.RESET,
this.guiLeft + this.xSize / 2,
this.typeArea.y + textMiddle,
titleColor);
this.prevtype.yPosition + textMiddle,
0xffffff);
if (this.handler.searchingAvailable()) {
GuiRecipe.toggleSearch.draw(mouseX, mouseY);
@@ -968,7 +865,7 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
this.fontRendererObj,
recipePage,
GuiRecipe.searchField.x + GuiRecipe.searchField.w + 22,
this.pageArea.y + textMiddle,
this.prevpage.yPosition + textMiddle,
0xffffff);
} else {
final String recipePage = NEIClientUtils.translate(
@@ -979,7 +876,7 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
this.fontRendererObj,
recipePage,
this.guiLeft + this.xSize / 2,
this.pageArea.y + textMiddle,
this.prevpage.yPosition + textMiddle,
0xffffff);
}
@@ -1000,8 +897,13 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
return new Rectangle(titleX, titleY, titleWidth, this.fontRendererObj.FONT_HEIGHT).contains(mousex, mousey);
}
private int getHandlerTitleColor(boolean hovered) {
return hovered ? ColorUtils.recipeTitleHover.getColor() : ColorUtils.recipeTitle.getColor();
private String getHandlerTitleColorCode(boolean hovered) {
final String key = hovered ? "recipe.title.color.hover" : "recipe.title.color.normal";
final String translated = NEIClientUtils.translate(key);
if (!translated.startsWith("nei.")) { // Optional localization string for resource packs
return translated;
}
return hovered ? EnumChatFormatting.YELLOW.toString() : EnumChatFormatting.WHITE.toString();
}
@Override
@@ -1083,7 +985,7 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
final int curRecipe = indices.isEmpty() ? 0 : indices.get(0);
final Recipe recipe = Recipe.of(gRecipe.handler.original, curRecipe);
return recipe.getRecipeId();
return recipe != null ? recipe.getRecipeId() : null;
}
return null;
@@ -1094,7 +996,7 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
private GuiOverlayButton[] overlayButtons = new GuiOverlayButton[0];
@Deprecated
public EmptyContainer slotcontainer;
public ContainerRecipe slotcontainer;
@Deprecated
public List<GuiButton> getOverlayButtons() {
Loaded 100 of 144 files, more files were not shown because too many files have changed in this diff. Show more