Skip to content

Commit

Permalink
more forge bus work
Browse files Browse the repository at this point in the history
  • Loading branch information
MehVahdJukaar committed Jul 30, 2024
1 parent 79378da commit cc4b308
Show file tree
Hide file tree
Showing 12 changed files with 304 additions and 393 deletions.
104 changes: 96 additions & 8 deletions src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
package org.violetmoon.zeta.event.bus;

import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
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.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.violetmoon.zeta.event.play.loading.ZAttachCapabilities;

import java.lang.annotation.Annotation;
import java.lang.invoke.MethodHandle;
Expand Down Expand Up @@ -43,7 +51,9 @@ protected void subscribeMethod(Method method, Object receiver, Class<?> owningCl
throw arityERR(method);

Class<?> eventType = method.getParameterTypes()[0];
if (!eventRoot.isAssignableFrom(eventType))

//check if it's already a forge event or it's a zeta event
if (!eventRoot.isAssignableFrom(eventType) || !Event.class.isAssignableFrom(eventType))
throw typeERR(method);

MethodHandle handle;
Expand All @@ -57,12 +67,13 @@ protected void subscribeMethod(Method method, Object receiver, Class<?> owningCl
if (receiver != null)
handle = handle.bindTo(receiver);

Consumer<? extends Event> consumer = remapMethod(handle, (Class<? extends E>) eventType);
forgeBus.addListener(consumer);
Consumer<? extends Event> consumer = remapMethod(handle, eventType);
registerListenerToForgeWithPriorityAndGenerics(owningClazz, consumer);
//store here so we can unregister later
convertedHandlers.put(new Key(method, receiver, owningClazz), consumer);
}


@Override
protected void unsubscribeMethod(Method m, Object receiver, Class<?> owningClazz) {
var handler = convertedHandlers.remove(new Key(m, receiver, owningClazz));
Expand All @@ -86,7 +97,9 @@ public <T extends E> T fire(@NotNull T event, Class<? super T> firedAs) {
return event;
}

// reflection hacks below. be warned
// 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

private <T extends E> Event remapEvent(@NotNull T event, Class<?> firedAs) {
Function<? extends E, ? extends Event> zetaToForgeFunc = zetaToForgeMap.get((Class<? extends E>) firedAs);
Expand All @@ -97,21 +110,40 @@ private <T extends E> Event remapEvent(@NotNull T event, Class<?> firedAs) {
}

// takes a method that takes a zeta event and turns into one that takes a forge event
private Consumer<? extends Event> remapMethod(MethodHandle zetaEventConsumer, Class<? extends E> zetaEventClass) {
private Consumer<? extends Event> remapMethod(MethodHandle originalEventConsumer, Class<?> zetaEventClass) {
// if it's already a forge event, just call it
if (Event.class.isAssignableFrom(zetaEventClass)) {
return event -> {
try {
originalEventConsumer.invoke(event);
} catch (Throwable e) {
throw new RuntimeException(e);
}
};
}

Function<? extends Event, ? extends E> forgeToZetaFunc = forgeToZetaMap.get(zetaEventClass);
if (forgeToZetaFunc == null) {
throw new RuntimeException("No forge-Event-wrapping constructor found for Zeta event class. You must register its subclass using registerSubclass. " + zetaEventClass);
}
return createForgeConsumer(zetaEventConsumer, forgeToZetaFunc);
return createForgeConsumer(originalEventConsumer, forgeToZetaFunc, zetaEventClass);
}

private <T extends E> Event createForgeEvent(@NotNull E event, Function<T, ? extends Event> function) {
return function.apply((T) event);
}

private <Z extends E, F extends Event> Consumer<F> createForgeConsumer(MethodHandle zetaEventConsumer, Function<F, Z> forgeToZetaFunc) {
private <Z extends E, F extends Event> Consumer<F> createForgeConsumer(MethodHandle zetaEventConsumer, Function<F, Z> forgeToZetaFunc,
Class<?> zetaEventClass) {
//hack for tick events
Phase phase = Phase.guessFromClassName(zetaEventClass);
return event -> {
try {
//luckily this phase madness will go away with new neoforge
if (phase != Phase.NONE && event instanceof TickEvent te) {
if (phase == Phase.START && te.phase != TickEvent.Phase.START) return;
if (phase == Phase.END && te.phase != TickEvent.Phase.END) return;
}
zetaEventConsumer.invoke(forgeToZetaFunc.apply(event));
} catch (Throwable e) {
throw new RuntimeException(e);
Expand All @@ -120,7 +152,7 @@ private <Z extends E, F extends Event> Consumer<F> createForgeConsumer(MethodHan
}


public <S extends C, C extends E> void registerSubClass(Class<C> eventClass, Class<S> zetaEventClass) {
public <S extends E, C extends E> void registerSubClass(Class<C> eventClass, Class<S> zetaEventClass) {
forgeToZetaMap.put(eventClass, findWrappingConstructor(zetaEventClass));
zetaToForgeMap.put(eventClass, findWrappedEvent(zetaEventClass));
}
Expand Down Expand Up @@ -158,4 +190,60 @@ public <S extends C, C extends E> void registerSubClass(Class<C> eventClass, Cla
throw new RuntimeException("No wrapped forge Event found for Zeta event class " + zetaEventClass);
}

//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

private void registerListenerToForgeWithPriorityAndGenerics(Class<?> owningClazz, Consumer<? extends Event> consumer) {
EventPriority priority = guessPriorityFromClassName(owningClazz);
//harcoded caps bs. Alternatively a registerGenerics method could have been added to the bus.
Class<?> generics = null;
if (owningClazz.isAssignableFrom(ZAttachCapabilities.BlockEntityCaps.class)) {
generics = BlockEntity.class;
}
if (owningClazz.isAssignableFrom(ZAttachCapabilities.ItemStackCaps.class)) {
generics = ItemStack.class;
}
if (owningClazz.isAssignableFrom(ZAttachCapabilities.LevelCaps.class)) {
generics = Level.class;
}
if (generics != null) {
forgeBus.addGenericListener(generics, priority, (Consumer<GenericEvent>) consumer);
} else {
forgeBus.addListener(priority, consumer);
}
}


private enum Phase {
NONE, START, END;

private static Phase guessFromClassName(Class<?> zetaEventClass) {
String simpleName = zetaEventClass.getSimpleName();
if (simpleName.equals("Start")) {
return START;
} else if (simpleName.equals("End")) {
return END;
} else {
return NONE;
}
}
}


private static final Map<Class<?>, EventPriority> CACHE = new HashMap<>();

private static EventPriority guessPriorityFromClassName(Class<?> zetaEventClass) {
return CACHE.computeIfAbsent(zetaEventClass, cl -> {
String simpleName = zetaEventClass.getSimpleName();
for (EventPriority p : EventPriority.values()) {
String name = WordUtils.capitalizeFully(p.name().toLowerCase());
if (simpleName.endsWith(name)) {
return p;
}
}
return EventPriority.NORMAL;
});
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@

import org.violetmoon.zeta.event.bus.IZetaLoadEvent;

public class ZConfigChanged implements IZetaLoadEvent { }
public interface ZConfigChanged extends IZetaLoadEvent { }
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@

import org.violetmoon.zeta.event.bus.IZetaLoadEvent;

public class ZModulesReady implements IZetaLoadEvent { }
public interface ZModulesReady extends IZetaLoadEvent { }
33 changes: 8 additions & 25 deletions src/main/java/org/violetmoon/zeta/event/load/ZRegister.java
Original file line number Diff line number Diff line change
Expand Up @@ -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 { }
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
package org.violetmoon.zeta.event.load;

import net.minecraft.core.RegistryAccess;
import org.violetmoon.zeta.event.bus.IZetaLoadEvent;

//TODO: just used by RecipeCrawlHandler
public class ZTagsUpdated implements IZetaLoadEvent { }
public interface ZTagsUpdated extends IZetaLoadEvent {

RegistryAccess getRegistryAccess();

boolean isOnClient();

}
Loading

0 comments on commit cc4b308

Please sign in to comment.