clean up xplat

This commit is contained in:
petrak@ 2022-12-30 13:07:21 -05:00
parent bdbb8b0e83
commit 5f9ced55fc
8 changed files with 173 additions and 208 deletions

View file

@ -4,13 +4,14 @@ import at.petrak.hexcasting.xplat.IXplatAbstractions;
import com.google.common.collect.Lists;
import com.mojang.datafixers.util.Pair;
import net.minecraft.client.Minecraft;
import net.minecraft.world.level.Level;
import net.minecraft.world.entity.player.Player;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.Registry;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
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.BeehiveBlock;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
@ -120,7 +121,7 @@ public final class ScryingLensOverlayRegistry {
* @throws IllegalArgumentException if the block is already registered.
*/
public static void addDisplayer(Block block, OverlayBuilder displayer) {
addDisplayer(IXplatAbstractions.INSTANCE.getID(block), displayer);
addDisplayer(Registry.BLOCK.getKey(block), displayer);
}
/**

View file

@ -11,7 +11,7 @@ import net.minecraft.world.level.Level;
import net.minecraft.world.phys.EntityHitResult;
import org.jetbrains.annotations.Nullable;
public class Brainsweeping {
public class BrainsweepingEvents {
public static InteractionResult interactWithBrainswept(Player player, Level world, InteractionHand hand,
Entity entity, @Nullable EntityHitResult hitResult) {
if (entity instanceof Mob mob && IXplatAbstractions.INSTANCE.isBrainswept(mob)) {

View file

@ -16,14 +16,12 @@ import at.petrak.hexcasting.interop.pehkui.PehkuiInterop;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Registry;
import net.minecraft.network.protocol.Packet;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.npc.VillagerProfession;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.CreativeModeTab;
import net.minecraft.world.item.Item;
@ -125,7 +123,7 @@ public interface IXplatAbstractions {
// Blocks
<T extends BlockEntity> BlockEntityType<T> createBlockEntityType(BiFunction<BlockPos, BlockState, T> func,
Block... blocks);
Block... blocks);
boolean tryPlaceFluid(Level level, InteractionHand hand, BlockPos pos, Fluid fluid);
@ -137,19 +135,6 @@ public interface IXplatAbstractions {
boolean isCorrectTierForDrops(Tier tier, BlockState bs);
// These don't need to be xplat anymore, but it does save refactoring if they're still defined here
default ResourceLocation getID(Block block) {
return Registry.BLOCK.getKey(block);
}
default ResourceLocation getID(Item item) {
return Registry.ITEM.getKey(item);
}
default ResourceLocation getID(VillagerProfession profession) {
return Registry.VILLAGER_PROFESSION.getKey(profession);
}
Ingredient getUnsealedIngredient(ItemStack stack);
IXplatTags tags();

View file

@ -15,7 +15,7 @@ import at.petrak.hexcasting.common.lib.*
import at.petrak.hexcasting.common.lib.hex.HexIotaTypes
import at.petrak.hexcasting.common.loot.HexLootHandler
import at.petrak.hexcasting.common.misc.AkashicTreeGrower
import at.petrak.hexcasting.common.misc.Brainsweeping
import at.petrak.hexcasting.common.misc.BrainsweepingEvents
import at.petrak.hexcasting.common.misc.PlayerPositionRecorder
import at.petrak.hexcasting.common.recipe.HexRecipeStuffRegistry
import at.petrak.hexcasting.fabric.event.VillagerConversionCallback
@ -63,8 +63,8 @@ object FabricHexInitializer : ModInitializer {
}
fun initListeners() {
UseEntityCallback.EVENT.register(Brainsweeping::interactWithBrainswept)
VillagerConversionCallback.EVENT.register(Brainsweeping::copyBrainsweepPostTransformation)
UseEntityCallback.EVENT.register(BrainsweepingEvents::interactWithBrainswept)
VillagerConversionCallback.EVENT.register(BrainsweepingEvents::copyBrainsweepPostTransformation)
AttackBlockCallback.EVENT.register { player, world, _, pos, _ ->
// SUCCESS cancels further processing and, on the client, sends a packet to the server.
// PASS falls back to further processing.

View file

@ -61,7 +61,6 @@ import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.npc.Villager;
import net.minecraft.world.entity.npc.VillagerProfession;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.*;
import net.minecraft.world.item.crafting.Ingredient;
@ -306,37 +305,19 @@ public class FabricXplatImpl implements IXplatAbstractions {
return false;
}
@Override
public ResourceLocation getID(Block block) {
return Registry.BLOCK.getKey(block);
}
@Override
public ResourceLocation getID(Item item) {
return Registry.ITEM.getKey(item);
}
@Override
public ResourceLocation getID(VillagerProfession profession) {
return Registry.VILLAGER_PROFESSION.getKey(profession);
}
@Override
public Ingredient getUnsealedIngredient(ItemStack stack) {
return FabricUnsealedIngredient.of(stack);
}
private static CreativeModeTab TAB = null;
private static Supplier<CreativeModeTab> TAB = Suppliers.memoize(() -> FabricItemGroupBuilder.create(
modLoc("creative_tab"))
.icon(HexItems::tabIcon)
.build());
@Override
public CreativeModeTab getTab() {
if (TAB == null) {
TAB = FabricItemGroupBuilder.create(modLoc("creative_tab"))
.icon(HexItems::tabIcon)
.build();
}
return TAB;
return TAB.get();
}
// do a stupid hack from botania

View file

@ -16,7 +16,7 @@ import at.petrak.hexcasting.common.lib.*;
import at.petrak.hexcasting.common.lib.hex.HexIotaTypes;
import at.petrak.hexcasting.common.loot.HexLootHandler;
import at.petrak.hexcasting.common.misc.AkashicTreeGrower;
import at.petrak.hexcasting.common.misc.Brainsweeping;
import at.petrak.hexcasting.common.misc.BrainsweepingEvents;
import at.petrak.hexcasting.common.misc.PlayerPositionRecorder;
import at.petrak.hexcasting.common.recipe.HexRecipeStuffRegistry;
import at.petrak.hexcasting.forge.cap.CapSyncers;
@ -70,175 +70,176 @@ import java.util.function.Consumer;
@Mod(HexAPI.MOD_ID)
public class ForgeHexInitializer {
public ForgeHexInitializer() {
initConfig();
initRegistry();
initListeners();
}
public ForgeHexInitializer() {
initConfig();
initRegistry();
initListeners();
}
private static void initConfig() {
var config = new ForgeConfigSpec.Builder().configure(ForgeHexConfig::new);
var clientConfig = new ForgeConfigSpec.Builder().configure(ForgeHexConfig.Client::new);
var serverConfig = new ForgeConfigSpec.Builder().configure(ForgeHexConfig.Server::new);
HexConfig.setCommon(config.getLeft());
HexConfig.setClient(clientConfig.getLeft());
HexConfig.setServer(serverConfig.getLeft());
var mlc = ModLoadingContext.get();
mlc.registerConfig(ModConfig.Type.COMMON, config.getRight());
mlc.registerConfig(ModConfig.Type.CLIENT, clientConfig.getRight());
mlc.registerConfig(ModConfig.Type.SERVER, serverConfig.getRight());
}
private static void initConfig() {
var config = new ForgeConfigSpec.Builder().configure(ForgeHexConfig::new);
var clientConfig = new ForgeConfigSpec.Builder().configure(ForgeHexConfig.Client::new);
var serverConfig = new ForgeConfigSpec.Builder().configure(ForgeHexConfig.Server::new);
HexConfig.setCommon(config.getLeft());
HexConfig.setClient(clientConfig.getLeft());
HexConfig.setServer(serverConfig.getLeft());
var mlc = ModLoadingContext.get();
mlc.registerConfig(ModConfig.Type.COMMON, config.getRight());
mlc.registerConfig(ModConfig.Type.CLIENT, clientConfig.getRight());
mlc.registerConfig(ModConfig.Type.SERVER, serverConfig.getRight());
}
private static void initRegistry() {
bind(Registry.SOUND_EVENT_REGISTRY, HexSounds::registerSounds);
bind(Registry.BLOCK_REGISTRY, HexBlocks::registerBlocks);
bind(Registry.ITEM_REGISTRY, HexBlocks::registerBlockItems);
bind(Registry.BLOCK_ENTITY_TYPE_REGISTRY, HexBlockEntities::registerTiles);
bind(Registry.ITEM_REGISTRY, HexItems::registerItems);
private static void initRegistry() {
bind(Registry.SOUND_EVENT_REGISTRY, HexSounds::registerSounds);
bind(Registry.BLOCK_REGISTRY, HexBlocks::registerBlocks);
bind(Registry.ITEM_REGISTRY, HexBlocks::registerBlockItems);
bind(Registry.BLOCK_ENTITY_TYPE_REGISTRY, HexBlockEntities::registerTiles);
bind(Registry.ITEM_REGISTRY, HexItems::registerItems);
bind(Registry.RECIPE_SERIALIZER_REGISTRY, HexRecipeStuffRegistry::registerSerializers);
bind(Registry.RECIPE_TYPE_REGISTRY, HexRecipeStuffRegistry::registerTypes);
bind(Registry.RECIPE_SERIALIZER_REGISTRY, HexRecipeStuffRegistry::registerSerializers);
bind(Registry.RECIPE_TYPE_REGISTRY, HexRecipeStuffRegistry::registerTypes);
bind(Registry.ENTITY_TYPE_REGISTRY, HexEntities::registerEntities);
bind(Registry.ENTITY_TYPE_REGISTRY, HexEntities::registerEntities);
bind(Registry.PARTICLE_TYPE_REGISTRY, HexParticles::registerParticles);
bind(Registry.PARTICLE_TYPE_REGISTRY, HexParticles::registerParticles);
ForgeHexArgumentTypeRegistry.ARGUMENT_TYPES.register(getModEventBus());
ForgeHexArgumentTypeRegistry.ARGUMENT_TYPES.register(getModEventBus());
HexIotaTypes.registerTypes();
HexIotaTypes.registerTypes();
HexAdvancementTriggers.registerTriggers();
}
HexAdvancementTriggers.registerTriggers();
}
// https://github.com/VazkiiMods/Botania/blob/1.18.x/Forge/src/main/java/vazkii/botania/forge/ForgeCommonInitializer.java
private static <T> void bind(ResourceKey<Registry<T>> registry,
Consumer<BiConsumer<T, ResourceLocation>> source) {
getModEventBus().addListener((RegisterEvent event) -> {
if (registry.equals(event.getRegistryKey())) {
source.accept((t, rl) -> event.register(registry, rl, () -> t));
}
});
}
// https://github.com/VazkiiMods/Botania/blob/1.18.x/Forge/src/main/java/vazkii/botania/forge/ForgeCommonInitializer.java
private static <T> void bind(ResourceKey<Registry<T>> registry,
Consumer<BiConsumer<T, ResourceLocation>> source) {
getModEventBus().addListener((RegisterEvent event) -> {
if (registry.equals(event.getRegistryKey())) {
source.accept((t, rl) -> event.register(registry, rl, () -> t));
}
});
}
private static void initListeners() {
var modBus = getModEventBus();
var evBus = MinecraftForge.EVENT_BUS;
private static void initListeners() {
var modBus = getModEventBus();
var evBus = MinecraftForge.EVENT_BUS;
DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> modBus.register(ForgeHexClientInitializer.class));
DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> modBus.register(ForgeHexClientInitializer.class));
modBus.addListener((FMLCommonSetupEvent evt) ->
evt.enqueueWork(() -> {
ForgePacketHandler.init();
HexComposting.setup();
HexStrippables.init();
RegisterPatterns.registerPatterns();
// Forge does not strictly require TreeGrowers to initialize during early game stages, unlike Fabric
// and Quilt.
// However, all launcher panic if the same resource is registered twice. But do need blocks and
// items to be completely initialized.
// Explicitly calling here avoids potential confusion, or reliance on tricks that may fail under
// compiler optimization.
AkashicTreeGrower.init();
modBus.addListener((FMLCommonSetupEvent evt) ->
evt.enqueueWork(() -> {
ForgePacketHandler.init();
HexComposting.setup();
HexStrippables.init();
RegisterPatterns.registerPatterns();
// Forge does not strictly require TreeGrowers to initialize during early game stages, unlike Fabric
// and Quilt.
// However, all launcher panic if the same resource is registered twice. But do need blocks and
// items to be completely initialized.
// Explicitly calling here avoids potential confusion, or reliance on tricks that may fail under
// compiler optimization.
AkashicTreeGrower.init();
HexInterop.init();
}));
HexInterop.init();
}));
// We have to do these at some point when the registries are still open
modBus.addListener((RegisterEvent evt) -> {
if (evt.getRegistryKey().equals(Registry.ITEM_REGISTRY)) {
CraftingHelper.register(ForgeUnsealedIngredient.ID, ForgeUnsealedIngredient.Serializer.INSTANCE);
CraftingHelper.register(ForgeModConditionalIngredient.ID,
ForgeModConditionalIngredient.Serializer.INSTANCE);
HexStatistics.register();
HexLootFunctions.registerSerializers((lift, id) ->
Registry.register(Registry.LOOT_FUNCTION_TYPE, id, lift));
}
});
// We have to do these at some point when the registries are still open
modBus.addListener((RegisterEvent evt) -> {
if (evt.getRegistryKey().equals(Registry.ITEM_REGISTRY)) {
CraftingHelper.register(ForgeUnsealedIngredient.ID, ForgeUnsealedIngredient.Serializer.INSTANCE);
CraftingHelper.register(ForgeModConditionalIngredient.ID,
ForgeModConditionalIngredient.Serializer.INSTANCE);
HexStatistics.register();
HexLootFunctions.registerSerializers((lift, id) ->
Registry.register(Registry.LOOT_FUNCTION_TYPE, id, lift));
}
});
modBus.addListener((FMLLoadCompleteEvent evt) ->
HexAPI.LOGGER.info(PatternRegistry.getPatternCountInfo()));
modBus.addListener((FMLLoadCompleteEvent evt) ->
HexAPI.LOGGER.info(PatternRegistry.getPatternCountInfo()));
evBus.addListener((PlayerInteractEvent.EntityInteract evt) -> {
var res = Brainsweeping.interactWithBrainswept(
evt.getEntity(), evt.getLevel(), evt.getHand(), evt.getTarget(), null);
if (res.consumesAction()) {
evt.setCanceled(true);
evt.setCancellationResult(res);
}
});
evBus.addListener((LivingConversionEvent.Post evt) ->
Brainsweeping.copyBrainsweepPostTransformation(evt.getEntity(), evt.getOutcome()));
evBus.addListener((PlayerInteractEvent.EntityInteract evt) -> {
var res = BrainsweepingEvents.interactWithBrainswept(
evt.getEntity(), evt.getLevel(), evt.getHand(), evt.getTarget(), null);
if (res.consumesAction()) {
evt.setCanceled(true);
evt.setCancellationResult(res);
}
});
evBus.addListener((LivingConversionEvent.Post evt) ->
BrainsweepingEvents.copyBrainsweepPostTransformation(evt.getEntity(), evt.getOutcome()));
evBus.addListener((LivingEvent.LivingTickEvent evt) -> {
OpFlight.INSTANCE.tickDownFlight(evt.getEntity());
ItemLens.tickLens(evt.getEntity());
});
evBus.addListener((LivingEvent.LivingTickEvent evt) -> {
OpFlight.INSTANCE.tickDownFlight(evt.getEntity());
ItemLens.tickLens(evt.getEntity());
});
evBus.addListener((TickEvent.LevelTickEvent evt) -> {
if (evt.phase == TickEvent.Phase.END && evt.level instanceof ServerLevel world) {
PlayerPositionRecorder.updateAllPlayers(world);
}
});
evBus.addListener((TickEvent.LevelTickEvent evt) -> {
if (evt.phase == TickEvent.Phase.END && evt.level instanceof ServerLevel world) {
PlayerPositionRecorder.updateAllPlayers(world);
}
});
evBus.addListener((RegisterCommandsEvent evt) -> HexCommands.register(evt.getDispatcher()));
evBus.addListener((RegisterCommandsEvent evt) -> HexCommands.register(evt.getDispatcher()));
evBus.addListener((PlayerEvent.BreakSpeed evt) -> {
var pos = evt.getPosition();
// tracing the dataflow, this is only empty if someone is calling a deprecated function for the
// break speed. This will probably not ever hapen, but hey! i will never complain about correctness
// enforced at the type level.
if (pos.isEmpty()) {
return;
}
evt.setCanceled(ItemJewelerHammer.shouldFailToBreak(evt.getEntity(), evt.getState(), pos.get()));
});
evBus.addListener((PlayerEvent.BreakSpeed evt) -> {
var pos = evt.getPosition();
// tracing the dataflow, this is only empty if someone is calling a deprecated function for the
// break speed. This will probably not ever hapen, but hey! i will never complain about correctness
// enforced at the type level.
if (pos.isEmpty()) {
return;
}
evt.setCanceled(ItemJewelerHammer.shouldFailToBreak(evt.getEntity(), evt.getState(), pos.get()));
});
evBus.addListener((LootTableLoadEvent evt) -> HexLootHandler.lootLoad(
evt.getName(),
builder -> evt.getTable().addPool(builder.build())));
evBus.addListener((LootTableLoadEvent evt) -> HexLootHandler.lootLoad(
evt.getName(),
builder -> evt.getTable().addPool(builder.build())));
// === Events implemented in other ways on Fabric
// === Events implemented in other ways on Fabric
// On Fabric this should be auto-synced
evBus.addListener((PlayerEvent.StartTracking evt) -> {
Entity target = evt.getTarget();
if (evt.getTarget() instanceof ServerPlayer serverPlayer &&
target instanceof Mob mob && IXplatAbstractions.INSTANCE.isBrainswept(mob)) {
ForgePacketHandler.getNetwork()
.send(PacketDistributor.PLAYER.with(() -> serverPlayer), MsgBrainsweepAck.of(mob));
}
});
// On Fabric this should be auto-synced
evBus.addListener((PlayerEvent.StartTracking evt) -> {
Entity target = evt.getTarget();
if (evt.getTarget() instanceof ServerPlayer serverPlayer &&
target instanceof Mob mob && IXplatAbstractions.INSTANCE.isBrainswept(mob)) {
ForgePacketHandler.getNetwork()
.send(PacketDistributor.PLAYER.with(() -> serverPlayer), MsgBrainsweepAck.of(mob));
}
});
// Implemented with a mixin on Farbc
evBus.addListener((BlockEvent.BlockToolModificationEvent evt) -> {
if (!evt.isSimulated() && evt.getToolAction() == ToolActions.AXE_STRIP) {
BlockState bs = evt.getState();
var output = HexStrippables.STRIPPABLES.get(bs.getBlock());
if (output != null) {
evt.setFinalState(output.withPropertiesOf(bs));
}
}
});
// Implemented with a mixin on Farbc
evBus.addListener((BlockEvent.BlockToolModificationEvent evt) -> {
if (!evt.isSimulated() && evt.getToolAction() == ToolActions.AXE_STRIP) {
BlockState bs = evt.getState();
var output = HexStrippables.STRIPPABLES.get(bs.getBlock());
if (output != null) {
evt.setFinalState(output.withPropertiesOf(bs));
}
}
});
// Caps are cardinal components on farbc
modBus.addListener(ForgeCapabilityHandler::registerCaps);
evBus.addGenericListener(ItemStack.class, ForgeCapabilityHandler::attachItemCaps);
evBus.addGenericListener(BlockEntity.class, ForgeCapabilityHandler::attachBlockEntityCaps);
evBus.addGenericListener(Entity.class, ForgeCapabilityHandler::attachEntityCaps);
// Caps are cardinal components on farbc
modBus.addListener(ForgeCapabilityHandler::registerCaps);
evBus.addGenericListener(ItemStack.class, ForgeCapabilityHandler::attachItemCaps);
evBus.addGenericListener(BlockEntity.class, ForgeCapabilityHandler::attachBlockEntityCaps);
evBus.addGenericListener(Entity.class, ForgeCapabilityHandler::attachEntityCaps);
modBus.register(HexForgeDataGenerators.class);
modBus.register(ForgeCapabilityHandler.class);
evBus.register(CapSyncers.class);
modBus.register(HexForgeDataGenerators.class);
modBus.register(ForgeCapabilityHandler.class);
evBus.register(CapSyncers.class);
if (ModList.get().isLoaded(HexInterop.Forge.CURIOS_API_ID)) {
modBus.addListener(CuriosApiInterop::onInterModEnqueue);
modBus.addListener(CuriosApiInterop::onClientSetup);
DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> modBus.addListener(CuriosRenderers::onLayerRegister));
}
}
if (ModList.get().isLoaded(HexInterop.Forge.CURIOS_API_ID)) {
modBus.addListener(CuriosApiInterop::onInterModEnqueue);
modBus.addListener(CuriosApiInterop::onClientSetup);
DistExecutor.unsafeRunWhenOn(Dist.CLIENT,
() -> () -> modBus.addListener(CuriosRenderers::onLayerRegister));
}
}
// aaaauughhg
private static IEventBus getModEventBus() {
return KotlinModLoadingContext.Companion.get().getKEventBus();
}
// aaaauughhg
private static IEventBus getModEventBus() {
return KotlinModLoadingContext.Companion.get().getKEventBus();
}
}

View file

@ -353,25 +353,22 @@ public class ForgeXplatImpl implements IXplatAbstractions {
return ForgeUnsealedIngredient.of(stack);
}
private static CreativeModeTab TAB = null;
private static Supplier<CreativeModeTab> TAB = Suppliers.memoize(() ->
new CreativeModeTab(HexAPI.MOD_ID) {
@Override
public ItemStack makeIcon() {
return HexItems.tabIcon();
}
@Override
public void fillItemList(NonNullList<ItemStack> p_40778_) {
super.fillItemList(p_40778_);
}
});
@Override
public CreativeModeTab getTab() {
if (TAB == null) {
TAB = new CreativeModeTab(HexAPI.MOD_ID) {
@Override
public ItemStack makeIcon() {
return HexItems.tabIcon();
}
@Override
public void fillItemList(NonNullList<ItemStack> p_40778_) {
super.fillItemList(p_40778_);
}
};
}
return TAB;
return TAB.get();
}
@Override

View file

@ -10,7 +10,7 @@ jetbrainsAnnotationsVersion=23.0.0
minecraftVersion=1.19.2
kotlinVersion=1.7.20
modVersion=0.10.3
modVersion=0.11.0
paucalVersion=0.5.0
patchouliVersion=77