diff --git a/src/main/java/org/violetmoon/quark/base/client/handler/ClientUtil.java b/src/main/java/org/violetmoon/quark/base/client/handler/ClientUtil.java new file mode 100644 index 0000000000..a3dbc5a9b4 --- /dev/null +++ b/src/main/java/org/violetmoon/quark/base/client/handler/ClientUtil.java @@ -0,0 +1,92 @@ +package org.violetmoon.quark.base.client.handler; + +import java.util.Random; + +import org.violetmoon.quark.base.Quark; +import org.violetmoon.quark.base.handler.MiscUtil; +import org.violetmoon.zeta.client.config.screen.ZetaScreen; +import org.violetmoon.zeta.client.event.play.ZScreen; +import org.violetmoon.zeta.event.bus.PlayEvent; + +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.PoseStack; + +import net.minecraft.Util; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.resources.language.I18n; +import net.minecraft.resources.ResourceLocation; + +public class ClientUtil { + + public static final ResourceLocation GENERAL_ICONS = new ResourceLocation(Quark.MOD_ID, "textures/gui/general_icons.png"); + + private static int progress; + + private static final int BASIC_GUI_TEXT_COLOR = 0x404040; + + @PlayEvent + public static void onKeystroke(ZScreen.KeyPressed.Pre event) { + final String[] ids = new String[] { + "-FCYE87P5L0", "mybsDDymrsc", "6a4BWpBJppI", "thpTOAS1Vgg", "ZNcBZM5SvbY", "_qJEoSa3Ie0", + "RWeyOyY_puQ", "VBbeuXW8Nko", "LIDe-yTxda0", "BVVfMFS3mgc", "m5qwcYL8a0o", "UkY8HvgvBJ8", + "4K4b9Z9lSwc", "tyInv6RWL0Q", "tIWpr3tHzII", "AFJPFfnzZ7w", "846cjX0ZTrk", "XEOCbFJjRw0", + "GEo5bmUKFvI", "b6li05zh3Kg", "_EEo-iE5u_A", "SPYX2y4NzTU", "UDxID0_A9x4", "ZBl48MK17cI", + "l6p8FDJqUj4" + }; + final int[] keys = new int[] { 265, 265, 264, 264, 263, 262, 263, 262, 66, 65 }; + if(event.getScreen() instanceof ZetaScreen) { + if(keys[progress] == event.getKeyCode()) { + progress++; + + if(progress >= keys.length) { + progress = 0; + Util.getPlatform().openUri("https://www.youtube.com/watch?v=" + ids[new Random().nextInt(ids.length)]); + } + } else + progress = 0; + } + } + + public static int getGuiTextColor(String name) { + return getGuiTextColor(name, BASIC_GUI_TEXT_COLOR); + } + + public static int getGuiTextColor(String name, int base) { + int ret = base; + + String hex = I18n.get("quark.gui.color." + name); + if(hex.matches("#[A-F0-9]{6}")) + ret = Integer.valueOf(hex.substring(1), 16); + return ret; + } + + public static void drawChatBubble(GuiGraphics guiGraphics, int x, int y, Font font, String text, float alpha, boolean extendRight) { + PoseStack matrix = guiGraphics.pose(); + + matrix.pushPose(); + matrix.translate(0, 0, 200); + int w = font.width(text); + int left = x - (extendRight ? 0 : w); + int top = y - 8; + + RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, alpha); + + if(extendRight) { + guiGraphics.blit(MiscUtil.GENERAL_ICONS, left, top, 227, 9, 6, 17, 256, 256); + for(int i = 0; i < w; i++) + guiGraphics.blit(MiscUtil.GENERAL_ICONS, left + i + 6, top, 232, 9, 1, 17, 256, 256); + guiGraphics.blit(MiscUtil.GENERAL_ICONS, left + w + 5, top, 236, 9, 5, 17, 256, 256); + } else { + guiGraphics.blit(MiscUtil.GENERAL_ICONS, left, top, 242, 9, 5, 17, 256, 256); + for(int i = 0; i < w; i++) + guiGraphics.blit(MiscUtil.GENERAL_ICONS, left + i + 5, top, 248, 9, 1, 17, 256, 256); + guiGraphics.blit(MiscUtil.GENERAL_ICONS, left + w + 5, top, 250, 9, 6, 17, 256, 256); + } + + int alphaInt = (int) (256F * alpha) << 24; + guiGraphics.drawString(font, text, left + 5, top + 3, alphaInt, false); + matrix.popPose(); + } + +} diff --git a/src/main/java/org/violetmoon/quark/base/handler/FuelHandler.java b/src/main/java/org/violetmoon/quark/base/handler/FuelHandler.java deleted file mode 100644 index 558a81216a..0000000000 --- a/src/main/java/org/violetmoon/quark/base/handler/FuelHandler.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.violetmoon.quark.base.handler; - -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.Item; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.SlabBlock; - -import org.violetmoon.quark.base.Quark; -import org.violetmoon.zeta.util.BlockUtils; -import org.violetmoon.quark.content.building.block.VerticalSlabBlock; -import org.violetmoon.zeta.event.bus.LoadEvent; -import org.violetmoon.zeta.event.bus.PlayEvent; -import org.violetmoon.zeta.event.load.ZLoadComplete; -import org.violetmoon.zeta.event.play.ZFurnaceFuelBurnTime; - -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; - -public class FuelHandler { - - private static final Map fuelValues = new HashMap<>(); - - public static void addFuel(Item item, int fuel) { - if(fuel > 0 && item != null && !fuelValues.containsKey(item)) - fuelValues.put(item, fuel); - } - - public static void addFuel(Block block, int fuel) { - addFuel(block.asItem(), fuel); - } - - public static void addWood(Block block) { - String regname = Objects.toString(Quark.ZETA.registry.getRegistryName(block, BuiltInRegistries.BLOCK)); - if(regname.contains("crimson") || regname.contains("warped")) - return; //do nothing if block is crimson or warped, since they aren't flammable. #3549 - if(block instanceof VerticalSlabBlock || block instanceof SlabBlock) - addFuel(block, 150); - else - addFuel(block, 300); - } - - @LoadEvent - public static void addAllWoods(ZLoadComplete event) { - for(Block block : BuiltInRegistries.BLOCK) { - ResourceLocation regname = Quark.ZETA.registry.getRegistryName(block, BuiltInRegistries.BLOCK); - if(block != null && regname.getNamespace().equals(Quark.MOD_ID) && BlockUtils.isWoodBased(block.defaultBlockState())) - addWood(block); - } - } - - @PlayEvent - public static void getFuel(ZFurnaceFuelBurnTime event) { - Item item = event.getItemStack().getItem(); - if(fuelValues.containsKey(item)) - event.setBurnTime(fuelValues.get(item)); - } -} diff --git a/src/main/java/org/violetmoon/quark/base/handler/MiscUtil.java b/src/main/java/org/violetmoon/quark/base/handler/MiscUtil.java deleted file mode 100644 index d58d9d804b..0000000000 --- a/src/main/java/org/violetmoon/quark/base/handler/MiscUtil.java +++ /dev/null @@ -1,294 +0,0 @@ -package org.violetmoon.quark.base.handler; - -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.brigadier.StringReader; -import com.mojang.brigadier.exceptions.CommandSyntaxException; - -import net.minecraft.Util; -import net.minecraft.client.gui.Font; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.resources.language.I18n; -import net.minecraft.commands.arguments.blocks.BlockStateParser; -import net.minecraft.commands.arguments.blocks.BlockStateParser.BlockResult; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.network.protocol.Packet; -import net.minecraft.network.protocol.game.ClientGamePacketListener; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.util.RandomSource; -import net.minecraft.world.Container; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.WorldlyContainer; -import net.minecraft.world.WorldlyContainerHolder; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.entity.Mob; -import net.minecraft.world.entity.MobSpawnType; -import net.minecraft.world.entity.ai.goal.Goal; -import net.minecraft.world.entity.ai.goal.GoalSelector; -import net.minecraft.world.entity.ai.goal.WrappedGoal; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.DyeColor; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.enchantment.Enchantment; -import net.minecraft.world.level.ChunkPos; -import net.minecraft.world.level.LevelAccessor; -import net.minecraft.world.level.LightLayer; -import net.minecraft.world.level.ServerLevelAccessor; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.properties.BlockStateProperties; -import net.minecraft.world.level.block.state.properties.BooleanProperty; -import net.minecraft.world.phys.Vec2; -import net.minecraft.world.phys.Vec3; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.items.IItemHandler; -import net.minecraftforge.items.ItemHandlerHelper; -import net.minecraftforge.items.ItemStackHandler; -import net.minecraftforge.items.wrapper.InvWrapper; -import net.minecraftforge.items.wrapper.SidedInvWrapper; - -import org.jetbrains.annotations.NotNull; - -import org.violetmoon.quark.base.Quark; -import org.violetmoon.zeta.util.BlockUtils; -import org.violetmoon.quark.content.experimental.module.EnchantmentsBegoneModule; -import org.violetmoon.zeta.client.config.screen.ZetaScreen; -import org.violetmoon.zeta.client.event.play.ZScreen; -import org.violetmoon.zeta.event.bus.PlayEvent; - -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Random; -import java.util.Set; - -public class MiscUtil { - - public static final ResourceLocation GENERAL_ICONS = new ResourceLocation(Quark.MOD_ID, "textures/gui/general_icons.png"); - - public static final Direction[] HORIZONTALS = new Direction[] { - Direction.NORTH, - Direction.SOUTH, - Direction.WEST, - Direction.EAST - }; - - public static final DyeColor[] CREATIVE_COLOR_ORDER = new DyeColor[] { - DyeColor.WHITE, DyeColor.LIGHT_GRAY, DyeColor.GRAY, DyeColor.BLACK, - DyeColor.BROWN, DyeColor.RED, DyeColor.ORANGE, DyeColor.YELLOW, - DyeColor.LIME, DyeColor.GREEN, DyeColor.CYAN, DyeColor.LIGHT_BLUE, - DyeColor.BLUE, DyeColor.PURPLE, DyeColor.MAGENTA, DyeColor.PINK - }; - - public static BooleanProperty directionProperty(Direction direction) { - return switch(direction) { - case DOWN -> BlockStateProperties.DOWN; - case UP -> BlockStateProperties.UP; - case NORTH -> BlockStateProperties.NORTH; - case SOUTH -> BlockStateProperties.SOUTH; - case WEST -> BlockStateProperties.WEST; - case EAST -> BlockStateProperties.EAST; - }; - } - - /** - * Reconstructs the goal selector's list to add in a new goal. - * - * This is because vanilla doesn't play it safe around CMEs with skeletons. - * See: https://github.com/VazkiiMods/Quark/issues/4356 - * - * If a Skeleton is killed with Thorns damage and drops its weapon, it will reassess its goals. - * Because the thorns damage is being dealt during goal execution of the MeleeAttackGoal or RangedBowAttackGoal, - * this will cause a CME if the attack goal is not the VERY LAST goal in the set. - * - * Thankfully, the set GoalSelector uses is Linked, so we can just reconstruct the set and avoid the problem. - */ - public static void addGoalJustAfterLatestWithPriority(GoalSelector selector, int priority, Goal goal) { - Set allGoals = new LinkedHashSet<>(selector.getAvailableGoals()); - WrappedGoal latestWithPriority = null; - for(WrappedGoal wrappedGoal : allGoals) { - if(wrappedGoal.getPriority() == priority) - latestWithPriority = wrappedGoal; - } - - selector.removeAllGoals(g -> true); - if(latestWithPriority == null) - selector.addGoal(priority, goal); - - for(WrappedGoal wrappedGoal : allGoals) { - selector.addGoal(wrappedGoal.getPriority(), wrappedGoal.getGoal()); - if(wrappedGoal == latestWithPriority) - selector.addGoal(priority, goal); - } - } - - public static void damageStack(Player player, InteractionHand hand, ItemStack stack, int dmg) { - stack.hurtAndBreak(dmg, player, (p) -> p.broadcastBreakEvent(hand)); - } - - public static void initializeEnchantmentList(Iterable enchantNames, List enchants) { - enchants.clear(); - for(String s : enchantNames) { - Enchantment enchant = BuiltInRegistries.ENCHANTMENT.get(new ResourceLocation(s)); - if(enchant != null && !EnchantmentsBegoneModule.shouldBegone(enchant)) - enchants.add(enchant); - } - } - - public static Vec2 getMinecraftAngles(Vec3 direction) { - // - - direction = direction.normalize(); - - double pitch = Math.asin(direction.y); - double yaw = Math.asin(direction.x / Math.cos(pitch)); - - return new Vec2((float) (pitch * 180 / Math.PI), (float) (-yaw * 180 / Math.PI)); - } - - public static boolean validSpawnLight(ServerLevelAccessor world, BlockPos pos, RandomSource rand) { - if(world.getBrightness(LightLayer.SKY, pos) > rand.nextInt(32)) { - return false; - } else { - int light = world.getLevel().isThundering() ? world.getMaxLocalRawBrightness(pos, 10) : world.getMaxLocalRawBrightness(pos); - return light == 0; - } - } - - public static boolean validSpawnLocation(@NotNull EntityType type, @NotNull LevelAccessor world, MobSpawnType reason, BlockPos pos) { - BlockPos below = pos.below(); - if(reason == MobSpawnType.SPAWNER) - return true; - BlockState state = world.getBlockState(below); - return BlockUtils.isStoneBased(state, world, below) && state.isValidSpawn(world, below, type); - } - - public static void syncTE(BlockEntity tile) { - Packet packet = tile.getUpdatePacket(); - - if(packet != null && tile.getLevel() instanceof ServerLevel serverLevel) { - serverLevel.getChunkSource().chunkMap - .getPlayers(new ChunkPos(tile.getBlockPos()), false) - .forEach(e -> e.connection.send(packet)); - } - } - - public static ItemStack putIntoInv(ItemStack stack, LevelAccessor level, BlockPos blockPos, BlockEntity tile, Direction face, boolean simulate, boolean doSimulation) { - IItemHandler handler = null; - - if(level != null && blockPos != null && level.getBlockState(blockPos).getBlock() instanceof WorldlyContainerHolder holder) { - handler = new SidedInvWrapper(holder.getContainer(level.getBlockState(blockPos), level, blockPos), face); - } else if(tile != null) { - LazyOptional opt = tile.getCapability(ForgeCapabilities.ITEM_HANDLER, face); - if(opt.isPresent()) - handler = opt.orElse(new ItemStackHandler()); - else if(tile instanceof WorldlyContainer container) - handler = new SidedInvWrapper(container, face); - else if(tile instanceof Container container) - handler = new InvWrapper(container); - } - - if(handler != null) - return (simulate && !doSimulation) ? ItemStack.EMPTY : ItemHandlerHelper.insertItem(handler, stack, simulate); - - return stack; - } - - public static boolean canPutIntoInv(ItemStack stack, LevelAccessor level, BlockPos blockPos, BlockEntity tile, Direction face, boolean doSimulation) { - return putIntoInv(stack, level, blockPos, tile, face, true, doSimulation).isEmpty(); - } - - public static BlockState fromString(String key) { - try { - BlockResult result = BlockStateParser.parseForBlock(BuiltInRegistries.BLOCK.asLookup(), new StringReader(key), false); - BlockState state = result.blockState(); - return state == null ? Blocks.AIR.defaultBlockState() : state; - } catch (CommandSyntaxException e) { - return Blocks.AIR.defaultBlockState(); - } - } - - //gets rid of lambdas that could contain references to blockstate properties we might not have - public static BlockBehaviour.Properties copyPropertySafe(BlockBehaviour blockBehaviour) { - BlockBehaviour.Properties p = BlockBehaviour.Properties.copy(blockBehaviour); - p.lightLevel(s -> 0); - p.offsetType(BlockBehaviour.OffsetType.NONE); - p.mapColor(blockBehaviour.defaultMapColor()); - return p; - } - - public static class Client { - private static int progress; - - private static final int BASIC_GUI_TEXT_COLOR = 0x404040; - - @PlayEvent - public static void onKeystroke(ZScreen.KeyPressed.Pre event) { - final String[] ids = new String[] { - "-FCYE87P5L0", "mybsDDymrsc", "6a4BWpBJppI", "thpTOAS1Vgg", "ZNcBZM5SvbY", "_qJEoSa3Ie0", - "RWeyOyY_puQ", "VBbeuXW8Nko", "LIDe-yTxda0", "BVVfMFS3mgc", "m5qwcYL8a0o", "UkY8HvgvBJ8", - "4K4b9Z9lSwc", "tyInv6RWL0Q", "tIWpr3tHzII", "AFJPFfnzZ7w", "846cjX0ZTrk", "XEOCbFJjRw0", - "GEo5bmUKFvI", "b6li05zh3Kg", "_EEo-iE5u_A", "SPYX2y4NzTU", "UDxID0_A9x4", "ZBl48MK17cI", - "l6p8FDJqUj4" - }; - final int[] keys = new int[] { 265, 265, 264, 264, 263, 262, 263, 262, 66, 65 }; - if(event.getScreen() instanceof ZetaScreen) { - if(keys[progress] == event.getKeyCode()) { - progress++; - - if(progress >= keys.length) { - progress = 0; - Util.getPlatform().openUri("https://www.youtube.com/watch?v=" + ids[new Random().nextInt(ids.length)]); - } - } else - progress = 0; - } - } - - public static int getGuiTextColor(String name) { - return getGuiTextColor(name, BASIC_GUI_TEXT_COLOR); - } - - public static int getGuiTextColor(String name, int base) { - int ret = base; - - String hex = I18n.get("quark.gui.color." + name); - if(hex.matches("#[A-F0-9]{6}")) - ret = Integer.valueOf(hex.substring(1), 16); - return ret; - } - - public static void drawChatBubble(GuiGraphics guiGraphics, int x, int y, Font font, String text, float alpha, boolean extendRight) { - PoseStack matrix = guiGraphics.pose(); - - matrix.pushPose(); - matrix.translate(0, 0, 200); - int w = font.width(text); - int left = x - (extendRight ? 0 : w); - int top = y - 8; - - RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, alpha); - - if(extendRight) { - guiGraphics.blit(MiscUtil.GENERAL_ICONS, left, top, 227, 9, 6, 17, 256, 256); - for(int i = 0; i < w; i++) - guiGraphics.blit(MiscUtil.GENERAL_ICONS, left + i + 6, top, 232, 9, 1, 17, 256, 256); - guiGraphics.blit(MiscUtil.GENERAL_ICONS, left + w + 5, top, 236, 9, 5, 17, 256, 256); - } else { - guiGraphics.blit(MiscUtil.GENERAL_ICONS, left, top, 242, 9, 5, 17, 256, 256); - for(int i = 0; i < w; i++) - guiGraphics.blit(MiscUtil.GENERAL_ICONS, left + i + 5, top, 248, 9, 1, 17, 256, 256); - guiGraphics.blit(MiscUtil.GENERAL_ICONS, left + w + 5, top, 250, 9, 6, 17, 256, 256); - } - - int alphaInt = (int) (256F * alpha) << 24; - guiGraphics.drawString(font, text, left + 5, top + 3, alphaInt, false); - matrix.popPose(); - } - } -} diff --git a/src/main/java/org/violetmoon/quark/base/handler/RecipeCrawlHandler.java b/src/main/java/org/violetmoon/quark/base/handler/RecipeCrawlHandler.java deleted file mode 100644 index e3ea4a19c0..0000000000 --- a/src/main/java/org/violetmoon/quark/base/handler/RecipeCrawlHandler.java +++ /dev/null @@ -1,191 +0,0 @@ -package org.violetmoon.quark.base.handler; - -import com.google.common.collect.*; - -import net.minecraft.core.NonNullList; -import net.minecraft.core.RegistryAccess; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.server.packs.resources.SimplePreparableReloadListener; -import net.minecraft.util.profiling.ProfilerFiller; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.*; - -import org.jetbrains.annotations.Nullable; - -import org.violetmoon.quark.base.Quark; -import org.violetmoon.zeta.event.bus.LoadEvent; -import org.violetmoon.zeta.event.bus.PlayEvent; -import org.violetmoon.zeta.event.load.ZAddReloadListener; -import org.violetmoon.zeta.event.load.ZTagsUpdated; -import org.violetmoon.zeta.event.play.ZRecipeCrawl; -import org.violetmoon.zeta.event.play.ZServerTick; -import org.violetmoon.zeta.util.RegistryUtil; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Set; -import java.util.function.Consumer; - -// TODO TODO: split off from Quark - -public class RecipeCrawlHandler { - - private static final List> recipesToLazyDigest = new ArrayList<>(); - private static final Multimap recipeDigestion = HashMultimap.create(); - private static final Multimap backwardsDigestion = HashMultimap.create(); - - private static final Object mutex = new Object(); - private static boolean needsCrawl = false; - private static boolean mayCrawl = false; - - @LoadEvent - public static void addListener(ZAddReloadListener event) { - event.addListener(new SimplePreparableReloadListener() { - @Override - protected Void prepare(ResourceManager mgr, ProfilerFiller prof) { - clear(); - return null; - } - - @Override - protected void apply(Void what, ResourceManager mgr, ProfilerFiller prof) { - needsCrawl = true; - } - }); - } - - @LoadEvent - public static void tagsHaveUpdated(ZTagsUpdated event) { - mayCrawl = true; - } - - private static void clear() { - mayCrawl = false; - Quark.ZETA.playBus.fire(new ZRecipeCrawl.Reset()); - } - - @SuppressWarnings("ConstantValue") // some nullchecks on stuff that is ostensibly non-null, but you never know with mods - private static void load(RecipeManager manager, RegistryAccess access) { - if(!manager.getRecipes().isEmpty()) { - Quark.ZETA.playBus.fire(new ZRecipeCrawl.Starting()); - - recipesToLazyDigest.clear(); - recipeDigestion.clear(); - backwardsDigestion.clear(); - - for(Recipe recipe : manager.getRecipes()) { - try { - if(recipe == null) - throw new IllegalStateException("Recipe is null"); - if(recipe.getIngredients() == null) - throw new IllegalStateException("Recipe ingredients are null"); - if(recipe.getResultItem(access) == null) - throw new IllegalStateException("Recipe getResultItem is null"); - - ZRecipeCrawl.Visit event; - if(recipe instanceof ShapedRecipe sr) - event = new ZRecipeCrawl.Visit.Shaped(sr, access); - else if(recipe instanceof ShapelessRecipe sr) - event = new ZRecipeCrawl.Visit.Shapeless(sr, access); - else if(recipe instanceof CustomRecipe cr) - event = new ZRecipeCrawl.Visit.Custom(cr, access); - else if(recipe instanceof AbstractCookingRecipe acr) - event = new ZRecipeCrawl.Visit.Cooking(acr, access); - else - event = new ZRecipeCrawl.Visit.Misc(recipe, access); - - recipesToLazyDigest.add(recipe); - Quark.ZETA.playBus.fire(event); - } catch (Exception e) { - if(recipe == null) - Quark.LOG.error("Encountered null recipe in RecipeManager.getRecipes. This is not good"); - else - Quark.LOG.error("Failed to scan recipe " + recipe.getId() + ". This should be reported to " + recipe.getId().getNamespace() + "!", e); - } - } - } - } - - @PlayEvent - public static void onTick(ZServerTick.Start tick) { - synchronized (mutex) { - if(mayCrawl && needsCrawl) { - RecipeManager manager = tick.getServer().getRecipeManager(); - RegistryAccess access = tick.getServer().registryAccess(); - load(manager, access); - needsCrawl = false; - } - - if(!recipesToLazyDigest.isEmpty()) { - recipeDigestion.clear(); - backwardsDigestion.clear(); - - for(Recipe recipe : recipesToLazyDigest) - digest(recipe, tick.getServer().registryAccess()); - - recipesToLazyDigest.clear(); - Quark.ZETA.playBus.fire(new ZRecipeCrawl.Digest(recipeDigestion, backwardsDigestion)); - } - } - } - - private static void digest(Recipe recipe, RegistryAccess access) { - ItemStack out = recipe.getResultItem(access); - Item outItem = out.getItem(); - - NonNullList ingredients = recipe.getIngredients(); - for(Ingredient ingredient : ingredients) { - for(ItemStack inStack : ingredient.getItems()) { - recipeDigestion.put(inStack.getItem(), out); - backwardsDigestion.put(outItem, inStack); - } - } - } - - /* - * Derivation list -> items to add and then derive (raw materials) - * Whitelist -> items to add and not derive from - * Blacklist -> items to ignore - */ - - public static void recursivelyFindCraftedItemsFromStrings(@Nullable Collection derivationList, @Nullable Collection whitelist, @Nullable Collection blacklist, Consumer callback) { - List parsedDerivationList = derivationList == null ? null : RegistryUtil.massRegistryGet(derivationList, BuiltInRegistries.ITEM); - List parsedWhitelist = whitelist == null ? null : RegistryUtil.massRegistryGet(whitelist, BuiltInRegistries.ITEM); - List parsedBlacklist = blacklist == null ? null : RegistryUtil.massRegistryGet(blacklist, BuiltInRegistries.ITEM); - - recursivelyFindCraftedItems(parsedDerivationList, parsedWhitelist, parsedBlacklist, callback); - } - - public static void recursivelyFindCraftedItems(@Nullable Collection derivationList, @Nullable Collection whitelist, @Nullable Collection blacklist, Consumer callback) { - Collection trueDerivationList = derivationList == null ? Lists.newArrayList() : derivationList; - Collection trueWhitelist = whitelist == null ? Lists.newArrayList() : whitelist; - Collection trueBlacklist = blacklist == null ? Lists.newArrayList() : blacklist; - - Streams.concat(trueDerivationList.stream(), trueWhitelist.stream()).forEach(callback); - - Set scanned = Sets.newHashSet(trueDerivationList); - List toScan = Lists.newArrayList(trueDerivationList); - - while(!toScan.isEmpty()) { - Item scan = toScan.remove(0); - - if(recipeDigestion.containsKey(scan)) { - for(ItemStack digestedStack : recipeDigestion.get(scan)) { - Item candidate = digestedStack.getItem(); - - if(!scanned.contains(candidate)) { - scanned.add(candidate); - toScan.add(candidate); - - if(!trueBlacklist.contains(candidate)) - callback.accept(candidate); - } - } - } - } - } - -} diff --git a/src/main/java/org/violetmoon/quark/base/handler/StructureBlockReplacementHandler.java b/src/main/java/org/violetmoon/quark/base/handler/StructureBlockReplacementHandler.java deleted file mode 100644 index 3b512fdd6d..0000000000 --- a/src/main/java/org/violetmoon/quark/base/handler/StructureBlockReplacementHandler.java +++ /dev/null @@ -1,100 +0,0 @@ -package org.violetmoon.quark.base.handler; - -import net.minecraft.core.Holder; -import net.minecraft.core.Registry; -import net.minecraft.core.registries.Registries; -import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.level.ServerLevelAccessor; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.levelgen.structure.Structure; -import net.minecraft.world.level.levelgen.structure.StructurePiece; -import net.minecraft.world.level.levelgen.structure.pieces.PiecesContainer; - -import org.jetbrains.annotations.Nullable; - -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; - -public class StructureBlockReplacementHandler { - - private static Set functions = new HashSet<>(); - - private static final ThreadLocal structureHolder = new ThreadLocal<>(); - - public static void addReplacement(StructureFunction func) { - functions.add(func); - } - - @Nullable - public static Holder getStructure(ServerLevelAccessor accessor, StructureHolder structure) { - Optional> registry = accessor.registryAccess().registry(Registries.STRUCTURE); - Optional> holder = registry - .flatMap((reg) -> reg.getResourceKey(structure.currentStructure).flatMap(reg::getHolder)); - - return holder.isEmpty() ? null : holder.get(); - } - - @Nullable - public static ResourceKey getStructureKey(ServerLevelAccessor accessor, StructureHolder structure) { - Optional> res = accessor.registryAccess().registry(Registries.STRUCTURE) - .flatMap((it) -> it.getResourceKey(structure.currentStructure)); - - return res.isEmpty() ? null : res.get(); - } - - @Nullable - public static ResourceLocation getStructureRes(ServerLevelAccessor accessor, StructureHolder structure) { - Optional res = accessor.registryAccess().registry(Registries.STRUCTURE) - .map((it) -> it.getKey(structure.currentStructure)); - - return res.isEmpty() ? null : res.get(); - } - - public static boolean isStructure(ServerLevelAccessor accessor, StructureHolder structure, ResourceKey target) { - ResourceKey curr = getStructureKey(accessor, structure); - return curr != null && curr.equals(target); - } - - public static BlockState getResultingBlockState(ServerLevelAccessor level, BlockState blockstate) { - StructureHolder curr = getCurrentStructureHolder(); - - if(curr != null && curr.currentStructure != null) - for(StructureFunction fun : functions) { - - BlockState res = fun.transformBlockstate(level, blockstate, curr); - if(res != null) - return res; - } - - return blockstate; - } - - private static StructureHolder getCurrentStructureHolder() { - return structureHolder.get(); - } - - public static void setActiveStructure(Structure structure, PiecesContainer components) { - StructureHolder curr = getCurrentStructureHolder(); - if(curr == null) { - curr = new StructureHolder(); - structureHolder.set(curr); - } - - curr.currentStructure = structure; - curr.currentComponents = components == null ? null : components.pieces(); - } - - @FunctionalInterface - public interface StructureFunction { - BlockState transformBlockstate(ServerLevelAccessor level, BlockState state, StructureHolder structureHolder); - } - - public static class StructureHolder { - public Structure currentStructure; - public List currentComponents; - } - -} diff --git a/src/main/java/org/violetmoon/quark/base/handler/ToolInteractionHandler.java b/src/main/java/org/violetmoon/quark/base/handler/ToolInteractionHandler.java deleted file mode 100644 index f331db442a..0000000000 --- a/src/main/java/org/violetmoon/quark/base/handler/ToolInteractionHandler.java +++ /dev/null @@ -1,130 +0,0 @@ -package org.violetmoon.quark.base.handler; - -import com.google.common.collect.HashBiMap; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.Multimap; - -import net.minecraft.advancements.CriteriaTriggers; -import net.minecraft.core.BlockPos; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.InteractionResult; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.Items; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.LevelEvent; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.properties.Property; -import net.minecraftforge.common.ToolAction; -import net.minecraftforge.common.ToolActions; - -import org.apache.commons.lang3.tuple.Pair; - -import org.violetmoon.zeta.advancement.modifier.WaxModifier; -import org.violetmoon.zeta.event.bus.LoadEvent; -import org.violetmoon.zeta.event.bus.PlayEvent; -import org.violetmoon.zeta.event.load.ZCommonSetup; -import org.violetmoon.zeta.event.play.ZBlock; -import org.violetmoon.zeta.event.play.entity.player.ZRightClickBlock; -import org.violetmoon.zeta.module.ZetaModule; - -import java.util.*; - -public final class ToolInteractionHandler { - - private static final Map cleanToWaxMap = HashBiMap.create(); - private static final Map> interactionMaps = new HashMap<>(); - - private static final Multimap> waxingByModule = HashMultimap.create(); - - public static void registerWaxedBlock(ZetaModule module, Block clean, Block waxed) { - cleanToWaxMap.put(clean, waxed); - registerInteraction(ToolActions.AXE_WAX_OFF, waxed, clean); - - waxingByModule.put(module, Pair.of(clean, waxed)); - } - - public static void registerInteraction(ToolAction action, Block in, Block out) { - if(!interactionMaps.containsKey(action)) - interactionMaps.put(action, new HashMap<>()); - - Map map = interactionMaps.get(action); - map.put(in, out); - } - - @LoadEvent - public static void addModifiers(ZCommonSetup event) { - event.enqueueWork(() -> { - for(ZetaModule module : waxingByModule.keySet()) { - Collection> pairs = waxingByModule.get(module); - Set unwaxed = new HashSet<>(); - Set waxed = new HashSet<>(); - - for(Pair pair : pairs) { - unwaxed.add(pair.getLeft()); - waxed.add(pair.getRight()); - } - - //TODO: what - module.zeta.advancementModifierRegistry.addModifier(new WaxModifier(module, unwaxed, waxed)); - } - }); - } - - @PlayEvent - public static void toolActionEvent(ZBlock.BlockToolModification event) { - ToolAction action = event.getToolAction(); - - if(interactionMaps.containsKey(action)) { - Map map = interactionMaps.get(action); - BlockState state = event.getState(); - Block block = state.getBlock(); - - if(map.containsKey(block)) { - Block finalBlock = map.get(block); - event.setFinalState(copyState(state, finalBlock)); - } - } - } - - @PlayEvent - public static void itemUse(ZRightClickBlock event) { - ItemStack stack = event.getItemStack(); - - if(stack.getItem() == Items.HONEYCOMB) { - BlockPos pos = event.getPos(); - Level world = event.getLevel(); - BlockState state = world.getBlockState(pos); - Block block = state.getBlock(); - - if(cleanToWaxMap.containsKey(block)) { - Block alternate = cleanToWaxMap.get(block); - - if(event.getEntity() instanceof ServerPlayer sp) - CriteriaTriggers.ITEM_USED_ON_BLOCK.trigger(sp, pos, stack); - - if(!world.isClientSide) - world.setBlockAndUpdate(pos, copyState(state, alternate)); - world.levelEvent(event.getPlayer(), LevelEvent.PARTICLES_AND_SOUND_WAX_ON, pos, 0); - - if(!event.getPlayer().getAbilities().instabuild) - stack.setCount(stack.getCount() - 1); - - event.setCanceled(true); - event.setCancellationResult(InteractionResult.SUCCESS); - } - } - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - private static BlockState copyState(BlockState original, Block newBlock) { - BlockState retState = newBlock.defaultBlockState(); - for(Property prop : original.getProperties()) - if(retState.hasProperty(prop)) - retState = retState.setValue(prop, original.getValue(prop)); - - return retState; - - } - -} diff --git a/src/main/java/org/violetmoon/quark/base/proxy/CommonProxy.java b/src/main/java/org/violetmoon/quark/base/proxy/CommonProxy.java index 00e5a8d65e..cfda570b96 100644 --- a/src/main/java/org/violetmoon/quark/base/proxy/CommonProxy.java +++ b/src/main/java/org/violetmoon/quark/base/proxy/CommonProxy.java @@ -63,10 +63,7 @@ public void start() { Quark.ZETA.loadBus .subscribe(ContributorRewardHandler.class) .subscribe(EntitySpawnHandler.class) - .subscribe(FuelHandler.class) .subscribe(QuarkSounds.class) - .subscribe(RecipeCrawlHandler.class) - .subscribe(ToolInteractionHandler.class) .subscribe(WoodSetHandler.class) .subscribe(WorldGenHandler.class) .subscribe(this); @@ -74,12 +71,8 @@ public void start() { Quark.ZETA.playBus .subscribe(CapabilityHandler.class) .subscribe(ContributorRewardHandler.class) - .subscribe(FuelHandler.class) - .subscribe(RecipeCrawlHandler.class) .subscribe(SyncedFlagHandler.class) - .subscribe(ToolInteractionHandler.class); - MinecraftForge.EVENT_BUS.register(ToolInteractionHandler.class); IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus(); bus.addListener(this::configChanged); WorldGenHandler.registerBiomeModifier(bus); diff --git a/src/main/java/org/violetmoon/quark/mixin/mixins/StructurePieceMixin.java b/src/main/java/org/violetmoon/quark/mixin/mixins/StructurePieceMixin.java deleted file mode 100644 index ea2683910f..0000000000 --- a/src/main/java/org/violetmoon/quark/mixin/mixins/StructurePieceMixin.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.violetmoon.quark.mixin.mixins; - -import net.minecraft.world.level.ServerLevelAccessor; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.levelgen.structure.StructurePiece; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.ModifyVariable; - -import org.violetmoon.quark.base.handler.StructureBlockReplacementHandler; - -@Mixin(StructurePiece.class) -public class StructurePieceMixin { - - @ModifyVariable( - method = "createChest(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/level/levelgen/structure/BoundingBox;Lnet/minecraft/util/RandomSource;Lnet/minecraft/core/BlockPos;Lnet/minecraft/resources/ResourceLocation;Lnet/minecraft/world/level/block/state/BlockState;)Z", - at = @At( - value = "INVOKE", target = "Lnet/minecraft/world/level/ServerLevelAccessor;setBlock(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;I)Z", - shift = At.Shift.BY, by = -2 - ), - argsOnly = true - ) - protected BlockState modifyBlockstateForChest(BlockState state, ServerLevelAccessor accessor) { - return StructureBlockReplacementHandler.getResultingBlockState(accessor, state); - } - - @ModifyVariable( - method = "placeBlock(Lnet/minecraft/world/level/WorldGenLevel;Lnet/minecraft/world/level/block/state/BlockState;IIILnet/minecraft/world/level/levelgen/structure/BoundingBox;)V", - at = @At( - value = "INVOKE", target = "Lnet/minecraft/world/level/WorldGenLevel;setBlock(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;I)Z", - shift = At.Shift.BY, by = -2 - ), - argsOnly = true - ) - protected BlockState modifyBlockstate(BlockState state, WorldGenLevel level) { - return StructureBlockReplacementHandler.getResultingBlockState(level, state); - } - -} diff --git a/src/main/java/org/violetmoon/quark/mixin/mixins/StructureStartMixin.java b/src/main/java/org/violetmoon/quark/mixin/mixins/StructureStartMixin.java deleted file mode 100644 index 994ea255d9..0000000000 --- a/src/main/java/org/violetmoon/quark/mixin/mixins/StructureStartMixin.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.violetmoon.quark.mixin.mixins; - -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.ChunkPos; -import net.minecraft.world.level.StructureManager; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.chunk.ChunkGenerator; -import net.minecraft.world.level.levelgen.structure.BoundingBox; -import net.minecraft.world.level.levelgen.structure.Structure; -import net.minecraft.world.level.levelgen.structure.StructureStart; -import net.minecraft.world.level.levelgen.structure.pieces.PiecesContainer; - -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import org.violetmoon.quark.base.handler.StructureBlockReplacementHandler; - -@Mixin(StructureStart.class) -public class StructureStartMixin { - - @Shadow - @Final - private PiecesContainer pieceContainer; - - @Shadow - @Final - private Structure structure; - - @Inject(method = "placeInChunk", at = @At("HEAD")) - public void injectReference(WorldGenLevel level, StructureManager manager, ChunkGenerator generator, RandomSource random, BoundingBox bounds, ChunkPos pos, CallbackInfo callback) { - StructureBlockReplacementHandler.setActiveStructure(structure, pieceContainer); - } - - @Inject(method = "placeInChunk", at = @At("RETURN")) - public void resetReference(WorldGenLevel level, StructureManager manager, ChunkGenerator generator, RandomSource random, BoundingBox bounds, ChunkPos pos, CallbackInfo callback) { - StructureBlockReplacementHandler.setActiveStructure(null, null); - } - -} diff --git a/src/main/java/org/violetmoon/quark/mixin/mixins/StructureTemplateMixin.java b/src/main/java/org/violetmoon/quark/mixin/mixins/StructureTemplateMixin.java deleted file mode 100644 index 8f5421fb0b..0000000000 --- a/src/main/java/org/violetmoon/quark/mixin/mixins/StructureTemplateMixin.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.violetmoon.quark.mixin.mixins; - -import net.minecraft.world.level.ServerLevelAccessor; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.ModifyVariable; - -import org.violetmoon.quark.base.handler.StructureBlockReplacementHandler; - -@Mixin(StructureTemplate.class) -public class StructureTemplateMixin { - - @ModifyVariable( - method = "placeInWorld(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/core/BlockPos;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/levelgen/structure/templatesystem/StructurePlaceSettings;Lnet/minecraft/util/RandomSource;I)Z", - at = @At(value = "FIELD", target = "Lnet/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplate$StructureBlockInfo;nbt:Lnet/minecraft/nbt/CompoundTag;", ordinal = 0), - index = 22 - ) - private BlockState captureLocalBlockstate(BlockState state, ServerLevelAccessor accessor) { - return StructureBlockReplacementHandler.getResultingBlockState(accessor, state); - } -} diff --git a/src/main/resources/quark.mixins.json b/src/main/resources/quark.mixins.json index d627baa036..9e983751d5 100644 --- a/src/main/resources/quark.mixins.json +++ b/src/main/resources/quark.mixins.json @@ -62,9 +62,6 @@ "SpawnerBlockEntityMixin", "SpongeBlockMixin", "SpringFeatureMixin", - "StructurePieceMixin", - "StructureStartMixin", - "StructureTemplateMixin", "TemptGoalMixin", "TemptingSensorMixin", "TripWireHookBlockMixin",