diff --git a/src/main/java/org/violetmoon/zeta/Zeta.java b/src/main/java/org/violetmoon/zeta/Zeta.java index 1a147e7..2d87485 100644 --- a/src/main/java/org/violetmoon/zeta/Zeta.java +++ b/src/main/java/org/violetmoon/zeta/Zeta.java @@ -1,7 +1,10 @@ package org.violetmoon.zeta; -import java.util.function.Supplier; - +import com.google.common.base.Stopwatch; +import net.minecraft.core.BlockPos; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.phys.BlockHitResult; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.Nullable; @@ -13,21 +16,13 @@ import org.violetmoon.zeta.config.SectionDefinition; import org.violetmoon.zeta.event.bus.IZetaLoadEvent; import org.violetmoon.zeta.event.bus.IZetaPlayEvent; -import org.violetmoon.zeta.event.bus.LoadEvent; -import org.violetmoon.zeta.event.bus.PlayEvent; import org.violetmoon.zeta.event.bus.ZetaEventBus; import org.violetmoon.zeta.item.ext.ItemExtensionFactory; import org.violetmoon.zeta.module.ModuleFinder; import org.violetmoon.zeta.module.ZetaCategory; import org.violetmoon.zeta.module.ZetaModuleManager; import org.violetmoon.zeta.network.ZetaNetworkHandler; -import org.violetmoon.zeta.registry.BrewingRegistry; -import org.violetmoon.zeta.registry.CraftingExtensionsRegistry; -import org.violetmoon.zeta.registry.DyeablesRegistry; -import org.violetmoon.zeta.registry.PottedPlantRegistry; -import org.violetmoon.zeta.registry.RenderLayerRegistry; -import org.violetmoon.zeta.registry.VariantRegistry; -import org.violetmoon.zeta.registry.ZetaRegistry; +import org.violetmoon.zeta.registry.*; import org.violetmoon.zeta.util.NameChanger; import org.violetmoon.zeta.util.RaytracingUtil; import org.violetmoon.zeta.util.RegistryUtil; @@ -38,179 +33,196 @@ import org.violetmoon.zeta.util.zetalist.ZetaList; import org.violetmoon.zeta.world.EntitySpawnHandler; -import net.minecraft.core.BlockPos; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.phys.BlockHitResult; +import java.util.function.Supplier; /** * do not touch forge OR quark from this package, it will later be split off */ public abstract class Zeta implements IZeta { - - public static final String ZETA_ID = "zeta"; - public static final Logger GLOBAL_LOG = LogManager.getLogger(ZETA_ID); - - public Zeta(String modid, Logger log, ZetaSide side) { - this.log = log; - - this.modid = modid; - this.side = side; - this.loadBus = new ZetaEventBus<>(this, LoadEvent.class, IZetaLoadEvent.class, log); - this.playBus = new ZetaEventBus<>(this, PlayEvent.class, IZetaPlayEvent.class, null); - - this.modules = createModuleManager(); - this.registry = createRegistry(); - this.renderLayerRegistry = createRenderLayerRegistry(); - this.dyeables = createDyeablesRegistry(); - this.craftingExtensions = createCraftingExtensionsRegistry(); - this.brewingRegistry = createBrewingRegistry(); - this.advancementModifierRegistry = createAdvancementModifierRegistry(); - this.pottedPlantRegistry = createPottedPlantRegistry(); - - this.blockExtensions = createBlockExtensionFactory(); - this.itemExtensions = createItemExtensionFactory(); - this.capabilityManager = createCapabilityManager(); - - this.raytracingUtil = createRaytracingUtil(); - this.nameChanger = createNameChanger(); - this.fuel = createFuelHandler(); - - this.entitySpawn = createEntitySpawnHandler(); - - loadBus.subscribe(craftingExtensions) - .subscribe(dyeables) - .subscribe(brewingRegistry) - .subscribe(advancementModifierRegistry) - .subscribe(fuel) - .subscribe(entitySpawn); - - playBus.subscribe(fuel); - - ZetaList.INSTANCE.register(this); - } - - //core - public final Logger log; - public final String modid; - public final ZetaSide side; - public final ZetaEventBus loadBus; - public final ZetaEventBus playBus; - public final ZetaModuleManager modules; - - //registry - public final ZetaRegistry registry; - public final RegistryUtil registryUtil = new RegistryUtil(this); //TODO: Delete this, only needed cause there's no way to get early registry names. - public final RenderLayerRegistry renderLayerRegistry; - public final DyeablesRegistry dyeables; - public final CraftingExtensionsRegistry craftingExtensions; - public final BrewingRegistry brewingRegistry; - public final AdvancementModifierRegistry advancementModifierRegistry; - public final PottedPlantRegistry pottedPlantRegistry; - public final RequiredModTooltipHandler requiredModTooltipHandler = new RequiredModTooltipHandler(); //TODO, find better spot or remove this. - public final VariantRegistry variantRegistry = new VariantRegistry(this); - - //extensions - public final ZetaCapabilityManager capabilityManager; - public final BlockExtensionFactory blockExtensions; - public final ItemExtensionFactory itemExtensions; - - //misc :tada: - public final RaytracingUtil raytracingUtil; - public final NameChanger nameChanger; - public final FuelHandler fuel; - - //config (which isn't set in the constructor b/c module loading has to happen first) - public ConfigManager configManager; - public IZetaConfigInternals configInternals; - - //network (which isn't set in the constructor b/c it has a user-specified protocol version TODO this isnt good api design, imo) - public ZetaNetworkHandler network; - - // worldgen - public EntitySpawnHandler entitySpawn; - - /** - * @param categories List of module categories in this mod, if null, will not load Modules but still load general config - * @param finder Module finder instance to locate the modules this Zeta will load, if null, will not load Modules but still load general config - * @param rootPojo General config object root - */ - public void loadModules(@Nullable Iterable categories, @Nullable ModuleFinder finder, Object rootPojo) { - if(categories != null && finder != null) { - modules.initCategories(categories); - modules.load(finder); - } - - //The reason why there's a circular dependency between configManager and configInternals: - // - ConfigManager determines the shape and layout of the config file - // - The platform-specific configInternals loads the actual values, from the platform-specfic config file - // - Only then can ConfigManager do the initial config load - - this.configManager = new ConfigManager(this, rootPojo); - this.configInternals = makeConfigInternals(configManager.getRootConfig()); - this.configManager.onReload(); - } - - // modloader services - public abstract boolean isModLoaded(String modid); - public abstract @Nullable String getModDisplayName(String modid); - public T modIntegration(String compatWith, Supplier> yes, Supplier> no) { - try { - return (isModLoaded(compatWith) ? yes : no).get().get(); - } catch (Exception e) { - throw new RuntimeException("Zeta: " + modid + " threw exception initializing compat with " + compatWith, e); - } - } - - // config - public abstract IZetaConfigInternals makeConfigInternals(SectionDefinition rootSection); - - // general xplat stuff - public ZetaModuleManager createModuleManager() { - return new ZetaModuleManager(this); - } - public abstract ZetaRegistry createRegistry(); - public RenderLayerRegistry createRenderLayerRegistry() { - return new RenderLayerRegistry(); - } - public abstract CraftingExtensionsRegistry createCraftingExtensionsRegistry(); - public DyeablesRegistry createDyeablesRegistry() { - return new DyeablesRegistry(); - } - public abstract BrewingRegistry createBrewingRegistry(); - public AdvancementModifierRegistry createAdvancementModifierRegistry() { - return new AdvancementModifierRegistry(this); - } - public abstract PottedPlantRegistry createPottedPlantRegistry(); - public abstract ZetaCapabilityManager createCapabilityManager(); - public BlockExtensionFactory createBlockExtensionFactory() { - return BlockExtensionFactory.DEFAULT; - } - public abstract ItemExtensionFactory createItemExtensionFactory(); - public abstract RaytracingUtil createRaytracingUtil(); - public NameChanger createNameChanger() { - return new NameChanger(); - } - public FuelHandler createFuelHandler() { - return new FuelHandler(this); - } - public EntitySpawnHandler createEntitySpawnHandler() { - return new EntitySpawnHandler(this); - } - - public abstract ZetaNetworkHandler createNetworkHandler(int protocolVersion); - - // event bus - public abstract T fireExternalEvent(T impl); - - // ummmmmm why is this here - public abstract boolean fireRightClickBlock(Player player, InteractionHand hand, BlockPos pos, BlockHitResult bhr); - - // Let's Jump - public abstract void start(); - - @Override - public Zeta asZeta() { - return this; - } + + public Zeta(String modid, Logger log, ZetaSide side, boolean isProduction) { + this.log = log; + + this.modid = modid; + this.side = side; + this.isProduction = isProduction; + + + this.modules = createModuleManager(); + this.registry = createRegistry(); + this.renderLayerRegistry = createRenderLayerRegistry(); + this.dyeables = createDyeablesRegistry(); + this.craftingExtensions = createCraftingExtensionsRegistry(); + this.brewingRegistry = createBrewingRegistry(); + this.advancementModifierRegistry = createAdvancementModifierRegistry(); + this.pottedPlantRegistry = createPottedPlantRegistry(); + + this.blockExtensions = createBlockExtensionFactory(); + this.itemExtensions = createItemExtensionFactory(); + this.capabilityManager = createCapabilityManager(); + + this.raytracingUtil = createRaytracingUtil(); + this.nameChanger = createNameChanger(); + this.fuel = createFuelHandler(); + + this.entitySpawn = createEntitySpawnHandler(); + + Stopwatch stopwatch = Stopwatch.createStarted(); + this.loadBus = this.createLoadBus(); + this.playBus = this.createPlayBus(); + long elapsed = stopwatch.stop().elapsed().toMillis(); + + ZetaList.INSTANCE.register(this); + } + + //core + public final Logger log; + public final String modid; + public final ZetaSide side; + public final boolean isProduction; + public final ZetaEventBus loadBus; + public final ZetaEventBus playBus; + public final ZetaModuleManager modules; + + //registry + public final ZetaRegistry registry; + public final RegistryUtil registryUtil = new RegistryUtil(this); //TODO: Delete this, only needed cause there's no way to get early registry names. + public final RenderLayerRegistry renderLayerRegistry; + public final DyeablesRegistry dyeables; + public final CraftingExtensionsRegistry craftingExtensions; + public final BrewingRegistry brewingRegistry; + public final AdvancementModifierRegistry advancementModifierRegistry; + public final PottedPlantRegistry pottedPlantRegistry; + public final RequiredModTooltipHandler requiredModTooltipHandler = new RequiredModTooltipHandler(); //TODO, find better spot or remove this. + public final VariantRegistry variantRegistry = new VariantRegistry(this); + + //extensions + public final ZetaCapabilityManager capabilityManager; + public final BlockExtensionFactory blockExtensions; + public final ItemExtensionFactory itemExtensions; + + //misc :tada: + public final RaytracingUtil raytracingUtil; + public final NameChanger nameChanger; + public final FuelHandler fuel; + + //config (which isn't set in the constructor b/c module loading has to happen first) + public ConfigManager configManager; + public IZetaConfigInternals configInternals; + + //network (which isn't set in the constructor b/c it has a user-specified protocol version TODO this isnt good api design, imo) + public ZetaNetworkHandler network; + + // worldgen + public EntitySpawnHandler entitySpawn; + + protected abstract ZetaEventBus createPlayBus(); + + protected abstract ZetaEventBus createLoadBus(); + + /** + * @param categories List of module categories in this mod, if null, will not load Modules but still load general config + * @param finder Module finder instance to locate the modules this Zeta will load, if null, will not load Modules but still load general config + * @param rootPojo General config object root + */ + public void loadModules(@Nullable Iterable categories, @Nullable ModuleFinder finder, Object rootPojo) { + if (categories != null && finder != null) { + modules.initCategories(categories); + modules.load(finder); + } + + //The reason why there's a circular dependency between configManager and configInternals: + // - ConfigManager determines the shape and layout of the config file + // - The platform-specific configInternals loads the actual values, from the platform-specfic config file + // - Only then can ConfigManager do the initial config load + + this.configManager = new ConfigManager(this, rootPojo); + this.configInternals = makeConfigInternals(configManager.getRootConfig()); + this.configManager.onReload(); + } + + // modloader services + public abstract boolean isModLoaded(String modid); + + public abstract @Nullable String getModDisplayName(String modid); + + public T modIntegration(String compatWith, Supplier> yes, Supplier> no) { + try { + return (isModLoaded(compatWith) ? yes : no).get().get(); + } catch (Exception e) { + throw new RuntimeException("Zeta: " + modid + " threw exception initializing compat with " + compatWith, e); + } + } + + // config + public abstract IZetaConfigInternals makeConfigInternals(SectionDefinition rootSection); + + // general xplat stuff + public ZetaModuleManager createModuleManager() { + return new ZetaModuleManager(this); + } + + public abstract ZetaRegistry createRegistry(); + + public RenderLayerRegistry createRenderLayerRegistry() { + return new RenderLayerRegistry(); + } + + public abstract CraftingExtensionsRegistry createCraftingExtensionsRegistry(); + + public DyeablesRegistry createDyeablesRegistry() { + return new DyeablesRegistry(); + } + + public abstract BrewingRegistry createBrewingRegistry(); + + public AdvancementModifierRegistry createAdvancementModifierRegistry() { + return new AdvancementModifierRegistry(this); + } + + public abstract PottedPlantRegistry createPottedPlantRegistry(); + + public abstract ZetaCapabilityManager createCapabilityManager(); + + public BlockExtensionFactory createBlockExtensionFactory() { + return BlockExtensionFactory.DEFAULT; + } + + public abstract ItemExtensionFactory createItemExtensionFactory(); + + public abstract RaytracingUtil createRaytracingUtil(); + + public NameChanger createNameChanger() { + return new NameChanger(); + } + + public FuelHandler createFuelHandler() { + return new FuelHandler(this); + } + + public EntitySpawnHandler createEntitySpawnHandler() { + return new EntitySpawnHandler(this); + } + + public abstract ZetaNetworkHandler createNetworkHandler(int protocolVersion); + + // ummmmmm why is this here?? + public abstract boolean fireRightClickBlock(Player player, InteractionHand hand, BlockPos pos, BlockHitResult bhr); + + // Let's Jump + public void start(){ + loadBus.subscribe(craftingExtensions) + .subscribe(dyeables) + .subscribe(brewingRegistry) + .subscribe(fuel) + .subscribe(entitySpawn); + + playBus.subscribe(fuel) + .subscribe(advancementModifierRegistry); + } + + @Override + public Zeta asZeta() { + return this; + } } diff --git a/src/main/java/org/violetmoon/zeta/advancement/AdvancementModifierRegistry.java b/src/main/java/org/violetmoon/zeta/advancement/AdvancementModifierRegistry.java index 8c63bff..4c4df9f 100644 --- a/src/main/java/org/violetmoon/zeta/advancement/AdvancementModifierRegistry.java +++ b/src/main/java/org/violetmoon/zeta/advancement/AdvancementModifierRegistry.java @@ -17,7 +17,9 @@ import org.violetmoon.zeta.advancement.modifier.WaxModifier; import org.violetmoon.zeta.api.IAdvancementModifier; import org.violetmoon.zeta.api.IAdvancementModifierDelegate; +import org.violetmoon.zeta.client.event.play.ZScreen; 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.ZGatherAdvancementModifiers; @@ -36,7 +38,10 @@ import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.block.Block; +import org.violetmoon.zetaimplforge.api.ForgeZGatherAdvancementModifiers; +import org.violetmoon.zetaimplforge.client.event.play.ForgeZEarlyRender; +//TODO: make this zeta-independent public class AdvancementModifierRegistry { protected final Zeta zeta; protected final Multimap modifiers = HashMultimap.create(); @@ -59,11 +64,11 @@ public void addModifier(IAdvancementModifier mod) { modifiers.put(r, mod); } - @LoadEvent + @PlayEvent public void addListeners(ZAddReloadListener event) { if(!gatheredAddons) { IAdvancementModifierDelegate delegateImpl = new DelegateImpl(); - zeta.loadBus.fireExternal(new ZGatherAdvancementModifiers() { + zeta.loadBus.fire(new ZGatherAdvancementModifiers() { @Override public void register(IAdvancementModifier modifier) { addModifier(modifier); diff --git a/src/main/java/org/violetmoon/zeta/client/ClientRegistryExtension.java b/src/main/java/org/violetmoon/zeta/client/ClientRegistryExtension.java index 660f0a6..09e866f 100644 --- a/src/main/java/org/violetmoon/zeta/client/ClientRegistryExtension.java +++ b/src/main/java/org/violetmoon/zeta/client/ClientRegistryExtension.java @@ -9,6 +9,7 @@ import org.violetmoon.zeta.client.event.load.ZAddItemColorHandlers; import org.violetmoon.zeta.client.event.load.ZClientSetup; import org.violetmoon.zeta.event.bus.LoadEvent; +import org.violetmoon.zeta.event.load.ZLoadComplete; import org.violetmoon.zeta.registry.DyeablesRegistry; import org.violetmoon.zeta.registry.RenderLayerRegistry; import org.violetmoon.zeta.registry.ZetaRegistry; @@ -56,32 +57,16 @@ public void registerItemColorHandlers(ZAddItemColorHandlers event) { } } - //these are in Post events to give other listeners a chance to populate .registerNamed @LoadEvent - public void registerBlockColorsPost(ZAddBlockColorHandlers.Post event) { - registry.finalizeBlockColors((block, name) -> { - Function blockColorCreator = event.getNamedBlockColors().get(name); - if(blockColorCreator == null) - z.log.error("Unknown block color creator {} used on block {}", name, block); - else - event.register(blockColorCreator.apply(block), block); - }); + public void registerRenderLayers(ZClientSetup event) { + z.renderLayerRegistry.finalize(this::doSetRenderLayer); } - @LoadEvent - public void registerItemColorsPost(ZAddItemColorHandlers.Post event) { - registry.finalizeItemColors((item, name) -> { - Function itemColorCreator = event.getNamedItemColors().get(name); - if(itemColorCreator == null) - z.log.error("Unknown item color creator {} used on item {}", name, item); - else - event.register(itemColorCreator.apply(item), item); - }); - } + //I hope this won't run on dedicated servers @LoadEvent - public void registerRenderLayers(ZClientSetup event) { - z.renderLayerRegistry.finalize(this::doSetRenderLayer); + public void onLoadComplete(ZLoadComplete event){ + z.registry.validateColorsProviders(); } protected abstract void doSetRenderLayer(Block block, RenderLayerRegistry.Layer layer); diff --git a/src/main/java/org/violetmoon/zeta/client/ClientTicker.java b/src/main/java/org/violetmoon/zeta/client/ClientTicker.java index cb28ee2..b3a3d42 100644 --- a/src/main/java/org/violetmoon/zeta/client/ClientTicker.java +++ b/src/main/java/org/violetmoon/zeta/client/ClientTicker.java @@ -1,44 +1,46 @@ package org.violetmoon.zeta.client; +import net.minecraft.client.Minecraft; +import org.jetbrains.annotations.ApiStatus; import org.violetmoon.zeta.client.event.play.ZClientTick; +import org.violetmoon.zeta.client.event.play.ZRenderGuiOverlay; import org.violetmoon.zeta.client.event.play.ZRenderTick; import org.violetmoon.zeta.event.bus.PlayEvent; -import org.violetmoon.zeta.event.bus.ZPhase; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.screens.Screen; +//TODO: 1.21. replace with minecraft own ticker. Tbh this is legacy already and should be replaced with Minecraft.getPartialTicks() +@Deprecated public final class ClientTicker { - public int ticksInGame = 0; - public float partialTicks = 0; - public float delta = 0; - public float total = 0; - - @PlayEvent - public void onRenderTick(ZRenderTick event) { - if(event.isStartPhase()) - partialTicks = event.getRenderTickTime(); - else - endRenderTick(); - } - - @PlayEvent - public void onEndClientTick(ZClientTick event) { - if(event.getPhase() != ZPhase.END) - return; - - Screen gui = Minecraft.getInstance().screen; - if(gui == null || !gui.isPauseScreen()) { - ticksInGame++; - partialTicks = 0; - } - - endRenderTick(); - } - - public void endRenderTick() { - float oldTotal = total; - total = ticksInGame + partialTicks; - delta = total - oldTotal; - } + + //no need to have more than 1 instance of this class. Ticks are always the same + public static final ClientTicker INSTANCE = new ClientTicker(); + + private ClientTicker() { + } + + public float partialTicks = 0; + public float delta = 0; + public float total = 0; + + public int ticksInGame = 0; + + @ApiStatus.Internal + @PlayEvent + public void onRenderTick(ZRenderTick.Start event) { + partialTicks = Minecraft.getInstance().getPartialTick(); + delta = Minecraft.getInstance().getDeltaFrameTime(); + total = ticksInGame + partialTicks; + } + + @ApiStatus.Internal + @PlayEvent + public void onEndClientTick(ZClientTick.End event) { + if (!Minecraft.getInstance().isPaused()) { + ticksInGame++; + } + } + + @PlayEvent + public void pre(ZRenderGuiOverlay.ChatPanel.Pre event) { + int aa = 1; + } } diff --git a/src/main/java/org/violetmoon/zeta/client/TopLayerTooltipHandler.java b/src/main/java/org/violetmoon/zeta/client/TopLayerTooltipHandler.java deleted file mode 100644 index c590f35..0000000 --- a/src/main/java/org/violetmoon/zeta/client/TopLayerTooltipHandler.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.violetmoon.zeta.client; - -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -import org.joml.Matrix4f; -import org.violetmoon.zeta.client.event.play.ZRenderTick; -import org.violetmoon.zeta.event.bus.PlayEvent; - -import com.mojang.blaze3d.platform.Window; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.VertexSorting; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.Component; - -@Deprecated // Very hacky for what it does. -public class TopLayerTooltipHandler { - - private List tooltip; - private int tooltipX, tooltipY; - - @PlayEvent - public void renderTick(ZRenderTick event) { - if(tooltip != null && event.isEndPhase()) { - Minecraft mc = Minecraft.getInstance(); - Screen screen = mc.screen; - - Matrix4f projectionMatrix = RenderSystem.getProjectionMatrix(); - VertexSorting vertexSorting = RenderSystem.getVertexSorting(); - - // Set correct projection matrix - Window window = mc.getWindow(); - Matrix4f matrix4f = new Matrix4f().setOrtho( - 0.0F, - (float) ((double) window.getWidth() / window.getGuiScale()), - (float) ((double) window.getHeight() / window.getGuiScale()), - 0.0F, - 1000.0F, - net.minecraftforge.client.ForgeHooksClient.getGuiFarPlane() - ); - RenderSystem.setProjectionMatrix(matrix4f, VertexSorting.ORTHOGRAPHIC_Z); - PoseStack posestack = RenderSystem.getModelViewStack(); - posestack.pushPose(); - posestack.setIdentity(); - posestack.translate(0.0D, 0.0D, 1000F - net.minecraftforge.client.ForgeHooksClient.getGuiFarPlane()); - RenderSystem.applyModelViewMatrix(); - // End - - GuiGraphics guiGraphics = new GuiGraphics(mc, mc.renderBuffers().bufferSource()); - - if(screen != null) - guiGraphics.renderTooltip(mc.font, tooltip, Optional.empty(), tooltipX, tooltipY); - - // Reset projection matrix - guiGraphics.flush(); - posestack.popPose(); - RenderSystem.applyModelViewMatrix(); - RenderSystem.setProjectionMatrix(projectionMatrix, vertexSorting); - // End - - tooltip = null; - } - } - - public void setTooltip(List tooltip, int x, int y) { - this.tooltip = tooltip.stream().map(Component::literal).collect(Collectors.toList()); - this.tooltipX = x; - this.tooltipY = y; - } - -} diff --git a/src/main/java/org/violetmoon/zeta/client/ZetaClient.java b/src/main/java/org/violetmoon/zeta/client/ZetaClient.java index 83a6328..e0f03a6 100644 --- a/src/main/java/org/violetmoon/zeta/client/ZetaClient.java +++ b/src/main/java/org/violetmoon/zeta/client/ZetaClient.java @@ -23,22 +23,18 @@ import net.minecraft.world.level.block.Block; public abstract class ZetaClient implements IZeta { + public ZetaClient(Zeta zeta) { this.zeta = zeta; this.loadBus = zeta.loadBus; this.playBus = zeta.playBus; - this.ticker = createClientTicker(); this.clientConfigManager = createClientConfigManager(); - this.topLayerTooltipHandler = createTopLayerTooltipHandler(); this.clientRegistryExtension = createClientRegistryExtension(); loadBus.subscribe(clientRegistryExtension) .subscribe(clientConfigManager); - playBus.subscribe(ticker) - .subscribe(topLayerTooltipHandler); - ZetaClientList.INSTANCE.register(this); } @@ -48,23 +44,13 @@ public ZetaClient(Zeta zeta) { public ResourceLocation generalIcons = new ResourceLocation("zeta", "textures/gui/general_icons.png"); - public final ClientTicker ticker; public final ClientConfigManager clientConfigManager; - public final TopLayerTooltipHandler topLayerTooltipHandler; public final ClientRegistryExtension clientRegistryExtension; - public ClientTicker createClientTicker() { - return new ClientTicker(); - } - public ClientConfigManager createClientConfigManager() { return new ClientConfigManager(this); } - public TopLayerTooltipHandler createTopLayerTooltipHandler() { - return new TopLayerTooltipHandler(); - } - //ummm ?? public void sendToServer(IZetaMessage msg) { if(Minecraft.getInstance().getConnection() == null) @@ -87,8 +73,6 @@ public void sendToServer(IZetaMessage msg) { // The name is unwieldy on purpose, usages of this function should stick out. public abstract @Nullable RegistryAccess hackilyGetCurrentClientLevelRegistryAccess(); - public abstract void start(); - @Override public Zeta asZeta() { return zeta; diff --git a/src/main/java/org/violetmoon/zeta/client/event/load/ZAddBlockColorHandlers.java b/src/main/java/org/violetmoon/zeta/client/event/load/ZAddBlockColorHandlers.java index 5a7febc..1d75b70 100644 --- a/src/main/java/org/violetmoon/zeta/client/event/load/ZAddBlockColorHandlers.java +++ b/src/main/java/org/violetmoon/zeta/client/event/load/ZAddBlockColorHandlers.java @@ -3,6 +3,7 @@ import java.util.Map; import java.util.function.Function; +import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.event.bus.IZetaLoadEvent; import net.minecraft.client.color.block.BlockColor; @@ -11,11 +12,6 @@ public interface ZAddBlockColorHandlers extends IZetaLoadEvent { void register(BlockColor c, Block... blocks); - void registerNamed(Function c, String... names); + void registerNamed(Zeta myZeta, Function c, String... names); BlockColors getBlockColors(); - - Post makePostEvent(); - interface Post extends ZAddBlockColorHandlers { - Map> getNamedBlockColors(); - } } diff --git a/src/main/java/org/violetmoon/zeta/client/event/load/ZAddItemColorHandlers.java b/src/main/java/org/violetmoon/zeta/client/event/load/ZAddItemColorHandlers.java index 5e11982..ad32f37 100644 --- a/src/main/java/org/violetmoon/zeta/client/event/load/ZAddItemColorHandlers.java +++ b/src/main/java/org/violetmoon/zeta/client/event/load/ZAddItemColorHandlers.java @@ -3,6 +3,7 @@ import java.util.Map; import java.util.function.Function; +import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.event.bus.IZetaLoadEvent; import net.minecraft.client.color.item.ItemColor; @@ -12,11 +13,6 @@ public interface ZAddItemColorHandlers extends IZetaLoadEvent { void register(ItemColor c, ItemLike... items); - void registerNamed(Function c, String... names); + void registerNamed(Zeta myZeta, Function c, String... names); ItemColors getItemColors(); - - Post makePostEvent(); - interface Post extends ZAddItemColorHandlers { - Map> getNamedItemColors(); - } } diff --git a/src/main/java/org/violetmoon/zeta/client/event/load/ZRegisterClientReloadListener.java b/src/main/java/org/violetmoon/zeta/client/event/load/ZRegisterClientReloadListener.java new file mode 100644 index 0000000..52e5fc5 --- /dev/null +++ b/src/main/java/org/violetmoon/zeta/client/event/load/ZRegisterClientReloadListener.java @@ -0,0 +1,12 @@ +package org.violetmoon.zeta.client.event.load; + +import java.util.function.Consumer; + +import org.violetmoon.zeta.event.bus.IZetaLoadEvent; + +import net.minecraft.server.packs.resources.PreparableReloadListener; + +public interface ZRegisterClientReloadListener extends IZetaLoadEvent, Consumer { + @Override + void accept(PreparableReloadListener bleh); +} diff --git a/src/main/java/org/violetmoon/zeta/client/event/load/ZRegisterReloadListeners.java b/src/main/java/org/violetmoon/zeta/client/event/load/ZRegisterReloadListeners.java deleted file mode 100644 index a828ea9..0000000 --- a/src/main/java/org/violetmoon/zeta/client/event/load/ZRegisterReloadListeners.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.violetmoon.zeta.client.event.load; - -import java.util.function.Consumer; - -import org.violetmoon.zeta.event.bus.IZetaLoadEvent; - -import net.minecraft.server.packs.resources.PreparableReloadListener; - -public record ZRegisterReloadListeners(Consumer manager) implements IZetaLoadEvent, Consumer { - @Override - public void accept(PreparableReloadListener bleh) { - manager.accept(bleh); - } -} diff --git a/src/main/java/org/violetmoon/zeta/client/event/play/ZClientTick.java b/src/main/java/org/violetmoon/zeta/client/event/play/ZClientTick.java index 10a9ae3..b5671ca 100644 --- a/src/main/java/org/violetmoon/zeta/client/event/play/ZClientTick.java +++ b/src/main/java/org/violetmoon/zeta/client/event/play/ZClientTick.java @@ -1,8 +1,12 @@ package org.violetmoon.zeta.client.event.play; import org.violetmoon.zeta.event.bus.IZetaPlayEvent; -import org.violetmoon.zeta.event.bus.ZPhase; public interface ZClientTick extends IZetaPlayEvent { - ZPhase getPhase(); + + interface Start extends ZClientTick { + } + + interface End extends ZClientTick { + } } diff --git a/src/main/java/org/violetmoon/zeta/client/event/play/ZFirstClientTick.java b/src/main/java/org/violetmoon/zeta/client/event/play/ZFirstClientTick.java index e0c09a7..5b67350 100644 --- a/src/main/java/org/violetmoon/zeta/client/event/play/ZFirstClientTick.java +++ b/src/main/java/org/violetmoon/zeta/client/event/play/ZFirstClientTick.java @@ -2,4 +2,4 @@ import org.violetmoon.zeta.event.bus.IZetaLoadEvent; -public class ZFirstClientTick implements IZetaLoadEvent { } +public interface ZFirstClientTick extends IZetaLoadEvent { } diff --git a/src/main/java/org/violetmoon/zeta/client/event/play/ZRenderTick.java b/src/main/java/org/violetmoon/zeta/client/event/play/ZRenderTick.java index 697bcaf..48d8a0b 100644 --- a/src/main/java/org/violetmoon/zeta/client/event/play/ZRenderTick.java +++ b/src/main/java/org/violetmoon/zeta/client/event/play/ZRenderTick.java @@ -10,9 +10,10 @@ */ public interface ZRenderTick extends IZetaPlayEvent { float getRenderTickTime(); - boolean isEndPhase(); - default boolean isStartPhase() { - return !isEndPhase(); + interface Start extends ZRenderTick { + } + + interface End extends ZRenderTick { } } diff --git a/src/main/java/org/violetmoon/zeta/client/event/play/ZScreenshot.java b/src/main/java/org/violetmoon/zeta/client/event/play/ZScreenshot.java index 8492d4e..22e6bd7 100644 --- a/src/main/java/org/violetmoon/zeta/client/event/play/ZScreenshot.java +++ b/src/main/java/org/violetmoon/zeta/client/event/play/ZScreenshot.java @@ -2,4 +2,4 @@ import org.violetmoon.zeta.event.bus.IZetaPlayEvent; -public class ZScreenshot implements IZetaPlayEvent { } +public interface ZScreenshot extends IZetaPlayEvent { } diff --git a/src/main/java/org/violetmoon/zeta/config/ConfigManager.java b/src/main/java/org/violetmoon/zeta/config/ConfigManager.java index 781c8c5..395551e 100644 --- a/src/main/java/org/violetmoon/zeta/config/ConfigManager.java +++ b/src/main/java/org/violetmoon/zeta/config/ConfigManager.java @@ -1,13 +1,5 @@ package org.violetmoon.zeta.config; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Consumer; - import org.jetbrains.annotations.Nullable; import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.event.play.loading.ZGatherAdditionalFlags; @@ -15,181 +7,184 @@ import org.violetmoon.zeta.module.ZetaModule; import org.violetmoon.zeta.module.ZetaModuleManager; +import java.util.*; +import java.util.function.Consumer; + public class ConfigManager { - private final Zeta z; - private final ConfigFlagManager cfm; - private final SectionDefinition rootConfig; - - //for updating the values of @Config annotations to match the current state of the config - // and other "listening for config load" purposes - private final List> databindings = new ArrayList<>(); - private Consumer onConfigReloadJEI; - - //ummmmmmm i think my abstraction isn't very good - private final @Nullable SectionDefinition generalSection; - private final Map categoriesToSections = new HashMap<>(); - - private final Map> categoryEnabledOptions = new HashMap<>(); - private final Map> ignoreAntiOverlapOptions = new HashMap<>(); - private final Map> moduleEnabledOptions = new HashMap<>(); - - //state - private final Set enabledCategories = new HashSet<>(); - - public ConfigManager(Zeta z, Object rootPojo) { - this.z = z; - this.cfm = new ConfigFlagManager(z); - ZetaModuleManager modules = z.modules; - - //all modules are enabled by default - enabledCategories.addAll(modules.getCategories()); - - SectionDefinition.Builder rootConfigBuilder = new SectionDefinition.Builder().name(""); - - // "general" section - if(rootPojo == null) - generalSection = null; - else { - //TODO: where to put this lol - z.loadBus.subscribe(rootPojo).subscribe(rootPojo.getClass()); - z.playBus.subscribe(rootPojo).subscribe(rootPojo.getClass()); - - generalSection = rootConfigBuilder.addSubsection(general -> ConfigObjectMapper.readInto(general.name("general"), rootPojo, databindings, cfm)); - } - - // "categories" section, holding the category enablement options - rootConfigBuilder.addSubsection(categories -> { - categories.name("categories"); - for(ZetaCategory category : modules.getInhabitedCategories()) - categoryEnabledOptions.put(category, categories.addValue(b -> b.name(category.name).defaultValue(true))); - }); - - // per-category options - for(ZetaCategory category : modules.getInhabitedCategories()) { - categoriesToSections.put(category, rootConfigBuilder.addSubsection(categorySectionBuilder -> { - categorySectionBuilder.name(category.name); - for(ZetaModule module : modules.modulesInCategory(category)) { - // module flag - cfm.putModuleFlag(module); - - // module enablement option - moduleEnabledOptions.put(module, categorySectionBuilder.addValue(moduleEnabledOptionBuilder -> moduleEnabledOptionBuilder - .name(module.displayName) - .englishDisplayName(module.displayName) - .comment(module.description) - .defaultValue(module.enabledByDefault))); - - // per-module options - categorySectionBuilder.addSubsection(moduleSectionBuilder -> { - moduleSectionBuilder - .name(module.lowercaseName) - .englishDisplayName(module.displayName) - .comment(module.description); - - // @Config options - ConfigObjectMapper.readInto(moduleSectionBuilder, module, databindings, cfm); - - // anti overlap option - if(!module.antiOverlap.isEmpty()) { - ignoreAntiOverlapOptions.put(module, moduleSectionBuilder.addValue(antiOverlapOptionBuilder -> { - antiOverlapOptionBuilder.name("Ignore Anti Overlap") - .comment("This feature disables itself if any of the following mods are loaded:") - .defaultValue(false); - - for(String modid : module.antiOverlap) - antiOverlapOptionBuilder.comment(" - " + modid); - - antiOverlapOptionBuilder.comment("This is done to prevent content overlap.") - .comment("You can turn this on to force the feature to be loaded even if the above mods are also loaded."); - })); - } - }); - } - })); - } - - //grab any extra flags - z.playBus.fire(new ZGatherAdditionalFlags(cfm)); - - //managing module enablement in one go - //adding this to the *start* of the list so modules are enabled before anything else runs - //Its Janky ! - databindings.add(0, i -> { - categoryEnabledOptions.forEach((category, option) -> setCategoryEnabled(category, i.get(option))); - ignoreAntiOverlapOptions.forEach((module, option) -> module.ignoreAntiOverlap = !ZetaGeneralConfig.useAntiOverlap || i.get(option)); - moduleEnabledOptions.forEach((module, option) -> { - setModuleEnabled(module, i.get(option)); - cfm.putModuleFlag(module); - }); - - //update extra flags - z.playBus.fire(new ZGatherAdditionalFlags(cfm)); - }); - - this.rootConfig = rootConfigBuilder.build(); - rootConfig.finish(); - } - - public SectionDefinition getRootConfig() { - return rootConfig; - } - - // mapping between internal and external representations of the config (??????) - - public @Nullable SectionDefinition getGeneralSection() { - return generalSection; - } - - public SectionDefinition getCategorySection(ZetaCategory cat) { - return categoriesToSections.get(cat); - } - - public ValueDefinition getCategoryEnabledOption(ZetaCategory cat) { - return categoryEnabledOptions.get(cat); - } - - public ValueDefinition getModuleEnabledOption(ZetaModule module) { - return moduleEnabledOptions.get(module); - } - - // support for the options added by this class - - private void setCategoryEnabled(ZetaCategory cat, boolean enabled) { - if(enabled) - enabledCategories.add(cat); - else - enabledCategories.remove(cat); - - //TODO: hacky, just forcing setEnabled to rerun since it checks category enablement - for(ZetaModule mod : z.modules.modulesInCategory(cat)) { - mod.setEnabled(z, mod.enabled); - } - } - - private void setModuleEnabled(ZetaModule module, boolean enabled) { - module.setEnabled(z, enabled); - } - - public boolean isCategoryEnabled(ZetaCategory cat) { - return enabledCategories.contains(cat); - } - - // ummm - - public ConfigFlagManager getConfigFlagManager() { - return cfm; - } - - public void onReload() { - IZetaConfigInternals internals = z.configInternals; - databindings.forEach(c -> c.accept(internals)); - - if(onConfigReloadJEI != null) - onConfigReloadJEI.accept(internals); - } - - public void setJeiReloadListener(Consumer consumer) { - this.onConfigReloadJEI = consumer; - consumer.accept(z.configInternals); //run it now as well - } + private final Zeta z; + private final ConfigFlagManager cfm; + private final SectionDefinition rootConfig; + + //for updating the values of @Config annotations to match the current state of the config + // and other "listening for config load" purposes + private final List> databindings = new ArrayList<>(); + private Consumer onConfigReloadJEI; + + //ummmmmmm i think my abstraction isn't very good + private final @Nullable SectionDefinition generalSection; + private final Map categoriesToSections = new HashMap<>(); + + private final Map> categoryEnabledOptions = new HashMap<>(); + private final Map> ignoreAntiOverlapOptions = new HashMap<>(); + private final Map> moduleEnabledOptions = new HashMap<>(); + + //state + private final Set enabledCategories = new HashSet<>(); + + public ConfigManager(Zeta z, Object rootPojo) { + this.z = z; + this.cfm = new ConfigFlagManager(z); + ZetaModuleManager modules = z.modules; + + //all modules are enabled by default + enabledCategories.addAll(modules.getCategories()); + + SectionDefinition.Builder rootConfigBuilder = new SectionDefinition.Builder().name(""); + + // "general" section + if (rootPojo == null) + generalSection = null; + else { + //TODO: where to put this lol + z.loadBus.subscribe(rootPojo).subscribe(rootPojo.getClass()); + z.playBus.subscribe(rootPojo).subscribe(rootPojo.getClass()); + + generalSection = rootConfigBuilder.addSubsection(general -> ConfigObjectMapper.readInto(general.name("general"), rootPojo, databindings, cfm)); + } + + // "categories" section, holding the category enablement options + rootConfigBuilder.addSubsection(categories -> { + categories.name("categories"); + for (ZetaCategory category : modules.getInhabitedCategories()) + categoryEnabledOptions.put(category, categories.addValue(b -> b.name(category.name).defaultValue(true))); + }); + + // per-category options + for (ZetaCategory category : modules.getInhabitedCategories()) { + categoriesToSections.put(category, rootConfigBuilder.addSubsection(categorySectionBuilder -> { + categorySectionBuilder.name(category.name); + for (ZetaModule module : modules.modulesInCategory(category)) { + // module flag + cfm.putModuleFlag(module); + + // module enablement option + moduleEnabledOptions.put(module, categorySectionBuilder.addValue(moduleEnabledOptionBuilder -> moduleEnabledOptionBuilder + .name(module.displayName) + .englishDisplayName(module.displayName) + .comment(module.description) + .defaultValue(module.enabledByDefault))); + + // per-module options + categorySectionBuilder.addSubsection(moduleSectionBuilder -> { + moduleSectionBuilder + .name(module.lowercaseName) + .englishDisplayName(module.displayName) + .comment(module.description); + + // @Config options + ConfigObjectMapper.readInto(moduleSectionBuilder, module, databindings, cfm); + + // anti overlap option + if (!module.antiOverlap.isEmpty()) { + ignoreAntiOverlapOptions.put(module, moduleSectionBuilder.addValue(antiOverlapOptionBuilder -> { + antiOverlapOptionBuilder.name("Ignore Anti Overlap") + .comment("This feature disables itself if any of the following mods are loaded:") + .defaultValue(false); + + for (String modid : module.antiOverlap) + antiOverlapOptionBuilder.comment(" - " + modid); + + antiOverlapOptionBuilder.comment("This is done to prevent content overlap.") + .comment("You can turn this on to force the feature to be loaded even if the above mods are also loaded."); + })); + } + }); + } + })); + } + + //grab any extra flags + z.playBus.fire(() -> cfm, ZGatherAdditionalFlags.class); + + //managing module enablement in one go + //adding this to the *start* of the list so modules are enabled before anything else runs + //Its Janky ! + databindings.add(0, i -> { + categoryEnabledOptions.forEach((category, option) -> setCategoryEnabled(category, i.get(option))); + ignoreAntiOverlapOptions.forEach((module, option) -> module.ignoreAntiOverlap = !ZetaGeneralConfig.useAntiOverlap || i.get(option)); + moduleEnabledOptions.forEach((module, option) -> { + setModuleEnabled(module, i.get(option)); + cfm.putModuleFlag(module); + }); + + //update extra flags + z.playBus.fire(() -> cfm, ZGatherAdditionalFlags.class); + }); + + this.rootConfig = rootConfigBuilder.build(); + rootConfig.finish(); + } + + public SectionDefinition getRootConfig() { + return rootConfig; + } + + // mapping between internal and external representations of the config (??????) + + public @Nullable SectionDefinition getGeneralSection() { + return generalSection; + } + + public SectionDefinition getCategorySection(ZetaCategory cat) { + return categoriesToSections.get(cat); + } + + public ValueDefinition getCategoryEnabledOption(ZetaCategory cat) { + return categoryEnabledOptions.get(cat); + } + + public ValueDefinition getModuleEnabledOption(ZetaModule module) { + return moduleEnabledOptions.get(module); + } + + // support for the options added by this class + + private void setCategoryEnabled(ZetaCategory cat, boolean enabled) { + if (enabled) + enabledCategories.add(cat); + else + enabledCategories.remove(cat); + + //TODO: hacky, just forcing setEnabled to rerun since it checks category enablement + for (ZetaModule mod : z.modules.modulesInCategory(cat)) { + mod.setEnabled(z, mod.enabled); + } + } + + private void setModuleEnabled(ZetaModule module, boolean enabled) { + module.setEnabled(z, enabled); + } + + public boolean isCategoryEnabled(ZetaCategory cat) { + return enabledCategories.contains(cat); + } + + // ummm + + public ConfigFlagManager getConfigFlagManager() { + return cfm; + } + + public void onReload() { + IZetaConfigInternals internals = z.configInternals; + databindings.forEach(c -> c.accept(internals)); + + if (onConfigReloadJEI != null) + onConfigReloadJEI.accept(internals); + } + + public void setJeiReloadListener(Consumer consumer) { + this.onConfigReloadJEI = consumer; + consumer.accept(z.configInternals); //run it now as well + } } diff --git a/src/main/java/org/violetmoon/zeta/config/ZetaGeneralConfig.java b/src/main/java/org/violetmoon/zeta/config/ZetaGeneralConfig.java index 3ecc06e..c9f7f91 100644 --- a/src/main/java/org/violetmoon/zeta/config/ZetaGeneralConfig.java +++ b/src/main/java/org/violetmoon/zeta/config/ZetaGeneralConfig.java @@ -5,6 +5,7 @@ import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.event.bus.LoadEvent; import org.violetmoon.zeta.event.load.ZConfigChanged; +import org.violetmoon.zeta.mod.ZetaMod; import org.violetmoon.zeta.piston.ZetaPistonStructureResolver; import com.google.common.collect.Lists; @@ -59,8 +60,8 @@ private ZetaGeneralConfig() { @LoadEvent public static void configChanged(ZConfigChanged e) { - ZetaPistonStructureResolver.GlobalSettings.requestEnabled(Zeta.ZETA_ID, usePistonLogicRepl); - ZetaPistonStructureResolver.GlobalSettings.requestPushLimit(Zeta.ZETA_ID, pistonPushLimit); + ZetaPistonStructureResolver.GlobalSettings.requestEnabled(ZetaMod.ZETA_ID, usePistonLogicRepl); + ZetaPistonStructureResolver.GlobalSettings.requestPushLimit(ZetaMod.ZETA_ID, pistonPushLimit); } } diff --git a/src/main/java/org/violetmoon/zeta/event/bus/StandaloneZetaEventBus.java b/src/main/java/org/violetmoon/zeta/event/bus/StandaloneZetaEventBus.java new file mode 100644 index 0000000..4bdc955 --- /dev/null +++ b/src/main/java/org/violetmoon/zeta/event/bus/StandaloneZetaEventBus.java @@ -0,0 +1,186 @@ +package org.violetmoon.zeta.event.bus; + +import java.lang.annotation.Annotation; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; + +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.violetmoon.zeta.Zeta; + +/** + * A polymorphic event bus. Events can be fired under one of their supertypes, allowing a sort of API/impl split of events. + * + * Due to implementation complexity, there is unfortunately no support for: + * - generic events (like Forge's RegistryEvent) + * - registering an anonymous `Consumer` (like Forge's "addListener" method) + * Supported Java reflection APIs don't expose this information. Forge can only get at it with a library internally using sun.misc.Unsafe. + */ +public class StandaloneZetaEventBus extends ZetaEventBus { + + private final Map, Listeners> listenerMap = new HashMap<>(); + + /** + * @param subscriberAnnotation The annotation that subscribe()/unsubscribe() will pay attention to. + * @param eventRoot The superinterface of all events fired on this bus. + * @param logSpam + */ + public StandaloneZetaEventBus(Class subscriberAnnotation, Class eventRoot, @Nullable Logger logSpam, Zeta ofZeta) { + super(subscriberAnnotation, eventRoot, logSpam, ofZeta); + } + + @Override + protected void subscribeMethod(Method m, Object receiver, Class owningClazz) { + getListenersFor(m).subscribe(receiver, owningClazz, m); + } + + @Override + protected void unsubscribeMethod(Method m, Object receiver, Class owningClazz) { + getListenersFor(m).unsubscribe(receiver, owningClazz, m); + } + + /** + * Fires an event on the event bus. Each subscriber will be visited in order. + */ + @Override + public T fire(@NotNull T event) { + Listeners subs = listenerMap.get(event.getClass()); + if(subs != null) { + if(logSpam != null) + logSpam.info("Dispatching {} to {} listener{}", logSpamSimpleName(event.getClass()), subs.size(), subs.size() > 1 ? "s" : ""); + + subs.doFire(event); + } + + return event; + } + + /** + * Fires an event on the event bus. Each subscriber will be visited in order. + * Listeners for "firedAs" will be invoked, instead of listeners for the event's own class. + *

+ * (The generic should be Class<? super T & ? extends E>, but unfortunately, javac.) + */ + @Override + public T fire(@NotNull T event, Class firedAs) { + Listeners subs = listenerMap.get(firedAs); + if(subs != null) { + if(logSpam != null) + logSpam.info("Dispatching {} (as {}) to {} listener{}", logSpamSimpleName(event.getClass()), logSpamSimpleName(firedAs), subs.size(), subs.size() > 1 ? "s" : ""); + + subs.doFire(event); + } + + return event; + } + + //this is really silly + private String logSpamSimpleName(Class clazz) { + String[] split = clazz.getName().split("\\."); + return split[split.length - 1]; + } + + /** + * Picks out the "Foo" in "void handleFoo(Foo event)", and gets/creates the Listeners corresponding to that type. + */ + @SuppressWarnings("unchecked") + private Listeners getListenersFor(Method method) { + if(method.getParameterCount() != 1) + throw arityERR(method); + + Class eventType = method.getParameterTypes()[0]; + if(!eventRoot.isAssignableFrom(eventType)) + throw typeERR(method); + + return listenerMap.computeIfAbsent((Class) eventType, __ -> new Listeners()); + } + + /** + * Mildly overengineered since I want method dispatching to hopefully be low-overhead... don't mind me + * MethodHandle is magic free performance right + * Pausefrogeline + */ + private class Listeners { + + private final Map handles = new LinkedHashMap<>(); + + private record Subscriber(@Nullable Object receiver, Class owningClazz, Method method) { + @Override + public boolean equals(Object object) { + if(this == object) return true; + if(object == null || getClass() != object.getClass()) return false; + Subscriber that = (Subscriber) object; + return receiver == that.receiver && //<-- object identity compare + Objects.equals(owningClazz, that.owningClazz) && + Objects.equals(method, that.method); + } + + @Override + public int hashCode() { + return System.identityHashCode(receiver) + owningClazz.hashCode() + method.hashCode(); + } + + MethodHandle unreflect() { + MethodHandle handle; + try { + handle = MethodHandles.publicLookup().unreflect(method); + } catch (Exception e) { + throw new RuntimeException(e); + } + + //fill in the "this" parameter + if(receiver != null) + handle = handle.bindTo(receiver); + return handle; + } + } + + + void subscribe(@Nullable Object receiver, Class owningClazz, Method method) { + try { + handles.computeIfAbsent(new Subscriber(receiver, owningClazz, method), Subscriber::unreflect); + } catch (Exception e) { + throw unreflectERR(method, e); + } + } + + void unsubscribe(@Nullable Object receiver, Class owningClazz, Method method) { + handles.remove(new Subscriber(receiver, owningClazz, method)); + } + + int size() { + return handles.size(); + } + + //just hoisting the instanceof out of the loop.. No profiling just vibes <3 + void doFire(E event) { + try { + if(event instanceof Cancellable cancellable) + doFireCancellable(cancellable); + else + doFireNonCancellable(event); + } catch (Throwable e) { + throw new RuntimeException("Exception while firing event " + event + ": ", e); + } + } + + void doFireCancellable(Cancellable event) throws Throwable { + for(MethodHandle handle : handles.values()) { + handle.invoke(event); + if(event.isCanceled()) break; + } + } + + void doFireNonCancellable(E event) throws Throwable { + for(MethodHandle handle : handles.values()) + handle.invoke(event); + } + } + +} diff --git a/src/main/java/org/violetmoon/zeta/event/bus/ZPhase.java b/src/main/java/org/violetmoon/zeta/event/bus/ZPhase.java deleted file mode 100644 index aad6d02..0000000 --- a/src/main/java/org/violetmoon/zeta/event/bus/ZPhase.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.violetmoon.zeta.event.bus; - -public enum ZPhase { - START, END; -} diff --git a/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java b/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java index 001a5e4..5df5d37 100644 --- a/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java +++ b/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java @@ -1,265 +1,153 @@ package org.violetmoon.zeta.event.bus; -import java.lang.annotation.Annotation; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import java.util.stream.Stream; - +import com.google.common.base.Preconditions; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.violetmoon.zeta.Zeta; +import org.violetmoon.zeta.client.ClientTicker; +import org.violetmoon.zeta.mod.ZetaMod; -import com.google.common.base.Preconditions; - -/** - * A polymorphic event bus. Events can be fired under one of their supertypes, allowing a sort of API/impl split of events. - * - * Due to implementation complexity, there is unfortunately no support for: - * - generic events (like Forge's RegistryEvent) - * - registering an anonymous `Consumer` (like Forge's "addListener" method) - * Supported Java reflection APIs don't expose this information. Forge can only get at it with a library internally using sun.misc.Unsafe. - */ -public class ZetaEventBus { - private final Zeta z; - private final Class subscriberAnnotation; - private final Class eventRoot; - private final @Nullable Logger logSpam; - - private final Map, Listeners> listenerMap = new HashMap<>(); - - /** - * @param subscriberAnnotation The annotation that subscribe()/unsubscribe() will pay attention to. - * @param eventRoot The superinterface of all events fired on this bus. - */ - public ZetaEventBus(Zeta z, Class subscriberAnnotation, Class eventRoot, @Nullable Logger logSpam) { - Preconditions.checkArgument(eventRoot.isInterface(), "Event roots should be an interface"); - - this.z = z; - this.subscriberAnnotation = subscriberAnnotation; - this.eventRoot = eventRoot; - this.logSpam = logSpam; - } - - /** - * If the parameter is a Class: subscribes all static methods from it (and its superclasses) to the event bus. - * Otherwise, subscribes all non-static methods on that object (and its superclasses) to the event bus. - * (Note that the event bus will hold a reference to this object.) - */ - public ZetaEventBus subscribe(@NotNull Object target) { - Preconditions.checkNotNull(target, "null passed to subscribe"); - - Object receiver; - Class owningClazz; - if(target instanceof Class clazz) { - receiver = null; - owningClazz = clazz; - } else { - receiver = target; - owningClazz = target.getClass(); - } - - streamAnnotatedMethods(owningClazz, receiver == null).forEach(m -> getListenersFor(m).subscribe(receiver, owningClazz, m)); - return this; - } - - /** - * If the parameter is a Class: unsubscribes all static methods from it (and its superclasses) from the event bus. - * Otherwise, unsubscribes all non-static methods on that object (and its superclasses) from the event bus. - */ - public ZetaEventBus unsubscribe(@NotNull Object target) { - Preconditions.checkNotNull(target, "null passed to unsubscribe"); - - Object receiver; - Class owningClazz; - if(target instanceof Class clazz) { - receiver = null; - owningClazz = clazz; - } else { - receiver = target; - owningClazz = target.getClass(); - } - - streamAnnotatedMethods(owningClazz, receiver == null).forEach(m -> getListenersFor(m).unsubscribe(receiver, owningClazz, m)); - return this; - } - - /** - * Fires an event on the event bus. Each subscriber will be visited in order. - */ - public T fire(@NotNull T event) { - Listeners subs = listenerMap.get(event.getClass()); - if(subs != null) { - if(logSpam != null) - logSpam.info("Dispatching {} to {} listener{}", logspamSimpleName(event.getClass()), subs.size(), subs.size() > 1 ? "s" : ""); - - subs.doFire(event); - } - - return event; - } - - /** - * Fires an event on the event bus. Each subscriber will be visited in order. - * Listeners for "firedAs" will be invoked, instead of listeners for the event's own class. - *

- * (The generic should be Class<? super T & ? extends E>, but unfortunately, javac.) - */ - public T fire(@NotNull T event, Class firedAs) { - Listeners subs = listenerMap.get(firedAs); - if(subs != null) { - if(logSpam != null) - logSpam.info("Dispatching {} (as {}) to {} listener{}", logspamSimpleName(event.getClass()), logspamSimpleName(firedAs), subs.size(), subs.size() > 1 ? "s" : ""); - - subs.doFire(event); - } - - return event; - } - - //this is really silly - private String logspamSimpleName(Class clazz) { - String[] split = clazz.getName().split("\\."); - return split[split.length - 1]; - } - - public T fireExternal(@NotNull T event, Class firedAs) { - event = fire(event, firedAs); - - if(event instanceof Cancellable cancellable && cancellable.isCanceled()) - return event; - else - return z.fireExternalEvent(event); // Interfaces with the platform-specific event bus utility - } - - /** - * Grabs methods from this class (and its superclasses, recursively) that are annotated with this bus's - * annotation; and of the requested staticness. - */ - private Stream streamAnnotatedMethods(Class owningClazz, boolean wantStatic) { - return Arrays.stream(owningClazz.getMethods()) - .filter(m -> m.isAnnotationPresent(subscriberAnnotation) && ((m.getModifiers() & Modifier.STATIC) != 0) == wantStatic); - } - - /** - * Picks out the "Foo" in "void handleFoo(Foo event)", and gets/creates the Listeners corresponding to that type. - */ - @SuppressWarnings("unchecked") - private Listeners getListenersFor(Method method) { - if(method.getParameterCount() != 1) - throw arityERR(method); - - Class eventType = method.getParameterTypes()[0]; - if(!eventRoot.isAssignableFrom(eventType)) - throw typeERR(method); - - return listenerMap.computeIfAbsent((Class) eventType, __ -> new Listeners()); - } - - /** - * Mildly overengineered since I want method dispatching to hopefully be low-overhead... don't mind me - * MethodHandle is magic free performance right - * Pausefrogeline - */ - private class Listeners { - private record Subscriber(@Nullable Object receiver, Class owningClazz, Method method) { - @Override - public boolean equals(Object object) { - if(this == object) return true; - if(object == null || getClass() != object.getClass()) return false; - Subscriber that = (Subscriber) object; - return receiver == that.receiver && //<-- object identity compare - Objects.equals(owningClazz, that.owningClazz) && - Objects.equals(method, that.method); - } - - @Override - public int hashCode() { - return System.identityHashCode(receiver) + owningClazz.hashCode() + method.hashCode(); - } - - MethodHandle unreflect() { - MethodHandle handle; - try { - handle = MethodHandles.publicLookup().unreflect(method); - } catch (Exception e) { - throw new RuntimeException(e); - } - - //fill in the "this" parameter - if(receiver != null) - handle = handle.bindTo(receiver); - return handle; - } - } - - private final Map handles = new LinkedHashMap<>(); - - void subscribe(@Nullable Object receiver, Class owningClazz, Method method) { - try { - handles.computeIfAbsent(new Subscriber(receiver, owningClazz, method), Subscriber::unreflect); - } catch (Exception e) { - throw unreflectERR(method, e); - } - } - - void unsubscribe(@Nullable Object receiver, Class owningClazz, Method method) { - handles.remove(new Subscriber(receiver, owningClazz, method)); - } - - int size() { - return handles.size(); - } - - //just hoisting the instanceof out of the loop.. No profiling just vibes <3 - void doFire(E event) { - try { - if(event instanceof Cancellable cancellable) - doFireCancellable(cancellable); - else - doFireNonCancellable(event); - } catch (Throwable e) { - throw new RuntimeException("Exception while firing event " + event + ": ", e); - } - } - - void doFireCancellable(Cancellable event) throws Throwable { - for(MethodHandle handle : handles.values()) { - handle.invoke(event); - if(event.isCanceled()) break; - } - } - - void doFireNonCancellable(E event) throws Throwable { - for(MethodHandle handle : handles.values()) - handle.invoke(event); - } - } - - private RuntimeException arityERR(Method method) { - return methodProblem("Method annotated with @" + subscriberAnnotation.getSimpleName() + - " should take 1 parameter.", method, null); - } - - private RuntimeException typeERR(Method method) { - return methodProblem("Method annotated with @" + subscriberAnnotation.getSimpleName() + - " should take an implementor of " + eventRoot.getSimpleName() + ".", method, null); - } - - private RuntimeException unreflectERR(Method method, Throwable cause) { - return methodProblem("Exception unreflecting a @" + subscriberAnnotation.getSimpleName() + - " method, is it public?", method, cause); - } +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Stream; - private static RuntimeException methodProblem(String problem, Method method, @Nullable Throwable cause) { - return new RuntimeException("%s%nMethod class: %s%nMethod name: %s".formatted( - problem, method.getDeclaringClass().getName(), method.getName()), cause); - } +public abstract class ZetaEventBus { + + protected final Class subscriberAnnotation; + protected final Class eventRoot; + protected final @Nullable Logger logSpam; + //each bus belongs to a specific zeta. Internally they can however delegate to an internal shared data structure such as to the forge event bus + protected final Zeta ofZeta; + + /** + * @param subscriberAnnotation The annotation that subscribe()/unsubscribe() will pay attention to. + * @param eventRoot The superinterface of all events fired on this bus. + */ + public ZetaEventBus(Class subscriberAnnotation, Class eventRoot, + @Nullable Logger logSpam, Zeta ofZeta) { + Preconditions.checkArgument(eventRoot.isInterface(), "Event roots should be an interface"); + + this.subscriberAnnotation = subscriberAnnotation; + this.eventRoot = eventRoot; + this.logSpam = logSpam; + this.ofZeta = ofZeta; + } + + /** + * If the parameter is a Class: subscribes all static methods from it (and its superclasses) to the event bus. + * Otherwise, subscribes all non-static methods on that object (and its superclasses) to the event bus. + * (Note that the event bus will hold a reference to this object.) + */ + public ZetaEventBus subscribe(@NotNull Object target) { + Preconditions.checkNotNull(target, "null passed to subscribe"); + + Object receiver; + Class owningClazz; + if (target instanceof Class clazz) { + receiver = null; + owningClazz = clazz; + } else { + receiver = target; + owningClazz = target.getClass(); + } + streamAnnotatedMethods(owningClazz, receiver == null) + .forEach(m -> subscribeMethod(m, receiver, owningClazz)); + return this; + } + + + /** + * If the parameter is a Class: unsubscribes all static methods from it (and its superclasses) from the event bus. + * Otherwise, unsubscribes all non-static methods on that object (and its superclasses) from the event bus. + */ + public ZetaEventBus unsubscribe(@NotNull Object target) { + Preconditions.checkNotNull(target, "null passed to unsubscribe"); + + Object receiver; + Class owningClazz; + if (target instanceof Class clazz) { + receiver = null; + owningClazz = clazz; + } else { + receiver = target; + owningClazz = target.getClass(); + } + + streamAnnotatedMethods(owningClazz, receiver == null) + .forEach(m -> unsubscribeMethod(m, receiver, owningClazz)); + return this; + } + + protected abstract void unsubscribeMethod(Method m, Object receiver, Class owningClazz); + + protected abstract void subscribeMethod(Method m, Object receiver, Class owningClazz); + + + /** + * Fires an event on the event bus. Each subscriber will be visited in order. + */ + public abstract T fire(@NotNull T event); + + /** + * Fires an event on the event bus. Each subscriber will be visited in order. + * Listeners for "firedAs" will be invoked, instead of listeners for the event's own class. + *

+ * (The generic should be Class<? super T & ? extends E>, but unfortunately, javac.) + */ + public abstract T fire(@NotNull T event, Class firedAs); + + /** + * Grabs methods from this class (and its superclasses, recursively) that are annotated with this bus's + * annotation; and of the requested staticness. + */ + private Stream streamAnnotatedMethods(Class owningClazz, boolean wantStatic) { + Stream methods; + if (ofZeta.isProduction) { + // faster + methods = Arrays.stream(owningClazz.getMethods()); + } else { + // here for debug purposes as this will catch private stuff too + List list = new ArrayList<>(); + while (owningClazz != null) { + Collections.addAll(list, owningClazz.getDeclaredMethods()); + owningClazz = owningClazz.getSuperclass(); + } + methods = list.stream(); + } + return methods.filter(m -> m.isAnnotationPresent(subscriberAnnotation) && ((m.getModifiers() & Modifier.STATIC) != 0) == wantStatic); + } + + + protected RuntimeException arityERR(Method method) { + return methodProblem("Method annotated with @" + subscriberAnnotation.getSimpleName() + + " should take 1 parameter.", method, null); + } + + protected RuntimeException typeERR(Method method) { + return methodProblem("Method annotated with @" + subscriberAnnotation.getSimpleName() + + " should take an implementor of " + eventRoot.getSimpleName() + ".", method, null); + } + + protected RuntimeException unreflectERR(Method method, Throwable cause) { + return methodProblem("Exception unreflecting a @" + subscriberAnnotation.getSimpleName() + + " method, is it public?", method, cause); + } + + protected static RuntimeException methodProblem(String problem, Method method, @Nullable Throwable cause) { + return new RuntimeException("%s%nMethod class: %s%nMethod name: %s".formatted( + problem, method.getDeclaringClass().getName(), method.getName()), cause); + } + + //TODO or remove entirely. Platform specific behavior should be in fire implementation on each platform bus + @Deprecated(forRemoval = true) + public T fireExternal(@NotNull T event, Class firedAs) { + + return event; + } } diff --git a/src/main/java/org/violetmoon/zeta/event/load/ZAddReloadListener.java b/src/main/java/org/violetmoon/zeta/event/load/ZAddReloadListener.java index b46ce35..f7100c7 100644 --- a/src/main/java/org/violetmoon/zeta/event/load/ZAddReloadListener.java +++ b/src/main/java/org/violetmoon/zeta/event/load/ZAddReloadListener.java @@ -5,8 +5,9 @@ import net.minecraft.core.RegistryAccess; import net.minecraft.server.ReloadableServerResources; import net.minecraft.server.packs.resources.PreparableReloadListener; +import org.violetmoon.zeta.event.bus.IZetaPlayEvent; -public interface ZAddReloadListener extends IZetaLoadEvent { +public interface ZAddReloadListener extends IZetaPlayEvent { ReloadableServerResources getServerResources(); RegistryAccess getRegistryAccess(); void addListener(PreparableReloadListener listener); diff --git a/src/main/java/org/violetmoon/zeta/event/load/ZConfigChanged.java b/src/main/java/org/violetmoon/zeta/event/load/ZConfigChanged.java index 1e334e2..afa2e9d 100644 --- a/src/main/java/org/violetmoon/zeta/event/load/ZConfigChanged.java +++ b/src/main/java/org/violetmoon/zeta/event/load/ZConfigChanged.java @@ -2,4 +2,4 @@ import org.violetmoon.zeta.event.bus.IZetaLoadEvent; -public class ZConfigChanged implements IZetaLoadEvent { } +public interface ZConfigChanged extends IZetaLoadEvent { } diff --git a/src/main/java/org/violetmoon/zeta/event/load/ZGatherAdvancementModifiers.java b/src/main/java/org/violetmoon/zeta/event/load/ZGatherAdvancementModifiers.java index af535b5..51b4d56 100644 --- a/src/main/java/org/violetmoon/zeta/event/load/ZGatherAdvancementModifiers.java +++ b/src/main/java/org/violetmoon/zeta/event/load/ZGatherAdvancementModifiers.java @@ -14,6 +14,7 @@ import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.block.Block; +import org.violetmoon.zeta.event.bus.IZetaPlayEvent; public interface ZGatherAdvancementModifiers extends IZetaLoadEvent { void register(IAdvancementModifier modifier); diff --git a/src/main/java/org/violetmoon/zeta/event/load/ZModulesReady.java b/src/main/java/org/violetmoon/zeta/event/load/ZModulesReady.java index 25bb190..b6086fe 100644 --- a/src/main/java/org/violetmoon/zeta/event/load/ZModulesReady.java +++ b/src/main/java/org/violetmoon/zeta/event/load/ZModulesReady.java @@ -2,4 +2,4 @@ import org.violetmoon.zeta.event.bus.IZetaLoadEvent; -public class ZModulesReady implements IZetaLoadEvent { } +public interface ZModulesReady extends IZetaLoadEvent { } diff --git a/src/main/java/org/violetmoon/zeta/event/load/ZRegister.java b/src/main/java/org/violetmoon/zeta/event/load/ZRegister.java index b49697c..ba21fd6 100644 --- a/src/main/java/org/violetmoon/zeta/event/load/ZRegister.java +++ b/src/main/java/org/violetmoon/zeta/event/load/ZRegister.java @@ -10,36 +10,19 @@ import org.violetmoon.zeta.registry.ZetaRegistry; @SuppressWarnings("ClassCanBeRecord") -public class ZRegister implements IZetaLoadEvent { - public final Zeta zeta; +public interface ZRegister extends IZetaLoadEvent { - public ZRegister(Zeta zeta) { - this.zeta = zeta; - } + ZetaRegistry getRegistry(); - public ZetaRegistry getRegistry() { - return zeta.registry; - } + CraftingExtensionsRegistry getCraftingExtensionsRegistry(); - public CraftingExtensionsRegistry getCraftingExtensionsRegistry() { - return zeta.craftingExtensions; - } + BrewingRegistry getBrewingRegistry(); - public BrewingRegistry getBrewingRegistry() { - return zeta.brewingRegistry; - } + RenderLayerRegistry getRenderLayerRegistry(); - public RenderLayerRegistry getRenderLayerRegistry() { - return zeta.renderLayerRegistry; - } + AdvancementModifierRegistry getAdvancementModifierRegistry(); - public AdvancementModifierRegistry getAdvancementModifierRegistry() { - return zeta.advancementModifierRegistry; - } + VariantRegistry getVariantRegistry(); - public VariantRegistry getVariantRegistry() { - return zeta.variantRegistry; - } - - public static class Post implements IZetaLoadEvent { } + interface Post extends IZetaLoadEvent { } } diff --git a/src/main/java/org/violetmoon/zeta/event/load/ZTagsUpdated.java b/src/main/java/org/violetmoon/zeta/event/load/ZTagsUpdated.java index 8d8cfae..d5cbd46 100644 --- a/src/main/java/org/violetmoon/zeta/event/load/ZTagsUpdated.java +++ b/src/main/java/org/violetmoon/zeta/event/load/ZTagsUpdated.java @@ -1,6 +1,14 @@ package org.violetmoon.zeta.event.load; +import net.minecraft.core.RegistryAccess; import org.violetmoon.zeta.event.bus.IZetaLoadEvent; +import org.violetmoon.zeta.event.bus.IZetaPlayEvent; //TODO: just used by RecipeCrawlHandler -public class ZTagsUpdated implements IZetaLoadEvent { } +public interface ZTagsUpdated extends IZetaPlayEvent { + + RegistryAccess getRegistryAccess(); + + boolean isOnClient(); + +} diff --git a/src/main/java/org/violetmoon/zeta/event/play/loading/ZGatherAdditionalFlags.java b/src/main/java/org/violetmoon/zeta/event/play/loading/ZGatherAdditionalFlags.java index b0145d2..a1b60ce 100644 --- a/src/main/java/org/violetmoon/zeta/event/play/loading/ZGatherAdditionalFlags.java +++ b/src/main/java/org/violetmoon/zeta/event/play/loading/ZGatherAdditionalFlags.java @@ -3,4 +3,7 @@ import org.violetmoon.zeta.config.ConfigFlagManager; import org.violetmoon.zeta.event.bus.IZetaPlayEvent; -public record ZGatherAdditionalFlags(ConfigFlagManager flagManager) implements IZetaPlayEvent { } +public interface ZGatherAdditionalFlags extends IZetaPlayEvent { + + ConfigFlagManager flagManager(); +} diff --git a/src/main/java/org/violetmoon/zeta/mod/ZetaClientProxy.java b/src/main/java/org/violetmoon/zeta/mod/ZetaClientProxy.java deleted file mode 100644 index 706b2ea..0000000 --- a/src/main/java/org/violetmoon/zeta/mod/ZetaClientProxy.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.violetmoon.zeta.mod; - -import org.violetmoon.zeta.Zeta; -import org.violetmoon.zeta.client.TopLayerTooltipHandler; -import org.violetmoon.zeta.client.ZetaClient; -import org.violetmoon.zeta.util.handler.RequiredModTooltipHandler; - -public class ZetaClientProxy extends ZetaModProxy { - - public static ZetaClient ZETA_CLIENT; - - @Override - public void registerEvents(Zeta zeta) { - super.registerEvents(zeta); - - zeta.playBus - .subscribe(TopLayerTooltipHandler.class) - .subscribe(new RequiredModTooltipHandler.Client(zeta)); - } - - @Override - public void setClientZeta(Object obj) { - ZETA_CLIENT = (ZetaClient) obj; - } - -} diff --git a/src/main/java/org/violetmoon/zeta/mod/ZetaMod.java b/src/main/java/org/violetmoon/zeta/mod/ZetaMod.java index bea5684..46d43d5 100644 --- a/src/main/java/org/violetmoon/zeta/mod/ZetaMod.java +++ b/src/main/java/org/violetmoon/zeta/mod/ZetaMod.java @@ -1,26 +1,30 @@ package org.violetmoon.zeta.mod; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.config.ZetaGeneralConfig; -import org.violetmoon.zeta.event.bus.LoadEvent; -import org.violetmoon.zeta.event.load.ZCommonSetup; import org.violetmoon.zeta.network.ZetaModInternalNetwork; -import org.violetmoon.zetaimplforge.config.ConfigEventDispatcher; public class ZetaMod { + public static final String ZETA_ID = "zeta"; + public static final Logger LOGGER = LogManager.getLogger(ZETA_ID); + + //zeta mod own zeta thing public static Zeta ZETA; - public static ZetaModProxy proxy; - - public static void start(Zeta zeta, ZetaModProxy proxy) { - ZetaMod.ZETA = zeta; - ZetaMod.proxy = proxy; + public ZetaMod(Zeta zeta) { + ZETA = zeta; + + start(); + } + + private void start() { ZETA.start(); ZETA.loadModules(null, null, ZetaGeneralConfig.INSTANCE); - + ZetaModInternalNetwork.init(); - proxy.registerEvents(zeta); } } diff --git a/src/main/java/org/violetmoon/zeta/mod/ZetaModProxy.java b/src/main/java/org/violetmoon/zeta/mod/ZetaModProxy.java deleted file mode 100644 index 1ed6586..0000000 --- a/src/main/java/org/violetmoon/zeta/mod/ZetaModProxy.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.violetmoon.zeta.mod; - -import org.violetmoon.zeta.Zeta; -import org.violetmoon.zeta.config.SyncedFlagHandler; -import org.violetmoon.zeta.config.ZetaGeneralConfig; -import org.violetmoon.zeta.util.handler.RecipeCrawlHandler; -import org.violetmoon.zeta.util.handler.ToolInteractionHandler; -import org.violetmoon.zeta.world.EntitySpawnHandler; -import org.violetmoon.zeta.world.WorldGenHandler; - -public class ZetaModProxy { - - public void registerEvents(Zeta zeta) { - zeta.loadBus - .subscribe(RecipeCrawlHandler.class) - .subscribe(ToolInteractionHandler.class) - .subscribe(EntitySpawnHandler.class) - .subscribe(WorldGenHandler.class) - .subscribe(ZetaGeneralConfig.class); - - zeta.playBus - .subscribe(RecipeCrawlHandler.class) - .subscribe(ToolInteractionHandler.class) - .subscribe(SyncedFlagHandler.class); - } - - // Cast up obj to ZetaClient on the client proxy - public void setClientZeta(Object obj) { - // NO-OP - } - -} diff --git a/src/main/java/org/violetmoon/zeta/module/ZetaModuleManager.java b/src/main/java/org/violetmoon/zeta/module/ZetaModuleManager.java index b299fdf..724bbfb 100644 --- a/src/main/java/org/violetmoon/zeta/module/ZetaModuleManager.java +++ b/src/main/java/org/violetmoon/zeta/module/ZetaModuleManager.java @@ -15,6 +15,7 @@ import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.event.load.ZModulesReady; import org.violetmoon.zeta.util.ZetaSide; +import org.violetmoon.zetaimplforge.event.load.ForgeZModulesReady; /** * TODO: other forms of module discovery and replacement (like a Forge-only module, or other types of 'replacement' modules) @@ -129,7 +130,7 @@ public void load(ModuleFinder finder) { z.log.info("Constructed {} modules.", modulesByKey.size()); - z.loadBus.fire(new ZModulesReady()); + z.loadBus.fire(new ForgeZModulesReady()); } private ZetaModule constructAndSetup(TentativeModule t) { diff --git a/src/main/java/org/violetmoon/zeta/piston/ZetaPistonStructureResolver.java b/src/main/java/org/violetmoon/zeta/piston/ZetaPistonStructureResolver.java index d9a9fe5..4bffb78 100644 --- a/src/main/java/org/violetmoon/zeta/piston/ZetaPistonStructureResolver.java +++ b/src/main/java/org/violetmoon/zeta/piston/ZetaPistonStructureResolver.java @@ -7,7 +7,6 @@ import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.NotNull; -import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.api.ICollateralMover; import org.violetmoon.zeta.api.ICollateralMover.MoveResult; import org.violetmoon.zeta.api.IConditionalSticky; @@ -27,6 +26,7 @@ import net.minecraft.world.level.block.piston.PistonStructureResolver; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.PushReaction; +import org.violetmoon.zeta.mod.ZetaMod; public class ZetaPistonStructureResolver extends PistonStructureResolver { @@ -60,9 +60,9 @@ public static void requestEnabled(String modid, boolean enablePlease) { enabled = !wantsEnabled.isEmpty(); if(!wasEnabled && enabled) - Zeta.GLOBAL_LOG.info("'{}' is enabling Zeta's piston structure resolver.", modid); + ZetaMod.LOGGER.info("'{}' is enabling Zeta's piston structure resolver.", modid); else if(wasEnabled && !enabled) - Zeta.GLOBAL_LOG.info("Zeta's piston structure resolver is now disabled."); + ZetaMod.LOGGER.info("Zeta's piston structure resolver is now disabled."); } public static void requestPushLimit(String modid, int pushLimitPlease) { @@ -72,7 +72,7 @@ public static void requestPushLimit(String modid, int pushLimitPlease) { pushLimit = wantsPushLimit.values().intStream().max().orElse(12); if(wasPushLimit < pushLimit) - Zeta.GLOBAL_LOG.info("'{}' is raising Zeta's piston structure resolver push limit to {} blocks.", modid, pushLimit); + ZetaMod.LOGGER.info("'{}' is raising Zeta's piston structure resolver push limit to {} blocks.", modid, pushLimit); } } diff --git a/src/main/java/org/violetmoon/zeta/registry/CreativeTabManager.java b/src/main/java/org/violetmoon/zeta/registry/CreativeTabManager.java index 7fb0f92..0dcab31 100644 --- a/src/main/java/org/violetmoon/zeta/registry/CreativeTabManager.java +++ b/src/main/java/org/violetmoon/zeta/registry/CreativeTabManager.java @@ -11,8 +11,8 @@ import java.util.Map.Entry; import java.util.function.Supplier; -import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.config.ZetaGeneralConfig; +import org.violetmoon.zeta.mod.ZetaMod; import org.violetmoon.zeta.module.IDisableable; import com.google.common.collect.HashMultimap; @@ -144,7 +144,7 @@ public static void buildContents(BuildCreativeModeTabContentsEvent event) { logVerbose(() -> "front empty=" + front.isEmpty() + " / behind empty=" + behind.isEmpty()); if(entries.isEmpty()) { - Zeta.GLOBAL_LOG.error("entries map for tab " + tabKey + " is empty, this should never happen"); + ZetaMod.LOGGER.error("entries map for tab " + tabKey + " is empty, this should never happen"); return; } @@ -235,8 +235,8 @@ private static boolean appendNextTo(ResourceKey tabKey, Mutable logVerbose(() -> "target is " + target); if(log) { - Zeta.GLOBAL_LOG.error("Creative tab loop found when adding {} next to {}", firstSetItem, target); - Zeta.GLOBAL_LOG.error("For more info enable Creative Verbose Logging in the Zeta config, or set Force Creative Tab Appends to true to disable this behavior"); + ZetaMod.LOGGER.error("Creative tab loop found when adding {} next to {}", firstSetItem, target); + ZetaMod.LOGGER.error("For more info enable Creative Verbose Logging in the Zeta config, or set Force Creative Tab Appends to true to disable this behavior"); } map.remove(firstSet); @@ -277,7 +277,7 @@ private static boolean appendNextTo(ResourceKey tabKey, Mutable private static void logVerbose(Supplier s) { if(ZetaGeneralConfig.enableCreativeVerboseLogging) - Zeta.GLOBAL_LOG.warn(s.get()); + ZetaMod.LOGGER.warn(s.get()); } private static class CreativeTabAdditions { diff --git a/src/main/java/org/violetmoon/zeta/registry/ZetaRegistry.java b/src/main/java/org/violetmoon/zeta/registry/ZetaRegistry.java index 9787dc6..8fc463e 100644 --- a/src/main/java/org/violetmoon/zeta/registry/ZetaRegistry.java +++ b/src/main/java/org/violetmoon/zeta/registry/ZetaRegistry.java @@ -6,10 +6,11 @@ import java.util.IdentityHashMap; import java.util.List; import java.util.Map; -import java.util.function.BiConsumer; +import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Nullable; import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.item.ZetaBlockItem; @@ -141,14 +142,45 @@ public void clearDeferCache(ResourceLocation resourceLocation) { defers.removeAll(resourceLocation); } - public void finalizeBlockColors(BiConsumer consumer) { - blocksToColorProviderName.forEach(consumer); - blocksToColorProviderName.clear(); + @ApiStatus.Internal + public void assignBlockColor(String name, Consumer regFunc) { + boolean success = false; + var iterator = blocksToColorProviderName.entrySet().iterator(); + while(iterator.hasNext()) { + var entry = iterator.next(); + if(entry.getValue().equals(name)) { + success = true; + regFunc.accept(entry.getKey()); + iterator.remove(); + } + } + if (!success) + z.log.error("Unknown block color creator {} used on block", name); } - public void finalizeItemColors(BiConsumer consumer) { - itemsToColorProviderName.forEach(consumer); - itemsToColorProviderName.clear(); + @ApiStatus.Internal + public void assignItemColor(String name, Consumer regFunc) { + boolean success = false; + var iterator = itemsToColorProviderName.entrySet().iterator(); + while(iterator.hasNext()) { + var entry = iterator.next(); + if(entry.getValue().equals(name)) { + success = true; + regFunc.accept(entry.getKey()); + iterator.remove(); + } + } + if (!success) + z.log.error("Unknown item color creator {} used on item", name); + } + + @ApiStatus.Internal + public void validateColorsProviders(){ + if(!blocksToColorProviderName.isEmpty()) + z.log.error("Block color providers {} were not assigned to any blocks", blocksToColorProviderName.values()); + if(!itemsToColorProviderName.isEmpty()) + z.log.error("Item color providers {} were not assigned to any items", itemsToColorProviderName.values()); + } /// performing registration (dynamic registry jank - for registering ConfiguredFeature etc through code) /// diff --git a/src/main/java/org/violetmoon/zeta/util/ZetaSide.java b/src/main/java/org/violetmoon/zeta/util/ZetaSide.java index 7db143a..7d6eb42 100644 --- a/src/main/java/org/violetmoon/zeta/util/ZetaSide.java +++ b/src/main/java/org/violetmoon/zeta/util/ZetaSide.java @@ -1,5 +1,9 @@ package org.violetmoon.zeta.util; +/** + * Don't confuse with logical side. + * These two are better called as "Local Game" and "Dedicated Server" + */ public enum ZetaSide { CLIENT, SERVER; diff --git a/src/main/java/org/violetmoon/zeta/util/handler/RecipeCrawlHandler.java b/src/main/java/org/violetmoon/zeta/util/handler/RecipeCrawlHandler.java index ff0784e..a0bbe0e 100644 --- a/src/main/java/org/violetmoon/zeta/util/handler/RecipeCrawlHandler.java +++ b/src/main/java/org/violetmoon/zeta/util/handler/RecipeCrawlHandler.java @@ -7,15 +7,13 @@ import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Nullable; -import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.event.bus.IZetaPlayEvent; -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.zetalist.ZetaList; +import org.violetmoon.zeta.mod.ZetaMod; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; @@ -47,7 +45,7 @@ public class RecipeCrawlHandler { private static boolean needsCrawl = false; private static boolean mayCrawl = false; - @LoadEvent + @PlayEvent public static void addListener(ZAddReloadListener event) { event.addListener(new SimplePreparableReloadListener() { @Override @@ -63,7 +61,7 @@ protected void apply(Void what, ResourceManager mgr, ProfilerFiller prof) { }); } - @LoadEvent + @PlayEvent public static void tagsHaveUpdated(ZTagsUpdated event) { mayCrawl = true; } @@ -74,7 +72,7 @@ private static void clear() { } private static void fire(IZetaPlayEvent event) { - ZetaList.INSTANCE.fireEvent(event); + ZetaMod.ZETA.playBus.fire(event); } @SuppressWarnings("ConstantValue") @@ -96,7 +94,8 @@ private static void load(RecipeManager manager, RegistryAccess access) { if (recipe.getResultItem(access) == null) throw new IllegalStateException("Recipe getResultItem is null"); - ZRecipeCrawl.Visit event; + boolean isMisc = false; + IZetaPlayEvent event; if (recipe instanceof ShapedRecipe sr) event = new ZRecipeCrawl.Visit.Shaped(sr, access); else if (recipe instanceof ShapelessRecipe sr) @@ -105,20 +104,21 @@ 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 + else { event = new ZRecipeCrawl.Visit.Misc(recipe, access); - + isMisc = true; + } //misc recipes could have custom logic that we cant make many assumptions on. For example FD cutting board recipes are lossy. //for instance a hanging sign can be cut into a plank. A hanging sign is magnetic but this does not mean planks are - if(!(event instanceof ZRecipeCrawl.Visit.Misc)) { + if(!isMisc) { vanillaRecipesToLazyDigest.add(recipe); } fire(event); } catch (Exception e) { if (recipe == null) - Zeta.GLOBAL_LOG.error("Encountered null recipe in RecipeManager.getRecipes. This is not good"); + ZetaMod.LOGGER.error("Encountered null recipe in RecipeManager.getRecipes. This is not good"); else - Zeta.GLOBAL_LOG.error("Failed to scan recipe " + recipe.getId() + ". This should be reported to " + recipe.getId().getNamespace() + "!", e); + ZetaMod.LOGGER.error("Failed to scan recipe " + recipe.getId() + ". This should be reported to " + recipe.getId().getNamespace() + "!", e); } } } diff --git a/src/main/java/org/violetmoon/zeta/util/zetalist/ZetaList.java b/src/main/java/org/violetmoon/zeta/util/zetalist/ZetaList.java index f59ac40..e424f11 100644 --- a/src/main/java/org/violetmoon/zeta/util/zetalist/ZetaList.java +++ b/src/main/java/org/violetmoon/zeta/util/zetalist/ZetaList.java @@ -5,7 +5,6 @@ import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.event.bus.IZetaLoadEvent; -import org.violetmoon.zeta.event.bus.IZetaPlayEvent; public class ZetaList { @@ -19,19 +18,11 @@ public void register(T z) { knownZetas.add(z); } - public void fireEvent(E event) { - knownZetas.forEach(z -> z.asZeta().playBus.fire(event)); - } - - public void fireEvent(E event, Class eventClass) { - knownZetas.forEach(z -> z.asZeta().playBus.fire(event, eventClass)); - } - - public void fireEvent(E event) { + public void fireLoadEvent(E event) { knownZetas.forEach(z -> z.asZeta().loadBus.fire(event)); } - public void fireEvent(E event, Class eventClass) { + public void fireLoadEvent(E event, Class eventClass) { knownZetas.forEach(z -> z.asZeta().loadBus.fire(event, eventClass)); } diff --git a/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java b/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java index f11f24e..ec558bd 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java +++ b/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java @@ -1,109 +1,62 @@ package org.violetmoon.zetaimplforge; +import net.minecraft.core.BlockPos; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.FlowerPotBlock; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraftforge.client.event.RegisterColorHandlersEvent; +import net.minecraftforge.common.ForgeConfigSpec; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.AttachCapabilitiesEvent; +import net.minecraftforge.event.entity.player.PlayerInteractEvent; +import net.minecraftforge.eventbus.api.Event; +import net.minecraftforge.eventbus.api.EventPriority; +import net.minecraftforge.eventbus.api.IEventBus; +import net.minecraftforge.fml.ModList; +import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; +import net.minecraftforge.fml.loading.FMLEnvironment; +import net.minecraftforge.registries.RegisterEvent; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.Nullable; import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.block.ext.BlockExtensionFactory; import org.violetmoon.zeta.capability.ZetaCapabilityManager; +import org.violetmoon.zeta.client.event.load.*; +import org.violetmoon.zeta.client.event.play.*; import org.violetmoon.zeta.config.IZetaConfigInternals; import org.violetmoon.zeta.config.SectionDefinition; -import org.violetmoon.zeta.event.bus.ZResult; -import org.violetmoon.zeta.event.load.ZAddReloadListener; -import org.violetmoon.zeta.event.load.ZCommonSetup; -import org.violetmoon.zeta.event.load.ZEntityAttributeCreation; -import org.violetmoon.zeta.event.load.ZGatherAdvancementModifiers; -import org.violetmoon.zeta.event.load.ZLoadComplete; -import org.violetmoon.zeta.event.load.ZRegister; -import org.violetmoon.zeta.event.load.ZTagsUpdated; -import org.violetmoon.zeta.event.play.ZAnvilRepair; -import org.violetmoon.zeta.event.play.ZAnvilUpdate; -import org.violetmoon.zeta.event.play.ZBlock; -import org.violetmoon.zeta.event.play.ZBonemeal; -import org.violetmoon.zeta.event.play.ZFurnaceFuelBurnTime; -import org.violetmoon.zeta.event.play.ZItemTooltip; -import org.violetmoon.zeta.event.play.ZLevelTick; -import org.violetmoon.zeta.event.play.ZPlayNoteBlock; -import org.violetmoon.zeta.event.play.ZServerTick; -import org.violetmoon.zeta.event.play.entity.ZEntityConstruct; -import org.violetmoon.zeta.event.play.entity.ZEntityInteract; -import org.violetmoon.zeta.event.play.entity.ZEntityItemPickup; -import org.violetmoon.zeta.event.play.entity.ZEntityJoinLevel; -import org.violetmoon.zeta.event.play.entity.ZEntityMobGriefing; -import org.violetmoon.zeta.event.play.entity.ZEntityTeleport; -import org.violetmoon.zeta.event.play.entity.living.ZAnimalTame; -import org.violetmoon.zeta.event.play.entity.living.ZBabyEntitySpawn; -import org.violetmoon.zeta.event.play.entity.living.ZLivingChangeTarget; -import org.violetmoon.zeta.event.play.entity.living.ZLivingConversion; -import org.violetmoon.zeta.event.play.entity.living.ZLivingDeath; -import org.violetmoon.zeta.event.play.entity.living.ZLivingDrops; -import org.violetmoon.zeta.event.play.entity.living.ZLivingFall; -import org.violetmoon.zeta.event.play.entity.living.ZLivingTick; -import org.violetmoon.zeta.event.play.entity.living.ZMobSpawnEvent; -import org.violetmoon.zeta.event.play.entity.living.ZSleepingLocationCheck; -import org.violetmoon.zeta.event.play.entity.player.ZPlayer; -import org.violetmoon.zeta.event.play.entity.player.ZPlayerDestroyItem; -import org.violetmoon.zeta.event.play.entity.player.ZPlayerInteract; -import org.violetmoon.zeta.event.play.entity.player.ZPlayerTick; -import org.violetmoon.zeta.event.play.entity.player.ZRightClickBlock; -import org.violetmoon.zeta.event.play.entity.player.ZRightClickItem; -import org.violetmoon.zeta.event.play.loading.ZAttachCapabilities; -import org.violetmoon.zeta.event.play.loading.ZLootTableLoad; -import org.violetmoon.zeta.event.play.loading.ZVillagerTrades; -import org.violetmoon.zeta.event.play.loading.ZWandererTrades; +import org.violetmoon.zeta.event.bus.*; +import org.violetmoon.zeta.event.load.*; +import org.violetmoon.zeta.event.play.*; +import org.violetmoon.zeta.event.play.entity.*; +import org.violetmoon.zeta.event.play.entity.living.*; +import org.violetmoon.zeta.event.play.entity.player.*; +import org.violetmoon.zeta.event.play.loading.*; import org.violetmoon.zeta.item.ext.ItemExtensionFactory; import org.violetmoon.zeta.network.ZetaNetworkHandler; -import org.violetmoon.zeta.registry.BrewingRegistry; -import org.violetmoon.zeta.registry.CraftingExtensionsRegistry; -import org.violetmoon.zeta.registry.CreativeTabManager; -import org.violetmoon.zeta.registry.PottedPlantRegistry; -import org.violetmoon.zeta.registry.ZetaRegistry; +import org.violetmoon.zeta.registry.*; import org.violetmoon.zeta.util.RaytracingUtil; import org.violetmoon.zeta.util.ZetaSide; -import org.violetmoon.zetaimplforge.api.GatherAdvancementModifiersEvent; +import org.violetmoon.zetaimplforge.api.ForgeZGatherAdvancementModifiers; import org.violetmoon.zetaimplforge.block.IForgeBlockBlockExtensions; import org.violetmoon.zetaimplforge.capability.ForgeCapabilityManager; +import org.violetmoon.zetaimplforge.client.event.load.*; +import org.violetmoon.zetaimplforge.client.event.play.*; import org.violetmoon.zetaimplforge.config.ConfigEventDispatcher; import org.violetmoon.zetaimplforge.config.ForgeBackedConfig; import org.violetmoon.zetaimplforge.config.TerribleForgeConfigHackery; -import org.violetmoon.zetaimplforge.event.load.ForgeZAddReloadListener; -import org.violetmoon.zetaimplforge.event.load.ForgeZCommonSetup; -import org.violetmoon.zetaimplforge.event.load.ForgeZEntityAttributeCreation; -import org.violetmoon.zetaimplforge.event.load.ForgeZLoadComplete; -import org.violetmoon.zetaimplforge.event.play.ForgeZAnvilRepair; -import org.violetmoon.zetaimplforge.event.play.ForgeZAnvilUpdate; -import org.violetmoon.zetaimplforge.event.play.ForgeZBlock; -import org.violetmoon.zetaimplforge.event.play.ForgeZBonemeal; -import org.violetmoon.zetaimplforge.event.play.ForgeZFurnaceFuelBurnTime; -import org.violetmoon.zetaimplforge.event.play.ForgeZItemTooltip; -import org.violetmoon.zetaimplforge.event.play.ForgeZLevelTick; -import org.violetmoon.zetaimplforge.event.play.ForgeZPlayNoteBlock; -import org.violetmoon.zetaimplforge.event.play.ForgeZServerTick; -import org.violetmoon.zetaimplforge.event.play.entity.ForgeZEntityConstruct; -import org.violetmoon.zetaimplforge.event.play.entity.ForgeZEntityInteract; -import org.violetmoon.zetaimplforge.event.play.entity.ForgeZEntityItemPickup; -import org.violetmoon.zetaimplforge.event.play.entity.ForgeZEntityJoinLevel; -import org.violetmoon.zetaimplforge.event.play.entity.ForgeZEntityMobGriefing; -import org.violetmoon.zetaimplforge.event.play.entity.ForgeZEntityTeleport; -import org.violetmoon.zetaimplforge.event.play.entity.living.ForgeZAnimalTame; -import org.violetmoon.zetaimplforge.event.play.entity.living.ForgeZBabyEntitySpawn; -import org.violetmoon.zetaimplforge.event.play.entity.living.ForgeZLivingChangeTarget; -import org.violetmoon.zetaimplforge.event.play.entity.living.ForgeZLivingConversion; -import org.violetmoon.zetaimplforge.event.play.entity.living.ForgeZLivingDeath; -import org.violetmoon.zetaimplforge.event.play.entity.living.ForgeZLivingDrops; -import org.violetmoon.zetaimplforge.event.play.entity.living.ForgeZLivingFall; -import org.violetmoon.zetaimplforge.event.play.entity.living.ForgeZLivingTick; -import org.violetmoon.zetaimplforge.event.play.entity.living.ForgeZMobSpawnEvent; -import org.violetmoon.zetaimplforge.event.play.entity.living.ForgeZSleepingLocationCheck; -import org.violetmoon.zetaimplforge.event.play.entity.player.ForgeZPlayer; -import org.violetmoon.zetaimplforge.event.play.entity.player.ForgeZPlayerDestroyItem; -import org.violetmoon.zetaimplforge.event.play.entity.player.ForgeZPlayerInteract; -import org.violetmoon.zetaimplforge.event.play.entity.player.ForgeZPlayerTick; -import org.violetmoon.zetaimplforge.event.play.entity.player.ForgeZRightClickBlock; -import org.violetmoon.zetaimplforge.event.play.entity.player.ForgeZRightClickItem; -import org.violetmoon.zetaimplforge.event.play.loading.ForgeZAttachCapabilities; -import org.violetmoon.zetaimplforge.event.play.loading.ForgeZLootTableLoad; -import org.violetmoon.zetaimplforge.event.play.loading.ForgeZVillagerTrades; -import org.violetmoon.zetaimplforge.event.play.loading.ForgeZWandererTrades; +import org.violetmoon.zetaimplforge.event.ForgeZetaEventBus; +import org.violetmoon.zetaimplforge.event.load.*; +import org.violetmoon.zetaimplforge.event.play.*; +import org.violetmoon.zetaimplforge.event.play.entity.*; +import org.violetmoon.zetaimplforge.event.play.entity.living.*; +import org.violetmoon.zetaimplforge.event.play.entity.player.*; +import org.violetmoon.zetaimplforge.event.play.loading.*; import org.violetmoon.zetaimplforge.item.IForgeItemItemExtensions; import org.violetmoon.zetaimplforge.network.ForgeZetaNetworkHandler; import org.violetmoon.zetaimplforge.registry.ForgeBrewingRegistry; @@ -111,523 +64,144 @@ import org.violetmoon.zetaimplforge.registry.ForgeZetaRegistry; import org.violetmoon.zetaimplforge.util.ForgeRaytracingUtil; -import net.minecraft.core.BlockPos; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.FlowerPotBlock; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.phys.BlockHitResult; -import net.minecraftforge.common.ForgeConfigSpec; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.AddReloadListenerEvent; -import net.minecraftforge.event.AnvilUpdateEvent; -import net.minecraftforge.event.AttachCapabilitiesEvent; -import net.minecraftforge.event.LootTableLoadEvent; -import net.minecraftforge.event.TagsUpdatedEvent; -import net.minecraftforge.event.TickEvent; -import net.minecraftforge.event.entity.EntityAttributeCreationEvent; -import net.minecraftforge.event.entity.EntityEvent; -import net.minecraftforge.event.entity.EntityJoinLevelEvent; -import net.minecraftforge.event.entity.EntityMobGriefingEvent; -import net.minecraftforge.event.entity.EntityTeleportEvent; -import net.minecraftforge.event.entity.living.AnimalTameEvent; -import net.minecraftforge.event.entity.living.BabyEntitySpawnEvent; -import net.minecraftforge.event.entity.living.LivingChangeTargetEvent; -import net.minecraftforge.event.entity.living.LivingConversionEvent; -import net.minecraftforge.event.entity.living.LivingDeathEvent; -import net.minecraftforge.event.entity.living.LivingDropsEvent; -import net.minecraftforge.event.entity.living.LivingEvent; -import net.minecraftforge.event.entity.living.LivingFallEvent; -import net.minecraftforge.event.entity.living.MobSpawnEvent; -import net.minecraftforge.event.entity.player.AnvilRepairEvent; -import net.minecraftforge.event.entity.player.BonemealEvent; -import net.minecraftforge.event.entity.player.EntityItemPickupEvent; -import net.minecraftforge.event.entity.player.ItemTooltipEvent; -import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent; -import net.minecraftforge.event.entity.player.PlayerEvent; -import net.minecraftforge.event.entity.player.PlayerInteractEvent; -import net.minecraftforge.event.entity.player.SleepingLocationCheckEvent; -import net.minecraftforge.event.furnace.FurnaceFuelBurnTimeEvent; -import net.minecraftforge.event.level.BlockEvent; -import net.minecraftforge.event.level.NoteBlockEvent; -import net.minecraftforge.event.village.VillagerTradesEvent; -import net.minecraftforge.event.village.WandererTradesEvent; -import net.minecraftforge.eventbus.api.Event; -import net.minecraftforge.eventbus.api.EventPriority; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.ModList; -import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; -import net.minecraftforge.fml.event.lifecycle.FMLLoadCompleteEvent; -import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; -import net.minecraftforge.fml.loading.FMLEnvironment; -import net.minecraftforge.registries.RegisterEvent; +import java.util.function.Function; /** * ideally do not touch quark from this package, it will later be split off */ public class ForgeZeta extends Zeta { - public ForgeZeta(String modid, Logger log) { - super(modid, log, ZetaSide.fromClient(FMLEnvironment.dist.isClient())); - } - - @Override - public boolean isModLoaded(String modid) { - return ModList.get().isLoaded(modid); - } - - @Override - public @Nullable String getModDisplayName(String modid) { - return ModList.get().getModContainerById(modid) - .map(c -> c.getModInfo().getDisplayName()) - .orElse(null); - } - - @Override - public IZetaConfigInternals makeConfigInternals(SectionDefinition rootSection) { - ForgeConfigSpec.Builder bob = new ForgeConfigSpec.Builder(); - ForgeBackedConfig forge = new ForgeBackedConfig(rootSection, bob); - ForgeConfigSpec spec = bob.build(); - - TerribleForgeConfigHackery.registerAndLoadConfigEarlierThanUsual(spec); - - return forge; - } - - @Override - public ZetaRegistry createRegistry() { - return new ForgeZetaRegistry(this); - } - - @Override - public CraftingExtensionsRegistry createCraftingExtensionsRegistry() { - return new ForgeCraftingExtensionsRegistry(); - } - - @Override - public BrewingRegistry createBrewingRegistry() { - return new ForgeBrewingRegistry(this); - } - - @Override - public PottedPlantRegistry createPottedPlantRegistry() { - return (resloc, potted) -> ((FlowerPotBlock)Blocks.FLOWER_POT).addPlant(resloc, () -> potted); - } - - @Override - public ZetaCapabilityManager createCapabilityManager() { - return new ForgeCapabilityManager(); - } - - @Override - public BlockExtensionFactory createBlockExtensionFactory() { - return block -> IForgeBlockBlockExtensions.INSTANCE; - } - - @Override - public ItemExtensionFactory createItemExtensionFactory() { - return stack -> IForgeItemItemExtensions.INSTANCE; - } - - @Override - public RaytracingUtil createRaytracingUtil() { - return new ForgeRaytracingUtil(); - } - - @Override - public ZetaNetworkHandler createNetworkHandler(int protocolVersion) { - return new ForgeZetaNetworkHandler(this, protocolVersion); - } - - @Override - public boolean fireRightClickBlock(Player player, InteractionHand hand, BlockPos pos, BlockHitResult bhr) { - return MinecraftForge.EVENT_BUS.post(new PlayerInteractEvent.RightClickBlock(player, hand, pos, bhr)); - } - - @Override - public T fireExternalEvent(T impl) { - if(impl instanceof ZGatherAdvancementModifiers advancementModifiers) - MinecraftForge.EVENT_BUS.post(new GatherAdvancementModifiersEvent(this, advancementModifiers)); - - return impl; - } - - @SuppressWarnings("duplicates") - @Override - public void start() { - //TODO: sort these somehow lol - - //load - IEventBus modbus = FMLJavaModLoadingContext.get().getModEventBus(); - modbus.addListener(EventPriority.HIGHEST, this::registerHighest); - modbus.addListener(this::commonSetup); - modbus.addListener(this::loadComplete); - modbus.addListener(this::entityAttributeCreation); - MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); - MinecraftForge.EVENT_BUS.addListener(this::tagsUpdated); - - // TODO FIX very ugly & bad - modbus.addListener(EventPriority.LOWEST, CreativeTabManager::buildContents); - modbus.addListener(ConfigEventDispatcher::configChanged); - - //play - MinecraftForge.EVENT_BUS.addListener(this::rightClickBlock); - MinecraftForge.EVENT_BUS.addListener(EventPriority.LOW, this::rightClickBlockLow); - MinecraftForge.EVENT_BUS.addListener(this::rightClickItem); - MinecraftForge.EVENT_BUS.addListener(this::livingDeath); - MinecraftForge.EVENT_BUS.addListener(EventPriority.LOWEST, this::livingDeathLowest); - MinecraftForge.EVENT_BUS.addListener(this::livingTick); - MinecraftForge.EVENT_BUS.addListener(this::playNoteBlock); - MinecraftForge.EVENT_BUS.addListener(this::lootTableLoad); - MinecraftForge.EVENT_BUS.addListener(this::livingConversion); - MinecraftForge.EVENT_BUS.addListener(this::livingConversionPre); - MinecraftForge.EVENT_BUS.addListener(this::livingConversionPost); - MinecraftForge.EVENT_BUS.addListener(this::anvilUpdate); - MinecraftForge.EVENT_BUS.addListener(EventPriority.LOWEST, this::anvilUpdateLowest); - MinecraftForge.EVENT_BUS.addListener(EventPriority.HIGHEST, this::anvilUpdateHighest); - MinecraftForge.EVENT_BUS.addListener(this::entityConstruct); - MinecraftForge.EVENT_BUS.addListener(this::entityInteract); - MinecraftForge.EVENT_BUS.addListener(this::entityMobGriefing); - MinecraftForge.EVENT_BUS.addListener(this::livingDrops); - MinecraftForge.EVENT_BUS.addListener(this::livingDropsLowest); - MinecraftForge.EVENT_BUS.addListener(this::playerTickStart); - MinecraftForge.EVENT_BUS.addListener(this::playerTickEnd); - MinecraftForge.EVENT_BUS.addListener(this::babyEntitySpawn); - MinecraftForge.EVENT_BUS.addListener(this::babyEntitySpawnLowest); - MinecraftForge.EVENT_BUS.addListener(this::entityJoinLevel); - - MinecraftForge.EVENT_BUS.addGenericListener(ItemStack.class, this::itemStackCaps); - MinecraftForge.EVENT_BUS.addGenericListener(BlockEntity.class, this::blockEntityCaps); - MinecraftForge.EVENT_BUS.addGenericListener(Level.class, this::levelCaps); - - MinecraftForge.EVENT_BUS.addListener(this::serverTickStart); - MinecraftForge.EVENT_BUS.addListener(this::serverTickEnd); - MinecraftForge.EVENT_BUS.addListener(this::levelTickStart); - MinecraftForge.EVENT_BUS.addListener(this::levelTickEnd); - MinecraftForge.EVENT_BUS.addListener(this::playerInteract); - MinecraftForge.EVENT_BUS.addListener(this::playerInteractEntityInteractSpecific); - MinecraftForge.EVENT_BUS.addListener(this::playerInteractEntityInteract); - MinecraftForge.EVENT_BUS.addListener(this::playerInteractRightClickBlock); - MinecraftForge.EVENT_BUS.addListener(this::playerInteractRightClickItem); - MinecraftForge.EVENT_BUS.addListener(this::playerDestroyItem); - MinecraftForge.EVENT_BUS.addListener(this::mobSpawn); - MinecraftForge.EVENT_BUS.addListener(this::mobSpawnFinalizeSpawn); - MinecraftForge.EVENT_BUS.addListener(this::mobSpawnFinalizeSpawnLowest); - MinecraftForge.EVENT_BUS.addListener(this::livingChangeTarget); - MinecraftForge.EVENT_BUS.addListener(this::sleepingLocationCheck); - MinecraftForge.EVENT_BUS.addListener(this::villagerTrades); - MinecraftForge.EVENT_BUS.addListener(this::anvilRepair); - MinecraftForge.EVENT_BUS.addListener(this::player); - MinecraftForge.EVENT_BUS.addListener(this::playerBreakSpeed); - MinecraftForge.EVENT_BUS.addListener(this::playerClone); - MinecraftForge.EVENT_BUS.addListener(this::playerLoggedIn); - MinecraftForge.EVENT_BUS.addListener(this::playerLoggedOut); - MinecraftForge.EVENT_BUS.addListener(this::entityItemPickup); - MinecraftForge.EVENT_BUS.addListener(this::blockBreak); - MinecraftForge.EVENT_BUS.addListener(this::blockEntityPlace); - MinecraftForge.EVENT_BUS.addListener(this::blockToolModification); - MinecraftForge.EVENT_BUS.addListener(this::animalTame); - MinecraftForge.EVENT_BUS.addListener(this::bonemeal); - MinecraftForge.EVENT_BUS.addListener(this::entityTeleport); - MinecraftForge.EVENT_BUS.addListener(this::livingFall); - MinecraftForge.EVENT_BUS.addListener(this::wandererTrades); - MinecraftForge.EVENT_BUS.addListener(this::furnaceFuelBurnTime); - MinecraftForge.EVENT_BUS.addListener(this::itemTooltip); - } - - private boolean registerDone = false; - public void registerHighest(RegisterEvent e) { - if(registerDone) - return; - - registerDone = true; // do this *before* actually registering to prevent weird ??race conditions?? or something? - //idk whats going on, all i know is i started the game, got a log with 136 "duplicate criterion id" errors, and i don't want to see that again - - loadBus.fire(new ZRegister(this)); - loadBus.fire(new ZRegister.Post()); - } - - public void commonSetup(FMLCommonSetupEvent e) { - loadBus.fire(new ForgeZCommonSetup(e), ZCommonSetup.class); - } - - public void loadComplete(FMLLoadCompleteEvent e) { - loadBus.fire(new ForgeZLoadComplete(e), ZLoadComplete.class); - } - - public void entityAttributeCreation(EntityAttributeCreationEvent e) { - loadBus.fire(new ForgeZEntityAttributeCreation(e), ZEntityAttributeCreation.class); - } - - public void addReloadListener(AddReloadListenerEvent e) { - loadBus.fire(new ForgeZAddReloadListener(e), ZAddReloadListener.class); - } - - public void tagsUpdated(TagsUpdatedEvent e) { - loadBus.fire(new ZTagsUpdated()); - } - - public void rightClickBlock(PlayerInteractEvent.RightClickBlock e) { - playBus.fire(new ForgeZRightClickBlock(e), ZRightClickBlock.class); - } - - public void rightClickBlockLow(PlayerInteractEvent.RightClickBlock e) { - playBus.fire(new ForgeZRightClickBlock.Low(e), ZRightClickBlock.Low.class); - } - - public void rightClickItem(PlayerInteractEvent.RightClickItem e) { - playBus.fire(new ForgeZRightClickItem(e), ZRightClickItem.class); - } - - public void livingDeath(LivingDeathEvent e) { - playBus.fire(new ForgeZLivingDeath(e), ZLivingDeath.class); - } - - public void livingDeathLowest(LivingDeathEvent e) { - playBus.fire(new ForgeZLivingDeath.Lowest(e), ZLivingDeath.Lowest.class); - } - - public void livingTick(LivingEvent.LivingTickEvent e) { - playBus.fire(new ForgeZLivingTick(e), ZLivingTick.class); - } - - public void playNoteBlock(NoteBlockEvent.Play e) { - playBus.fire(new ForgeZPlayNoteBlock(e), ZPlayNoteBlock.class); - } - - public void lootTableLoad(LootTableLoadEvent e) { - playBus.fire(new ForgeZLootTableLoad(e), ZLootTableLoad.class); - } - - public void livingConversion(LivingConversionEvent e) { - playBus.fire(new ForgeZLivingConversion(e), ZLivingConversion.class); - } - - public void livingConversionPre(LivingConversionEvent.Pre e) { - playBus.fire(new ForgeZLivingConversion.Pre(e), ZLivingConversion.Pre.class); - } - - public void livingConversionPost(LivingConversionEvent.Post e) { - playBus.fire(new ForgeZLivingConversion.Post(e), ZLivingConversion.Post.class); - } - - public void anvilUpdate(AnvilUpdateEvent e) { - playBus.fire(new ForgeZAnvilUpdate(e), ZAnvilUpdate.class); - } - - public void anvilUpdateLowest(AnvilUpdateEvent e) { - playBus.fire(new ForgeZAnvilUpdate.Lowest(e), ZAnvilUpdate.Lowest.class); - } - - public void anvilUpdateHighest(AnvilUpdateEvent e) { - playBus.fire(new ForgeZAnvilUpdate.Highest(e), ZAnvilUpdate.Highest.class); - } - - public void entityConstruct(EntityEvent.EntityConstructing e) { - playBus.fire(new ForgeZEntityConstruct(e), ZEntityConstruct.class); - } - - public void entityInteract(PlayerInteractEvent.EntityInteract e) { - playBus.fire(new ForgeZEntityInteract(e), ZEntityInteract.class); - } - - public void entityMobGriefing(EntityMobGriefingEvent e) { - playBus.fire(new ForgeZEntityMobGriefing(e), ZEntityMobGriefing.class); - } - - public void livingDrops(LivingDropsEvent e) { - playBus.fire(new ForgeZLivingDrops(e), ZLivingDrops.class); - } - - public void livingDropsLowest(LivingDropsEvent e) { - playBus.fire(new ForgeZLivingDrops.Lowest(e), ZLivingDrops.Lowest.class); - } - - public void playerTickStart(TickEvent.PlayerTickEvent e) { - if (e.phase == TickEvent.Phase.START) - playBus.fire(new ForgeZPlayerTick.Start(e), ZPlayerTick.Start.class); - } - - public void playerTickEnd(TickEvent.PlayerTickEvent e) { - if (e.phase == TickEvent.Phase.END) - playBus.fire(new ForgeZPlayerTick.End(e), ZPlayerTick.End.class); - } - - public void babyEntitySpawn(BabyEntitySpawnEvent e) { - playBus.fire(new ForgeZBabyEntitySpawn(e), ZBabyEntitySpawn.class); - } - - public void babyEntitySpawnLowest(BabyEntitySpawnEvent e) { - playBus.fire(new ForgeZBabyEntitySpawn.Lowest(e), ZBabyEntitySpawn.Lowest.class); - } - - public void entityJoinLevel(EntityJoinLevelEvent e) { - playBus.fire(new ForgeZEntityJoinLevel(e), ZEntityJoinLevel.class); - } - - public void itemStackCaps(AttachCapabilitiesEvent e) { - playBus.fire(new ForgeZAttachCapabilities.ItemStackCaps(capabilityManager, e), ZAttachCapabilities.ItemStackCaps.class); - } - - public void blockEntityCaps(AttachCapabilitiesEvent e) { - playBus.fire(new ForgeZAttachCapabilities.BlockEntityCaps(capabilityManager, e), ZAttachCapabilities.BlockEntityCaps.class); - } - - public void levelCaps(AttachCapabilitiesEvent e) { - playBus.fire(new ForgeZAttachCapabilities.LevelCaps(capabilityManager, e), ZAttachCapabilities.LevelCaps.class); - } - - public void serverTickStart(TickEvent.ServerTickEvent e) { - if (e.phase == TickEvent.Phase.START) - playBus.fire(new ForgeZServerTick.Start(e), ZServerTick.Start.class); - } - - public void serverTickEnd(TickEvent.ServerTickEvent e) { - if (e.phase == TickEvent.Phase.END) - playBus.fire(new ForgeZServerTick.End(e), ZServerTick.End.class); - } - - public void levelTickStart(TickEvent.LevelTickEvent e) { - if (e.phase == TickEvent.Phase.START) - playBus.fire(new ForgeZLevelTick.Start(e), ZLevelTick.Start.class); - } - - public void levelTickEnd(TickEvent.LevelTickEvent e) { - if (e.phase == TickEvent.Phase.END) - playBus.fire(new ForgeZLevelTick.End(e), ZLevelTick.End.class); - } - - public void playerInteract(PlayerInteractEvent e) { - playBus.fire(new ForgeZPlayerInteract(e), ZPlayerInteract.class); - } - - public void playerInteractEntityInteractSpecific(PlayerInteractEvent.EntityInteractSpecific e) { - playBus.fire(new ForgeZPlayerInteract.EntityInteractSpecific(e), ZPlayerInteract.EntityInteractSpecific.class); - } - - public void playerInteractEntityInteract(PlayerInteractEvent.EntityInteract e) { - playBus.fire(new ForgeZPlayerInteract.EntityInteract(e), ZPlayerInteract.EntityInteract.class); - } - - public void playerInteractRightClickBlock(PlayerInteractEvent.RightClickBlock e) { - playBus.fire(new ForgeZPlayerInteract.RightClickBlock(e), ZPlayerInteract.RightClickBlock.class); - } - - public void playerInteractRightClickItem(PlayerInteractEvent.RightClickItem e) { - playBus.fire(new ForgeZPlayerInteract.RightClickItem(e), ZPlayerInteract.RightClickItem.class); - } - - public void playerDestroyItem(PlayerDestroyItemEvent e) { - playBus.fire(new ForgeZPlayerDestroyItem(e), ZPlayerDestroyItem.class); - } - - public void mobSpawn(MobSpawnEvent e) { - playBus.fire(new ForgeZMobSpawnEvent(e), ZMobSpawnEvent.class); - } - - public void mobSpawnFinalizeSpawn(MobSpawnEvent.FinalizeSpawn e) { - playBus.fire(new ForgeZMobSpawnEvent.FinalizeSpawn(e), ZMobSpawnEvent.CheckSpawn.class); - } - - public void mobSpawnFinalizeSpawnLowest(MobSpawnEvent.FinalizeSpawn e) { - playBus.fire(new ForgeZMobSpawnEvent.FinalizeSpawn.Lowest(e), ZMobSpawnEvent.CheckSpawn.Lowest.class); - } - - public void livingChangeTarget(LivingChangeTargetEvent e) { - playBus.fire(new ForgeZLivingChangeTarget(e), ZLivingChangeTarget.class); - } - - public void sleepingLocationCheck(SleepingLocationCheckEvent e) { - playBus.fire(new ForgeZSleepingLocationCheck(e), ZSleepingLocationCheck.class); - } - - public void entityItemPickup(EntityItemPickupEvent e) { - playBus.fire(new ForgeZEntityItemPickup(e), ZEntityItemPickup.class); - } - - public void blockBreak(BlockEvent.BreakEvent e) { - playBus.fire(new ForgeZBlock.Break(e), ZBlock.Break.class); - } - - public void blockEntityPlace(BlockEvent.EntityPlaceEvent e) { - playBus.fire(new ForgeZBlock.EntityPlace(e), ZBlock.EntityPlace.class); - } - - public void blockToolModification(BlockEvent.BlockToolModificationEvent e) { - playBus.fire(new ForgeZBlock.BlockToolModification(e), ZBlock.BlockToolModification.class); - } - - public void animalTame(AnimalTameEvent e) { - playBus.fire(new ForgeZAnimalTame(e), ZAnimalTame.class); - } - - public void villagerTrades(VillagerTradesEvent e) { - playBus.fire(new ForgeZVillagerTrades(e), ZVillagerTrades.class); - } - - public void anvilRepair(AnvilRepairEvent e) { - playBus.fire(new ForgeZAnvilRepair(e), ZAnvilRepair.class); - } - - public void player(PlayerEvent e) { - playBus.fire(new ForgeZPlayer(e), ZPlayer.class); - } - - public void playerBreakSpeed(PlayerEvent.BreakSpeed e) { - playBus.fire(new ForgeZPlayer.BreakSpeed(e), ZPlayer.BreakSpeed.class); - } - - public void playerClone(PlayerEvent.Clone e) { - playBus.fire(new ForgeZPlayer.Clone(e), ZPlayer.Clone.class); - } - - public void playerLoggedIn(PlayerEvent.PlayerLoggedInEvent e) { - playBus.fire(new ForgeZPlayer.LoggedIn(e), ZPlayer.LoggedIn.class); - } - - public void playerLoggedOut(PlayerEvent.PlayerLoggedOutEvent e) { - playBus.fire(new ForgeZPlayer.LoggedOut(e), ZPlayer.LoggedOut.class); - } - - public void bonemeal(BonemealEvent e) { - playBus.fire(new ForgeZBonemeal(e), ZBonemeal.class); - } - - public void entityTeleport(EntityTeleportEvent e) { - playBus.fire(new ForgeZEntityTeleport(e), ZEntityTeleport.class); - } - - public void livingFall(LivingFallEvent e) { - playBus.fire(new ForgeZLivingFall(e), ZLivingFall.class); - } - - public void wandererTrades(WandererTradesEvent e) { - playBus.fire(new ForgeZWandererTrades(e), ZWandererTrades.class); - } - - public void furnaceFuelBurnTime(FurnaceFuelBurnTimeEvent e) { - playBus.fire(new ForgeZFurnaceFuelBurnTime(e), ZFurnaceFuelBurnTime.class); - } - - public void itemTooltip(ItemTooltipEvent e) { - playBus.fire(new ForgeZItemTooltip(e), ZItemTooltip.class); - } - - public static ZResult from(Event.Result r) { - return switch(r) { - case DENY -> ZResult.DENY; - case DEFAULT -> ZResult.DEFAULT; - case ALLOW -> ZResult.ALLOW; - }; - } - - public static Event.Result to(ZResult r) { - return switch(r) { - case DENY -> Event.Result.DENY; - case DEFAULT -> Event.Result.DEFAULT; - case ALLOW -> Event.Result.ALLOW; - }; - } + public ForgeZeta(String modid, Logger log) { + super(modid, log, ZetaSide.fromClient(FMLEnvironment.dist.isClient()), FMLEnvironment.production); + } + + @Override + protected ZetaEventBus createLoadBus() { + //return new StandaloneZetaEventBus<>(LoadEvent.class, IZetaLoadEvent.class, log); + return ForgeZetaEventBus.ofLoadBus( log, this); + } + + @Override + protected ForgeZetaEventBus createPlayBus() { + return ForgeZetaEventBus.ofPlayBus(log, this); + } + + @Override + public boolean isModLoaded(String modid) { + return ModList.get().isLoaded(modid); + } + + @Override + public @Nullable String getModDisplayName(String modid) { + return ModList.get().getModContainerById(modid) + .map(c -> c.getModInfo().getDisplayName()) + .orElse(null); + } + + @Override + public IZetaConfigInternals makeConfigInternals(SectionDefinition rootSection) { + ForgeConfigSpec.Builder bob = new ForgeConfigSpec.Builder(); + ForgeBackedConfig forge = new ForgeBackedConfig(rootSection, bob); + ForgeConfigSpec spec = bob.build(); + + TerribleForgeConfigHackery.registerAndLoadConfigEarlierThanUsual(spec); + + return forge; + } + + @Override + public ZetaRegistry createRegistry() { + return new ForgeZetaRegistry(this); + } + + @Override + public CraftingExtensionsRegistry createCraftingExtensionsRegistry() { + return new ForgeCraftingExtensionsRegistry(); + } + + @Override + public BrewingRegistry createBrewingRegistry() { + return new ForgeBrewingRegistry(this); + } + + @Override + public PottedPlantRegistry createPottedPlantRegistry() { + return (resloc, potted) -> ((FlowerPotBlock) Blocks.FLOWER_POT).addPlant(resloc, () -> potted); + } + + @Override + public ZetaCapabilityManager createCapabilityManager() { + return ForgeCapabilityManager.INSTANCE; + } + + @Override + public BlockExtensionFactory createBlockExtensionFactory() { + return block -> IForgeBlockBlockExtensions.INSTANCE; + } + + @Override + public ItemExtensionFactory createItemExtensionFactory() { + return stack -> IForgeItemItemExtensions.INSTANCE; + } + + @Override + public RaytracingUtil createRaytracingUtil() { + return new ForgeRaytracingUtil(); + } + + @Override + public ZetaNetworkHandler createNetworkHandler(int protocolVersion) { + return new ForgeZetaNetworkHandler(this, protocolVersion); + } + + @Override + public boolean fireRightClickBlock(Player player, InteractionHand hand, BlockPos pos, BlockHitResult bhr) { + return MinecraftForge.EVENT_BUS.post(new PlayerInteractEvent.RightClickBlock(player, hand, pos, bhr)); + } + + @SuppressWarnings("duplicates") + @Override + public void start() { + super.start(); + //load + IEventBus modbus = FMLJavaModLoadingContext.get().getModEventBus(); + + modbus.addListener(EventPriority.LOWEST, CreativeTabManager::buildContents); + modbus.addListener(ConfigEventDispatcher::configChanged); + + modbus.addListener(EventPriority.HIGHEST, this::registerHighest); + } + + private boolean registerDone = false; + + public void registerHighest(RegisterEvent e) { + if (registerDone) + return; + + registerDone = true; // do this *before* actually registering to prevent weird ??race conditions?? or something? + //idk whats going on, all i know is i started the game, got a log with 136 "duplicate criterion id" errors, and i don't want to see that again + + loadBus.fire(new ForgeZRegister(this)); + loadBus.fire(new ForgeZRegister.Post()); + } + + + //public void addReloadListener(AddReloadListenerEvent e) { + // loadBus.fire(new ForgeZAddReloadListener(e), ZAddReloadListener.class); + //} + + public static ZResult from(Event.Result r) { + return switch (r) { + case DENY -> ZResult.DENY; + case DEFAULT -> ZResult.DEFAULT; + case ALLOW -> ZResult.ALLOW; + }; + } + + public static Event.Result to(ZResult r) { + return switch (r) { + case DENY -> Event.Result.DENY; + case DEFAULT -> Event.Result.DEFAULT; + case ALLOW -> Event.Result.ALLOW; + }; + } } diff --git a/src/main/java/org/violetmoon/zetaimplforge/api/GatherAdvancementModifiersEvent.java b/src/main/java/org/violetmoon/zetaimplforge/api/ForgeZGatherAdvancementModifiers.java similarity index 54% rename from src/main/java/org/violetmoon/zetaimplforge/api/GatherAdvancementModifiersEvent.java rename to src/main/java/org/violetmoon/zetaimplforge/api/ForgeZGatherAdvancementModifiers.java index e3630bb..fc827ac 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/api/GatherAdvancementModifiersEvent.java +++ b/src/main/java/org/violetmoon/zetaimplforge/api/ForgeZGatherAdvancementModifiers.java @@ -1,5 +1,6 @@ package org.violetmoon.zetaimplforge.api; +import net.minecraftforge.fml.event.IModBusEvent; import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.api.IAdvancementModifier; import org.violetmoon.zeta.api.IAdvancementModifierDelegate; @@ -7,31 +8,21 @@ import net.minecraftforge.eventbus.api.Event; -public class GatherAdvancementModifiersEvent extends Event implements ZGatherAdvancementModifiers { - private final Zeta zeta; - private final ZGatherAdvancementModifiers inner; +public class ForgeZGatherAdvancementModifiers extends Event implements ZGatherAdvancementModifiers, IModBusEvent { + private final ZGatherAdvancementModifiers wrapped; - public GatherAdvancementModifiersEvent(Zeta zeta, ZGatherAdvancementModifiers inner) { - this.zeta = zeta; - this.inner = inner; - } - - public Zeta getZeta() { - return zeta; - } - - public String getModid() { - return zeta.modid; + public ForgeZGatherAdvancementModifiers(ZGatherAdvancementModifiers inner) { + this.wrapped = inner; } @Override public void register(IAdvancementModifier modifier) { - inner.register(modifier); + wrapped.register(modifier); } @Override public IAdvancementModifierDelegate getDelegate() { - return inner.getDelegate(); + return wrapped.getDelegate(); } //Note there are a ton of default methods available in ZGatherAdvancementModifiers for you to call. diff --git a/src/main/java/org/violetmoon/zetaimplforge/capability/ForgeCapabilityManager.java b/src/main/java/org/violetmoon/zetaimplforge/capability/ForgeCapabilityManager.java index ffef9b3..e572102 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/capability/ForgeCapabilityManager.java +++ b/src/main/java/org/violetmoon/zetaimplforge/capability/ForgeCapabilityManager.java @@ -19,6 +19,15 @@ import net.minecraftforge.event.AttachCapabilitiesEvent; public class ForgeCapabilityManager implements ZetaCapabilityManager { + + //Why is this a singleton instance? + // Because attach capability event fires on the mod-independent PLAY bus and this would have to be passed in the event which just fires once instead of once per mod. + + public static final ForgeCapabilityManager INSTANCE = new ForgeCapabilityManager(); + + private ForgeCapabilityManager() { + } + protected Map, Capability> toForge = new IdentityHashMap<>(); @SuppressWarnings("unchecked") diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/ForgeZetaClient.java b/src/main/java/org/violetmoon/zetaimplforge/client/ForgeZetaClient.java index d1b29b4..f6c6d42 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/ForgeZetaClient.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/ForgeZetaClient.java @@ -1,59 +1,5 @@ package org.violetmoon.zetaimplforge.client; -import org.jetbrains.annotations.Nullable; -import org.violetmoon.zeta.Zeta; -import org.violetmoon.zeta.client.ClientRegistryExtension; -import org.violetmoon.zeta.client.HumanoidArmorModelGetter; -import org.violetmoon.zeta.client.ZetaClient; -import org.violetmoon.zeta.client.event.load.ZAddBlockColorHandlers; -import org.violetmoon.zeta.client.event.load.ZAddItemColorHandlers; -import org.violetmoon.zeta.client.event.load.ZAddModelLayers; -import org.violetmoon.zeta.client.event.load.ZAddModels; -import org.violetmoon.zeta.client.event.load.ZClientSetup; -import org.violetmoon.zeta.client.event.load.ZKeyMapping; -import org.violetmoon.zeta.client.event.load.ZModel; -import org.violetmoon.zeta.client.event.load.ZRegisterLayerDefinitions; -import org.violetmoon.zeta.client.event.load.ZRegisterReloadListeners; -import org.violetmoon.zeta.client.event.load.ZTooltipComponents; -import org.violetmoon.zeta.client.event.play.ZClientTick; -import org.violetmoon.zeta.client.event.play.ZFirstClientTick; -import org.violetmoon.zeta.client.event.play.ZGatherTooltipComponents; -import org.violetmoon.zeta.client.event.play.ZHighlightBlock; -import org.violetmoon.zeta.client.event.play.ZInput; -import org.violetmoon.zeta.client.event.play.ZInputUpdate; -import org.violetmoon.zeta.client.event.play.ZRenderContainerScreen; -import org.violetmoon.zeta.client.event.play.ZRenderGuiOverlay; -import org.violetmoon.zeta.client.event.play.ZRenderLiving; -import org.violetmoon.zeta.client.event.play.ZRenderPlayer; -import org.violetmoon.zeta.client.event.play.ZRenderTick; -import org.violetmoon.zeta.client.event.play.ZRenderTooltip; -import org.violetmoon.zeta.client.event.play.ZScreen; -import org.violetmoon.zeta.client.event.play.ZScreenshot; -import org.violetmoon.zeta.util.zetalist.ZetaClientList; -import org.violetmoon.zetaimplforge.client.event.load.ForgeZAddBlockColorHandlers; -import org.violetmoon.zetaimplforge.client.event.load.ForgeZAddItemColorHandlers; -import org.violetmoon.zetaimplforge.client.event.load.ForgeZAddModelLayers; -import org.violetmoon.zetaimplforge.client.event.load.ForgeZAddModels; -import org.violetmoon.zetaimplforge.client.event.load.ForgeZClientSetup; -import org.violetmoon.zetaimplforge.client.event.load.ForgeZKeyMapping; -import org.violetmoon.zetaimplforge.client.event.load.ForgeZModel; -import org.violetmoon.zetaimplforge.client.event.load.ForgeZRegisterLayerDefinitions; -import org.violetmoon.zetaimplforge.client.event.load.ForgeZTooltipComponents; -import org.violetmoon.zetaimplforge.client.event.play.ForgeZClientTick; -import org.violetmoon.zetaimplforge.client.event.play.ForgeZGatherTooltipComponents; -import org.violetmoon.zetaimplforge.client.event.play.ForgeZHighlightBlock; -import org.violetmoon.zetaimplforge.client.event.play.ForgeZInput; -import org.violetmoon.zetaimplforge.client.event.play.ForgeZInputUpdate; -import org.violetmoon.zetaimplforge.client.event.play.ForgeZRenderContainerScreen; -import org.violetmoon.zetaimplforge.client.event.play.ForgeZRenderGuiOverlay; -import org.violetmoon.zetaimplforge.client.event.play.ForgeZRenderLiving; -import org.violetmoon.zetaimplforge.client.event.play.ForgeZRenderPlayer; -import org.violetmoon.zetaimplforge.client.event.play.ForgeZRenderTick; -import org.violetmoon.zetaimplforge.client.event.play.ForgeZRenderTooltip; -import org.violetmoon.zetaimplforge.client.event.play.ForgeZScreen; -import org.violetmoon.zetaimplforge.mixin.mixins.client.AccessorBlockColors; -import org.violetmoon.zetaimplforge.mixin.mixins.client.AccessorItemColors; - import net.minecraft.client.Minecraft; import net.minecraft.client.color.block.BlockColor; import net.minecraft.client.color.block.BlockColors; @@ -65,349 +11,59 @@ import net.minecraft.world.item.Item; import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.Block; -import net.minecraftforge.client.event.ContainerScreenEvent; -import net.minecraftforge.client.event.EntityRenderersEvent; -import net.minecraftforge.client.event.InputEvent; -import net.minecraftforge.client.event.ModelEvent; -import net.minecraftforge.client.event.MovementInputUpdateEvent; -import net.minecraftforge.client.event.RegisterClientReloadListenersEvent; -import net.minecraftforge.client.event.RegisterClientTooltipComponentFactoriesEvent; -import net.minecraftforge.client.event.RegisterColorHandlersEvent; -import net.minecraftforge.client.event.RegisterKeyMappingsEvent; -import net.minecraftforge.client.event.RenderGuiOverlayEvent; -import net.minecraftforge.client.event.RenderHighlightEvent; -import net.minecraftforge.client.event.RenderLivingEvent; -import net.minecraftforge.client.event.RenderPlayerEvent; -import net.minecraftforge.client.event.RenderTooltipEvent; -import net.minecraftforge.client.event.ScreenEvent; -import net.minecraftforge.client.event.ScreenshotEvent; -import net.minecraftforge.client.gui.overlay.VanillaGuiOverlay; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.TickEvent; -import net.minecraftforge.eventbus.api.EventPriority; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; -import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.fml.util.thread.EffectiveSide; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.server.ServerLifecycleHooks; +import org.jetbrains.annotations.Nullable; +import org.violetmoon.zeta.Zeta; +import org.violetmoon.zeta.client.ClientRegistryExtension; +import org.violetmoon.zeta.client.HumanoidArmorModelGetter; +import org.violetmoon.zeta.client.ZetaClient; +import org.violetmoon.zeta.event.bus.StandaloneZetaEventBus; +import org.violetmoon.zetaimplforge.mixin.mixins.client.AccessorBlockColors; +import org.violetmoon.zetaimplforge.mixin.mixins.client.AccessorItemColors; public class ForgeZetaClient extends ZetaClient { - public ForgeZetaClient(Zeta z) { - super(z); - } - - @Override - public @Nullable BlockColor getBlockColor(BlockColors bcs, Block block) { - return ForgeRegistries.BLOCKS.getDelegate(block) - .map(ref -> ((AccessorBlockColors) bcs).zeta$getBlockColors().get(ref)) - .orElse(null); - } - - @Override - public @Nullable ItemColor getItemColor(ItemColors ics, ItemLike itemlike) { - return ForgeRegistries.ITEMS.getDelegate(itemlike.asItem()) - .map(ref -> ((AccessorItemColors) ics).zeta$getItemColors().get(ref)) - .orElse(null); - } - - @Override - public ClientRegistryExtension createClientRegistryExtension() { - return new ForgeClientRegistryExtension(zeta); - } - - @Override - public void setBlockEntityWithoutLevelRenderer(Item item, BlockEntityWithoutLevelRenderer bewlr) { - ((IZetaForgeItemStuff) item).zeta$setBlockEntityWithoutLevelRenderer(bewlr); - } - - @Override - public void setHumanoidArmorModel(Item item, HumanoidArmorModelGetter modelGetter) { - ((IZetaForgeItemStuff) item).zeta$setHumanoidArmorModel(modelGetter); - } - - @Override - public RegistryAccess hackilyGetCurrentClientLevelRegistryAccess() { - if(EffectiveSide.get().isServer()) - return ServerLifecycleHooks.getCurrentServer().registryAccess(); - - ClientPacketListener conn = Minecraft.getInstance().getConnection(); - return conn == null ? null : conn.registryAccess(); - } - - @Override - public void start() { - IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus(); - - bus.addListener(this::registerBlockColors); - bus.addListener(this::registerItemColors); - bus.addListener(this::clientSetup); - bus.addListener(this::registerReloadListeners); - bus.addListener(this::modelModifyBakingResult); - bus.addListener(this::modelBakingCompleted); - bus.addListener(this::modelRegisterAdditional); - bus.addListener(this::modelRegisterGeometryLoaders); - bus.addListener(this::modelLayers); - bus.addListener(this::registerKeybinds); - bus.addListener(this::registerAdditionalModels); - bus.addListener(this::registerClientTooltipComponentFactories); - bus.addListener(this::registerLayerDefinitions); - - MinecraftForge.EVENT_BUS.addListener(this::renderTick); - MinecraftForge.EVENT_BUS.addListener(this::clientTick); - MinecraftForge.EVENT_BUS.addListener(this::inputMouseButton); - MinecraftForge.EVENT_BUS.addListener(this::inputKey); - MinecraftForge.EVENT_BUS.addListener(this::screenshot); - MinecraftForge.EVENT_BUS.addListener(this::movementInputUpdate); - MinecraftForge.EVENT_BUS.addListener(this::renderBlockHighlight); - MinecraftForge.EVENT_BUS.addListener(this::gatherTooltipComponents); - - MinecraftForge.EVENT_BUS.addListener(this::renderContainerScreenForeground); - MinecraftForge.EVENT_BUS.addListener(this::renderContainerScreenBackground); - - MinecraftForge.EVENT_BUS.addListener(this::renderGameOverlayNeitherPreNorPost); - MinecraftForge.EVENT_BUS.addListener(this::renderGuiOverlayPre); - MinecraftForge.EVENT_BUS.addListener(this::renderGuiOverlayPost); - MinecraftForge.EVENT_BUS.addListener(this::renderPlayerPre); - MinecraftForge.EVENT_BUS.addListener(this::renderPlayerPost); - MinecraftForge.EVENT_BUS.addListener(EventPriority.HIGHEST, this::renderLivingPreHighest); - MinecraftForge.EVENT_BUS.addListener(EventPriority.LOWEST, this::renderLivingPostLowest); - MinecraftForge.EVENT_BUS.addListener(this::renderTooltipGatherComponents); - MinecraftForge.EVENT_BUS.addListener(this::renderTooltipGatherComponentsLow); - - MinecraftForge.EVENT_BUS.addListener(this::screenInitPre); - MinecraftForge.EVENT_BUS.addListener(this::screenInitPost); - MinecraftForge.EVENT_BUS.addListener(this::screenRenderPre); - MinecraftForge.EVENT_BUS.addListener(this::screenRenderPost); - MinecraftForge.EVENT_BUS.addListener(this::screenMouseButtonPressedPre); - MinecraftForge.EVENT_BUS.addListener(this::screenMouseButtonPressedPost); - MinecraftForge.EVENT_BUS.addListener(this::screenMouseScrolledPre); - MinecraftForge.EVENT_BUS.addListener(this::screenMouseScrolledPost); - MinecraftForge.EVENT_BUS.addListener(this::screenKeyPressedPre); - MinecraftForge.EVENT_BUS.addListener(this::screenKeyPressedPost); - MinecraftForge.EVENT_BUS.addListener(this::screenCharacterTypedPre); - MinecraftForge.EVENT_BUS.addListener(this::screenCharacterTypedPost); - MinecraftForge.EVENT_BUS.addListener(this::screenOpening); - } - - public void registerBlockColors(RegisterColorHandlersEvent.Block event) { - ZAddBlockColorHandlers e = loadBus.fire(new ForgeZAddBlockColorHandlers(event), ZAddBlockColorHandlers.class); - loadBus.fire(e.makePostEvent(), ZAddBlockColorHandlers.Post.class); - } - - public void registerItemColors(RegisterColorHandlersEvent.Item event) { - ZAddItemColorHandlers e = loadBus.fire(new ForgeZAddItemColorHandlers(event), ZAddItemColorHandlers.class); - loadBus.fire(e.makePostEvent(), ZAddItemColorHandlers.Post.class); - } - - public void clientSetup(FMLClientSetupEvent event) { - loadBus.fire(new ForgeZClientSetup(event), ZClientSetup.class); - } - - public void registerReloadListeners(RegisterClientReloadListenersEvent event) { - loadBus.fire(new ZRegisterReloadListeners(event::registerReloadListener), ZRegisterReloadListeners.class); - } - - public void modelModifyBakingResult(ModelEvent.ModifyBakingResult e) { - loadBus.fire(new ForgeZModel.ModifyBakingResult(e), ZModel.ModifyBakingResult.class); - } - - public void modelBakingCompleted(ModelEvent.BakingCompleted e) { - loadBus.fire(new ForgeZModel.BakingCompleted(e), ZModel.BakingCompleted.class); - } - - public void modelRegisterAdditional(ModelEvent.RegisterAdditional e) { - loadBus.fire(new ForgeZModel.RegisterAdditional(e), ZModel.RegisterAdditional.class); - } - - public void modelRegisterGeometryLoaders(ModelEvent.RegisterGeometryLoaders e) { - loadBus.fire(new ForgeZModel.RegisterGeometryLoaders(e), ZModel.RegisterGeometryLoaders.class); - } - - public void modelLayers(EntityRenderersEvent.AddLayers event) { - loadBus.fire(new ForgeZAddModelLayers(event), ZAddModelLayers.class); - } - - public void registerKeybinds(RegisterKeyMappingsEvent event) { - loadBus.fire(new ForgeZKeyMapping(event), ZKeyMapping.class); - } - - public void registerAdditionalModels(ModelEvent.RegisterAdditional event) { - loadBus.fire(new ForgeZAddModels(event), ZAddModels.class); - } - - public void registerClientTooltipComponentFactories(RegisterClientTooltipComponentFactoriesEvent event) { - loadBus.fire(new ForgeZTooltipComponents(event), ZTooltipComponents.class); - } - - public void registerLayerDefinitions(EntityRenderersEvent.RegisterLayerDefinitions e) { - loadBus.fire(new ForgeZRegisterLayerDefinitions(e), ZRegisterLayerDefinitions.class); - } - - //TODO: move ticker stuff out of forge event handlers, subscribe to them from zeta - // Also these events are a mess lol; sometimes there's 2 start/end events, sometimes there's - // one event with multiple Phases... bad - public void renderTick(TickEvent.RenderTickEvent e) { - playBus.fire(new ForgeZRenderTick(e), ZRenderTick.class); - } - - boolean clientTicked = false; - public void clientTick(TickEvent.ClientTickEvent e) { - if(!clientTicked) { - loadBus.fire(new ZFirstClientTick()); - clientTicked = true; - } - - playBus.fire(new ForgeZClientTick(e), ZClientTick.class); - } - - public void inputMouseButton(InputEvent.MouseButton e) { - playBus.fire(new ForgeZInput.MouseButton(e), ZInput.MouseButton.class); - } - - public void inputKey(InputEvent.Key e) { - playBus.fire(new ForgeZInput.Key(e), ZInput.Key.class); - } - - public void screenshot(ScreenshotEvent e) { - playBus.fire(new ZScreenshot()); - } - - public void movementInputUpdate(MovementInputUpdateEvent e) { - playBus.fire(new ForgeZInputUpdate(e), ZInputUpdate.class); - } - - public void renderBlockHighlight(RenderHighlightEvent.Block e) { - playBus.fire(new ForgeZHighlightBlock(e), ZHighlightBlock.class); - } - - public void gatherTooltipComponents(RenderTooltipEvent.GatherComponents e) { - playBus.fire(new ForgeZGatherTooltipComponents(e), ZGatherTooltipComponents.class); - } - - public void renderContainerScreenForeground(ContainerScreenEvent.Render.Foreground e) { - playBus.fire(new ForgeZRenderContainerScreen.Foreground(e), ZRenderContainerScreen.Foreground.class); - } - - public void renderContainerScreenBackground(ContainerScreenEvent.Render.Background e) { - playBus.fire(new ForgeZRenderContainerScreen.Background(e), ZRenderContainerScreen.Background.class); - } - - //TODO: This probably should have been a PRE/POST event (just copying quark here) - public void renderGameOverlayNeitherPreNorPost(RenderGuiOverlayEvent e) { - if(e.getOverlay() == VanillaGuiOverlay.CROSSHAIR.type()) - playBus.fire(new ForgeZRenderGuiOverlay.Crosshair(e), ZRenderGuiOverlay.Crosshair.class); - else if(e.getOverlay() == VanillaGuiOverlay.HOTBAR.type()) - playBus.fire(new ForgeZRenderGuiOverlay.Hotbar(e), ZRenderGuiOverlay.Hotbar.class); - } - - public void renderGuiOverlayPre(RenderGuiOverlayEvent.Pre e) { - if (e.getOverlay() == VanillaGuiOverlay.HOTBAR.type()) - playBus.fire(new ForgeZRenderGuiOverlay.Hotbar.Pre(e), ZRenderGuiOverlay.Hotbar.Pre.class); - else if (e.getOverlay() == VanillaGuiOverlay.CROSSHAIR.type()) - playBus.fire(new ForgeZRenderGuiOverlay.Crosshair.Pre(e), ZRenderGuiOverlay.Crosshair.Pre.class); - else if (e.getOverlay() == VanillaGuiOverlay.PLAYER_HEALTH.type()) - playBus.fire(new ForgeZRenderGuiOverlay.PlayerHealth.Pre(e), ZRenderGuiOverlay.PlayerHealth.Pre.class); - else if (e.getOverlay() == VanillaGuiOverlay.ARMOR_LEVEL.type()) - playBus.fire(new ForgeZRenderGuiOverlay.ArmorLevel.Pre(e), ZRenderGuiOverlay.ArmorLevel.Pre.class); - else if (e.getOverlay() == VanillaGuiOverlay.DEBUG_TEXT.type()) - playBus.fire(new ForgeZRenderGuiOverlay.DebugText.Pre(e), ZRenderGuiOverlay.DebugText.Pre.class); - else if (e.getOverlay() == VanillaGuiOverlay.POTION_ICONS.type()) - playBus.fire(new ForgeZRenderGuiOverlay.PotionIcons.Pre(e), ZRenderGuiOverlay.PotionIcons.Pre.class); - else if (e.getOverlay() == VanillaGuiOverlay.CHAT_PANEL.type()) - playBus.fire(new ForgeZRenderGuiOverlay.ChatPanel.Pre(e), ZRenderGuiOverlay.ChatPanel.Pre.class); - } - - public void renderGuiOverlayPost(RenderGuiOverlayEvent.Post e) { - if (e.getOverlay() == VanillaGuiOverlay.HOTBAR.type()) - playBus.fire(new ForgeZRenderGuiOverlay.Hotbar.Post(e), ZRenderGuiOverlay.Hotbar.Post.class); - else if (e.getOverlay() == VanillaGuiOverlay.CROSSHAIR.type()) - playBus.fire(new ForgeZRenderGuiOverlay.Crosshair.Post(e), ZRenderGuiOverlay.Crosshair.Post.class); - else if (e.getOverlay() == VanillaGuiOverlay.PLAYER_HEALTH.type()) - playBus.fire(new ForgeZRenderGuiOverlay.PlayerHealth.Post(e), ZRenderGuiOverlay.PlayerHealth.Post.class); - else if (e.getOverlay() == VanillaGuiOverlay.ARMOR_LEVEL.type()) - playBus.fire(new ForgeZRenderGuiOverlay.ArmorLevel.Post(e), ZRenderGuiOverlay.ArmorLevel.Post.class); - else if (e.getOverlay() == VanillaGuiOverlay.DEBUG_TEXT.type()) - playBus.fire(new ForgeZRenderGuiOverlay.DebugText.Post(e), ZRenderGuiOverlay.DebugText.Post.class); - else if (e.getOverlay() == VanillaGuiOverlay.POTION_ICONS.type()) - playBus.fire(new ForgeZRenderGuiOverlay.PotionIcons.Post(e), ZRenderGuiOverlay.PotionIcons.Post.class); - else if (e.getOverlay() == VanillaGuiOverlay.CHAT_PANEL.type()) - playBus.fire(new ForgeZRenderGuiOverlay.ChatPanel.Post(e), ZRenderGuiOverlay.ChatPanel.Post.class); - } - - public void renderPlayerPre(RenderPlayerEvent.Pre e) { - playBus.fire(new ForgeZRenderPlayer.Pre(e), ZRenderPlayer.Pre.class); - } - - public void renderPlayerPost(RenderPlayerEvent.Post e) { - playBus.fire(new ForgeZRenderPlayer.Post(e), ZRenderPlayer.Post.class); - } - - public void renderLivingPreHighest(RenderLivingEvent.Pre e) { - playBus.fire(new ForgeZRenderLiving.PreHighest(e), ZRenderLiving.PreHighest.class); - } - - public void renderLivingPostLowest(RenderLivingEvent.Post e) { - playBus.fire(new ForgeZRenderLiving.PostLowest(e), ZRenderLiving.PostLowest.class); - } - - public void renderTooltipGatherComponents(RenderTooltipEvent.GatherComponents e) { - playBus.fire(new ForgeZRenderTooltip.GatherComponents(e), ZRenderTooltip.GatherComponents.class); - } - - public void renderTooltipGatherComponentsLow(RenderTooltipEvent.GatherComponents e) { - playBus.fire(new ForgeZRenderTooltip.GatherComponents.Low(e), ZRenderTooltip.GatherComponents.Low.class); - } - - public void screenInitPre(ScreenEvent.Init.Pre e) { - playBus.fire(new ForgeZScreen.Init.Pre(e), ZScreen.Init.Pre.class); - } - - public void screenInitPost(ScreenEvent.Init.Post e) { - playBus.fire(new ForgeZScreen.Init.Post(e), ZScreen.Init.Post.class); - } - - public void screenRenderPre(ScreenEvent.Render.Pre e) { - playBus.fire(new ForgeZScreen.Render.Pre(e), ZScreen.Render.Pre.class); - } - - public void screenRenderPost(ScreenEvent.Render.Post e) { - playBus.fire(new ForgeZScreen.Render.Post(e), ZScreen.Render.Post.class); - } - - public void screenMouseButtonPressedPre(ScreenEvent.MouseButtonPressed.Pre e) { - playBus.fire(new ForgeZScreen.MouseButtonPressed.Pre(e), ZScreen.MouseButtonPressed.Pre.class); - } - - public void screenMouseButtonPressedPost(ScreenEvent.MouseButtonPressed.Post e) { - playBus.fire(new ForgeZScreen.MouseButtonPressed.Post(e), ZScreen.MouseButtonPressed.Post.class); - } - - public void screenMouseScrolledPre(ScreenEvent.MouseScrolled.Pre e) { - playBus.fire(new ForgeZScreen.MouseScrolled.Pre(e), ZScreen.MouseScrolled.Pre.class); - } - - public void screenMouseScrolledPost(ScreenEvent.MouseScrolled.Post e) { - playBus.fire(new ForgeZScreen.MouseScrolled.Post(e), ZScreen.MouseScrolled.Post.class); - } - - public void screenKeyPressedPre(ScreenEvent.KeyPressed.Pre e) { - playBus.fire(new ForgeZScreen.KeyPressed.Pre(e), ZScreen.KeyPressed.Pre.class); - } - - public void screenKeyPressedPost(ScreenEvent.KeyPressed.Post e) { - playBus.fire(new ForgeZScreen.KeyPressed.Post(e), ZScreen.KeyPressed.Post.class); - } - - public void screenCharacterTypedPre(ScreenEvent.CharacterTyped.Pre e) { - playBus.fire(new ForgeZScreen.CharacterTyped.Pre(e), ZScreen.CharacterTyped.Pre.class); - } - - public void screenCharacterTypedPost(ScreenEvent.CharacterTyped.Post e) { - playBus.fire(new ForgeZScreen.CharacterTyped.Post(e), ZScreen.CharacterTyped.Post.class); - } + public ForgeZetaClient(Zeta z) { + super(z); + } + + @Override + public @Nullable BlockColor getBlockColor(BlockColors bcs, Block block) { + return ForgeRegistries.BLOCKS.getDelegate(block) + .map(ref -> ((AccessorBlockColors) bcs).zeta$getBlockColors().get(ref)) + .orElse(null); + } + + @Override + public @Nullable ItemColor getItemColor(ItemColors ics, ItemLike itemlike) { + return ForgeRegistries.ITEMS.getDelegate(itemlike.asItem()) + .map(ref -> ((AccessorItemColors) ics).zeta$getItemColors().get(ref)) + .orElse(null); + } + + @Override + public ClientRegistryExtension createClientRegistryExtension() { + return new ForgeClientRegistryExtension(zeta); + } + + @Override + public void setBlockEntityWithoutLevelRenderer(Item item, BlockEntityWithoutLevelRenderer bewlr) { + ((IZetaForgeItemStuff) item).zeta$setBlockEntityWithoutLevelRenderer(bewlr); + } + + @Override + public void setHumanoidArmorModel(Item item, HumanoidArmorModelGetter modelGetter) { + ((IZetaForgeItemStuff) item).zeta$setHumanoidArmorModel(modelGetter); + } + + @Override + public RegistryAccess hackilyGetCurrentClientLevelRegistryAccess() { + if (EffectiveSide.get().isServer()) + return ServerLifecycleHooks.getCurrentServer().registryAccess(); + + ClientPacketListener conn = Minecraft.getInstance().getConnection(); + return conn == null ? null : conn.registryAccess(); + } - public void screenOpening(ScreenEvent.Opening e) { - playBus.fire(new ForgeZScreen.Opening(e), ZScreen.Opening.class); - } } diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZAddBlockColorHandlers.java b/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZAddBlockColorHandlers.java index 8c705d3..4b194c5 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZAddBlockColorHandlers.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZAddBlockColorHandlers.java @@ -1,58 +1,40 @@ package org.violetmoon.zetaimplforge.client.event.load; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; - -import org.violetmoon.zeta.client.event.load.ZAddBlockColorHandlers; - import net.minecraft.client.color.block.BlockColor; import net.minecraft.client.color.block.BlockColors; import net.minecraft.world.level.block.Block; import net.minecraftforge.client.event.RegisterColorHandlersEvent; +import org.violetmoon.zeta.Zeta; +import org.violetmoon.zeta.client.event.load.ZAddBlockColorHandlers; +import org.violetmoon.zeta.registry.ZetaRegistry; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; public class ForgeZAddBlockColorHandlers implements ZAddBlockColorHandlers { - protected final RegisterColorHandlersEvent.Block e; - protected final Map> namedBlockColors; - - public ForgeZAddBlockColorHandlers(RegisterColorHandlersEvent.Block e) { - this(e, new HashMap<>()); - } - - protected ForgeZAddBlockColorHandlers(RegisterColorHandlersEvent.Block e, Map> namedBlockColors) { - this.e = e; - this.namedBlockColors = namedBlockColors; - } - - @Override - public void register(BlockColor blockColor, Block... blocks) { - e.register(blockColor, blocks); - } - - @Override - public void registerNamed(Function c, String... names) { - for(String name : names) - namedBlockColors.put(name, c); - } - - @Override - public BlockColors getBlockColors() { - return e.getBlockColors(); - } - - @Override - public ZAddBlockColorHandlers.Post makePostEvent() { - return new Post(e, namedBlockColors); - } - - public static class Post extends ForgeZAddBlockColorHandlers implements ZAddBlockColorHandlers.Post { - public Post(RegisterColorHandlersEvent.Block e, Map> namedBlockColors) { - super(e, namedBlockColors); - } - - @Override - public Map> getNamedBlockColors() { - return namedBlockColors; - } - } + protected final RegisterColorHandlersEvent.Block e; + + public ForgeZAddBlockColorHandlers(RegisterColorHandlersEvent.Block e) { + this.e = e; + } + + @Override + public void register(BlockColor blockColor, Block... blocks) { + e.register(blockColor, blocks); + } + + // yes passing zeta like this here is terribly ugly but i cant add more params to this event since it's a forge event wrapper + @Override + public void registerNamed(Zeta myZeta, Function c, String... names) { + for (String name : names) { + myZeta.registry.assignBlockColor(name, b -> register(c.apply(b), b)); + } + } + + @Override + public BlockColors getBlockColors() { + return e.getBlockColors(); + } + } diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZAddItemColorHandlers.java b/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZAddItemColorHandlers.java index de05e1c..1579372 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZAddItemColorHandlers.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZAddItemColorHandlers.java @@ -1,9 +1,8 @@ package org.violetmoon.zetaimplforge.client.event.load; -import java.util.HashMap; -import java.util.Map; import java.util.function.Function; +import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.client.event.load.ZAddItemColorHandlers; import net.minecraft.client.color.item.ItemColor; @@ -14,15 +13,9 @@ public class ForgeZAddItemColorHandlers implements ZAddItemColorHandlers { protected final RegisterColorHandlersEvent.Item e; - protected final Map> namedItemColors; public ForgeZAddItemColorHandlers(RegisterColorHandlersEvent.Item e) { - this(e, new HashMap<>()); - } - - public ForgeZAddItemColorHandlers(RegisterColorHandlersEvent.Item e, Map> namedItemColors) { this.e = e; - this.namedItemColors = namedItemColors; } @Override @@ -31,9 +24,10 @@ public void register(ItemColor c, ItemLike... items) { } @Override - public void registerNamed(Function c, String... names) { - for(String name : names) - namedItemColors.put(name, c); + public void registerNamed(Zeta myZeta, Function c, String... names) { + for (String name : names) { + myZeta.registry.assignItemColor(name, b -> register(c.apply(b), b)); + } } @Override @@ -41,19 +35,4 @@ public ItemColors getItemColors() { return e.getItemColors(); } - @Override - public Post makePostEvent() { - return new Post(e, namedItemColors); - } - - public static class Post extends ForgeZAddItemColorHandlers implements ZAddItemColorHandlers.Post { - public Post(RegisterColorHandlersEvent.Item e, Map> namedItemColors) { - super(e, namedItemColors); - } - - @Override - public Map> getNamedItemColors() { - return namedItemColors; - } - } } diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZModel.java b/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZModel.java index 3ad2b97..b897be6 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZModel.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZModel.java @@ -12,6 +12,7 @@ import net.minecraftforge.client.model.geometry.IGeometryLoader; public class ForgeZModel implements ZModel { + public static class ModifyBakingResult extends ForgeZModel implements ZModel.ModifyBakingResult { private final ModelEvent.ModifyBakingResult e; diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZClientTick.java b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZClientTick.java index 3a82e0f..a950ad9 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZClientTick.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZClientTick.java @@ -1,34 +1,26 @@ package org.violetmoon.zetaimplforge.client.event.play; import org.violetmoon.zeta.client.event.play.ZClientTick; -import org.violetmoon.zeta.event.bus.ZPhase; import net.minecraftforge.event.TickEvent.ClientTickEvent; -import net.minecraftforge.event.TickEvent.Phase; public class ForgeZClientTick implements ZClientTick { - private final ClientTickEvent e; + public final ClientTickEvent e; public ForgeZClientTick(ClientTickEvent e) { this.e = e; } - @Override - public ZPhase getPhase() { - return from(e.phase); + public static class Start extends ForgeZClientTick implements ZClientTick.Start { + public Start(ClientTickEvent e) { + super(e); + } } - public static ZPhase from(Phase r) { - return switch(r) { - case START -> ZPhase.START; - case END -> ZPhase.END; - }; + public static class End extends ForgeZClientTick implements ZClientTick.End { + public End(ClientTickEvent e) { + super(e); + } } - public static Phase to(ZPhase r) { - return switch(r) { - case START -> Phase.START; - case END -> Phase.END; - }; - } } diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZEarlyRender.java b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZEarlyRender.java index 86e206c..06816e7 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZEarlyRender.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZEarlyRender.java @@ -1,11 +1,12 @@ package org.violetmoon.zetaimplforge.client.event.play; +import net.minecraftforge.eventbus.api.Event; import org.violetmoon.zeta.client.event.play.ZEarlyRender; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; -public class ForgeZEarlyRender implements ZEarlyRender { +public class ForgeZEarlyRender extends Event implements ZEarlyRender { @Override public GuiGraphics guiGraphics() { return new GuiGraphics(Minecraft.getInstance(), Minecraft.getInstance().renderBuffers().bufferSource()); diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderGuiOverlay.java b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderGuiOverlay.java index 3a589a4..6843279 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderGuiOverlay.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderGuiOverlay.java @@ -1,5 +1,6 @@ package org.violetmoon.zetaimplforge.client.event.play; +import net.minecraftforge.eventbus.api.Event; import org.violetmoon.zeta.client.event.play.ZRenderGuiOverlay; import com.mojang.blaze3d.platform.Window; @@ -9,8 +10,8 @@ import net.minecraftforge.client.event.RenderGuiOverlayEvent; import net.minecraftforge.client.gui.overlay.ForgeGui; -public class ForgeZRenderGuiOverlay implements ZRenderGuiOverlay { - private final RenderGuiOverlayEvent e; +public class ForgeZRenderGuiOverlay implements ZRenderGuiOverlay { + public final RenderGuiOverlayEvent e; public ForgeZRenderGuiOverlay(RenderGuiOverlayEvent e) { this.e = e; diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderLiving.java b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderLiving.java index 23b6fd3..385a837 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderLiving.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderLiving.java @@ -8,7 +8,7 @@ import net.minecraftforge.client.event.RenderLivingEvent; public abstract class ForgeZRenderLiving implements ZRenderLiving { - protected final RenderLivingEvent e; + public final RenderLivingEvent e; public ForgeZRenderLiving(RenderLivingEvent e) { this.e = e; diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderPlayer.java b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderPlayer.java index 76019e1..2988bc1 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderPlayer.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderPlayer.java @@ -8,9 +8,10 @@ import net.minecraft.client.renderer.entity.player.PlayerRenderer; import net.minecraft.world.entity.player.Player; import net.minecraftforge.client.event.RenderPlayerEvent; +import org.violetmoon.zeta.event.bus.IZetaPlayEvent; public abstract class ForgeZRenderPlayer implements ZRenderPlayer { - private final RenderPlayerEvent e; + public final RenderPlayerEvent e; public ForgeZRenderPlayer(RenderPlayerEvent e) { this.e = e; @@ -35,12 +36,14 @@ public ForgeZRenderPlayer(RenderPlayerEvent e) { public Player getEntity() {return e.getEntity();} public static class Pre extends ForgeZRenderPlayer implements ZRenderPlayer.Pre { + public Pre(RenderPlayerEvent.Pre e) { super(e); } } - public static class Post extends ForgeZRenderPlayer implements ZRenderPlayer.Post { + public static class Post extends ForgeZRenderPlayer implements ZRenderPlayer.Post, IZetaPlayEvent { + public Post(RenderPlayerEvent.Post e) { super(e); } diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderTick.java b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderTick.java index b79fa10..d8611d3 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderTick.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderTick.java @@ -4,14 +4,30 @@ import net.minecraftforge.event.TickEvent; -public record ForgeZRenderTick(TickEvent.RenderTickEvent e) implements ZRenderTick { - @Override - public float getRenderTickTime() { - return e.renderTickTime; +import java.util.Objects; + +public class ForgeZRenderTick implements ZRenderTick { + public final TickEvent.RenderTickEvent e; + + public ForgeZRenderTick(TickEvent.RenderTickEvent e) { + this.e = e; + } + + @Override + public float getRenderTickTime() { + return e.renderTickTime; + } + + public static class Start extends ForgeZRenderTick implements ZRenderTick.Start { + public Start(TickEvent.RenderTickEvent e) { + super(e); + } } - @Override - public boolean isEndPhase() { - return e.phase == TickEvent.Phase.END; + public static class End extends ForgeZRenderTick implements ZRenderTick.End { + public End(TickEvent.RenderTickEvent e) { + super(e); + } } + } diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZScreen.java b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZScreen.java index ae7b6f6..be632e2 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZScreen.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZScreen.java @@ -10,7 +10,7 @@ import net.minecraftforge.client.event.ScreenEvent; public class ForgeZScreen implements ZScreen { - private final ScreenEvent e; + public final ScreenEvent e; public ForgeZScreen(ScreenEvent e) { this.e = e; @@ -58,7 +58,7 @@ public Post(ScreenEvent.Init.Post e) { } public static class Render extends ForgeZScreen implements ZScreen.Render { - private final ScreenEvent.Render e; + public final ScreenEvent.Render e; public Render(ScreenEvent.Render e) { super(e); @@ -81,13 +81,13 @@ public int getMouseY() { } public static class Pre extends ForgeZScreen.Render implements ZScreen.Render.Pre { - public Pre(ScreenEvent.Render e) { + public Pre(ScreenEvent.Render.Pre e) { super(e); } } public static class Post extends ForgeZScreen.Render implements ZScreen.Render.Post { - public Post(ScreenEvent.Render e) { + public Post(ScreenEvent.Render.Post e) { super(e); } } diff --git a/src/main/java/org/violetmoon/zetaimplforge/config/ConfigEventDispatcher.java b/src/main/java/org/violetmoon/zetaimplforge/config/ConfigEventDispatcher.java index 6c722fe..51caf4d 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/config/ConfigEventDispatcher.java +++ b/src/main/java/org/violetmoon/zetaimplforge/config/ConfigEventDispatcher.java @@ -4,6 +4,7 @@ import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.event.load.ZConfigChanged; import org.violetmoon.zeta.util.zetalist.ZetaList; +import org.violetmoon.zetaimplforge.event.load.ForgeZConfigChange; public class ConfigEventDispatcher { public static void configChanged(ModConfigEvent event) { @@ -16,6 +17,7 @@ public static void configChanged(ModConfigEvent event) { // "The Forge config api writes to the config file on every single change // to the config, which would cause the file watcher to trigger // a config reload while the config gui is committing changes." + //TODO: investigate. this doesnt look that sound if(System.currentTimeMillis() - z.configInternals.debounceTime() > 20) handleConfigChange(z); } @@ -28,7 +30,7 @@ public static void dispatchAllInitialLoads() { private static void handleConfigChange(Zeta z) { z.configManager.onReload(); - z.loadBus.fire(new ZConfigChanged()); + z.loadBus.fire(new ForgeZConfigChange()); } } diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/ForgeEventsRemapper.java b/src/main/java/org/violetmoon/zetaimplforge/event/ForgeEventsRemapper.java new file mode 100644 index 0000000..9718cf4 --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/event/ForgeEventsRemapper.java @@ -0,0 +1,443 @@ +package org.violetmoon.zetaimplforge.event; + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import net.minecraftforge.client.event.RenderGuiOverlayEvent; +import net.minecraftforge.client.gui.overlay.VanillaGuiOverlay; +import net.minecraftforge.event.TickEvent; +import net.minecraftforge.eventbus.api.Event; +import net.minecraftforge.eventbus.api.EventPriority; +import net.minecraftforge.eventbus.api.GenericEvent; +import net.minecraftforge.eventbus.api.IEventBus; +import org.apache.commons.lang3.text.WordUtils; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.violetmoon.zeta.client.event.play.ZRenderGuiOverlay; + +import java.lang.invoke.MethodHandle; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.regex.Pattern; + +//@SuppressWarnings({"unchecked","rawtypes"}) +public class ForgeEventsRemapper { + + private final Class forgeEventRoot; + private final Class zetaEventRoot; + + private final Map, Function> forgeToZetaMap = new Object2ObjectOpenHashMap<>(); + private final Map, Function> zetaToForgeMap = new Object2ObjectOpenHashMap<>(); + private final Map, Class> generics = new Object2ObjectOpenHashMap<>(); + + + // hack needed to store classes of each Z event to Forge event. + // Needed because java has type erasure so forge be able to add listeners to anonymous generic lambdas without being passed an event type class + private final Map, Class> zetaToForgeEventClassHack = new Object2ObjectOpenHashMap<>(); + + public ForgeEventsRemapper(Class zetaEventRoot, Class forgeEventRoot) { + this.forgeEventRoot = forgeEventRoot; + this.zetaEventRoot = zetaEventRoot; + } + + // reflection hacks and ugly code below. Turn back now. You have been warned + + // good thing is most of this can be removed in 1.21 since Event is an interface there so we can pass zeta events directly. Just need to make zeta event extend Event + + /** + * Given an event object which is NOT a subtype of Event class, remap it to a forge event + */ + protected F remapEvent(@NotNull Z2 zetaEvent, Class firedAs) { + Function zetaToForgeFunc = zetaToForgeMap.get(firedAs); + if (zetaToForgeFunc == null) { + // remap is null. no checks because micro optimization. It means it must be a forge event already + return (F) zetaEvent; + } + return createForgeEvent(zetaEvent, zetaToForgeFunc); + } + + // takes a method that takes a zeta event and turns into one that takes a forge event + + /** + * Given a MethodHandle of a method which takes a Zeta event, remaps it to a method which takes a Forge event, so we can register it with Forge event bus + */ + protected Consumer remapMethod(MethodHandle originalEventConsumer, Class zetaEventBaseClass, Class forgeEventClass) { + Function forgeToZetaFunc = forgeToZetaMap.get(zetaEventBaseClass); + if (forgeToZetaFunc == null) { + // no remap needed + if (forgeEventRoot.isAssignableFrom(zetaEventBaseClass)) { + forgeToZetaFunc = event -> { + try { + return (Z) event; + } catch (Exception e) { + throw new RuntimeException(e); + } + }; + } else + throw new RuntimeException("Could not convert Zeta event class " + zetaEventBaseClass + " to Forge event. You must register its subclass using registerSubclass."); + } + return createForgeConsumer(originalEventConsumer, forgeToZetaFunc, zetaEventBaseClass, forgeEventClass); + } + + + // generic bs + private F createForgeEvent(@NotNull Z event, Function function) { + return function.apply((T) event); + } + + // generic bs + // Creates the Forge Event Consumer that will be registered with Forge Event Bus + private Consumer createForgeConsumer( + MethodHandle zetaEventConsumer, Function forgeToZetaFunc, Class zetaEventBaseClass, Class forgeEventClass) { + + //special cases fo forge events that are to be sub divided into phases + + // for gui overlay event + VanillaGuiOverlay overlay = guessGuiOverlayFromClassName(zetaEventBaseClass, forgeEventClass); + if (overlay != null) { + //here we know that phase must not be null + return event -> { + try { + RenderGuiOverlayEvent rge = (RenderGuiOverlayEvent) event; + if (rge.getOverlay() != overlay.type()) return; + zetaEventConsumer.invoke(forgeToZetaFunc.apply(event)); + } catch (Throwable e) { + throw new RuntimeException(e); + } + }; + } + + //hack for tick events + Phase phase = Phase.guessFromClassName(zetaEventBaseClass, forgeEventClass); + if (phase != Phase.NONE) { + return event -> { + try { + //luckily this phase madness will go away with new neoforge + TickEvent te = (TickEvent) event; + if ((phase == Phase.START) ^ (te.phase == TickEvent.Phase.START)) return; + zetaEventConsumer.invoke(forgeToZetaFunc.apply(event)); + } catch (Throwable e) { + throw new RuntimeException(e); + } + }; + } + + return event -> { + try { + zetaEventConsumer.invoke(forgeToZetaFunc.apply(event)); + } catch (Throwable e) { + throw new RuntimeException(e); + } + }; + } + + // for generic events + // auto register ones are deprecated. Register manually, its faster and requires no reflection hacks + @Deprecated + public void registerWrapperWithGeneric(Class baseZetaEventClass, Class forgeZetaEventClass, Class genericClass) { + registerWrapper(baseZetaEventClass, forgeZetaEventClass); + generics.put(baseZetaEventClass, genericClass); + } + + @Deprecated + public void registerWrapper(Class baseZetaEventClass, Class forgeZetaEventClass) { + + registerWrapper(baseZetaEventClass, forgeZetaEventClass, null); + } + + @Deprecated + public void registerWrapperWithGeneric(Class baseZetaEventClass, Class forgeZetaEventClass, + Function constructor, Class genericClass) { + registerWrapper(baseZetaEventClass, forgeZetaEventClass, constructor); + generics.put(baseZetaEventClass, genericClass); + } + + //register known ones + public void registerWrapper(Class baseZetaEventClass, Class forgeEventClass, + Function constructor, Function unwrapper) { + zetaToForgeEventClassHack.put(baseZetaEventClass, forgeEventClass); + forgeToZetaMap.put(baseZetaEventClass, constructor); + zetaToForgeMap.put(baseZetaEventClass, unwrapper); + } + + public void registerWrapperWithGenerics(Class baseZetaEventClass, Class forgeEventClass, + Function constructor, Function unwrapper, + Class genericClass) { + zetaToForgeEventClassHack.put(baseZetaEventClass, forgeEventClass); + forgeToZetaMap.put(baseZetaEventClass, constructor); + zetaToForgeMap.put(baseZetaEventClass, unwrapper); + generics.put(baseZetaEventClass, genericClass); + } + + + @Deprecated + public void registerWrapper(Class baseZetaEventClass, Class forgeZetaEventClass, + @Nullable Function constructor) { + Object old1; + Object old2 = null; + boolean isNoWrapper = false; + + if (constructor == null) { + // if it's an Event already just returns the no argument constructor. Provided it subclasses its abstract impl + if (forgeEventRoot.isAssignableFrom(forgeZetaEventClass)) { + zetaToForgeEventClassHack.put(baseZetaEventClass, forgeZetaEventClass); + + if (baseZetaEventClass.isAssignableFrom(forgeZetaEventClass)) { + constructor = event -> { + try { + return (ZF) event; + } catch (Exception e) { + throw new RuntimeException(e); + } + }; + } else { + constructor = findWrappedZetaEvent(forgeZetaEventClass, baseZetaEventClass); + } + + isNoWrapper = true; + } + if (constructor == null) { + constructor = findForgeWrapper(forgeZetaEventClass, baseZetaEventClass); + } + } + if (constructor == null) { + throw new RuntimeException("No Forge-Event-wrapping constructor found for Zeta event class " + forgeZetaEventClass); + } else { + old1 = forgeToZetaMap.put(baseZetaEventClass, constructor); + } + + Function zetaToForge = null; + if (!isNoWrapper) { + zetaToForge = findWrappedForgeEvent(forgeZetaEventClass, baseZetaEventClass); + } + + if (zetaToForge == null) { + zetaToForge = findZetaWrapper(forgeZetaEventClass); + } + + if (zetaToForge != null) { + old2 = zetaToForgeMap.put(baseZetaEventClass, zetaToForge); + } + + if (old1 != null || old2 != null) { + throw new RuntimeException("Event class " + baseZetaEventClass + " already registered"); + } + } + + // This is where the magic happens + + // Explanation: + // The whole point of these methods is to automatically convert a Zeta event to a Forge event, and vice versa. + // This is done since we can only have zeta event consumer methods in our common code, however we can only register to the forge bus a consumer of the forge Event class. + // For this reason here we have some functions that, with a lot of assumptions, try to find wrappers and unwrapper functions for each Forge-Zeta classes pair + + /** + * @param zetaEventClass i.e: ForgeZClientSetup.class + * @param baseZetaEventClass i.e: ZClientSetup.class + *

+ * Attempts to find a constructor of zetaEventClass which takes an Event as a parameter. This is used for simple forge Event wrappers + * in this example the one found will be new ForgeZClientSetup(FMLClientSetupEvent event) + */ + private Function findForgeWrapper(Class zetaEventClass, Class baseZetaEventClass) { + + // Find the constructor that takes a single parameter of type A + for (Constructor constructor : zetaEventClass.getConstructors()) { + Class[] parameterTypes = constructor.getParameterTypes(); + if (parameterTypes.length == 1 && forgeEventRoot.isAssignableFrom(parameterTypes[0])) { + zetaToForgeEventClassHack.put(baseZetaEventClass, parameterTypes[0]); + + return event -> { + try { + return (Z2) constructor.newInstance(event); + } catch (Exception e) { + throw new RuntimeException("Failed to create new instance of event class " + zetaEventClass, e); + } + }; + } + } + return null; + } + + /** + * @param zetaEventClass i.e: ForgeZRegister.class + *

+ * Tries to find a constructor that takes a single parameter with type of Zeta event. This convention is used to create Zeta specific event. + * The wrapper pattern is used here to provide platform specific implementation. + * In this example the one returned would be new ForgeZRegister(ZRegister event) + * If no wrapper constructor is found and the provided class implements Event already returns null. Exception otherwise. + */ + private Function findZetaWrapper(Class zetaEventClass) { + // Find the constructor that takes a single parameter of type A + for (Constructor constructor : zetaEventClass.getConstructors()) { + Class[] parameterTypes = constructor.getParameterTypes(); + if (parameterTypes.length == 1 && zetaEventRoot.isAssignableFrom(parameterTypes[0])) { + return event -> { + try { + return (F2) constructor.newInstance(event); + } catch (Exception e) { + throw new RuntimeException("Failed to create new instance of event class " + zetaEventClass, e); + } + }; + } + } + + if (forgeEventRoot.isAssignableFrom(zetaEventClass)) { + return null; + } + + throw new RuntimeException("No Zeta-Event-wrapping constructor found for Zeta event class " + zetaEventClass); + } + + + private Function findWrappedForgeEvent(Class zetaEventClass, Class baseZetaEventClass) { + + Field eventField = findFieldInClassHierarchy(zetaEventClass, f -> + forgeEventRoot.isAssignableFrom(f.getType())); + if (eventField != null) { + //hack + eventField.setAccessible(true); + if (!zetaToForgeEventClassHack.containsKey(baseZetaEventClass)) { + zetaToForgeEventClassHack.put(baseZetaEventClass, eventField.getType()); + } + return instance -> { + try { + return (F2) eventField.get(instance); + } catch (Exception e) { + throw new RuntimeException(e); + } + }; + } + + //tries to unwrap first. Then if its already a forge event we just keep it + if (forgeEventRoot.isAssignableFrom(zetaEventClass)) { + if (!zetaToForgeEventClassHack.containsKey(baseZetaEventClass)) { + zetaToForgeEventClassHack.put(baseZetaEventClass, zetaEventClass); + } + return null; + } + + throw new RuntimeException("No e forge Event found for Zeta event class " + zetaEventClass); + } + + private Function findWrappedZetaEvent(Class zetaEventClass, Class baseZetaEventClass) { + Field eventField = findFieldInClassHierarchy(zetaEventClass, f -> zetaEventRoot.isAssignableFrom(f.getType())); + if (eventField != null) { + //hack + eventField.setAccessible(true); + return instance -> { + try { + return (Z2) eventField.get(instance); + } catch (Exception e) { + throw new RuntimeException(e); + } + }; + } + + throw new RuntimeException("No e Zeta Event found for Zeta event class " + zetaEventClass); + } + + public static Field findFieldInClassHierarchy(Class clazz, Predicate predicate) { + while (clazz != null) { + for (Field f : clazz.getDeclaredFields()) { + if (predicate.test(f)) { + return f; + } + } + clazz = clazz.getSuperclass(); + } + return null; + } + + //bad string based conversions stuff mess + + //TODO: refactor in 1.21 using interfaces and stuff. This is just here for now as i want to keep binary compatibility + + protected void registerListenerToForgeWithPriorityAndGenerics( + IEventBus bus, Class owningClazz, Consumer consumer, Class zetaEventClass, Class forgeEventClass) { + EventPriority priority = guessPriorityFromClassName(owningClazz); + Class gen = generics.get(zetaEventClass); + if (forgeEventClass == null) { + throw new RuntimeException("No event type found for " + zetaEventClass); + } + if (gen != null) { + bus.addGenericListener(gen, priority, false, forgeEventClass, (Consumer) (Object) consumer); + } else { + bus.addListener(priority, false, forgeEventClass, consumer); + } + } + + public Object remapAndRegister(IEventBus forgeBus, Class owningClazz, MethodHandle handle, Class zetaEventClass) { + Class forgeEventClass = zetaToForgeEventClassHack.get(zetaEventClass); + + Consumer consumer = this.remapMethod(handle, zetaEventClass, forgeEventClass); + + registerListenerToForgeWithPriorityAndGenerics(forgeBus, owningClazz, consumer, zetaEventClass, forgeEventClass); + + return consumer; + } + + + private enum Phase { + NONE, START, END; + + private static Phase guessFromClassName(Class zetaEventClass, Class forgeClass) { + if (!TickEvent.class.isAssignableFrom(forgeClass)) return NONE; + String simpleName = zetaEventClass.getSimpleName(); + if (simpleName.equals("Start")) { + return START; + } else if (simpleName.equals("End")) { + return END; + } else { + return NONE; + } + } + } + + private static final Map, VanillaGuiOverlay> GUI_OVERLAY_CACHE = new ConcurrentHashMap<>(); + private static final Pattern INNER_CLASS_PATTERN = Pattern.compile("\\$([^$]+)\\$"); + + @Nullable + private static VanillaGuiOverlay guessGuiOverlayFromClassName(Class zetaEventClass, Class forgeEventClass) { + if (!RenderGuiOverlayEvent.class.isAssignableFrom(forgeEventClass)) return null; + return GUI_OVERLAY_CACHE.computeIfAbsent(zetaEventClass, zec -> { + var match = INNER_CLASS_PATTERN.matcher(zetaEventClass.getName()); + if (!match.find()) return null; + String simpleName = match.group(1); + for (VanillaGuiOverlay overlay : VanillaGuiOverlay.values()) { + if (simpleName.equalsIgnoreCase(overlay.name().replace("_", ""))) { + return overlay; + } + } + return null; + }); + } + + + private static final Map, EventPriority> PRIORITY_CACHE = new ConcurrentHashMap<>(); + + private static EventPriority guessPriorityFromClassName(Class zetaEventClass) { + return PRIORITY_CACHE.computeIfAbsent(zetaEventClass, zec -> { + String simpleName = zec.getSimpleName(); + for (EventPriority p : EventPriority.values()) { + String name = WordUtils.capitalizeFully(p.name().toLowerCase()); + if (simpleName.endsWith(name)) { + return p; + } + } + return EventPriority.NORMAL; + }); + } + + public ForgeEventsRemapper makeCopy() { + ForgeEventsRemapper copy = new ForgeEventsRemapper<>(zetaEventRoot, forgeEventRoot); + copy.forgeToZetaMap.putAll(forgeToZetaMap); + copy.zetaToForgeMap.putAll(zetaToForgeMap); + copy.generics.putAll(generics); + copy.zetaToForgeEventClassHack.putAll(zetaToForgeEventClassHack); + return copy; + } + +} diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/ForgeZetaEventBus.java b/src/main/java/org/violetmoon/zetaimplforge/event/ForgeZetaEventBus.java new file mode 100644 index 0000000..0fa6f11 --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/event/ForgeZetaEventBus.java @@ -0,0 +1,408 @@ +package org.violetmoon.zetaimplforge.event; + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import net.minecraft.Util; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.client.event.RenderGuiOverlayEvent; +import net.minecraftforge.client.event.RenderLivingEvent; +import net.minecraftforge.client.event.RenderPlayerEvent; +import net.minecraftforge.client.event.ScreenEvent; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.AttachCapabilitiesEvent; +import net.minecraftforge.event.TickEvent; +import net.minecraftforge.event.entity.EntityAttributeCreationEvent; +import net.minecraftforge.event.entity.living.*; +import net.minecraftforge.event.entity.player.ItemTooltipEvent; +import net.minecraftforge.event.entity.player.PlayerInteractEvent; +import net.minecraftforge.eventbus.api.Event; +import net.minecraftforge.eventbus.api.IEventBus; +import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; +import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; +import net.minecraftforge.fml.loading.FMLEnvironment; +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.violetmoon.zeta.Zeta; +import org.violetmoon.zeta.client.event.load.*; +import org.violetmoon.zeta.client.event.play.*; +import org.violetmoon.zeta.event.bus.*; +import org.violetmoon.zeta.event.load.*; +import org.violetmoon.zeta.event.play.*; +import org.violetmoon.zeta.event.play.entity.*; +import org.violetmoon.zeta.event.play.entity.living.*; +import org.violetmoon.zeta.event.play.entity.player.*; +import org.violetmoon.zeta.event.play.loading.*; +import org.violetmoon.zetaimplforge.api.ForgeZGatherAdvancementModifiers; +import org.violetmoon.zetaimplforge.capability.ForgeCapabilityManager; +import org.violetmoon.zetaimplforge.client.event.load.*; +import org.violetmoon.zetaimplforge.client.event.play.*; +import org.violetmoon.zetaimplforge.event.load.*; +import org.violetmoon.zetaimplforge.event.play.*; +import org.violetmoon.zetaimplforge.event.play.entity.*; +import org.violetmoon.zetaimplforge.event.play.entity.living.*; +import org.violetmoon.zetaimplforge.event.play.entity.player.*; +import org.violetmoon.zetaimplforge.event.play.loading.*; + +import java.lang.annotation.Annotation; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Method; +import java.util.Map; +import java.util.function.Function; + +// this is super jank. Basically converts all zeta events to forge ones, then delegates to the forge bus directly +public class ForgeZetaEventBus extends ZetaEventBus { + + // needed so we can unregister later + private final Map convertedHandlers = new Object2ObjectOpenHashMap<>(); + + private final IEventBus forgeBus; + private final Class forgeEventRoot; //probably not needed can be replaced with Event + private final ForgeEventsRemapper remapper; + + /** + * @param subscriberAnnotation The annotation that subscribe()/unsubscribe() will pay attention to. + * @param eventRoot The superinterface of all events fired on this bus. + */ + protected ForgeZetaEventBus(Class subscriberAnnotation, Class eventRoot, + @Nullable Logger logSpam, IEventBus forgeBus, Class forgeEventRoot, + Zeta ofZeta, ForgeEventsRemapper remapper) { + super(subscriberAnnotation, eventRoot, logSpam, ofZeta); + this.forgeBus = forgeBus; + this.forgeEventRoot = forgeEventRoot; + this.remapper = remapper; + } + + public static ForgeZetaEventBus ofLoadBus(@Nullable Logger logSpam, Zeta ofZeta) { + return new ForgeZetaEventBus<>( + LoadEvent.class, IZetaLoadEvent.class, + logSpam, FMLJavaModLoadingContext.get().getModEventBus(), Event.class, + ofZeta, LOAD_EVENTS_REMAPPER); + } + + public static ForgeZetaEventBus ofPlayBus(@Nullable Logger logSpam, Zeta ofZeta) { + return new ForgeZetaEventBus<>( + PlayEvent.class, IZetaPlayEvent.class, + logSpam, MinecraftForge.EVENT_BUS, Event.class, + ofZeta, PLAY_EVENTS_REMAPPER); + } + + + @Override + protected void subscribeMethod(Method method, Object receiver, Class owningClazz) { + if (method.getParameterCount() != 1) + throw arityERR(method); + + Class zetaEventClass = method.getParameterTypes()[0]; + + //check if it's already a forge event, or it's a zeta event + if (!eventRoot.isAssignableFrom(zetaEventClass) && !forgeEventRoot.isAssignableFrom(zetaEventClass)) + throw typeERR(method); + + MethodHandle handle; + try { + handle = MethodHandles.publicLookup().unreflect(method); + } catch (Exception e) { + throw new RuntimeException(e); + } + + //fill in the "this" parameter + if (receiver != null) + handle = handle.bindTo(receiver); + + Object convertedMethod = remapper.remapAndRegister(forgeBus, owningClazz, handle, zetaEventClass); + //store here so we can unregister later + convertedHandlers.put(new Key(method, receiver, owningClazz), convertedMethod); + } + + @Override + protected void unsubscribeMethod(Method m, Object receiver, Class owningClazz) { + var handler = convertedHandlers.remove(new Key(m, receiver, owningClazz)); + if (handler != null) { + forgeBus.unregister(handler); + } + } + + private record Key(Method method, Object receiver, Class owningClazz) { + } + + @Override + public T fire(@NotNull T event) { + forgeBus.post(remapper.remapEvent(event, event.getClass())); + return event; + } + + @Override + public T fire(@NotNull T event, Class firedAs) { + forgeBus.post(remapper.remapEvent(event, firedAs)); + return event; + } + + // all these are for bus specific events. The only bus that should have specific stuff is the play one + + // for generic events + public void registerWrapperWithGenerics(Class baseZetaEventClass, Class forgeZetaEventClass, Class genericClass) { + synchronized (remapper) { + remapper.registerWrapperWithGeneric(baseZetaEventClass, forgeZetaEventClass, genericClass); + } + } + + public void registerWrapper(Class baseZetaEventClass, Class forgeZetaEventClass) { + synchronized (remapper) { + remapper.registerWrapper(baseZetaEventClass, forgeZetaEventClass, null); + } + } + + public void registerWrapperWithGenerics(Class baseZetaEventClass, Class forgeZetaEventClass, + Function constructor, Class genericClass) { + synchronized (remapper) { + remapper.registerWrapperWithGeneric(baseZetaEventClass, forgeZetaEventClass, constructor, genericClass); + } + } + + public void registerWrapper(Class baseZetaEventClass, Class forgeZetaEventClass, + @Nullable Function constructor) { + synchronized (remapper) { + remapper.registerWrapper(baseZetaEventClass, forgeZetaEventClass, constructor); + } + } + + // I would love to put this code in the mod proxy but that needs to do event setup stuff which requires these busses to be fully initialized + + // instances so we don't create multiple as reflections take time and memory + private static final ForgeEventsRemapper LOAD_EVENTS_REMAPPER = Util.make(new ForgeEventsRemapper<>(IZetaLoadEvent.class, Event.class), r -> { + + //TODO: repace all these with explicit ones + + // adds known events subclasses to the bus + r.registerWrapper(ZCommonSetup.class, FMLCommonSetupEvent.class, + ForgeZCommonSetup::new, ForgeZCommonSetup::e); + r.registerWrapper(ZEntityAttributeCreation.class, EntityAttributeCreationEvent.class, + ForgeZEntityAttributeCreation::new, ForgeZEntityAttributeCreation::e); + r.registerWrapper(ZModulesReady.class, ForgeZModulesReady.class); + r.registerWrapper(ZRegister.class, ForgeZRegister.class); + r.registerWrapper(ZRegister.Post.class, ForgeZRegister.Post.class); + r.registerWrapper(ZConfigChanged.class, ForgeZConfigChange.class); + r.registerWrapper(ZLoadComplete.class, ForgeZLoadComplete.class); + + //zeta own + r.registerWrapper(ZGatherAdvancementModifiers.class, ForgeZGatherAdvancementModifiers.class); + + // client ones again? + if (FMLEnvironment.dist == Dist.DEDICATED_SERVER) return; + + r.registerWrapper(ZAddModels.class, ForgeZAddModels.class); + r.registerWrapper(ZAddModelLayers.class, ForgeZAddModelLayers.class); + r.registerWrapper(ZClientSetup.class, ForgeZClientSetup.class); + r.registerWrapper(ZKeyMapping.class, ForgeZKeyMapping.class); + r.registerWrapper(ZModel.RegisterGeometryLoaders.class, ForgeZModel.RegisterGeometryLoaders.class); + r.registerWrapper(ZModel.RegisterAdditional.class, ForgeZModel.RegisterAdditional.class); + r.registerWrapper(ZModel.BakingCompleted.class, ForgeZModel.BakingCompleted.class); + r.registerWrapper(ZModel.ModifyBakingResult.class, ForgeZModel.ModifyBakingResult.class); + r.registerWrapper(ZRegisterLayerDefinitions.class, ForgeZRegisterLayerDefinitions.class); + r.registerWrapper(ZTooltipComponents.class, ForgeZTooltipComponents.class); + r.registerWrapper(ZRegisterClientReloadListener.class, ForgeZRegisterClientReloadListener.class); + r.registerWrapper(ZFirstClientTick.class, ForgeZFirstClientTick.class); + + r.registerWrapper(ZAddBlockColorHandlers.class, ForgeZAddBlockColorHandlers.class); + r.registerWrapper(ZAddItemColorHandlers.class, ForgeZAddItemColorHandlers.class); + }); + + private static final ForgeEventsRemapper PLAY_EVENTS_REMAPPER = Util.make(new ForgeEventsRemapper<>(IZetaPlayEvent.class, Event.class), r -> { + + r.registerWrapper(ZAnvilRepair.class, ForgeZAnvilRepair.class); + r.registerWrapper(ZAnvilUpdate.Highest.class, ForgeZAnvilUpdate.Highest.class); + r.registerWrapper(ZAnvilUpdate.Lowest.class, ForgeZAnvilUpdate.Lowest.class); + r.registerWrapper(ZTagsUpdated.class, ForgeZTagsUpdated.class); + r.registerWrapper(ZBabyEntitySpawn.Lowest.class, BabyEntitySpawnEvent.class, + ForgeZBabyEntitySpawn.Lowest::new, a -> a.wrapped); + r.registerWrapper(ZBabyEntitySpawn.class, BabyEntitySpawnEvent.class, + ForgeZBabyEntitySpawn::new, a -> a.wrapped); + r.registerWrapper(ZBlock.Break.class, ForgeZBlock.Break.class); + r.registerWrapper(ZBlock.EntityPlace.class, ForgeZBlock.EntityPlace.class); + r.registerWrapper(ZBlock.BlockToolModification.class, ForgeZBlock.BlockToolModification.class); + r.registerWrapper(ZBonemeal.class, ForgeZBonemeal.class); + r.registerWrapper(ZEntityConstruct.class, ForgeZEntityConstruct.class); + r.registerWrapper(ZEntityInteract.class, PlayerInteractEvent.EntityInteract.class, + ForgeZEntityInteract::new, ForgeZEntityInteract::e); + r.registerWrapper(ZEntityItemPickup.class, ForgeZEntityItemPickup.class); + r.registerWrapper(ZEntityJoinLevel.class, ForgeZEntityJoinLevel.class); + r.registerWrapper(ZEntityMobGriefing.class, ForgeZEntityMobGriefing.class); + r.registerWrapper(ZEntityTeleport.class, ForgeZEntityTeleport.class); + r.registerWrapper(ZItemTooltip.class, ItemTooltipEvent.class, + ForgeZItemTooltip::new, ForgeZItemTooltip::e); + r.registerWrapper(ZLivingChangeTarget.class, LivingChangeTargetEvent.class, + ForgeZLivingChangeTarget::new, ForgeZLivingChangeTarget::e); + r.registerWrapper(ZLivingConversion.class, ForgeZLivingConversion.class); + r.registerWrapper(ZLivingConversion.Pre.class, ForgeZLivingConversion.Pre.class); + r.registerWrapper(ZLivingConversion.Post.class, ForgeZLivingConversion.Post.class); + r.registerWrapper(ZLivingDeath.class, ForgeZLivingDeath.class); + r.registerWrapper(ZLivingDeath.Lowest.class, ForgeZLivingDeath.Lowest.class); + r.registerWrapper(ZLivingDrops.class, LivingDropsEvent.class, + ForgeZLivingDrops::new, w -> w.e); + r.registerWrapper(ZLivingDrops.Lowest.class, LivingDropsEvent.class, + ForgeZLivingDrops.Lowest::new, w -> w.e); + r.registerWrapper(ZLivingFall.class, ForgeZLivingFall.class); + r.registerWrapper(ZLivingTick.class, LivingEvent.LivingTickEvent.class, + ForgeZLivingTick::new, ForgeZLivingTick::e); + r.registerWrapper(ZMobSpawnEvent.class, MobSpawnEvent.class, + ForgeZMobSpawnEvent::new, w -> w.e); + r.registerWrapper(ZMobSpawnEvent.CheckSpawn.class, MobSpawnEvent.FinalizeSpawn.class, + ForgeZMobSpawnEvent.FinalizeSpawn::new, w -> w.e); + r.registerWrapper(ZMobSpawnEvent.CheckSpawn.Lowest.class, MobSpawnEvent.FinalizeSpawn.class, + ForgeZMobSpawnEvent.FinalizeSpawn.Lowest::new, w -> w.e); + r.registerWrapper(ZPlayNoteBlock.class, ForgeZPlayNoteBlock.class); + r.registerWrapper(ZPlayer.BreakSpeed.class, ForgeZPlayer.BreakSpeed.class); + r.registerWrapper(ZPlayer.Clone.class, ForgeZPlayer.Clone.class); + r.registerWrapper(ZPlayerDestroyItem.class, ForgeZPlayerDestroyItem.class); + r.registerWrapper(ZPlayer.LoggedIn.class, ForgeZPlayer.LoggedIn.class); + r.registerWrapper(ZPlayer.LoggedOut.class, ForgeZPlayer.LoggedOut.class); + r.registerWrapper(ZPlayerTick.Start.class, TickEvent.PlayerTickEvent.class, + ForgeZPlayerTick.Start::new, w -> w.e); + r.registerWrapper(ZPlayerTick.End.class, TickEvent.PlayerTickEvent.class, + ForgeZPlayerTick.End::new, w -> w.e); + r.registerWrapper(ZPlayerInteract.class, ForgeZPlayerInteract.class); + r.registerWrapper(ZPlayerInteract.EntityInteractSpecific.class, ForgeZPlayerInteract.EntityInteractSpecific.class); + r.registerWrapper(ZPlayerInteract.EntityInteract.class, ForgeZPlayerInteract.EntityInteract.class); + r.registerWrapper(ZPlayerInteract.RightClickBlock.class, ForgeZPlayerInteract.RightClickBlock.class); + r.registerWrapper(ZPlayerInteract.RightClickItem.class, ForgeZPlayerInteract.RightClickItem.class); + r.registerWrapper(ZRightClickBlock.class, ForgeZRightClickBlock.class); + r.registerWrapper(ZRightClickBlock.Low.class, ForgeZRightClickBlock.Low.class); + r.registerWrapper(ZRightClickItem.class, ForgeZRightClickItem.class); + r.registerWrapper(ZLootTableLoad.class, ForgeZLootTableLoad.class); + r.registerWrapper(ZVillagerTrades.class, ForgeZVillagerTrades.class); + r.registerWrapper(ZWandererTrades.class, ForgeZWandererTrades.class); + r.registerWrapper(ZFurnaceFuelBurnTime.class, ForgeZFurnaceFuelBurnTime.class); + r.registerWrapper(ZGatherAdditionalFlags.class, ForgeZGatherAdditionalFlags.class); + r.registerWrapper(ZServerTick.Start.class, TickEvent.ServerTickEvent.class, + ForgeZServerTick.Start::new, w -> w.e); + r.registerWrapper(ZServerTick.End.class, TickEvent.ServerTickEvent.class, + ForgeZServerTick.End::new, w -> w.e); + r.registerWrapper(ZAddReloadListener.class, ForgeZAddReloadListener.class); + r.registerWrapper(ZGatherHints.class, ForgeZGatherHints.class); + r.registerWrapper(ZSleepingLocationCheck.class, ForgeZSleepingLocationCheck.class); + r.registerWrapper(ZAnimalTame.class, ForgeZAnimalTame.class); + r.registerWrapper(ZLevelTick.End.class, TickEvent.LevelTickEvent.class, + ForgeZLevelTick.End::new, w -> w.e); + r.registerWrapper(ZLevelTick.Start.class, TickEvent.LevelTickEvent.class, + ForgeZLevelTick.Start::new, w -> w.e); + + + //this is ugly. generic events here + r.registerWrapperWithGeneric(ZAttachCapabilities.BlockEntityCaps.class, + ForgeZAttachCapabilities.BlockEntityCaps.class, + (Function, ForgeZAttachCapabilities.BlockEntityCaps>) inner -> + new ForgeZAttachCapabilities.BlockEntityCaps(ForgeCapabilityManager.INSTANCE, inner), + BlockEntity.class); + r.registerWrapperWithGeneric(ZAttachCapabilities.ItemStackCaps.class, + ForgeZAttachCapabilities.ItemStackCaps.class, + (Function, ForgeZAttachCapabilities.ItemStackCaps>) inner -> + new ForgeZAttachCapabilities.ItemStackCaps(ForgeCapabilityManager.INSTANCE, inner), + ItemStack.class); + r.registerWrapperWithGeneric(ZAttachCapabilities.LevelCaps.class, + ForgeZAttachCapabilities.LevelCaps.class, + (Function, ForgeZAttachCapabilities.LevelCaps>) inner -> + new ForgeZAttachCapabilities.LevelCaps(ForgeCapabilityManager.INSTANCE, inner), + Level.class); + + // zeta specific ones + + r.registerWrapper(ZRecipeCrawl.Digest.class, ForgeZRecipeCrawl.Digest.class, + ForgeZRecipeCrawl::get, ForgeZRecipeCrawl.Digest::new); + r.registerWrapper(ZRecipeCrawl.Reset.class, ForgeZRecipeCrawl.Reset.class, + ForgeZRecipeCrawl::get, ForgeZRecipeCrawl.Reset::new); + r.registerWrapper(ZRecipeCrawl.Starting.class, ForgeZRecipeCrawl.Starting.class, + ForgeZRecipeCrawl::get, ForgeZRecipeCrawl.Starting::new); + r.registerWrapper(ZRecipeCrawl.Visit.Cooking.class, ForgeZRecipeCrawl.Visit.Cooking.class, + ForgeZRecipeCrawl::get, ForgeZRecipeCrawl.Visit.Cooking::new); + r.registerWrapper(ZRecipeCrawl.Visit.Custom.class, ForgeZRecipeCrawl.Visit.Custom.class, + ForgeZRecipeCrawl::get, ForgeZRecipeCrawl.Visit.Custom::new); + r.registerWrapper(ZRecipeCrawl.Visit.Misc.class, ForgeZRecipeCrawl.Visit.Misc.class, + ForgeZRecipeCrawl::get, ForgeZRecipeCrawl.Visit.Misc::new); + r.registerWrapper(ZRecipeCrawl.Visit.Shaped.class, ForgeZRecipeCrawl.Visit.Shaped.class, + ForgeZRecipeCrawl::get, ForgeZRecipeCrawl.Visit.Shaped::new); + r.registerWrapper(ZRecipeCrawl.Visit.Shapeless.class, ForgeZRecipeCrawl.Visit.Shapeless.class, + ForgeZRecipeCrawl::get, ForgeZRecipeCrawl.Visit.Shapeless::new); + + //Hmm client events here? maybe i should move them + if (FMLEnvironment.dist == Dist.DEDICATED_SERVER) return; + + r.registerWrapper(ZClientTick.End.class, TickEvent.ClientTickEvent.class, + ForgeZClientTick.End::new, w -> w.e); + r.registerWrapper(ZClientTick.Start.class, TickEvent.ClientTickEvent.class, + ForgeZClientTick.Start::new, w -> w.e); + r.registerWrapper(ZGatherTooltipComponents.class, ForgeZGatherTooltipComponents.class); + r.registerWrapper(ZHighlightBlock.class, ForgeZHighlightBlock.class); + r.registerWrapper(ZInput.MouseButton.class, ForgeZInput.MouseButton.class); + r.registerWrapper(ZInput.Key.class, ForgeZInput.Key.class); + r.registerWrapper(ZInputUpdate.class, ForgeZInputUpdate.class); + r.registerWrapper(ZRenderContainerScreen.Background.class, ForgeZRenderContainerScreen.Background.class); + r.registerWrapper(ZRenderContainerScreen.Foreground.class, ForgeZRenderContainerScreen.Foreground.class); + r.registerWrapper(ZRenderLiving.PostLowest.class, RenderLivingEvent.Post.class, + ForgeZRenderLiving.PostLowest::new, w -> w.e); + r.registerWrapper(ZRenderLiving.PreHighest.class, RenderLivingEvent.Pre.class, + ForgeZRenderLiving.PreHighest::new, w -> w.e); + r.registerWrapper(ZRenderPlayer.Post.class, RenderPlayerEvent.Post.class, + ForgeZRenderPlayer.Post::new, w -> w.e); + r.registerWrapper(ZRenderPlayer.Pre.class, RenderPlayerEvent.Pre.class, + ForgeZRenderPlayer.Pre::new, w -> w.e); + r.registerWrapper(ZRenderTick.End.class, TickEvent.RenderTickEvent.class, + ForgeZRenderTick.End::new, w -> w.e); + r.registerWrapper(ZRenderTick.Start.class, TickEvent.RenderTickEvent.class, + ForgeZRenderTick.Start::new, w -> w.e); + r.registerWrapper(ZRenderTooltip.GatherComponents.class, ForgeZRenderTooltip.GatherComponents.class); + r.registerWrapper(ZRenderTooltip.GatherComponents.Low.class, ForgeZRenderTooltip.GatherComponents.Low.class); + r.registerWrapper(ZScreen.Opening.class, ForgeZScreen.Opening.class); + r.registerWrapper(ZScreen.CharacterTyped.Pre.class, ForgeZScreen.CharacterTyped.Pre.class); + r.registerWrapper(ZScreen.CharacterTyped.Post.class, ForgeZScreen.CharacterTyped.Post.class); + r.registerWrapper(ZScreen.Init.Post.class, ForgeZScreen.Init.Post.class); + r.registerWrapper(ZScreen.Init.Pre.class, ForgeZScreen.Init.Pre.class); + r.registerWrapper(ZScreen.KeyPressed.Post.class, ForgeZScreen.KeyPressed.Post.class); + r.registerWrapper(ZScreen.KeyPressed.Pre.class, ForgeZScreen.KeyPressed.Pre.class); + r.registerWrapper(ZScreen.MouseScrolled.Post.class, ForgeZScreen.MouseScrolled.Post.class); + r.registerWrapper(ZScreen.MouseScrolled.Pre.class, ForgeZScreen.MouseScrolled.Pre.class); + r.registerWrapper(ZScreen.MouseButtonPressed.Post.class, ForgeZScreen.MouseButtonPressed.Post.class); + r.registerWrapper(ZScreen.MouseButtonPressed.Pre.class, ForgeZScreen.MouseButtonPressed.Pre.class); + r.registerWrapper(ZScreen.Render.Post.class, ScreenEvent.Render.Post.class, + ForgeZScreen.Render.Post::new, w -> w.e); + r.registerWrapper(ZScreen.Render.Pre.class, ScreenEvent.Render.Pre.class, + ForgeZScreen.Render.Pre::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.ArmorLevel.Pre.class, RenderGuiOverlayEvent.Pre.class, + ForgeZRenderGuiOverlay.ArmorLevel.Pre::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.ArmorLevel.Post.class, RenderGuiOverlayEvent.Post.class, + ForgeZRenderGuiOverlay.ArmorLevel.Post::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.Crosshair.Post.class, RenderGuiOverlayEvent.Post.class, + ForgeZRenderGuiOverlay.Crosshair.Post::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.Crosshair.Pre.class, RenderGuiOverlayEvent.Pre.class, + ForgeZRenderGuiOverlay.Crosshair.Pre::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.DebugText.Pre.class, RenderGuiOverlayEvent.Pre.class, + ForgeZRenderGuiOverlay.DebugText.Pre::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.DebugText.Post.class, RenderGuiOverlayEvent.Post.class, + ForgeZRenderGuiOverlay.DebugText.Post::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.Hotbar.Pre.class, RenderGuiOverlayEvent.Pre.class, + ForgeZRenderGuiOverlay.Hotbar.Pre::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.Hotbar.Post.class, RenderGuiOverlayEvent.Post.class, + ForgeZRenderGuiOverlay.Hotbar.Post::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.PlayerHealth.Pre.class, RenderGuiOverlayEvent.Pre.class, + ForgeZRenderGuiOverlay.PlayerHealth.Pre::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.PlayerHealth.Post.class, RenderGuiOverlayEvent.Post.class, + ForgeZRenderGuiOverlay.PlayerHealth.Post::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.PotionIcons.Pre.class, RenderGuiOverlayEvent.Pre.class, + ForgeZRenderGuiOverlay.PotionIcons.Pre::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.PotionIcons.Post.class, RenderGuiOverlayEvent.Post.class, + ForgeZRenderGuiOverlay.PotionIcons.Post::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.ChatPanel.Pre.class, RenderGuiOverlayEvent.Pre.class, + ForgeZRenderGuiOverlay.ChatPanel.Pre::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.ChatPanel.Post.class, RenderGuiOverlayEvent.Post.class, + ForgeZRenderGuiOverlay.ChatPanel.Post::new, w -> w.e); + // zeta own event + r.registerWrapper(ZScreenshot.class, ForgeZScreenshot.class); + r.registerWrapper(ZEarlyRender.class, ForgeZEarlyRender.class); + + }); + + +} diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZConfigChange.java b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZConfigChange.java new file mode 100644 index 0000000..87bc302 --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZConfigChange.java @@ -0,0 +1,10 @@ +package org.violetmoon.zetaimplforge.event.load; + +import net.minecraftforge.eventbus.api.Event; +import net.minecraftforge.fml.event.IModBusEvent; +import org.violetmoon.zeta.event.load.ZConfigChanged; +import org.violetmoon.zeta.event.load.ZModulesReady; + +//aparently this cannot just be forge event. //TODO: investigate +public class ForgeZConfigChange extends Event implements ZConfigChanged, IModBusEvent { +} diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZEntityAttributeCreation.java b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZEntityAttributeCreation.java index 59851c1..5ca5b69 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZEntityAttributeCreation.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZEntityAttributeCreation.java @@ -7,12 +7,7 @@ import net.minecraft.world.entity.ai.attributes.AttributeSupplier; import net.minecraftforge.event.entity.EntityAttributeCreationEvent; -public class ForgeZEntityAttributeCreation implements ZEntityAttributeCreation { - private final EntityAttributeCreationEvent e; - - public ForgeZEntityAttributeCreation(EntityAttributeCreationEvent e) { - this.e = e; - } +public record ForgeZEntityAttributeCreation(EntityAttributeCreationEvent e) implements ZEntityAttributeCreation { @Override public void put(EntityType entity, AttributeSupplier map) { diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZFirstClientTick.java b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZFirstClientTick.java new file mode 100644 index 0000000..5a47771 --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZFirstClientTick.java @@ -0,0 +1,9 @@ +package org.violetmoon.zetaimplforge.event.load; + +import net.minecraftforge.eventbus.api.Event; +import net.minecraftforge.fml.event.IModBusEvent; +import org.violetmoon.zeta.client.event.play.ZFirstClientTick; + +public class ForgeZFirstClientTick extends Event implements ZFirstClientTick, IModBusEvent { + +} diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZGatherHints.java b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZGatherHints.java new file mode 100644 index 0000000..a47556b --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZGatherHints.java @@ -0,0 +1,46 @@ +package org.violetmoon.zetaimplforge.event.load; + +import net.minecraft.core.RegistryAccess; +import net.minecraft.network.chat.Component; +import net.minecraft.server.ReloadableServerResources; +import net.minecraft.server.packs.resources.PreparableReloadListener; +import net.minecraft.world.level.ItemLike; +import net.minecraftforge.event.AddReloadListenerEvent; +import net.minecraftforge.eventbus.api.Event; +import org.violetmoon.zeta.Zeta; +import org.violetmoon.zeta.config.ConfigFlagManager; +import org.violetmoon.zeta.event.play.loading.ZGatherHints; +import org.violetmoon.zeta.module.ZetaModule; + +public class ForgeZGatherHints extends Event implements ZGatherHints { + private final ZGatherHints wrapped; + + public ForgeZGatherHints(ZGatherHints e) { + this.wrapped = e; + } + + @Override + public void accept(ItemLike itemLike, Component extra) { + wrapped.accept(itemLike, extra); + } + + @Override + public RegistryAccess getRegistryAccess() { + return wrapped.getRegistryAccess(); + } + + @Override + public void hintItem(Zeta zeta, ItemLike itemLike, Object... extra) { + wrapped.hintItem(zeta, itemLike, extra); + } + + @Override + public void hintItem(Zeta zeta, ItemLike itemLike, String key, Object... extra) { + wrapped.hintItem(zeta, itemLike, key, extra); + } + + @Override + public void gatherHintsFromModule(ZetaModule module, ConfigFlagManager cfm) { + wrapped.gatherHintsFromModule(module, cfm); + } +} diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZModulesReady.java b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZModulesReady.java new file mode 100644 index 0000000..adaa3ba --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZModulesReady.java @@ -0,0 +1,9 @@ +package org.violetmoon.zetaimplforge.event.load; + +import net.minecraftforge.eventbus.api.Event; +import net.minecraftforge.fml.event.IModBusEvent; +import org.violetmoon.zeta.event.load.ZModulesReady; +import org.violetmoon.zeta.event.load.ZTagsUpdated; + +public class ForgeZModulesReady extends Event implements ZModulesReady, IModBusEvent { +} diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZRegister.java b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZRegister.java new file mode 100644 index 0000000..d72f2ff --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZRegister.java @@ -0,0 +1,49 @@ +package org.violetmoon.zetaimplforge.event.load; + +import net.minecraftforge.eventbus.api.Event; +import net.minecraftforge.fml.event.IModBusEvent; +import org.violetmoon.zeta.Zeta; +import org.violetmoon.zeta.advancement.AdvancementModifierRegistry; +import org.violetmoon.zeta.event.load.ZRegister; +import org.violetmoon.zeta.registry.*; + +public class ForgeZRegister extends Event implements ZRegister, IModBusEvent { + + private final Zeta zeta; + + public ForgeZRegister(Zeta zeta) { + this.zeta = zeta; + } + + @Override + public ZetaRegistry getRegistry() { + return zeta.registry; + } + + @Override + public CraftingExtensionsRegistry getCraftingExtensionsRegistry() { + return zeta.craftingExtensions; + } + + @Override + public BrewingRegistry getBrewingRegistry() { + return zeta.brewingRegistry; + } + + @Override + public RenderLayerRegistry getRenderLayerRegistry() { + return zeta.renderLayerRegistry; + } + + @Override + public AdvancementModifierRegistry getAdvancementModifierRegistry() { + return zeta.advancementModifierRegistry; + } + + @Override + public VariantRegistry getVariantRegistry() { + return zeta.variantRegistry; + } + + public static class Post extends Event implements ZRegister.Post, IModBusEvent { } +} diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZRegisterClientReloadListener.java b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZRegisterClientReloadListener.java new file mode 100644 index 0000000..538ed25 --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZRegisterClientReloadListener.java @@ -0,0 +1,13 @@ +package org.violetmoon.zetaimplforge.event.load; + +import net.minecraft.server.packs.resources.PreparableReloadListener; +import net.minecraftforge.client.event.RegisterClientReloadListenersEvent; +import org.violetmoon.zeta.client.event.load.ZRegisterClientReloadListener; + +public record ForgeZRegisterClientReloadListener(RegisterClientReloadListenersEvent event) implements ZRegisterClientReloadListener { + + @Override + public void accept(PreparableReloadListener bleh) { + event.registerReloadListener(bleh); + } +} diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZTagsUpdated.java b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZTagsUpdated.java new file mode 100644 index 0000000..d16ba84 --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZTagsUpdated.java @@ -0,0 +1,18 @@ +package org.violetmoon.zetaimplforge.event.load; + +import net.minecraft.core.RegistryAccess; +import net.minecraftforge.event.TagsUpdatedEvent; +import org.violetmoon.zeta.event.load.ZTagsUpdated; + +public record ForgeZTagsUpdated(TagsUpdatedEvent event) implements ZTagsUpdated { + + @Override + public RegistryAccess getRegistryAccess() { + return event.getRegistryAccess(); + } + + @Override + public boolean isOnClient() { + return event.getUpdateCause() == TagsUpdatedEvent.UpdateCause.CLIENT_PACKET_RECEIVED; + } +} diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/load/Test.java b/src/main/java/org/violetmoon/zetaimplforge/event/load/Test.java deleted file mode 100644 index 13e9efa..0000000 --- a/src/main/java/org/violetmoon/zetaimplforge/event/load/Test.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.violetmoon.zetaimplforge.event.load; - -import net.minecraftforge.event.AddReloadListenerEvent; -import net.minecraftforge.eventbus.EventBus; -import net.minecraftforge.eventbus.api.Event; -import org.jetbrains.annotations.NotNull; -import org.violetmoon.zeta.event.bus.IZetaLoadEvent; -import org.violetmoon.zeta.event.bus.ZetaEventBus; - -import java.util.Map; -import java.util.function.Consumer; -import java.util.function.Function; - -// This made sense when i wrote it. Now i have no clue -// Please somebody finish this -public class Test { - - private static final Map, Function> FORGE_TO_ZETA = Map.of( - ForgeZAddReloadListener.class, (Function) ForgeZAddReloadListener::new - ); - - public static Consumer remap(Consumer zetaEventConsumer, Class cl) { - Function forgeToZeta = (Function) FORGE_TO_ZETA.get(cl); - return getEventConsumer(zetaEventConsumer, forgeToZeta); - } - - @NotNull - private static Consumer getEventConsumer(Consumer zetaEventConsumer, Function forgeToZeta) { - return event -> zetaEventConsumer.accept(forgeToZeta.apply(event)); - } - - - public static class ExampleZetaBus{ - private EventBus forgeBus; - - public void addListener(Consumer zetaEventConsumer, Class cl){ - forgeBus.addListener(remap(zetaEventConsumer, cl)); - } - - } - -} diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZAddReloadListener.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZAddReloadListener.java similarity index 93% rename from src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZAddReloadListener.java rename to src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZAddReloadListener.java index e9ff204..0a49ba6 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZAddReloadListener.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZAddReloadListener.java @@ -1,4 +1,4 @@ -package org.violetmoon.zetaimplforge.event.load; +package org.violetmoon.zetaimplforge.event.play; import org.violetmoon.zeta.event.load.ZAddReloadListener; diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZItemTooltip.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZItemTooltip.java index 97fd494..0fc33bb 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZItemTooltip.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZItemTooltip.java @@ -12,12 +12,7 @@ import net.minecraft.world.item.TooltipFlag; import net.minecraftforge.event.entity.player.ItemTooltipEvent; -public class ForgeZItemTooltip implements ZItemTooltip { - private final ItemTooltipEvent e; - - public ForgeZItemTooltip(ItemTooltipEvent e) { - this.e = e; - } +public record ForgeZItemTooltip(ItemTooltipEvent e) implements ZItemTooltip { @Override public TooltipFlag getFlags() {return e.getFlags();} diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZLevelTick.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZLevelTick.java index 5064e61..705363b 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZLevelTick.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZLevelTick.java @@ -7,7 +7,7 @@ import net.minecraftforge.event.TickEvent; public class ForgeZLevelTick implements ZLevelTick { - private final TickEvent.LevelTickEvent e; + public final TickEvent.LevelTickEvent e; public ForgeZLevelTick(TickEvent.LevelTickEvent e) { this.e = e; diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZRecipeCrawl.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZRecipeCrawl.java new file mode 100644 index 0000000..4ddaeb2 --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZRecipeCrawl.java @@ -0,0 +1,80 @@ +package org.violetmoon.zetaimplforge.event.play; + +import net.minecraft.world.item.crafting.Recipe; +import net.minecraftforge.eventbus.api.Event; +import org.violetmoon.zeta.event.bus.IZetaPlayEvent; +import org.violetmoon.zeta.event.play.ZRecipeCrawl; + +public class ForgeZRecipeCrawl extends Event implements IZetaPlayEvent { + + private final W wrapped; + + public ForgeZRecipeCrawl(W wrapped) { + this.wrapped = wrapped; + } + + public W get() { + return wrapped; + } + + public static class Reset extends ForgeZRecipeCrawl { + public Reset(ZRecipeCrawl.Reset wrapped) { + super(wrapped); + } + } + + public static class Starting extends ForgeZRecipeCrawl { + public Starting(ZRecipeCrawl.Starting wrapped) { + super(wrapped); + } + } + + public static class Digest extends ForgeZRecipeCrawl { + public Digest(ZRecipeCrawl.Digest wrapped) { + super(wrapped); + } + } + + public static class Visit> extends ForgeZRecipeCrawl> { + public Visit(ZRecipeCrawl.Visit wrapped) { + super(wrapped); + } + + public static class Shaped extends ForgeZRecipeCrawl { + public Shaped(ZRecipeCrawl.Visit.Shaped wrapped) { + super(wrapped); + } + } + + public static class Shapeless extends ForgeZRecipeCrawl { + public Shapeless(ZRecipeCrawl.Visit.Shapeless wrapped) { + super(wrapped); + } + } + + public static class Custom extends ForgeZRecipeCrawl { + public Custom(ZRecipeCrawl.Visit.Custom wrapped) { + super(wrapped); + } + } + + public static class Cooking extends ForgeZRecipeCrawl { + public Cooking(ZRecipeCrawl.Visit.Cooking wrapped) { + super(wrapped); + } + } + + public static class Misc extends ForgeZRecipeCrawl { + public Misc(ZRecipeCrawl.Visit.Misc wrapped) { + super(wrapped); + } + } + + } + + + + + + +} diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZScreenshot.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZScreenshot.java new file mode 100644 index 0000000..65db1bc --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZScreenshot.java @@ -0,0 +1,7 @@ +package org.violetmoon.zetaimplforge.event.play; + +import net.minecraftforge.eventbus.api.Event; +import org.violetmoon.zeta.client.event.play.ZScreenshot; + +public class ForgeZScreenshot extends Event implements ZScreenshot { +} diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZServerTick.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZServerTick.java index 49a13fd..0a39c8f 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZServerTick.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZServerTick.java @@ -6,7 +6,7 @@ import net.minecraftforge.event.TickEvent; public class ForgeZServerTick implements ZServerTick { - private final TickEvent.ServerTickEvent e; + public final TickEvent.ServerTickEvent e; public ForgeZServerTick(TickEvent.ServerTickEvent e) { this.e = e; diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/ForgeZEntityInteract.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/ForgeZEntityInteract.java index 2a8c9df..8afa861 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/ForgeZEntityInteract.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/ForgeZEntityInteract.java @@ -9,13 +9,7 @@ import net.minecraft.world.level.Level; import net.minecraftforge.event.entity.player.PlayerInteractEvent; -public class ForgeZEntityInteract implements ZEntityInteract { - private final PlayerInteractEvent.EntityInteract e; - - public ForgeZEntityInteract(PlayerInteractEvent.EntityInteract e) { - this.e = e; - } - +public record ForgeZEntityInteract(PlayerInteractEvent.EntityInteract e) implements ZEntityInteract { @Override public Entity getTarget() { return e.getTarget(); diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZBabyEntitySpawn.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZBabyEntitySpawn.java index ad93dd3..ef0d4c1 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZBabyEntitySpawn.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZBabyEntitySpawn.java @@ -8,40 +8,40 @@ import net.minecraftforge.event.entity.living.BabyEntitySpawnEvent; public class ForgeZBabyEntitySpawn implements ZBabyEntitySpawn { - private final BabyEntitySpawnEvent e; + public final BabyEntitySpawnEvent wrapped; public ForgeZBabyEntitySpawn(BabyEntitySpawnEvent e) { - this.e = e; + this.wrapped = e; } @Override public Mob getParentA() { - return e.getParentA(); + return wrapped.getParentA(); } @Override public Mob getParentB() { - return e.getParentB(); + return wrapped.getParentB(); } @Override public Player getCausedByPlayer() { - return e.getCausedByPlayer(); + return wrapped.getCausedByPlayer(); } @Override public AgeableMob getChild() { - return e.getChild(); + return wrapped.getChild(); } @Override public void setChild(AgeableMob proposedChild) { - e.setChild(proposedChild); + wrapped.setChild(proposedChild); } public static class Lowest extends ForgeZBabyEntitySpawn implements ZBabyEntitySpawn.Lowest { - public Lowest(BabyEntitySpawnEvent e) { - super(e); + public Lowest(BabyEntitySpawnEvent wrapped) { + super(wrapped); } } } diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZLivingChangeTarget.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZLivingChangeTarget.java index d6dbfa1..0776f92 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZLivingChangeTarget.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZLivingChangeTarget.java @@ -5,12 +5,7 @@ import net.minecraft.world.entity.LivingEntity; import net.minecraftforge.event.entity.living.LivingChangeTargetEvent; -public class ForgeZLivingChangeTarget implements ZLivingChangeTarget { - private final LivingChangeTargetEvent e; - - public ForgeZLivingChangeTarget(LivingChangeTargetEvent e) { - this.e = e; - } +public record ForgeZLivingChangeTarget(LivingChangeTargetEvent e) implements ZLivingChangeTarget { @Override public LivingEntity getEntity() { diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZLivingDrops.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZLivingDrops.java index 037328a..8b49305 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZLivingDrops.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZLivingDrops.java @@ -10,7 +10,7 @@ import net.minecraftforge.event.entity.living.LivingDropsEvent; public class ForgeZLivingDrops implements ZLivingDrops { - private final LivingDropsEvent e; + public final LivingDropsEvent e; public ForgeZLivingDrops(LivingDropsEvent e) { this.e = e; diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZMobSpawnEvent.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZMobSpawnEvent.java index 64f2ec7..fed2b4e 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZMobSpawnEvent.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZMobSpawnEvent.java @@ -11,7 +11,7 @@ import net.minecraftforge.event.entity.living.MobSpawnEvent; public class ForgeZMobSpawnEvent implements ZMobSpawnEvent { - private final MobSpawnEvent e; + public final MobSpawnEvent e; public ForgeZMobSpawnEvent(MobSpawnEvent e) { this.e = e; @@ -53,7 +53,7 @@ public void setResult(ZResult value) { } public static class FinalizeSpawn extends ForgeZMobSpawnEvent implements ZMobSpawnEvent.CheckSpawn { - private final MobSpawnEvent.FinalizeSpawn e; + public final MobSpawnEvent.FinalizeSpawn e; public FinalizeSpawn(MobSpawnEvent.FinalizeSpawn e) { super(e); diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/player/ForgeZPlayerTick.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/player/ForgeZPlayerTick.java index 174ebcf..c0c80f6 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/player/ForgeZPlayerTick.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/player/ForgeZPlayerTick.java @@ -6,7 +6,7 @@ import net.minecraftforge.event.TickEvent; public abstract class ForgeZPlayerTick implements ZPlayerTick { - private final TickEvent.PlayerTickEvent e; + public final TickEvent.PlayerTickEvent e; protected ForgeZPlayerTick(TickEvent.PlayerTickEvent e) { this.e = e; diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/play/loading/ForgeZAttachCapabilities.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/loading/ForgeZAttachCapabilities.java index 95d342d..5fd2ca7 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/play/loading/ForgeZAttachCapabilities.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/loading/ForgeZAttachCapabilities.java @@ -1,5 +1,6 @@ package org.violetmoon.zetaimplforge.event.play.loading; +import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.capability.ZetaCapability; import org.violetmoon.zeta.capability.ZetaCapabilityManager; import org.violetmoon.zeta.event.play.loading.ZAttachCapabilities; diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/play/loading/ForgeZGatherAdditionalFlags.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/loading/ForgeZGatherAdditionalFlags.java new file mode 100644 index 0000000..89ea34b --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/loading/ForgeZGatherAdditionalFlags.java @@ -0,0 +1,19 @@ +package org.violetmoon.zetaimplforge.event.play.loading; + +import net.minecraftforge.eventbus.api.Event; +import org.violetmoon.zeta.config.ConfigFlagManager; +import org.violetmoon.zeta.event.play.loading.ZGatherAdditionalFlags; + +public class ForgeZGatherAdditionalFlags extends Event implements ZGatherAdditionalFlags { + + private final ZGatherAdditionalFlags wrapped; + + public ForgeZGatherAdditionalFlags(ZGatherAdditionalFlags wrapped) { + this.wrapped = wrapped; + } + + @Override + public ConfigFlagManager flagManager() { + return wrapped.flagManager(); + } +} diff --git a/src/main/java/org/violetmoon/zetaimplforge/mixin/mixins/client/GameRenderMixin.java b/src/main/java/org/violetmoon/zetaimplforge/mixin/mixins/client/GameRenderMixin.java index b582d40..59086e1 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/mixin/mixins/client/GameRenderMixin.java +++ b/src/main/java/org/violetmoon/zetaimplforge/mixin/mixins/client/GameRenderMixin.java @@ -5,6 +5,7 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.violetmoon.zeta.client.event.play.ZEarlyRender; +import org.violetmoon.zeta.mod.ZetaMod; import org.violetmoon.zeta.util.zetalist.ZetaClientList; import org.violetmoon.zetaimplforge.client.event.play.ForgeZEarlyRender; @@ -12,8 +13,9 @@ @Mixin(GameRenderer.class) public class GameRenderMixin { + @Inject(method = "render", at = @At(target = "Lnet/minecraft/util/profiling/ProfilerFiller;popPush(Ljava/lang/String;)V", value = "INVOKE", shift = At.Shift.AFTER)) private void quark$renderEvent(float v, long l, boolean b, CallbackInfo ci) { - ZetaClientList.INSTANCE.fireEvent(new ForgeZEarlyRender(), ZEarlyRender.class); + ZetaMod.ZETA.playBus.fire(new ForgeZEarlyRender(), ZEarlyRender.class); } } diff --git a/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaForgeMod.java b/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaForgeMod.java deleted file mode 100644 index 38bd970..0000000 --- a/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaForgeMod.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.violetmoon.zetaimplforge.mod; - -import org.apache.logging.log4j.LogManager; -import org.violetmoon.zeta.Zeta; -import org.violetmoon.zeta.mod.ZetaClientProxy; -import org.violetmoon.zeta.mod.ZetaMod; -import org.violetmoon.zeta.mod.ZetaModProxy; -import org.violetmoon.zeta.util.handler.ToolInteractionHandler; -import org.violetmoon.zetaimplforge.ForgeZeta; -import org.violetmoon.zetaimplforge.client.ForgeZetaClient; -import org.violetmoon.zetaimplforge.config.ConfigEventDispatcher; -import org.violetmoon.zetaimplforge.world.ZetaBiomeModifier; - -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.DistExecutor; -import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; -import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; - -@Mod("zeta") -public class ZetaForgeMod { - - public ZetaForgeMod() { - ForgeZeta zeta = new ForgeZeta(Zeta.ZETA_ID, LogManager.getLogger(Zeta.ZETA_ID + "-internal")); - - ZetaModProxy proxy = DistExecutor.runForDist(() -> ZetaClientProxy::new, () -> ZetaModProxy::new); - Object zetaClient = DistExecutor.runForDist(() -> () -> new ForgeZetaClient(zeta), () -> () -> new Object()); - - ZetaMod.start(zeta, proxy); - ZetaMod.proxy.setClientZeta(zetaClient); - - MinecraftForge.EVENT_BUS.register(ToolInteractionHandler.class); - ZetaBiomeModifier.registerBiomeModifier(FMLJavaModLoadingContext.get().getModEventBus()); - - IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus(); - bus.addListener(this::setup); - } - - public void setup(FMLCommonSetupEvent event) { - event.enqueueWork(ConfigEventDispatcher::dispatchAllInitialLoads); - } - -} diff --git a/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModClientProxy.java b/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModClientProxy.java new file mode 100644 index 0000000..d097651 --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModClientProxy.java @@ -0,0 +1,33 @@ +package org.violetmoon.zetaimplforge.mod; + +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.TickEvent; +import org.violetmoon.zeta.Zeta; +import org.violetmoon.zeta.client.ClientTicker; +import org.violetmoon.zeta.util.handler.RequiredModTooltipHandler; +import org.violetmoon.zeta.util.zetalist.ZetaList; +import org.violetmoon.zetaimplforge.event.load.ForgeZFirstClientTick; + +public class ZetaModClientProxy extends ZetaModCommonProxy { + + public ZetaModClientProxy(Zeta zeta) { + super(zeta); + + zeta.playBus + .subscribe(ClientTicker.INSTANCE) + .subscribe(new RequiredModTooltipHandler.Client(zeta)); + + MinecraftForge.EVENT_BUS.addListener(this::clientTick); + } + + // added once per zeta. Its fine as we then fire it on zeta load bos which is one per zeta too. + boolean clientTicked = false; + + public void clientTick(TickEvent.ClientTickEvent e) { + if (!clientTicked) { + ZetaList.INSTANCE.fireLoadEvent(new ForgeZFirstClientTick()); + clientTicked = true; + } + } + +} diff --git a/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModCommonProxy.java b/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModCommonProxy.java new file mode 100644 index 0000000..c77f491 --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModCommonProxy.java @@ -0,0 +1,75 @@ +package org.violetmoon.zetaimplforge.mod; + +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraftforge.client.event.RegisterColorHandlersEvent; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.common.capabilities.CapabilityManager; +import net.minecraftforge.event.AttachCapabilitiesEvent; +import net.minecraftforge.eventbus.api.IEventBus; +import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; +import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; +import org.violetmoon.zeta.Zeta; +import org.violetmoon.zeta.capability.ZetaCapabilityManager; +import org.violetmoon.zeta.client.event.load.*; +import org.violetmoon.zeta.client.event.play.*; +import org.violetmoon.zeta.config.SyncedFlagHandler; +import org.violetmoon.zeta.config.ZetaGeneralConfig; +import org.violetmoon.zeta.event.load.*; +import org.violetmoon.zeta.event.play.*; +import org.violetmoon.zeta.event.play.entity.*; +import org.violetmoon.zeta.event.play.entity.living.*; +import org.violetmoon.zeta.event.play.entity.player.*; +import org.violetmoon.zeta.event.play.loading.*; +import org.violetmoon.zeta.util.handler.RecipeCrawlHandler; +import org.violetmoon.zeta.util.handler.ToolInteractionHandler; +import org.violetmoon.zeta.world.EntitySpawnHandler; +import org.violetmoon.zeta.world.WorldGenHandler; +import org.violetmoon.zetaimplforge.api.ForgeZGatherAdvancementModifiers; +import org.violetmoon.zetaimplforge.capability.ForgeCapabilityManager; +import org.violetmoon.zetaimplforge.client.event.load.*; +import org.violetmoon.zetaimplforge.client.event.play.*; +import org.violetmoon.zetaimplforge.config.ConfigEventDispatcher; +import org.violetmoon.zetaimplforge.event.ForgeEventsRemapper; +import org.violetmoon.zetaimplforge.event.load.*; +import org.violetmoon.zetaimplforge.event.play.*; +import org.violetmoon.zetaimplforge.event.play.entity.*; +import org.violetmoon.zetaimplforge.event.play.entity.living.*; +import org.violetmoon.zetaimplforge.event.play.entity.player.*; +import org.violetmoon.zetaimplforge.event.play.loading.*; +import org.violetmoon.zetaimplforge.world.ZetaBiomeModifier; + +import java.util.function.Function; + +public class ZetaModCommonProxy { + + public ZetaModCommonProxy(Zeta zeta) { + IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus(); + bus.addListener(this::setup); + + zeta.loadBus + .subscribe(RecipeCrawlHandler.class) + .subscribe(ToolInteractionHandler.class) + .subscribe(EntitySpawnHandler.class) + .subscribe(WorldGenHandler.class) + .subscribe(ZetaGeneralConfig.class); + + zeta.playBus + .subscribe(RecipeCrawlHandler.class) + .subscribe(ToolInteractionHandler.class) + .subscribe(SyncedFlagHandler.class); + + + MinecraftForge.EVENT_BUS.register(ToolInteractionHandler.class); + ZetaBiomeModifier.registerBiomeModifier(FMLJavaModLoadingContext.get().getModEventBus()); + + } + + + public void setup(FMLCommonSetupEvent event) { + event.enqueueWork(ConfigEventDispatcher::dispatchAllInitialLoads); + } + + +} diff --git a/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModForge.java b/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModForge.java new file mode 100644 index 0000000..b4c5824 --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModForge.java @@ -0,0 +1,21 @@ +package org.violetmoon.zetaimplforge.mod; + +import org.violetmoon.zeta.mod.ZetaMod; +import org.violetmoon.zetaimplforge.ForgeZeta; + +import net.minecraftforge.fml.DistExecutor; +import net.minecraftforge.fml.common.Mod; + +@Mod(ZetaMod.ZETA_ID) +public class ZetaModForge extends ZetaMod{ + + public ZetaModForge() { + super(new ForgeZeta(ZetaMod.ZETA_ID, ZetaMod.LOGGER)); + + // creates 2 dist specific objects that will handle zeta specific & loader specific events needed for zeta to work + DistExecutor.runForDist(() -> () -> new ZetaModClientProxy(ZetaMod.ZETA), () -> () -> new ZetaModCommonProxy(ZetaMod.ZETA)); + + } + + +} diff --git a/src/main/java/org/violetmoon/zetaimplforge/world/ZetaBiomeModifier.java b/src/main/java/org/violetmoon/zetaimplforge/world/ZetaBiomeModifier.java index 36b21e3..7b8b259 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/world/ZetaBiomeModifier.java +++ b/src/main/java/org/violetmoon/zetaimplforge/world/ZetaBiomeModifier.java @@ -3,6 +3,7 @@ import java.util.List; import org.violetmoon.zeta.Zeta; +import org.violetmoon.zeta.mod.ZetaMod; import org.violetmoon.zeta.util.zetalist.ZetaList; import org.violetmoon.zeta.world.WorldGenHandler; @@ -24,8 +25,8 @@ public class ZetaBiomeModifier implements BiomeModifier { - public static final ResourceLocation RESOURCE = new ResourceLocation(Zeta.ZETA_ID, "biome_modifier"); - private static final RegistryObject> SERIALIZER = RegistryObject.create(RESOURCE, ForgeRegistries.Keys.BIOME_MODIFIER_SERIALIZERS, Zeta.ZETA_ID); + public static final ResourceLocation RESOURCE = new ResourceLocation(ZetaMod.ZETA_ID, "biome_modifier"); + private static final RegistryObject> SERIALIZER = RegistryObject.create(RESOURCE, ForgeRegistries.Keys.BIOME_MODIFIER_SERIALIZERS, ZetaMod.ZETA_ID); @Override public void modify(Holder biome, Phase phase, BiomeInfo.Builder builder) { @@ -56,7 +57,7 @@ public static void modifyBiome(Holder biome, ModifiableBiomeInfo.BiomeInf } public static void registerBiomeModifier(IEventBus bus) { - DeferredRegister> biomeModifiers = DeferredRegister.create(ForgeRegistries.Keys.BIOME_MODIFIER_SERIALIZERS, Zeta.ZETA_ID); + DeferredRegister> biomeModifiers = DeferredRegister.create(ForgeRegistries.Keys.BIOME_MODIFIER_SERIALIZERS, ZetaMod.ZETA_ID); biomeModifiers.register(bus); biomeModifiers.register(ZetaBiomeModifier.RESOURCE.getPath(), ZetaBiomeModifier::makeCodec); } diff --git a/src/main/resources/META-INF/mods.toml b/src/main/resources/META-INF/mods.toml index 12adcb4..3ab658a 100644 --- a/src/main/resources/META-INF/mods.toml +++ b/src/main/resources/META-INF/mods.toml @@ -15,4 +15,10 @@ description='''A fully featured Library designed around loading highly configura mandatory=true versionRange="[43.0.8,)" ordering="AFTER" + side="BOTH" + +[[dependencies.zeta]] + modId="quark" + mandatory=false + versionRange="[4.0-460,)" side="BOTH" \ No newline at end of file