1.18 Allow mod menus to have their own recipebook (#8028)

This commit is contained in:
Cyborgmas authored and GitHub committed 2022-03-24 22:08:17 +00:00
1 parent 093acab825
commit c7e4e60052
18 files changed
+1138

No files matched your search

@@ -0,0 +1,35 @@
/*
* Minecraft Forge - Forge Development LLC
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.debug.recipe.recipebook;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import net.minecraft.client.RecipeBookCategories;
import net.minecraft.stats.RecipeBook;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraftforge.client.RecipeBookRegistry;
import java.util.function.Supplier;
public class RecipeBookExtensionClientHelper
{
public static final Supplier<RecipeBookCategories> TESTING_SEARCH = Suppliers.memoize(() -> RecipeBookCategories.create("TESTING_SEARCH", new ItemStack(Items.COMPASS)));
public static final Supplier<RecipeBookCategories> TESTING_CAT_1 = Suppliers.memoize(() -> RecipeBookCategories.create("TESTING_CAT_1", new ItemStack(Items.DIAMOND)));
public static final Supplier<RecipeBookCategories> TESTING_CAT_2 = Suppliers.memoize(() -> RecipeBookCategories.create("TESTING_CAT_2", new ItemStack(Items.NETHERITE_INGOT)));
public static void init()
{
RecipeBookRegistry.addCategoriesToType(RecipeBookExtensionTest.TEST_TYPE, ImmutableList.of(TESTING_SEARCH.get(), TESTING_CAT_1.get(), TESTING_CAT_2.get()));
RecipeBookRegistry.addAggregateCategories(TESTING_SEARCH.get(), ImmutableList.of(TESTING_CAT_1.get(), TESTING_CAT_2.get()));
RecipeBookRegistry.addCategoriesFinder(RecipeBookTestRecipe.TYPE.get(), r ->
{
if (r.getResultItem().getItem() == Items.DIAMOND_BLOCK)
return TESTING_CAT_1.get();
else return TESTING_CAT_2.get();
});
}
}
@@ -0,0 +1,106 @@
/*
* Minecraft Forge - Forge Development LLC
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.debug.recipe.recipebook;
import net.minecraft.client.gui.screens.MenuScreens;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.SimpleContainer;
import net.minecraft.world.SimpleMenuProvider;
import net.minecraft.world.inventory.ContainerLevelAccess;
import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.inventory.RecipeBookType;
import net.minecraft.world.item.crafting.RecipeSerializer;
import net.minecraft.world.item.crafting.RecipeType;
import net.minecraft.world.level.block.Blocks;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.crafting.conditions.ICondition;
import net.minecraftforge.common.crafting.conditions.IConditionSerializer;
import net.minecraftforge.common.extensions.IForgeMenuType;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.network.NetworkHooks;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.RegistryObject;
@Mod(RecipeBookExtensionTest.MOD_ID)
public class RecipeBookExtensionTest
{
public static final boolean ENABLED = false;
public static final String MOD_ID = "recipe_book_extension_test";
public static final RecipeBookType TEST_TYPE = RecipeBookType.create("TESTING");
public static final DeferredRegister<RecipeSerializer<?>> RECIPE_SERIALIZER = DeferredRegister.create(ForgeRegistries.RECIPE_SERIALIZERS, MOD_ID);
public static final RegistryObject<RecipeSerializer<RecipeBookTestRecipe>> RECIPE_BOOK_TEST_RECIPE_SERIALIZER =
RECIPE_SERIALIZER.register("test_recipe", RecipeBookTestRecipeSerializer::new);
public static final DeferredRegister<MenuType<?>> MENU_TYPE = DeferredRegister.create(ForgeRegistries.CONTAINERS, MOD_ID);
public static final RegistryObject<MenuType<RecipeBookTestMenu>> RECIPE_BOOK_TEST_MENU_TYPE =
MENU_TYPE.register("test_recipe_menu", () -> IForgeMenuType.create(RecipeBookTestMenu::new));
public RecipeBookExtensionTest()
{
if (!ENABLED)
return;
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
RECIPE_SERIALIZER.register(FMLJavaModLoadingContext.get().getModEventBus());
MENU_TYPE.register(FMLJavaModLoadingContext.get().getModEventBus());
MinecraftForge.EVENT_BUS.addListener(this::onRightClick);
}
private void commonSetup(FMLCommonSetupEvent event)
{
event.enqueueWork(() ->
{
RecipeType.register(getId("test_recipe").toString());
});
}
private void onRightClick(PlayerInteractEvent.RightClickBlock event)
{
if (event.getWorld().isClientSide)
return;
if (event.getWorld().getBlockState(event.getPos()).getBlock() == Blocks.GRASS_BLOCK)
NetworkHooks.openGui((ServerPlayer) event.getPlayer(), new SimpleMenuProvider((id, inv, p) -> new RecipeBookTestMenu(id, inv, ContainerLevelAccess.create(event.getWorld(), event.getPos())), new TextComponent("Test")));
}
public static ResourceLocation getId(String name)
{
return new ResourceLocation(MOD_ID, name);
}
@Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
public static class ClientHandler
{
@SubscribeEvent
public static void clientSetup(FMLClientSetupEvent event)
{
if (!ENABLED)
return;
event.enqueueWork(() ->
{
MenuScreens.register(RECIPE_BOOK_TEST_MENU_TYPE.get(), RecipeBookTestScreen::new);
RecipeBookExtensionClientHelper.init();
});
}
}
public static class RecipeBookTestContainer extends SimpleContainer
{
public RecipeBookTestContainer()
{
super(8);
}
}
}
@@ -0,0 +1,292 @@
/*
* Minecraft Forge - Forge Development LLC
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.debug.recipe.recipebook;
import net.minecraft.core.NonNullList;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.recipebook.ServerPlaceRecipe;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.Container;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.player.StackedContents;
import net.minecraft.world.inventory.*;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Recipe;
import net.minecraft.world.level.block.Blocks;
import net.minecraftforge.debug.recipe.recipebook.RecipeBookExtensionTest.RecipeBookTestContainer;
import java.util.Optional;
public class RecipeBookTestMenu extends RecipeBookMenu<RecipeBookTestContainer>
{
private final RecipeBookTestContainer container = new RecipeBookTestContainer();
private final ResultContainer resultContainer = new ResultContainer();
private final Slot resultSlot;
private final ContainerLevelAccess access;
private final Player player;
public RecipeBookTestMenu(int id, Inventory inv, FriendlyByteBuf extraData)
{
this(id, inv, ContainerLevelAccess.NULL);
}
public RecipeBookTestMenu(int id, Inventory inv, ContainerLevelAccess access)
{
super(RecipeBookExtensionTest.RECIPE_BOOK_TEST_MENU_TYPE.get(), id);
this.access = access;
this.container.addListener(this::slotsChanged);
this.player = inv.player;
/**
* Copied from {@link ResultSlot} but not limited to {@link CraftingContainer}
*/
this.resultSlot = new Slot(this.resultContainer, 0, 144, 35)
{
private int removeCount;
@Override
public boolean mayPlace(ItemStack stack)
{
return false;
}
@Override
public void onTake(Player player, ItemStack stack)
{
this.checkTakeAchievements(stack);
Container craftingContainer = RecipeBookTestMenu.this.container;
NonNullList<ItemStack> remainders = player.level.getRecipeManager().getRemainingItemsFor(RecipeBookTestRecipe.TYPE.get(), RecipeBookTestMenu.this.container, player.level);
for (int i = 0; i < remainders.size(); ++i)
{
ItemStack toRemove = craftingContainer.getItem(i);
ItemStack toReplace = remainders.get(i);
if (!toRemove.isEmpty())
{
craftingContainer.removeItem(i, 1);
toRemove = craftingContainer.getItem(i);
}
if (!toReplace.isEmpty())
{
if (toRemove.isEmpty())
craftingContainer.setItem(i, toRemove);
else if (ItemStack.isSame(toRemove, toReplace) && ItemStack.tagMatches(toRemove, toReplace))
{
toReplace.grow(toRemove.getCount());
craftingContainer.setItem(i, toReplace);
}
else if (!player.getInventory().add(toReplace))
player.drop(toReplace, false);
}
}
}
@Override
public ItemStack remove(int amount)
{
if (this.hasItem())
this.removeCount += Math.min(amount, this.getItem().getCount());
return super.remove(amount);
}
@Override
public void onQuickCraft(ItemStack output, int amount)
{
this.removeCount += amount;
this.checkTakeAchievements(output);
}
@Override
protected void onSwapCraft(int amount)
{
this.removeCount = amount;
}
@Override
protected void checkTakeAchievements(ItemStack stack)
{
if (this.removeCount > 0)
stack.onCraftedBy(RecipeBookTestMenu.this.player.level, RecipeBookTestMenu.this.player, this.removeCount);
if (this.container instanceof RecipeHolder recipeHolder)
recipeHolder.awardUsedRecipes(RecipeBookTestMenu.this.player);
this.removeCount = 0;
}
};
this.addSlot(this.resultSlot); //slot 0
//slots 1 - 8
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 2; ++j)
this.addSlot(new Slot(this.container, j + i * 2, 30 + j * 18, 61 - i * 18));
}
//slots 9 to 35
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 9; ++j)
this.addSlot(new Slot(inv, j + i * 9 + 9, 8 + j * 18, 84 + i * 18));
}
//slots 36 to 44
for(int i = 0; i < 9; ++i)
this.addSlot(new Slot(inv, i, 8 + i * 18, 142));
}
@Override
public boolean stillValid(Player player)
{
return stillValid(this.access, player, Blocks.GRASS_BLOCK);
}
@Override
public void removed(Player player)
{
super.removed(player);
this.access.execute((level, pos) -> this.clearContainer(player, this.container));
}
@Override
public boolean canTakeItemForPickAll(ItemStack stack, Slot slot)
{
return slot != resultSlot;
}
@Override
public void slotsChanged(Container container)
{
this.access.execute((level, pos) ->
{
if (container == this.container)
{
Optional<RecipeBookTestRecipe> recipe = level.getRecipeManager()
.getRecipeFor(RecipeBookTestRecipe.TYPE.get(), this.container, level);
if (recipe.isEmpty())
this.resultContainer.setItem(0, ItemStack.EMPTY);
else if (player instanceof ServerPlayer sp && this.resultContainer.setRecipeUsed(level, sp, recipe.get())) {
ItemStack stack = recipe.get().assemble(this.container);
this.resultContainer.setItem(0, stack);
}
}
});
super.slotsChanged(container);
}
private static final int RESULT_SLOT = 0;
private static final int CRAFTING_START = 1;
private static final int CRAFTING_STOP = 8;
private static final int INVENTORY_START = 9;
private static final int INVENTORY_STOP = 44;
private static final int HOTBAR_START = 36;
/**
* Mostly copied from {@link CraftingMenu#quickMoveStack}
*/
public ItemStack quickMoveStack(Player player, int idx)
{
ItemStack ret = ItemStack.EMPTY;
Slot slot = this.slots.get(idx);
if (!slot.hasItem())
return ret;
ItemStack item = slot.getItem();
ret = item.copy();
if (idx == RESULT_SLOT)
{
if (!this.moveItemStackTo(item, INVENTORY_START, INVENTORY_STOP + 1, true))
return ItemStack.EMPTY;
slot.onQuickCraft(item, ret);
}
else if (idx >= INVENTORY_START && idx < INVENTORY_STOP + 1)
{
if (!this.moveItemStackTo(item, CRAFTING_START, CRAFTING_STOP + 1, false))
{
if (idx < HOTBAR_START)
{
if (!this.moveItemStackTo(item, HOTBAR_START, INVENTORY_STOP + 1, false))
return ItemStack.EMPTY;
}
else if (!this.moveItemStackTo(item, INVENTORY_START, HOTBAR_START, false))
return ItemStack.EMPTY;
}
}
else if (!this.moveItemStackTo(item, INVENTORY_START, INVENTORY_STOP + 1, false))
return ItemStack.EMPTY;
if (item.isEmpty())
slot.set(ItemStack.EMPTY);
else
slot.setChanged();
if (item.getCount() == ret.getCount())
return ItemStack.EMPTY;
slot.onTake(player, item);
if (idx == RESULT_SLOT)
player.drop(item, false);
return ret;
}
//RecipeBook stuff
@Override
public void fillCraftSlotsStackedContents(StackedContents contents)
{
this.container.fillStackedContents(contents);
}
@Override
public void clearCraftingContent()
{
this.container.clearContent();
this.resultContainer.clearContent();
}
@Override
public boolean recipeMatches(Recipe<? super RecipeBookTestContainer> recipe)
{
return recipe.matches(this.container, this.player.level);
}
@Override
public int getResultSlotIndex()
{
return RESULT_SLOT;
}
@Override
public int getGridWidth()
{
return 2;
}
@Override
public int getGridHeight()
{
return 4;
}
@Override
public int getSize()
{
return 9;
}
@Override
public RecipeBookType getRecipeBookType()
{
return RecipeBookExtensionTest.TEST_TYPE;
}
@Override
public boolean shouldMoveToInventory(int slotIdx)
{
return slotIdx != RESULT_SLOT;
}
}
@@ -0,0 +1,204 @@
/*
* Minecraft Forge - Forge Development LLC
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.debug.recipe.recipebook;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.gson.JsonElement;
import com.mojang.serialization.Codec;
import com.mojang.serialization.DataResult;
import com.mojang.serialization.Dynamic;
import com.mojang.serialization.JsonOps;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.NonNullList;
import net.minecraft.core.Registry;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.item.crafting.Recipe;
import net.minecraft.world.item.crafting.RecipeSerializer;
import net.minecraft.world.item.crafting.RecipeType;
import net.minecraft.world.item.crafting.ShapedRecipe;
import net.minecraft.world.level.Level;
import java.util.*;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class RecipeBookTestRecipe implements Recipe<RecipeBookExtensionTest.RecipeBookTestContainer>
{
@SuppressWarnings("unchecked")
public static final Supplier<RecipeType<RecipeBookTestRecipe>> TYPE = Suppliers.memoize(() -> (RecipeType<RecipeBookTestRecipe>) Registry.RECIPE_TYPE.get(RecipeBookExtensionTest.getId("test_recipe")));
public final ResourceLocation id;
public final Ingredients ingredients;
private final int width;
private final int height;
private final NonNullList<Ingredient> items;
public RecipeBookTestRecipe(ResourceLocation id, Ingredients ingredients)
{
this.id = id;
this.ingredients = ingredients;
this.width = ingredients.pattern.get(0).length();
this.height = ingredients.pattern.size();
List<String> pattern = new ArrayList<>(ingredients.pattern); //might need to reverse this list.
while (pattern.size() != 4)
pattern.add(" ");
this.items = pattern.stream()
.flatMap(s -> Stream.of(s.substring(0,1), s.substring(1, 2)))
.map(s -> s.equals(" ") ? Ingredient.EMPTY : ingredients.recipe.get(s))
.peek(i -> Objects.requireNonNull(i, "A key in sculpting pattern was not defined!"))
.collect(Collectors.toCollection(NonNullList::create));
}
/**
* Taken from {@link ShapedRecipe}
*/
@Override
public boolean matches(RecipeBookExtensionTest.RecipeBookTestContainer container, Level level)
{
for (int i = 0; i <= 2 - this.width; ++i)
{
for (int j = 0; j <= 4 - this.height; ++j)
{
if (this.matches(container, i, j, true) || this.matches(container, i, j, false))
return true;
}
}
return false;
}
private boolean matches(RecipeBookExtensionTest.RecipeBookTestContainer container, int x, int y, boolean mirror) //unsure about the last boolean
{
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 4; ++j)
{
int curX = i - x;
int curY = j - y;
Ingredient ingredient = Ingredient.EMPTY;
if (curX >= 0 && curY >= 0 && curX < this.width && curY < this.height)
{
int idx = mirror ? this.width - curX - 1 + curY * this.width : curX + curY * this.width;
ingredient = this.items.get(idx);
}
if (!ingredient.test(container.getItem(i + j * 2)))
return false;
}
}
return true;
}
@Override
public ItemStack assemble(RecipeBookExtensionTest.RecipeBookTestContainer p_44001_)
{
return this.getResultItem().copy();
}
@Override
public boolean canCraftInDimensions(int p_43999_, int p_44000_)
{
return this.width <= p_43999_ && this.height <= p_44000_; //used for recipe book
}
@Override
public ItemStack getResultItem()
{
return this.ingredients.result();
}
@Override
public ResourceLocation getId()
{
return this.id;
}
@Override
public RecipeSerializer<?> getSerializer()
{
return RecipeBookExtensionTest.RECIPE_BOOK_TEST_RECIPE_SERIALIZER.get();
}
@Override
public RecipeType<?> getType()
{
return TYPE.get();
}
@Override
public String getGroup()
{
return this.ingredients.group;
}
@Override
public NonNullList<Ingredient> getIngredients()
{
return this.items;
}
@Override
public boolean isIncomplete()
{
return this.getIngredients().isEmpty() ||
this.getIngredients().stream()
.filter((ingredient) -> !ingredient.isEmpty())
.anyMatch(i -> i.getItems().length == 0);
}
@Override
public ItemStack getToastSymbol()
{
return new ItemStack(Items.NETHERITE_BLOCK);
}
public record Ingredients(String group, List<String> pattern, Map<String, Ingredient> recipe, ItemStack result)
{
private static final Function<String, DataResult<String>> VERIFY_LENGTH_2 = s -> s.length() == 2 ? DataResult.success(s) :
DataResult.error("Key row length must be of 2!");
private static final Function<List<String>, DataResult<List<String>>> VERIFY_SIZE = l ->
{
if (l.size() <= 4 && l.size() >= 1)
{
List<String> temp = new ArrayList<>(l);
Collections.reverse(temp); //reverse so the first row is at the bottom in the json.
return DataResult.success(ImmutableList.copyOf(temp));
}
return DataResult.error("Pattern must have between 1 and 4 rows of keys");
};
private static final Function<String, DataResult<String>> VERIFY_LENGTH_1 = s -> s.length() == 1 ? DataResult.success(s) :
DataResult.error("Key must be a single character!");
public static final Codec<Ingredient> INGREDIENT_CODEC = Codec.PASSTHROUGH.comapFlatMap(obj ->
{
JsonElement json = obj.convert(JsonOps.INSTANCE).getValue();
try
{
return DataResult.success(Ingredient.fromJson(json));
}
catch (Exception e)
{
return DataResult.error("Failed to parse ingredient: " + e.getMessage());
}
}, ingredient -> new Dynamic<>(JsonOps.INSTANCE, ingredient.toJson()));
public static final Codec<Ingredients> CODEC = RecordCodecBuilder.create(inst ->
inst.group(
Codec.STRING.fieldOf("group").forGetter(Ingredients::group),
Codec.STRING.flatXmap(VERIFY_LENGTH_2, VERIFY_LENGTH_2).listOf().flatXmap(VERIFY_SIZE, VERIFY_SIZE).fieldOf("pattern").forGetter(Ingredients::pattern),
Codec.unboundedMap(Codec.STRING.flatXmap(VERIFY_LENGTH_1, VERIFY_LENGTH_1), INGREDIENT_CODEC).fieldOf("key").forGetter(Ingredients::recipe),
ItemStack.CODEC.fieldOf("result").forGetter(Ingredients::result)
).apply(inst, Ingredients::new)
);
}
}
@@ -0,0 +1,40 @@
/*
* Minecraft Forge - Forge Development LLC
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.debug.recipe.recipebook;
import com.google.gson.JsonObject;
import com.mojang.serialization.JsonOps;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.crafting.RecipeSerializer;
import net.minecraftforge.debug.recipe.recipebook.RecipeBookTestRecipe.Ingredients;
import net.minecraftforge.registries.ForgeRegistryEntry;
import javax.annotation.Nullable;
public class RecipeBookTestRecipeSerializer extends ForgeRegistryEntry<RecipeSerializer<?>> implements RecipeSerializer<RecipeBookTestRecipe>
{
@Override
public RecipeBookTestRecipe fromJson(ResourceLocation id, JsonObject json)
{
Ingredients ingredients = Ingredients.CODEC.parse(JsonOps.INSTANCE, json).getOrThrow(false, s->{});
return new RecipeBookTestRecipe(id, ingredients);
}
@Nullable
@Override
public RecipeBookTestRecipe fromNetwork(ResourceLocation id, FriendlyByteBuf buf)
{
Ingredients ingredients = buf.readWithCodec(Ingredients.CODEC);
return new RecipeBookTestRecipe(id, ingredients);
}
@Override
public void toNetwork(FriendlyByteBuf buffer, RecipeBookTestRecipe recipe)
{
buffer.writeWithCodec(Ingredients.CODEC, recipe.ingredients);
}
}
@@ -0,0 +1,146 @@
/*
* Minecraft Forge - Forge Development LLC
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.debug.recipe.recipebook;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.gui.components.ImageButton;
import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen;
import net.minecraft.client.gui.screens.inventory.CraftingScreen;
import net.minecraft.client.gui.screens.recipebook.RecipeBookComponent;
import net.minecraft.client.gui.screens.recipebook.RecipeUpdateListener;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.locale.Language;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.inventory.ClickType;
import net.minecraft.world.inventory.Slot;
/**
* Mostly copied from {@link CraftingScreen}
*/
public class RecipeBookTestScreen extends AbstractContainerScreen<RecipeBookTestMenu> implements RecipeUpdateListener
{
private static final ResourceLocation TEXTURE = RecipeBookExtensionTest.getId("textures/gui/container/recipe_book_test.png");
private static final ResourceLocation RECIPE_BUTTON_LOCATION = new ResourceLocation("textures/gui/recipe_button.png");
private final RecipeBookComponent recipeBookComponent = new RecipeBookComponent();
private boolean widthTooNarrow;
public RecipeBookTestScreen(RecipeBookTestMenu menu, Inventory inv, Component title)
{
super(menu, inv, title);
}
@Override
protected void init()
{
super.init();
this.widthTooNarrow = this.width < 379;
this.titleLabelX = this.imageWidth - this.font.width(Language.getInstance().getVisualOrder(this.title)) - 5;
this.recipeBookComponent.init(this.width, this.height, this.minecraft, this.widthTooNarrow, this.menu);
this.leftPos = this.recipeBookComponent.updateScreenPosition(this.width, this.imageWidth);
this.addRenderableWidget(new ImageButton(this.leftPos + 5, this.height / 2 - 49, 20, 18, 0, 0, 19, RECIPE_BUTTON_LOCATION, (button) ->
{
this.recipeBookComponent.toggleVisibility();
this.leftPos = this.recipeBookComponent.updateScreenPosition(this.width, this.imageWidth);
((ImageButton)button).setPosition(this.leftPos + 5, this.height / 2 - 49);
}));
this.addWidget(this.recipeBookComponent);
this.setInitialFocus(this.recipeBookComponent);
}
@Override
protected void containerTick()
{
super.containerTick();
this.recipeBookComponent.tick();
}
@Override
public void render(PoseStack stack, int mouseX, int mouseY, float partialTicks)
{
this.renderBackground(stack);
if (this.recipeBookComponent.isVisible() && this.widthTooNarrow)
{
this.renderBg(stack, partialTicks, mouseX, mouseY);
this.recipeBookComponent.render(stack, mouseX, mouseY, partialTicks);
}
else
{
this.recipeBookComponent.render(stack, mouseX, mouseY, partialTicks);
super.render(stack, mouseX, mouseY, partialTicks);
this.recipeBookComponent.renderGhostRecipe(stack, this.leftPos, this.topPos, true, partialTicks);
}
this.renderTooltip(stack, mouseX, mouseY);
this.recipeBookComponent.renderTooltip(stack, this.leftPos, this.topPos, mouseX, mouseY);
}
@Override
protected void renderBg(PoseStack stack, float partialTicks, int mouseX, int mouseY)
{
RenderSystem.setShader(GameRenderer::getPositionTexShader);
RenderSystem.setShaderTexture(0, TEXTURE);
int x = this.leftPos;
int y = this.topPos;
this.blit(stack, x, y, 0, 0, this.imageWidth, this.imageHeight);
}
/**
* Color gotten from super
*/
@Override
protected void renderLabels(PoseStack stack, int mouseX, int mouseY)
{
this.font.draw(stack, this.title, this.titleLabelX, this.titleLabelY, 4210752);
}
protected boolean isHovering(int x, int y, int width, int height, double mouseX, double mouseY)
{
return (!this.widthTooNarrow || !this.recipeBookComponent.isVisible()) && super.isHovering(x, y, width, height, mouseX, mouseY);
}
public boolean mouseClicked(double mouseX, double mouseY, int buttonId)
{
if (this.recipeBookComponent.mouseClicked(mouseX, mouseY, buttonId))
{
this.setFocused(this.recipeBookComponent);
return true;
}
return this.widthTooNarrow && this.recipeBookComponent.isVisible() || super.mouseClicked(mouseX, mouseY, buttonId);
}
protected boolean hasClickedOutside(double mouseX, double mouseY, int x, int y, int buttonIdx)
{
boolean flag = mouseX < (double)x || mouseY < (double)y || mouseX >= (double)(x + this.imageWidth) || mouseY >= (double)(y + this.imageHeight);
return flag && this.recipeBookComponent.hasClickedOutside(mouseX, mouseY, this.leftPos, this.topPos, this.imageWidth, this.imageHeight, buttonIdx);
}
protected void slotClicked(Slot slot, int mouseX, int mouseY, ClickType clickType)
{
super.slotClicked(slot, mouseX, mouseY, clickType);
this.recipeBookComponent.slotClicked(slot);
}
@Override
public void recipesUpdated()
{
this.recipeBookComponent.recipesUpdated();
}
@Override
public void removed()
{
this.recipeBookComponent.removed();
super.removed();
}
@Override
public RecipeBookComponent getRecipeBookComponent()
{
return this.recipeBookComponent;
}
}