diff --git a/.kubejs/event_groups/ClientEvents.json b/.kubejs/event_groups/ClientEvents.json deleted file mode 100644 index 94a1011a3..000000000 --- a/.kubejs/event_groups/ClientEvents.json +++ /dev/null @@ -1,53 +0,0 @@ -[ - { - "event": "highPriorityAssets", - "scripts": "client", - "type": "dev.latvian.mods.kubejs.client.GenerateClientAssetsEventJS" - }, - { - "event": "init", - "scripts": "client", - "type": "dev.latvian.mods.kubejs.client.ClientEventJS" - }, - { - "event": "loggedIn", - "scripts": "client", - "type": "dev.latvian.mods.kubejs.client.ClientEventJS" - }, - { - "event": "loggedOut", - "scripts": "client", - "type": "dev.latvian.mods.kubejs.client.ClientEventJS" - }, - { - "event": "tick", - "scripts": "client", - "type": "dev.latvian.mods.kubejs.client.ClientEventJS" - }, - { - "event": "painterUpdated", - "scripts": "client", - "type": "dev.latvian.mods.kubejs.client.ClientEventJS" - }, - { - "event": "leftDebugInfo", - "scripts": "client", - "type": "dev.latvian.mods.kubejs.client.DebugInfoEventJS" - }, - { - "event": "rightDebugInfo", - "scripts": "client", - "type": "dev.latvian.mods.kubejs.client.DebugInfoEventJS" - }, - { - "event": "paintScreen", - "scripts": "client", - "type": "dev.latvian.mods.kubejs.client.painter.screen.PaintScreenEventJS" - }, - { - "event": "atlasSpriteRegistry", - "scripts": "client", - "type": "dev.latvian.mods.kubejs.registry.RegistryEventJS", - "extra": "kubejs:requires_id" - } -] \ No newline at end of file diff --git a/.kubejs/event_groups/StartupEvents.json b/.kubejs/event_groups/StartupEvents.json deleted file mode 100644 index 1734201e2..000000000 --- a/.kubejs/event_groups/StartupEvents.json +++ /dev/null @@ -1,23 +0,0 @@ -[ - { - "event": "init", - "scripts": "startup", - "type": "dev.latvian.mods.kubejs.event.StartupEventJS" - }, - { - "event": "postInit", - "scripts": "startup", - "type": "dev.latvian.mods.kubejs.event.StartupEventJS" - }, - { - "event": "registry", - "scripts": "startup", - "type": "dev.latvian.mods.kubejs.registry.RegistryEventJS", - "extra": "kubejs:requires_registry" - }, - { - "event": "recipeSchemaRegistry", - "scripts": "startup", - "type": "dev.latvian.mods.kubejs.recipe.RecipeSchemaRegistryEventJS" - } -] \ No newline at end of file diff --git a/.kubejs/meta.json b/.kubejs/meta.json index 192f840af..32d3bcec3 100644 --- a/.kubejs/meta.json +++ b/.kubejs/meta.json @@ -1,6 +1,6 @@ { - "minecraft": 2004, - "type": "architectury", + "minecraft": 2006, + "type": "neoforge", "version": { "file": "gradle.properties", "pattern": "^mod_version=([\\w.]+)$", diff --git a/gradle.properties b/gradle.properties index f6a90b60c..632f047da 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ mod_author=LatvianModder curseforge_id=238086 modrinth_id=umyGl7zF minecraft_version=1.20.6 -neoforge_version=20.6.81-beta +neoforge_version=20.6.88-beta rhino_version=2006.2.4-build.13 min_rhino_version=2006.2.4-build.13 architectury_version=12.1.2 diff --git a/src/main/java/dev/latvian/mods/kubejs/BuiltinKubeJSPlugin.java b/src/main/java/dev/latvian/mods/kubejs/BuiltinKubeJSPlugin.java index e3e285fa7..9c0e940aa 100644 --- a/src/main/java/dev/latvian/mods/kubejs/BuiltinKubeJSPlugin.java +++ b/src/main/java/dev/latvian/mods/kubejs/BuiltinKubeJSPlugin.java @@ -80,6 +80,8 @@ import dev.latvian.mods.kubejs.misc.SoundEventBuilder; import dev.latvian.mods.kubejs.misc.VillagerProfessionBuilder; import dev.latvian.mods.kubejs.misc.VillagerTypeBuilder; +import dev.latvian.mods.kubejs.neoforge.KubeJSEntryPoint; +import dev.latvian.mods.kubejs.neoforge.NativeEventWrapper; import dev.latvian.mods.kubejs.player.PlayerStatsJS; import dev.latvian.mods.kubejs.recipe.InputReplacement; import dev.latvian.mods.kubejs.recipe.OutputReplacement; @@ -104,7 +106,6 @@ import dev.latvian.mods.kubejs.recipe.schema.minecraft.StonecuttingRecipeSchema; import dev.latvian.mods.kubejs.registry.RegistryInfo; import dev.latvian.mods.kubejs.script.BindingsEvent; -import dev.latvian.mods.kubejs.script.KubeJSContext; import dev.latvian.mods.kubejs.script.PlatformWrapper; import dev.latvian.mods.kubejs.script.ScriptType; import dev.latvian.mods.kubejs.script.WrapperRegistry; @@ -112,6 +113,7 @@ import dev.latvian.mods.kubejs.server.ServerScriptManager; import dev.latvian.mods.kubejs.util.ClassFilter; import dev.latvian.mods.kubejs.util.FluidAmounts; +import dev.latvian.mods.kubejs.util.ID; import dev.latvian.mods.kubejs.util.JsonIO; import dev.latvian.mods.kubejs.util.KubeJSPlugins; import dev.latvian.mods.kubejs.util.ListJS; @@ -122,9 +124,8 @@ import dev.latvian.mods.kubejs.util.RegExpJS; import dev.latvian.mods.kubejs.util.RotationAxis; import dev.latvian.mods.kubejs.util.ScheduledEvents; -import dev.latvian.mods.kubejs.util.StringWithContext; +import dev.latvian.mods.kubejs.util.TimeJS; import dev.latvian.mods.kubejs.util.UtilsJS; -import dev.latvian.mods.kubejs.util.WithContext; import dev.latvian.mods.kubejs.util.registrypredicate.RegistryPredicate; import dev.latvian.mods.unit.Unit; import net.minecraft.commands.arguments.selector.EntitySelector; @@ -168,6 +169,7 @@ import net.minecraft.world.level.storage.loot.providers.number.NumberProvider; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; +import net.neoforged.neoforge.common.NeoForge; import net.neoforged.neoforge.fluids.FluidStack; import org.joml.Matrix3f; import org.joml.Matrix4f; @@ -187,7 +189,7 @@ import java.util.UUID; import java.util.regex.Pattern; -public class BuiltinKubeJSPlugin extends KubeJSPlugin { +public class BuiltinKubeJSPlugin implements KubeJSPlugin { public static final HashMap GLOBAL = new HashMap<>(); @Override @@ -330,6 +332,15 @@ public void registerClasses(ScriptType type, ClassFilter filter) { filter.deny("org.spongepowered.asm"); // Sponge ASM filter.deny("org.openjdk.nashorn"); // Nashorn filter.deny("jdk.nashorn"); // Nashorn + filter.deny("org.lwjgl.system"); // LWJGL + + filter.allow("net.neoforged"); // Forge + filter.deny("net.neoforged.fml"); + filter.deny("net.neoforged.accesstransformer"); + filter.deny("net.neoforged.coremod"); + + filter.deny("cpw.mods.modlauncher"); // FML + filter.deny("cpw.mods.gross"); // Mods filter.allow("mezz.jei"); // JEI @@ -407,90 +418,93 @@ public void registerBindings(BindingsEvent event) { event.add("SoundType", SoundType.class); event.add("BlockProperties", BlockStateProperties.class); + + if (event.type().isStartup()) { + event.add("NativeEvents", new NativeEventWrapper("NativeEvents", NeoForge.EVENT_BUS)); + KubeJSEntryPoint.eventBus().ifPresent(bus -> event.add("NativeModEvents", new NativeEventWrapper("NativeModEvents", bus))); + } } @Override public void registerTypeWrappers(WrapperRegistry registry) { - registry.register(StringWithContext.class, (cx, o, target) -> StringWithContext.of(cx, o)); - registry.register(WithContext.class, WithContext::of); - registry.register(Holder.class, KubeJSTypeWrappers::holder); - registry.register(ResourceKey.class, KubeJSTypeWrappers::resourceKey); + registry.register(Holder.class, KubeJSTypeWrappers::holderOf); + registry.register(ResourceKey.class, KubeJSTypeWrappers::resourceKeyOf); registry.register(RegistryPredicate.class, RegistryPredicate::of); // Java / Minecraft // - registry.registerSimple(String.class, String::valueOf); - registry.registerSimple(CharSequence.class, String::valueOf); - registry.registerSimple(UUID.class, UUIDWrapper::fromString); - registry.registerSimple(Pattern.class, RegExpJS::of); - registry.registerSimple(JsonObject.class, MapJS::json); - registry.registerSimple(JsonArray.class, ListJS::json); - registry.registerSimple(JsonElement.class, JsonIO::of); - registry.registerSimple(JsonPrimitive.class, JsonIO::primitiveOf); - registry.registerSimple(Path.class, UtilsJS::getPath); - registry.registerSimple(File.class, UtilsJS::getFileFromPath); - registry.register(Unit.class, (cx, from, target) -> Painter.INSTANCE.unitOf(cx, from)); - registry.registerSimple(TemporalAmount.class, UtilsJS::getTemporalAmount); - registry.registerSimple(Duration.class, UtilsJS::getDuration); - - registry.register(ResourceLocation.class, (cx, from, target) -> UtilsJS.getMCID(cx, from)); - registry.register(CompoundTag.class, (from, target) -> NBTUtils.isTagCompound(from), (cx, o, target) -> NBTUtils.toTagCompound(cx, o)); - registry.register(CollectionTag.class, (from, target) -> NBTUtils.isTagCollection(from), (cx, o, target) -> NBTUtils.toTagCollection(cx, o)); - registry.register(ListTag.class, (from, target) -> NBTUtils.isTagCollection(from), (cx, o, target) -> NBTUtils.toTagList(cx, o)); - registry.register(Tag.class, (cx, from, target) -> NBTUtils.toTag(cx, from)); - registry.register(DataComponentMap.class, (cx, from, target) -> KubeJSComponents.mapOf(cx, from)); - registry.register(DataComponentPatch.class, (cx, from, target) -> KubeJSComponents.patchOf(cx, from)); - - registry.registerSimple(BlockPos.class, UtilsJS::blockPosOf); - registry.registerSimple(Vec3.class, UtilsJS::vec3Of); - - registry.register(Item.class, (cx, from, target) -> ItemStackJS.getRawItem(cx, from)); - registry.register(ItemLike.class, (cx, from, target) -> ItemStackJS.getRawItem(cx, from)); + registry.register(String.class, String::valueOf); + registry.register(CharSequence.class, String::valueOf); + registry.register(UUID.class, UUIDWrapper::fromString); + registry.register(Pattern.class, RegExpJS::of); + registry.register(JsonObject.class, MapJS::json); + registry.register(JsonArray.class, ListJS::json); + registry.register(JsonElement.class, JsonIO::of); + registry.register(JsonPrimitive.class, JsonIO::primitiveOf); + registry.register(Path.class, KubeJSTypeWrappers::pathOf); + registry.register(File.class, KubeJSTypeWrappers::fileOf); + registry.register(Unit.class, Painter.INSTANCE::unitOf); + registry.register(TemporalAmount.class, TimeJS::temporalAmountOf); + registry.register(Duration.class, TimeJS::durationOf); + + registry.register(ResourceLocation.class, ID::mc); + registry.register(CompoundTag.class, (from, target) -> NBTUtils.isTagCompound(from), NBTUtils::toTagCompound); + registry.register(CollectionTag.class, (from, target) -> NBTUtils.isTagCollection(from), NBTUtils::toTagCollection); + registry.register(ListTag.class, (from, target) -> NBTUtils.isTagCollection(from), NBTUtils::toTagList); + registry.register(Tag.class, NBTUtils::toTag); + registry.register(DataComponentMap.class, KubeJSComponents::mapOf); + registry.register(DataComponentPatch.class, KubeJSComponents::patchOf); + + registry.register(BlockPos.class, KubeJSTypeWrappers::blockPosOf); + registry.register(Vec3.class, KubeJSTypeWrappers::vec3Of); + + registry.register(Item.class, ItemStackJS::getRawItem); + registry.register(ItemLike.class, ItemStackJS::getRawItem); registry.registerEnumFromStringCodec(MobCategory.class, MobCategory.CODEC); - registry.registerSimple(AABB.class, AABBWrapper::wrap); - registry.register(IntProvider.class, (cx, o, target) -> UtilsJS.intProviderOf(cx, o)); - registry.registerSimple(NumberProvider.class, UtilsJS::numberProviderOf); + registry.register(AABB.class, AABBWrapper::wrap); + registry.register(IntProvider.class, KubeJSTypeWrappers::intProviderOf); + registry.register(NumberProvider.class, KubeJSTypeWrappers::numberProviderOf); registry.registerEnumFromStringCodec(LootContext.EntityTarget.class, LootContext.EntityTarget.CODEC); registry.registerEnumFromStringCodec(CopyNameFunction.NameSource.class, CopyNameFunction.NameSource.CODEC); - registry.registerSimple(Enchantment.Cost.class, EnchantmentBuilder::costOf); + registry.register(Enchantment.Cost.class, EnchantmentBuilder::costOf); registry.registerEnumFromStringCodec(ArmorItem.Type.class, ArmorItem.Type.CODEC); // KubeJS // - registry.registerSimple(Map.class, MapJS::of); - registry.registerSimple(List.class, ListJS::of); - registry.registerSimple(Iterable.class, ListJS::of); - registry.registerSimple(Collection.class, ListJS::of); - registry.registerSimple(Set.class, ListJS::ofSet); - registry.registerSimple(ItemStack.class, ItemStackJS::of); - registry.registerSimple(Ingredient.class, IngredientJS::of); - registry.registerSimple(InputReplacement.class, InputReplacement::of); - registry.registerSimple(OutputReplacement.class, OutputReplacement::of); - registry.registerSimple(InputItem.class, InputItem::of); - registry.registerSimple(OutputItem.class, OutputItem::of); - registry.registerSimple(BlockStatePredicate.class, BlockStatePredicate::of); - registry.register(RuleTest.class, (cx, from, target) -> BlockStatePredicate.ruleTestOf(cx, from)); - registry.registerSimple(FluidStack.class, FluidWrapper::wrap); - registry.registerSimple(dev.architectury.fluid.FluidStack.class, FluidWrapper::wrapArch); - registry.register(RecipeFilter.class, (cx, from, target) -> RecipeFilter.of(cx, from)); - registry.registerSimple(IngredientActionFilter.class, IngredientActionFilter::filterOf); - registry.registerSimple(Tier.class, ItemBuilder::toToolTier); - registry.registerSimple(PlayerSelector.class, PlayerSelector::of); - registry.register(DamageSource.class, (cx, from, target) -> DamageSourceWrapper.of(cx, from)); - registry.registerSimple(EntitySelector.class, UtilsJS::entitySelector); - registry.registerSimple(ReplacementMatch.class, ReplacementMatch::of); - registry.registerSimple(Stat.class, PlayerStatsJS::statOf); - registry.registerSimple(MapColor.class, MapColorHelper::of); + registry.register(Map.class, MapJS::of); + registry.register(List.class, ListJS::of); + registry.register(Iterable.class, ListJS::of); + registry.register(Collection.class, ListJS::of); + registry.register(Set.class, ListJS::ofSet); + registry.register(ItemStack.class, ItemStackJS::of); + registry.register(Ingredient.class, IngredientJS::of); + registry.register(InputReplacement.class, InputReplacement::of); + registry.register(OutputReplacement.class, OutputReplacement::of); + registry.register(InputItem.class, InputItem::of); + registry.register(OutputItem.class, OutputItem::of); + registry.register(BlockStatePredicate.class, BlockStatePredicate::of); + registry.register(RuleTest.class, BlockStatePredicate::ruleTestOf); + registry.register(FluidStack.class, FluidWrapper::wrap); + registry.register(dev.architectury.fluid.FluidStack.class, FluidWrapper::wrapArch); + registry.register(RecipeFilter.class, RecipeFilter::of); + registry.register(IngredientActionFilter.class, IngredientActionFilter::filterOf); + registry.register(Tier.class, ItemBuilder::toolTierOf); + registry.register(PlayerSelector.class, PlayerSelector::of); + registry.register(DamageSource.class, DamageSourceWrapper::of); + registry.register(EntitySelector.class, UtilsJS::entitySelector); + registry.register(ReplacementMatch.class, ReplacementMatch::of); + registry.register(Stat.class, PlayerStatsJS::statOf); + registry.register(MapColor.class, MapColorHelper::of); registry.register(SoundType.class, SoundTypeWrapper.INSTANCE); - registry.register(ParticleOptions.class, (cx, from, target) -> UtilsWrapper.particleOptions(new WithContext<>((KubeJSContext) cx, from))); - registry.register(ItemTintFunction.class, (cx, from, target) -> ItemTintFunction.of(cx, from)); - registry.register(BlockTintFunction.class, (cx, from, target) -> BlockTintFunction.of(cx, from)); + registry.register(ParticleOptions.class, UtilsWrapper::particleOptions); + registry.register(ItemTintFunction.class, ItemTintFunction::of); + registry.register(BlockTintFunction.class, BlockTintFunction::of); // components // - registry.registerSimple(Component.class, TextWrapper::of); - registry.registerSimple(MutableComponent.class, TextWrapper::of); - registry.registerSimple(Color.class, ColorWrapper::of); - registry.registerSimple(TextColor.class, from -> ColorWrapper.of(from).createTextColorJS()); - registry.registerSimple(ClickEvent.class, TextWrapper::clickEventOf); + registry.register(Component.class, TextWrapper::of); + registry.register(MutableComponent.class, TextWrapper::of); + registry.register(Color.class, ColorWrapper::of); + registry.register(TextColor.class, ColorWrapper::textColorOf); + registry.register(ClickEvent.class, TextWrapper::clickEventOf); // codecs registry.registerCodec(Fireworks.class, Fireworks.CODEC); diff --git a/src/main/java/dev/latvian/mods/kubejs/KubeJS.java b/src/main/java/dev/latvian/mods/kubejs/KubeJS.java index 929304f04..0f62027be 100644 --- a/src/main/java/dev/latvian/mods/kubejs/KubeJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/KubeJS.java @@ -6,16 +6,8 @@ import dev.architectury.utils.Env; import dev.architectury.utils.EnvExecutor; import dev.latvian.mods.kubejs.bindings.event.StartupEvents; -import dev.latvian.mods.kubejs.block.KubeJSBlockEventHandler; import dev.latvian.mods.kubejs.client.KubeJSClient; -import dev.latvian.mods.kubejs.entity.KubeJSEntityEventHandler; import dev.latvian.mods.kubejs.event.KubeStartupEvent; -import dev.latvian.mods.kubejs.gui.KubeJSMenu; -import dev.latvian.mods.kubejs.helpers.MiscHelper; -import dev.latvian.mods.kubejs.item.KubeJSItemEventHandler; -import dev.latvian.mods.kubejs.level.KubeJSWorldEventHandler; -import dev.latvian.mods.kubejs.player.KubeJSPlayerEventHandler; -import dev.latvian.mods.kubejs.recipe.KubeJSRecipeEventHandler; import dev.latvian.mods.kubejs.recipe.schema.RecipeNamespace; import dev.latvian.mods.kubejs.registry.RegistryInfo; import dev.latvian.mods.kubejs.script.ConsoleLine; @@ -26,7 +18,6 @@ import dev.latvian.mods.kubejs.script.ScriptType; import dev.latvian.mods.kubejs.script.ScriptsLoadedEvent; import dev.latvian.mods.kubejs.script.data.GeneratedResourcePack; -import dev.latvian.mods.kubejs.server.KubeJSServerEventHandler; import dev.latvian.mods.kubejs.util.ConsoleJS; import dev.latvian.mods.kubejs.util.KubeJSBackgroundThread; import dev.latvian.mods.kubejs.util.KubeJSPlugins; @@ -34,6 +25,7 @@ import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; +import net.neoforged.bus.api.IEventBus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -55,8 +47,8 @@ public class KubeJS { public static final String MOD_ID = "kubejs"; public static final String MOD_NAME = "KubeJS"; public static final Logger LOGGER = LoggerFactory.getLogger(MOD_NAME); - public static final int MC_VERSION_NUMBER = 2004; - public static final String MC_VERSION_STRING = "1.20.4"; + public static final int MC_VERSION_NUMBER = 2006; + public static final String MC_VERSION_STRING = "1.20.6"; public static String QUERY; public static final Component NAME_COMPONENT = Component.literal(MOD_NAME); @@ -81,7 +73,7 @@ public static ScriptManager getClientScriptManager() { public static Mod thisMod; - public KubeJS() throws Throwable { + public KubeJS(IEventBus bus) throws Throwable { instance = this; gameDirectory = Platform.getGameFolder().normalize().toAbsolutePath(); @@ -112,7 +104,7 @@ public KubeJS() throws Throwable { PROXY = EnvExecutor.getEnvSpecific(() -> KubeJSClient::new, () -> KubeJSCommon::new); - if (!MiscHelper.get().isDataGen()) { + if (!PlatformWrapper.isGeneratingData()) { new KubeJSBackgroundThread().start(); // Required to be called this way because ConsoleJS class hasn't been initialized yet ScriptType.STARTUP.console.setCapturingErrors(true); @@ -136,16 +128,7 @@ public KubeJS() throws Throwable { KubeJSPlugins.forEachPlugin(KubeJSPlugin::initStartup); - KubeJSWorldEventHandler.init(); - KubeJSPlayerEventHandler.init(); - KubeJSEntityEventHandler.init(); - KubeJSBlockEventHandler.init(); - KubeJSItemEventHandler.init(); - KubeJSServerEventHandler.init(); - KubeJSRecipeEventHandler.init(); - KubeJSMenu.init(); - - PROXY.init(); + PROXY.init(bus); for (var extraId : StartupEvents.REGISTRY.findUniqueExtraIds(ScriptType.STARTUP)) { if (extraId instanceof ResourceKey key) { @@ -177,10 +160,6 @@ public static void loadScripts(ScriptPack pack, Path dir, String path) { } } - public static String appendModId(String id) { - return id.indexOf(':') == -1 ? (MOD_ID + ":" + id) : id; - } - public static Path getGameDirectory() { return gameDirectory; } diff --git a/src/main/java/dev/latvian/mods/kubejs/KubeJSCodecs.java b/src/main/java/dev/latvian/mods/kubejs/KubeJSCodecs.java index bce40b64b..e4a0abc01 100644 --- a/src/main/java/dev/latvian/mods/kubejs/KubeJSCodecs.java +++ b/src/main/java/dev/latvian/mods/kubejs/KubeJSCodecs.java @@ -7,7 +7,6 @@ import com.mojang.serialization.DataResult; import com.mojang.serialization.JsonOps; import dev.latvian.mods.kubejs.util.UtilsJS; -import io.netty.buffer.ByteBuf; import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.codec.ByteBufCodecs; import net.minecraft.network.codec.StreamCodec; @@ -16,14 +15,10 @@ import net.minecraft.world.level.storage.loot.providers.number.NumberProvider; import net.minecraft.world.level.storage.loot.providers.number.NumberProviders; -import java.time.Duration; import java.util.Optional; import java.util.function.Function; public interface KubeJSCodecs { - Codec DURATION = stringResolverCodec(Duration::toString, UtilsJS::getDuration); - StreamCodec DURATION_STREAM = ByteBufCodecs.STRING_UTF8.map(UtilsJS::getDuration, Duration::toString); - StreamCodec INT_PROVIDER_STREAM_CODEC = ByteBufCodecs.fromCodecWithRegistries(IntProvider.CODEC); static Codec stringResolverCodec(Function toStringFunction, Function fromStringFunction) { diff --git a/src/main/java/dev/latvian/mods/kubejs/KubeJSCommon.java b/src/main/java/dev/latvian/mods/kubejs/KubeJSCommon.java index 288721c9d..fbcb71d3b 100644 --- a/src/main/java/dev/latvian/mods/kubejs/KubeJSCommon.java +++ b/src/main/java/dev/latvian/mods/kubejs/KubeJSCommon.java @@ -6,12 +6,13 @@ import net.minecraft.commands.CommandSourceStack; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.entity.player.Player; +import net.neoforged.bus.api.IEventBus; import org.jetbrains.annotations.Nullable; import java.util.List; public class KubeJSCommon { - public void init() { + public void init(IEventBus bus) { } public void clientSetup() { diff --git a/src/main/java/dev/latvian/mods/kubejs/KubeJSComponents.java b/src/main/java/dev/latvian/mods/kubejs/KubeJSComponents.java index e0c08c3f0..b78f6dfcd 100644 --- a/src/main/java/dev/latvian/mods/kubejs/KubeJSComponents.java +++ b/src/main/java/dev/latvian/mods/kubejs/KubeJSComponents.java @@ -7,32 +7,26 @@ import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import dev.latvian.mods.kubejs.script.KubeJSContext; import dev.latvian.mods.kubejs.util.Cast; -import dev.latvian.mods.kubejs.util.UtilsJS; import dev.latvian.mods.rhino.Context; import net.minecraft.core.HolderLookup; import net.minecraft.core.component.DataComponentMap; import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.component.DataComponentType; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.core.registries.Registries; import net.minecraft.nbt.NbtOps; import net.minecraft.nbt.Tag; import net.minecraft.nbt.TagParser; import net.minecraft.network.chat.Component; import net.minecraft.resources.RegistryOps; import net.minecraft.resources.ResourceLocation; -import net.neoforged.neoforge.registries.DeferredRegister; public interface KubeJSComponents { - DeferredRegister> DATA_COMPONENTS = DeferredRegister.create(Registries.DATA_COMPONENT_TYPE, KubeJS.MOD_ID); + // DeferredRegister> REGISTRY = DeferredRegister.create(Registries.DATA_COMPONENT_TYPE, KubeJS.MOD_ID); DynamicCommandExceptionType ERROR_UNKNOWN_COMPONENT = new DynamicCommandExceptionType((object) -> Component.translatableEscape("arguments.item.component.unknown", object)); Dynamic2CommandExceptionType ERROR_MALFORMED_COMPONENT = new Dynamic2CommandExceptionType((object, object2) -> Component.translatableEscape("arguments.item.component.malformed", object, object2)); SimpleCommandExceptionType ERROR_EXPECTED_COMPONENT = new SimpleCommandExceptionType(Component.translatable("arguments.item.component.expected")); - static void init() { - } - static DataComponentMap readMap(RegistryOps registryOps, StringReader reader) throws CommandSyntaxException { var builder = DataComponentMap.builder(); @@ -149,7 +143,7 @@ static StringBuilder patchToString(StringBuilder builder, HolderLookup.Provider if (id != null) { if (comp.getValue().isPresent()) { - var value = comp.getKey().codecOrThrow().encodeStart(dynamicOps, UtilsJS.cast(comp.getValue().get())).result().get(); + var value = comp.getKey().codecOrThrow().encodeStart(dynamicOps, Cast.to(comp.getValue().get())).result().get(); builder.append(id).append('=').append(value); } else { builder.append('!').append(id).append("={}"); diff --git a/src/main/java/dev/latvian/mods/kubejs/KubeJSPlugin.java b/src/main/java/dev/latvian/mods/kubejs/KubeJSPlugin.java index d3aa2690f..0199b124c 100644 --- a/src/main/java/dev/latvian/mods/kubejs/KubeJSPlugin.java +++ b/src/main/java/dev/latvian/mods/kubejs/KubeJSPlugin.java @@ -26,87 +26,82 @@ import java.util.List; import java.util.Map; -public class KubeJSPlugin { - public void init() { +public interface KubeJSPlugin { + default void init() { } - public void initStartup() { + default void initStartup() { } - public void clientInit() { + default void clientInit() { } - public void afterInit() { + default void afterInit() { } - public void onServerReload() { + default void onServerReload() { } /** * Call {@link EventGroupRegistry#register(EventGroup)} for event groups your mod adds */ - public void registerEvents(EventGroupRegistry registry) { + default void registerEvents(EventGroupRegistry registry) { } - public void registerClasses(ScriptType type, ClassFilter filter) { + default void registerClasses(ScriptType type, ClassFilter filter) { } - public void registerBindings(BindingsEvent event) { + default void registerBindings(BindingsEvent event) { } - public void registerTypeWrappers(WrapperRegistry registry) { + default void registerTypeWrappers(WrapperRegistry registry) { } - public void registerRecipeSchemas(RegisterRecipeSchemasEvent event) { + default void registerRecipeSchemas(RegisterRecipeSchemasEvent event) { } - public void registerRecipeComponents(RecipeComponentFactoryRegistryEvent event) { + default void registerRecipeComponents(RecipeComponentFactoryRegistryEvent event) { } - public void registerBlockEntityAttachments(List types) { + default void registerBlockEntityAttachments(List types) { } - public void attachServerData(AttachedData event) { + default void attachServerData(AttachedData event) { } - public void attachLevelData(AttachedData event) { + default void attachLevelData(AttachedData event) { } - public void attachPlayerData(AttachedData event) { + default void attachPlayerData(AttachedData event) { } - public void generateDataJsons(DataJsonGenerator generator) { + default void generateDataJsons(DataJsonGenerator generator) { } - public void generateAssetJsons(AssetJsonGenerator generator) { + default void generateAssetJsons(AssetJsonGenerator generator) { } - public void generateLang(LangKubeEvent event) { + default void generateLang(LangKubeEvent event) { } - public void loadCommonProperties(CommonProperties properties) { + default void loadCommonProperties(CommonProperties properties) { } - public void loadClientProperties(ClientProperties properties) { + default void loadClientProperties(ClientProperties properties) { } - public void loadDevProperties(DevProperties properties) { + default void loadDevProperties(DevProperties properties) { } - public void clearCaches() { + default void clearCaches() { } - public void exportServerData(DataExport export) { - } - - @Override - public String toString() { - return getClass().getName(); + default void exportServerData(DataExport export) { } /** * Only use this method if your mod adds runtime recipes and is conflicting with KubeJS recipe manager. Disable your other hook if "kubejs" mod is loaded! */ - public void injectRuntimeRecipes(RecipesKubeEvent event, RecipeManager manager, Map> recipesByName) { + default void injectRuntimeRecipes(RecipesKubeEvent event, RecipeManager manager, Map> recipesByName) { } } diff --git a/src/main/java/dev/latvian/mods/kubejs/KubeJSTypeWrappers.java b/src/main/java/dev/latvian/mods/kubejs/KubeJSTypeWrappers.java index 95896ce68..7b3315221 100644 --- a/src/main/java/dev/latvian/mods/kubejs/KubeJSTypeWrappers.java +++ b/src/main/java/dev/latvian/mods/kubejs/KubeJSTypeWrappers.java @@ -1,14 +1,36 @@ package dev.latvian.mods.kubejs; +import dev.latvian.mods.kubejs.level.BlockContainerJS; import dev.latvian.mods.kubejs.registry.RegistryInfo; +import dev.latvian.mods.kubejs.util.ID; +import dev.latvian.mods.kubejs.util.NBTUtils; import dev.latvian.mods.kubejs.util.UtilsJS; import dev.latvian.mods.rhino.Context; import dev.latvian.mods.rhino.type.TypeInfo; +import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; +import net.minecraft.nbt.NbtOps; import net.minecraft.resources.ResourceKey; +import net.minecraft.util.valueproviders.ClampedInt; +import net.minecraft.util.valueproviders.ClampedNormalInt; +import net.minecraft.util.valueproviders.ConstantInt; +import net.minecraft.util.valueproviders.IntProvider; +import net.minecraft.util.valueproviders.UniformInt; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.storage.loot.providers.number.BinomialDistributionGenerator; +import net.minecraft.world.level.storage.loot.providers.number.ConstantValue; +import net.minecraft.world.level.storage.loot.providers.number.NumberProvider; +import net.minecraft.world.level.storage.loot.providers.number.UniformGenerator; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +import java.io.File; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; public interface KubeJSTypeWrappers { - static Holder holder(Context cx, Object from, TypeInfo target) { + static Holder holderOf(Context cx, Object from, TypeInfo target) { if (from == null) { return null; } else if (from instanceof Holder h) { @@ -18,13 +40,13 @@ static Holder holder(Context cx, Object from, TypeInfo target) { var reg = RegistryInfo.ofClass(target.param(0).asClass()); if (reg != null) { - return reg.getHolder(UtilsJS.getMCID(cx, from)); + return reg.getHolder(ID.mc(from)); } return new Holder.Direct<>(from); } - static ResourceKey resourceKey(Context cx, Object from, TypeInfo target) { + static ResourceKey resourceKeyOf(Context cx, Object from, TypeInfo target) { if (from == null) { return null; } else if (from instanceof ResourceKey k) { @@ -34,15 +56,151 @@ static ResourceKey resourceKey(Context cx, Object from, TypeInfo target) { var cl = target.param(0).asClass(); if (cl == ResourceKey.class) { - return ResourceKey.createRegistryKey(UtilsJS.getMCID(cx, from)); + return ResourceKey.createRegistryKey(ID.mc(from)); } var reg = RegistryInfo.ofClass(cl); if (reg != null) { - return ResourceKey.create(reg.key, UtilsJS.getMCID(cx, from)); + return ResourceKey.create(reg.key, ID.mc(from)); } throw new IllegalArgumentException("Can't parse " + from + " as ResourceKey!"); } + + @SuppressWarnings("unchecked") + static IntProvider intProviderOf(Context cx, Object o) { + if (o instanceof Number n) { + return ConstantInt.of(n.intValue()); + } else if (o instanceof List l && !l.isEmpty()) { + var min = (Number) l.get(0); + var max = l.size() >= 2 ? (Number) l.get(1) : min; + return UniformInt.of(min.intValue(), max.intValue()); + } else if (o instanceof Map) { + var m = (Map) o; + + var intBounds = parseIntBounds(m); + if (intBounds != null) { + return intBounds; + } else if (m.containsKey("clamped")) { + var source = intProviderOf(cx, m.get("clamped")); + var clampTo = parseIntBounds(m); + if (clampTo != null) { + return ClampedInt.of(source, clampTo.getMinValue(), clampTo.getMaxValue()); + } + } else if (m.containsKey("clamped_normal")) { + var clampTo = parseIntBounds(m); + var mean = ((Number) m.get("mean")).intValue(); + var deviation = ((Number) m.get("deviation")).intValue(); + if (clampTo != null) { + return ClampedNormalInt.of(mean, deviation, clampTo.getMinValue(), clampTo.getMaxValue()); + } + } + + var decoded = IntProvider.CODEC.parse(NbtOps.INSTANCE, NBTUtils.toTagCompound(cx, m)).result(); + if (decoded.isPresent()) { + return decoded.get(); + } + } + + return ConstantInt.of(0); + } + + @SuppressWarnings("unchecked") + static NumberProvider numberProviderOf(Object o) { + if (o instanceof Number n) { + var f = n.floatValue(); + return UniformGenerator.between(f, f); + } else if (o instanceof List l && !l.isEmpty()) { + var min = (Number) l.get(0); + var max = l.size() >= 2 ? (Number) l.get(1) : min; + return UniformGenerator.between(min.floatValue(), max.floatValue()); + } else if (o instanceof Map) { + var m = (Map) o; + if (m.containsKey("min") && m.containsKey("max")) { + return UniformGenerator.between(((Number) m.get("min")).intValue(), ((Number) m.get("max")).floatValue()); + } else if (m.containsKey("n") && m.containsKey("p")) { + return BinomialDistributionGenerator.binomial(((Number) m.get("n")).intValue(), ((Number) m.get("p")).floatValue()); + } else if (m.containsKey("value")) { + var f = ((Number) m.get("value")).floatValue(); + return UniformGenerator.between(f, f); + } + } + + return ConstantValue.exactly(0); + } + + static Vec3 vec3Of(@Nullable Object o) { + if (o instanceof Vec3 vec) { + return vec; + } else if (o instanceof Entity entity) { + return entity.position(); + } else if (o instanceof List list && list.size() >= 3) { + return new Vec3(UtilsJS.parseDouble(list.get(0), 0), UtilsJS.parseDouble(list.get(1), 0), UtilsJS.parseDouble(list.get(2), 0)); + } else if (o instanceof BlockPos pos) { + return new Vec3(pos.getX() + 0.5D, pos.getY() + 0.5D, pos.getZ() + 0.5D); + } else if (o instanceof BlockContainerJS block) { + return new Vec3(block.getPos().getX() + 0.5D, block.getPos().getY() + 0.5D, block.getPos().getZ() + 0.5D); + } + + return Vec3.ZERO; + } + + static BlockPos blockPosOf(@Nullable Object o) { + if (o instanceof BlockPos pos) { + return pos; + } else if (o instanceof List list && list.size() >= 3) { + return new BlockPos(UtilsJS.parseInt(list.get(0), 0), UtilsJS.parseInt(list.get(1), 0), UtilsJS.parseInt(list.get(2), 0)); + } else if (o instanceof BlockContainerJS block) { + return block.getPos(); + } else if (o instanceof Vec3 vec) { + return BlockPos.containing(vec.x, vec.y, vec.z); + } + + return BlockPos.ZERO; + } + + private static UniformInt parseIntBounds(Map m) { + if (m.get("bounds") instanceof List bounds) { + return UniformInt.of(UtilsJS.parseInt(bounds.get(0), 0), UtilsJS.parseInt(bounds.get(1), 0)); + } else if (m.containsKey("min") && m.containsKey("max")) { + return UniformInt.of(((Number) m.get("min")).intValue(), ((Number) m.get("max")).intValue()); + } else if (m.containsKey("min_inclusive") && m.containsKey("max_inclusive")) { + return UniformInt.of(((Number) m.get("min_inclusive")).intValue(), ((Number) m.get("max_inclusive")).intValue()); + } else if (m.containsKey("value")) { + var f = ((Number) m.get("value")).intValue(); + return UniformInt.of(f, f); + } + return null; + } + + @Nullable + static Path pathOf(Object o) { + try { + if (o instanceof Path) { + return KubeJS.verifyFilePath((Path) o); + } else if (o == null || o.toString().isEmpty()) { + return null; + } + + return KubeJS.verifyFilePath(KubeJS.getGameDirectory().resolve(o.toString())); + } catch (Exception ex) { + return null; + } + } + + @Nullable + static File fileOf(Object o) { + try { + if (o instanceof File) { + return KubeJS.verifyFilePath(((File) o).toPath()).toFile(); + } else if (o == null || o.toString().isEmpty()) { + return null; + } + + return KubeJS.verifyFilePath(KubeJS.getGameDirectory().resolve(o.toString())).toFile(); + } catch (Exception ex) { + return null; + } + } } diff --git a/src/main/java/dev/latvian/mods/kubejs/bindings/BlockWrapper.java b/src/main/java/dev/latvian/mods/kubejs/bindings/BlockWrapper.java index 344b5729e..679465632 100644 --- a/src/main/java/dev/latvian/mods/kubejs/bindings/BlockWrapper.java +++ b/src/main/java/dev/latvian/mods/kubejs/bindings/BlockWrapper.java @@ -5,6 +5,7 @@ import dev.latvian.mods.kubejs.block.predicate.BlockPredicate; import dev.latvian.mods.kubejs.registry.RegistryInfo; import dev.latvian.mods.kubejs.typings.Info; +import dev.latvian.mods.kubejs.util.Cast; import dev.latvian.mods.kubejs.util.Tags; import net.minecraft.Util; import net.minecraft.core.Direction; @@ -12,16 +13,24 @@ import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.Optional; @Info("Various block related helper functions") public class BlockWrapper { + private static Collection ALL_STATE_CACHE = null; + public static BlockIDPredicate id(ResourceLocation id) { return new BlockIDPredicate(id); } @@ -89,4 +98,48 @@ public static List getTaggedIds(ResourceLocation tag) { } }); } + + public static Collection getAllBlockStates() { + if (ALL_STATE_CACHE != null) { + return ALL_STATE_CACHE; + } + + var states = new HashSet(); + for (var block : RegistryInfo.BLOCK.getArchitecturyRegistrar()) { + states.addAll(block.getStateDefinition().getPossibleStates()); + } + + ALL_STATE_CACHE = Collections.unmodifiableCollection(states); + return ALL_STATE_CACHE; + } + + public static BlockState parseBlockState(String string) { + if (string.isEmpty()) { + return Blocks.AIR.defaultBlockState(); + } + + var i = string.indexOf('['); + var hasProperties = i >= 0 && string.indexOf(']') == string.length() - 1; + var state = RegistryInfo.BLOCK.getValue(new ResourceLocation(hasProperties ? string.substring(0, i) : string)).defaultBlockState(); + + if (hasProperties) { + for (var s : string.substring(i + 1, string.length() - 1).split(",")) { + var s1 = s.split("=", 2); + + if (s1.length == 2 && !s1[0].isEmpty() && !s1[1].isEmpty()) { + var p = state.getBlock().getStateDefinition().getProperty(s1[0]); + + if (p != null) { + Optional o = p.getValue(s1[1]); + + if (o.isPresent()) { + state = state.setValue(p, Cast.to(o.get())); + } + } + } + } + } + + return state; + } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/bindings/ColorWrapper.java b/src/main/java/dev/latvian/mods/kubejs/bindings/ColorWrapper.java index 5a328f236..d3dbc66b3 100644 --- a/src/main/java/dev/latvian/mods/kubejs/bindings/ColorWrapper.java +++ b/src/main/java/dev/latvian/mods/kubejs/bindings/ColorWrapper.java @@ -6,6 +6,7 @@ import dev.latvian.mods.kubejs.color.SimpleColorWithAlpha; import net.minecraft.ChatFormatting; import net.minecraft.Util; +import net.minecraft.network.chat.TextColor; import net.minecraft.world.item.DyeColor; import java.util.HashMap; @@ -54,6 +55,10 @@ static Color of(Object o) { return NONE; } + static TextColor textColorOf(Object o) { + return of(o).createTextColorJS(); + } + static Color createMapped(Object o, String... names) { Color c = of(o); diff --git a/src/main/java/dev/latvian/mods/kubejs/bindings/DamageSourceWrapper.java b/src/main/java/dev/latvian/mods/kubejs/bindings/DamageSourceWrapper.java index fe36bb466..85a5bac8d 100644 --- a/src/main/java/dev/latvian/mods/kubejs/bindings/DamageSourceWrapper.java +++ b/src/main/java/dev/latvian/mods/kubejs/bindings/DamageSourceWrapper.java @@ -1,6 +1,6 @@ package dev.latvian.mods.kubejs.bindings; -import dev.latvian.mods.kubejs.util.UtilsJS; +import dev.latvian.mods.kubejs.util.ID; import dev.latvian.mods.rhino.Context; import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceKey; @@ -15,7 +15,7 @@ public static DamageSource of(Context cx, Object from) { case DamageSource source -> source; case Player player -> ServerLifecycleHooks.getCurrentServer().kjs$getOverworld().damageSources().playerAttack(player); case LivingEntity livingEntity -> ServerLifecycleHooks.getCurrentServer().kjs$getOverworld().damageSources().mobAttack(livingEntity); - case null, default -> ServerLifecycleHooks.getCurrentServer().kjs$getOverworld().damageSources().source(ResourceKey.create(Registries.DAMAGE_TYPE, UtilsJS.getMCID(cx, from))); + case null, default -> ServerLifecycleHooks.getCurrentServer().kjs$getOverworld().damageSources().source(ResourceKey.create(Registries.DAMAGE_TYPE, ID.mc(from))); }; } } diff --git a/src/main/java/dev/latvian/mods/kubejs/bindings/JavaWrapper.java b/src/main/java/dev/latvian/mods/kubejs/bindings/JavaWrapper.java index 2b37d8b63..f7c16a470 100644 --- a/src/main/java/dev/latvian/mods/kubejs/bindings/JavaWrapper.java +++ b/src/main/java/dev/latvian/mods/kubejs/bindings/JavaWrapper.java @@ -1,8 +1,8 @@ package dev.latvian.mods.kubejs.bindings; +import dev.latvian.mods.kubejs.script.KubeJSContext; import dev.latvian.mods.kubejs.typings.Info; import dev.latvian.mods.kubejs.util.ConsoleJS; -import dev.latvian.mods.kubejs.util.StringWithContext; import org.jetbrains.annotations.Nullable; import org.slf4j.LoggerFactory; @@ -13,8 +13,8 @@ public interface JavaWrapper { The returned object can have public static methods and fields accessed directly from it. Constructors can be used with the new keyword. """) - static Object loadClass(StringWithContext className) { - return className.cx().loadJavaClass(className.string(), true); + static Object loadClass(KubeJSContext cx, String className) { + return cx.loadJavaClass(className, true); } @Info(""" @@ -23,12 +23,12 @@ static Object loadClass(StringWithContext className) { Constructors can be used with the new keyword. """) @Nullable - static Object tryLoadClass(StringWithContext className) { - return className.cx().loadJavaClass(className.string(), false); + static Object tryLoadClass(KubeJSContext cx, String className) { + return cx.loadJavaClass(className, false); } @Info("Creates a custom ConsoleJS instance for you to use to, well, log stuff") - static ConsoleJS createConsole(StringWithContext name) { - return new ConsoleJS(name.cx().getType(), LoggerFactory.getLogger(name.string())); + static ConsoleJS createConsole(KubeJSContext cx, String name) { + return new ConsoleJS(cx.getType(), LoggerFactory.getLogger(name)); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/bindings/UtilsWrapper.java b/src/main/java/dev/latvian/mods/kubejs/bindings/UtilsWrapper.java index 9dcc0ab65..acc6fb2ac 100644 --- a/src/main/java/dev/latvian/mods/kubejs/bindings/UtilsWrapper.java +++ b/src/main/java/dev/latvian/mods/kubejs/bindings/UtilsWrapper.java @@ -3,13 +3,14 @@ import com.google.gson.JsonElement; import com.mojang.brigadier.StringReader; import dev.latvian.mods.kubejs.registry.RegistryInfo; +import dev.latvian.mods.kubejs.script.KubeJSContext; import dev.latvian.mods.kubejs.typings.Info; import dev.latvian.mods.kubejs.util.CountingMap; import dev.latvian.mods.kubejs.util.Lazy; import dev.latvian.mods.kubejs.util.RegExpJS; import dev.latvian.mods.kubejs.util.UtilsJS; -import dev.latvian.mods.kubejs.util.WithContext; import dev.latvian.mods.kubejs.util.WrappedJS; +import dev.latvian.mods.rhino.Context; import net.minecraft.Util; import net.minecraft.commands.arguments.ParticleArgument; import net.minecraft.core.particles.DustParticleOptions; @@ -223,14 +224,15 @@ static String snakeCaseToTitleCase(String string) { return UtilsJS.snakeCaseToTitleCase(string); } - static ParticleOptions particleOptions(WithContext o) { - if (o.value() instanceof ParticleOptions po) { + static ParticleOptions particleOptions(Context cx, Object o) { + if (o instanceof ParticleOptions po) { return po; } else if (o != null) { try { - var reader = new StringReader(o.value() instanceof JsonElement j ? j.getAsString() : o.toString()); - return ParticleArgument.readParticle(reader, o.cx().getRegistries()); - } catch (Exception ignored) { + var reader = new StringReader(o instanceof JsonElement j ? j.getAsString() : o.toString()); + return ParticleArgument.readParticle(reader, ((KubeJSContext) cx).getRegistries()); + } catch (Exception ex) { + ((KubeJSContext) cx).getConsole().warn("Failed to parse ParticleOptions from " + o + ": " + ex); } } @@ -242,6 +244,6 @@ static BlockState parseBlockState(Object o) { if (o instanceof BlockState bs) { return bs; } - return o == null ? Blocks.AIR.defaultBlockState() : UtilsJS.parseBlockState(o.toString()); + return o == null ? Blocks.AIR.defaultBlockState() : BlockWrapper.parseBlockState(o.toString()); } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/bindings/event/BlockEvents.java b/src/main/java/dev/latvian/mods/kubejs/bindings/event/BlockEvents.java index fc54ca38a..061148a7e 100644 --- a/src/main/java/dev/latvian/mods/kubejs/bindings/event/BlockEvents.java +++ b/src/main/java/dev/latvian/mods/kubejs/bindings/event/BlockEvents.java @@ -1,6 +1,5 @@ package dev.latvian.mods.kubejs.bindings.event; -import dev.latvian.mods.kubejs.bindings.BlockWrapper; import dev.latvian.mods.kubejs.block.BlockBrokenKubeEvent; import dev.latvian.mods.kubejs.block.BlockLeftClickedKubeEvent; import dev.latvian.mods.kubejs.block.BlockModificationKubeEvent; @@ -11,40 +10,22 @@ import dev.latvian.mods.kubejs.event.EventGroup; import dev.latvian.mods.kubejs.event.EventHandler; import dev.latvian.mods.kubejs.event.Extra; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.BlockItem; +import dev.latvian.mods.kubejs.event.SpecializedEventHandler; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.ResourceKey; import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.state.BlockState; public interface BlockEvents { EventGroup GROUP = EventGroup.of("BlockEvents"); - - Extra SUPPORTS_BLOCK = new Extra().transformer(BlockEvents::transformBlock).toString(o -> ((Block) o).kjs$getId()).identity().describeType(context -> context.javaType(Block.class)); - - private static Block transformBlock(Object o) { - if (o == null) { - return null; - } else if (o instanceof Block block) { - return block; - } else if (o instanceof BlockItem item) { - return item.getBlock(); - } else if (o instanceof BlockState state) { - return state.getBlock(); - } - - var id = ResourceLocation.tryParse(o.toString()); - var block = id == null ? null : BlockWrapper.getBlock(id); - return block == Blocks.AIR ? null : block; - } + Extra> SUPPORTS_BLOCK = Extra.registryKey(Registries.BLOCK, Block.class); EventHandler MODIFICATION = GROUP.startup("modification", () -> BlockModificationKubeEvent.class); - EventHandler RIGHT_CLICKED = GROUP.common("rightClicked", () -> BlockRightClickedKubeEvent.class).extra(SUPPORTS_BLOCK).hasResult(); - EventHandler LEFT_CLICKED = GROUP.common("leftClicked", () -> BlockLeftClickedKubeEvent.class).extra(SUPPORTS_BLOCK).hasResult(); - EventHandler PLACED = GROUP.common("placed", () -> BlockPlacedKubeEvent.class).extra(SUPPORTS_BLOCK).hasResult(); - EventHandler BROKEN = GROUP.common("broken", () -> BlockBrokenKubeEvent.class).extra(SUPPORTS_BLOCK).hasResult(); - EventHandler DETECTOR_CHANGED = GROUP.common("detectorChanged", () -> DetectorBlockKubeEvent.class).extra(Extra.STRING); - EventHandler DETECTOR_POWERED = GROUP.common("detectorPowered", () -> DetectorBlockKubeEvent.class).extra(Extra.STRING); - EventHandler DETECTOR_UNPOWERED = GROUP.common("detectorUnpowered", () -> DetectorBlockKubeEvent.class).extra(Extra.STRING); - EventHandler FARMLAND_TRAMPLED = GROUP.common("farmlandTrampled", () -> FarmlandTrampledKubeEvent.class).extra(SUPPORTS_BLOCK).hasResult(); + SpecializedEventHandler> RIGHT_CLICKED = GROUP.common("rightClicked", SUPPORTS_BLOCK, () -> BlockRightClickedKubeEvent.class).hasResult(); + SpecializedEventHandler> LEFT_CLICKED = GROUP.common("leftClicked", SUPPORTS_BLOCK, () -> BlockLeftClickedKubeEvent.class).hasResult(); + SpecializedEventHandler> PLACED = GROUP.common("placed", SUPPORTS_BLOCK, () -> BlockPlacedKubeEvent.class).hasResult(); + SpecializedEventHandler> BROKEN = GROUP.common("broken", SUPPORTS_BLOCK, () -> BlockBrokenKubeEvent.class).hasResult(); + SpecializedEventHandler DETECTOR_CHANGED = GROUP.common("detectorChanged", Extra.STRING, () -> DetectorBlockKubeEvent.class); + SpecializedEventHandler DETECTOR_POWERED = GROUP.common("detectorPowered", Extra.STRING, () -> DetectorBlockKubeEvent.class); + SpecializedEventHandler DETECTOR_UNPOWERED = GROUP.common("detectorUnpowered", Extra.STRING, () -> DetectorBlockKubeEvent.class); + SpecializedEventHandler> FARMLAND_TRAMPLED = GROUP.common("farmlandTrampled", SUPPORTS_BLOCK, () -> FarmlandTrampledKubeEvent.class).hasResult(); } diff --git a/src/main/java/dev/latvian/mods/kubejs/bindings/event/ClientEvents.java b/src/main/java/dev/latvian/mods/kubejs/bindings/event/ClientEvents.java index 39ca6b2b4..36362a5c7 100644 --- a/src/main/java/dev/latvian/mods/kubejs/bindings/event/ClientEvents.java +++ b/src/main/java/dev/latvian/mods/kubejs/bindings/event/ClientEvents.java @@ -10,9 +10,12 @@ import dev.latvian.mods.kubejs.event.EventGroup; import dev.latvian.mods.kubejs.event.EventHandler; import dev.latvian.mods.kubejs.event.Extra; +import dev.latvian.mods.kubejs.event.SpecializedEventHandler; +import net.minecraft.resources.ResourceLocation; public interface ClientEvents { EventGroup GROUP = EventGroup.of("ClientEvents"); + // add low assets EventHandler HIGH_ASSETS = GROUP.client("highPriorityAssets", () -> GenerateClientAssetsKubeEvent.class); EventHandler INIT = GROUP.startup("init", () -> ClientInitKubeEvent.class); @@ -23,6 +26,6 @@ public interface ClientEvents { EventHandler DEBUG_LEFT = GROUP.client("leftDebugInfo", () -> DebugInfoKubeEvent.class); EventHandler DEBUG_RIGHT = GROUP.client("rightDebugInfo", () -> DebugInfoKubeEvent.class); EventHandler PAINT_SCREEN = GROUP.client("paintScreen", () -> PaintScreenKubeEvent.class); - EventHandler ATLAS_SPRITE_REGISTRY = GROUP.client("atlasSpriteRegistry", () -> AtlasSpriteRegistryKubeEvent.class).extra(Extra.REQUIRES_ID); - EventHandler LANG = GROUP.client("lang", () -> LangKubeEvent.class).extra(Extra.REQUIRES_STRING); + SpecializedEventHandler ATLAS_SPRITE_REGISTRY = GROUP.client("atlasSpriteRegistry", Extra.ID, () -> AtlasSpriteRegistryKubeEvent.class).required(); + SpecializedEventHandler LANG = GROUP.client("lang", Extra.STRING, () -> LangKubeEvent.class).required(); } diff --git a/src/main/java/dev/latvian/mods/kubejs/bindings/event/EntityEvents.java b/src/main/java/dev/latvian/mods/kubejs/bindings/event/EntityEvents.java index b7f596d8f..14c85488a 100644 --- a/src/main/java/dev/latvian/mods/kubejs/bindings/event/EntityEvents.java +++ b/src/main/java/dev/latvian/mods/kubejs/bindings/event/EntityEvents.java @@ -6,29 +6,19 @@ import dev.latvian.mods.kubejs.entity.LivingEntityDropsKubeEvent; import dev.latvian.mods.kubejs.entity.LivingEntityHurtKubeEvent; import dev.latvian.mods.kubejs.event.EventGroup; -import dev.latvian.mods.kubejs.event.EventHandler; import dev.latvian.mods.kubejs.event.Extra; -import dev.latvian.mods.kubejs.registry.RegistryInfo; -import net.minecraft.resources.ResourceLocation; +import dev.latvian.mods.kubejs.event.SpecializedEventHandler; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.ResourceKey; import net.minecraft.world.entity.EntityType; public interface EntityEvents { EventGroup GROUP = EventGroup.of("EntityEvents"); + Extra>> SUPPORTS_ENTITY_TYPE = Extra.registryKey(Registries.ENTITY_TYPE, EntityType.class); - Extra SUPPORTS_ENTITY_TYPE = new Extra().transformer(EntityEvents::transformEntityType).identity().describeType(context -> context.javaType(EntityType.class)); - - private static Object transformEntityType(Object o) { - if (o == null || o instanceof EntityType) { - return o; - } - - var id = ResourceLocation.tryParse(o.toString()); - return id == null ? null : RegistryInfo.ENTITY_TYPE.getValue(id); - } - - EventHandler DEATH = GROUP.common("death", () -> LivingEntityDeathKubeEvent.class).extra(SUPPORTS_ENTITY_TYPE).hasResult(); - EventHandler HURT = GROUP.common("hurt", () -> LivingEntityHurtKubeEvent.class).extra(SUPPORTS_ENTITY_TYPE).hasResult(); - EventHandler CHECK_SPAWN = GROUP.common("checkSpawn", () -> CheckLivingEntitySpawnKubeEvent.class).extra(SUPPORTS_ENTITY_TYPE).hasResult(); - EventHandler SPAWNED = GROUP.common("spawned", () -> EntitySpawnedKubeEvent.class).extra(SUPPORTS_ENTITY_TYPE).hasResult(); - EventHandler ENTITY_DROPS = GROUP.common("drops", () -> LivingEntityDropsKubeEvent.class).extra(SUPPORTS_ENTITY_TYPE).hasResult(); + SpecializedEventHandler>> DEATH = GROUP.common("death", SUPPORTS_ENTITY_TYPE, () -> LivingEntityDeathKubeEvent.class).hasResult(); + SpecializedEventHandler>> HURT = GROUP.common("hurt", SUPPORTS_ENTITY_TYPE, () -> LivingEntityHurtKubeEvent.class).hasResult(); + SpecializedEventHandler>> CHECK_SPAWN = GROUP.common("checkSpawn", SUPPORTS_ENTITY_TYPE, () -> CheckLivingEntitySpawnKubeEvent.class).hasResult(); + SpecializedEventHandler>> SPAWNED = GROUP.common("spawned", SUPPORTS_ENTITY_TYPE, () -> EntitySpawnedKubeEvent.class).hasResult(); + SpecializedEventHandler>> ENTITY_DROPS = GROUP.common("drops", SUPPORTS_ENTITY_TYPE, () -> LivingEntityDropsKubeEvent.class).hasResult(); } diff --git a/src/main/java/dev/latvian/mods/kubejs/bindings/event/ItemEvents.java b/src/main/java/dev/latvian/mods/kubejs/bindings/event/ItemEvents.java index 6e10ce1a4..1069346cb 100644 --- a/src/main/java/dev/latvian/mods/kubejs/bindings/event/ItemEvents.java +++ b/src/main/java/dev/latvian/mods/kubejs/bindings/event/ItemEvents.java @@ -1,9 +1,9 @@ package dev.latvian.mods.kubejs.bindings.event; -import dev.latvian.mods.kubejs.bindings.ItemWrapper; import dev.latvian.mods.kubejs.event.EventGroup; import dev.latvian.mods.kubejs.event.EventHandler; import dev.latvian.mods.kubejs.event.Extra; +import dev.latvian.mods.kubejs.event.SpecializedEventHandler; import dev.latvian.mods.kubejs.item.FoodEatenKubeEvent; import dev.latvian.mods.kubejs.item.ItemClickedKubeEvent; import dev.latvian.mods.kubejs.item.ItemCraftedKubeEvent; @@ -16,41 +16,27 @@ import dev.latvian.mods.kubejs.item.ItemSmeltedKubeEvent; import dev.latvian.mods.kubejs.item.ItemTooltipKubeEvent; import dev.latvian.mods.kubejs.item.custom.ItemToolTierRegistryKubeEvent; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.ResourceKey; import net.minecraft.world.item.Item; -import net.minecraft.world.item.Items; -import net.minecraft.world.level.ItemLike; public interface ItemEvents { EventGroup GROUP = EventGroup.of("ItemEvents"); - - Extra SUPPORTS_ITEM = new Extra().transformer(ItemEvents::transformItem).toString(o -> ((Item) o).kjs$getId()).identity().describeType(context -> context.javaType(Item.class)); - - private static Object transformItem(Object o) { - if (o == null) { - return null; - } else if (o instanceof ItemLike item) { - return item.asItem(); - } - - var id = ResourceLocation.tryParse(o.toString()); - var item = id == null ? null : ItemWrapper.getItem(id); - return item == Items.AIR ? null : item; - } + Extra> SUPPORTS_ITEM = Extra.registryKey(Registries.ITEM, Item.class); EventHandler MODIFICATION = GROUP.startup("modification", () -> ItemModificationKubeEvent.class); EventHandler TOOL_TIER_REGISTRY = GROUP.startup("toolTierRegistry", () -> ItemToolTierRegistryKubeEvent.class); - EventHandler RIGHT_CLICKED = GROUP.common("rightClicked", () -> ItemClickedKubeEvent.class).extra(SUPPORTS_ITEM).hasResult(); - EventHandler CAN_PICK_UP = GROUP.common("canPickUp", () -> ItemPickedUpKubeEvent.class).extra(SUPPORTS_ITEM).hasResult(); - EventHandler PICKED_UP = GROUP.common("pickedUp", () -> ItemPickedUpKubeEvent.class).extra(SUPPORTS_ITEM); - EventHandler DROPPED = GROUP.common("dropped", () -> ItemDroppedKubeEvent.class).extra(SUPPORTS_ITEM).hasResult(); - EventHandler ENTITY_INTERACTED = GROUP.common("entityInteracted", () -> ItemEntityInteractedKubeEvent.class).extra(SUPPORTS_ITEM).hasResult(); - EventHandler CRAFTED = GROUP.common("crafted", () -> ItemCraftedKubeEvent.class).extra(SUPPORTS_ITEM); - EventHandler SMELTED = GROUP.common("smelted", () -> ItemSmeltedKubeEvent.class).extra(SUPPORTS_ITEM); - EventHandler FOOD_EATEN = GROUP.common("foodEaten", () -> FoodEatenKubeEvent.class).extra(SUPPORTS_ITEM).hasResult(); + SpecializedEventHandler> RIGHT_CLICKED = GROUP.common("rightClicked", SUPPORTS_ITEM, () -> ItemClickedKubeEvent.class).hasResult(); + SpecializedEventHandler> CAN_PICK_UP = GROUP.common("canPickUp", SUPPORTS_ITEM, () -> ItemPickedUpKubeEvent.class).hasResult(); + SpecializedEventHandler> PICKED_UP = GROUP.common("pickedUp", SUPPORTS_ITEM, () -> ItemPickedUpKubeEvent.class); + SpecializedEventHandler> DROPPED = GROUP.common("dropped", SUPPORTS_ITEM, () -> ItemDroppedKubeEvent.class).hasResult(); + SpecializedEventHandler> ENTITY_INTERACTED = GROUP.common("entityInteracted", SUPPORTS_ITEM, () -> ItemEntityInteractedKubeEvent.class).hasResult(); + SpecializedEventHandler> CRAFTED = GROUP.common("crafted", SUPPORTS_ITEM, () -> ItemCraftedKubeEvent.class); + SpecializedEventHandler> SMELTED = GROUP.common("smelted", SUPPORTS_ITEM, () -> ItemSmeltedKubeEvent.class); + SpecializedEventHandler> FOOD_EATEN = GROUP.common("foodEaten", SUPPORTS_ITEM, () -> FoodEatenKubeEvent.class).hasResult(); EventHandler TOOLTIP = GROUP.client("tooltip", () -> ItemTooltipKubeEvent.class); EventHandler MODEL_PROPERTIES = GROUP.startup("modelProperties", () -> ItemModelPropertiesKubeEvent.class); - EventHandler FIRST_RIGHT_CLICKED = GROUP.common("firstRightClicked", () -> ItemClickedKubeEvent.class).extra(ItemEvents.SUPPORTS_ITEM); - EventHandler FIRST_LEFT_CLICKED = GROUP.common("firstLeftClicked", () -> ItemClickedKubeEvent.class).extra(ItemEvents.SUPPORTS_ITEM); - EventHandler ITEM_DESTROYED = GROUP.common("destroyed", () -> ItemDestroyedKubeEvent.class).extra(SUPPORTS_ITEM); + SpecializedEventHandler> FIRST_RIGHT_CLICKED = GROUP.common("firstRightClicked", SUPPORTS_ITEM, () -> ItemClickedKubeEvent.class); + SpecializedEventHandler> FIRST_LEFT_CLICKED = GROUP.common("firstLeftClicked", SUPPORTS_ITEM, () -> ItemClickedKubeEvent.class); + SpecializedEventHandler> ITEM_DESTROYED = GROUP.common("destroyed", SUPPORTS_ITEM, () -> ItemDestroyedKubeEvent.class); } diff --git a/src/main/java/dev/latvian/mods/kubejs/bindings/event/LevelEvents.java b/src/main/java/dev/latvian/mods/kubejs/bindings/event/LevelEvents.java index abe034f02..7197ee8e4 100644 --- a/src/main/java/dev/latvian/mods/kubejs/bindings/event/LevelEvents.java +++ b/src/main/java/dev/latvian/mods/kubejs/bindings/event/LevelEvents.java @@ -1,16 +1,22 @@ package dev.latvian.mods.kubejs.bindings.event; import dev.latvian.mods.kubejs.event.EventGroup; -import dev.latvian.mods.kubejs.event.EventHandler; import dev.latvian.mods.kubejs.event.Extra; +import dev.latvian.mods.kubejs.event.SpecializedEventHandler; import dev.latvian.mods.kubejs.level.ExplosionKubeEvent; import dev.latvian.mods.kubejs.level.SimpleLevelKubeEvent; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.level.Level; public interface LevelEvents { EventGroup GROUP = EventGroup.of("LevelEvents"); - EventHandler LOADED = GROUP.server("loaded", () -> SimpleLevelKubeEvent.class).extra(Extra.ID); - EventHandler UNLOADED = GROUP.server("unloaded", () -> SimpleLevelKubeEvent.class).extra(Extra.ID); - EventHandler TICK = GROUP.common("tick", () -> SimpleLevelKubeEvent.class).extra(Extra.ID); - EventHandler BEFORE_EXPLOSION = GROUP.common("beforeExplosion", () -> ExplosionKubeEvent.Before.class).hasResult(); - EventHandler AFTER_EXPLOSION = GROUP.common("afterExplosion", () -> ExplosionKubeEvent.After.class); + Extra> SUPPORTS_LEVEL = Extra.registryKey(Registries.DIMENSION, Level.class); + + SpecializedEventHandler> LOADED = GROUP.server("loaded", SUPPORTS_LEVEL, () -> SimpleLevelKubeEvent.class); + SpecializedEventHandler> SAVED = GROUP.server("saved", SUPPORTS_LEVEL, () -> SimpleLevelKubeEvent.class); + SpecializedEventHandler> UNLOADED = GROUP.server("unloaded", SUPPORTS_LEVEL, () -> SimpleLevelKubeEvent.class); + SpecializedEventHandler> TICK = GROUP.common("tick", SUPPORTS_LEVEL, () -> SimpleLevelKubeEvent.class); + SpecializedEventHandler> BEFORE_EXPLOSION = GROUP.common("beforeExplosion", SUPPORTS_LEVEL, () -> ExplosionKubeEvent.Before.class).hasResult(); + SpecializedEventHandler> AFTER_EXPLOSION = GROUP.common("afterExplosion", SUPPORTS_LEVEL, () -> ExplosionKubeEvent.After.class); } diff --git a/src/main/java/dev/latvian/mods/kubejs/bindings/event/NetworkEvents.java b/src/main/java/dev/latvian/mods/kubejs/bindings/event/NetworkEvents.java index 8168ec82b..16f380a52 100644 --- a/src/main/java/dev/latvian/mods/kubejs/bindings/event/NetworkEvents.java +++ b/src/main/java/dev/latvian/mods/kubejs/bindings/event/NetworkEvents.java @@ -1,11 +1,12 @@ package dev.latvian.mods.kubejs.bindings.event; import dev.latvian.mods.kubejs.event.EventGroup; -import dev.latvian.mods.kubejs.event.EventHandler; import dev.latvian.mods.kubejs.event.Extra; +import dev.latvian.mods.kubejs.event.SpecializedEventHandler; import dev.latvian.mods.kubejs.net.NetworkKubeEvent; public interface NetworkEvents { EventGroup GROUP = EventGroup.of("NetworkEvents"); - EventHandler DATA_RECEIVED = GROUP.common("dataReceived", () -> NetworkKubeEvent.class).extra(Extra.REQUIRES_STRING).hasResult(); + + SpecializedEventHandler DATA_RECEIVED = GROUP.common("dataReceived", Extra.STRING, () -> NetworkKubeEvent.class).required().hasResult(); } diff --git a/src/main/java/dev/latvian/mods/kubejs/bindings/event/PlayerEvents.java b/src/main/java/dev/latvian/mods/kubejs/bindings/event/PlayerEvents.java index 508197234..eecb25283 100644 --- a/src/main/java/dev/latvian/mods/kubejs/bindings/event/PlayerEvents.java +++ b/src/main/java/dev/latvian/mods/kubejs/bindings/event/PlayerEvents.java @@ -3,52 +3,39 @@ import dev.latvian.mods.kubejs.event.EventGroup; import dev.latvian.mods.kubejs.event.EventHandler; import dev.latvian.mods.kubejs.event.Extra; +import dev.latvian.mods.kubejs.event.SpecializedEventHandler; import dev.latvian.mods.kubejs.player.ChestKubeEvent; import dev.latvian.mods.kubejs.player.InventoryChangedKubeEvent; import dev.latvian.mods.kubejs.player.InventoryKubeEvent; import dev.latvian.mods.kubejs.player.PlayerAdvancementKubeEvent; -import dev.latvian.mods.kubejs.player.PlayerChatDecorateKubeEvent; +import dev.latvian.mods.kubejs.player.PlayerChatReceivedKubeEvent; +import dev.latvian.mods.kubejs.player.PlayerClonedKubeEvent; import dev.latvian.mods.kubejs.player.PlayerRespawnedKubeEvent; import dev.latvian.mods.kubejs.player.SimplePlayerKubeEvent; import dev.latvian.mods.kubejs.player.StageChangedEvent; -import dev.latvian.mods.kubejs.registry.RegistryInfo; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.MenuType; +import net.minecraft.world.item.Item; public interface PlayerEvents { - Extra SUPPORTS_MENU_TYPE = new Extra().transformer(PlayerEvents::transformMenuType).identity().describeType(context -> context.javaType(MenuType.class)); - - static Object transformMenuType(Object o) { - if (o == null) { - return null; - } else if (o instanceof MenuType menuType) { - return menuType; - } else if (o instanceof AbstractContainerMenu menu) { - try { - return menu.getType(); - } catch (Exception ex) { - return null; - } - } - - var id = ResourceLocation.tryParse(o.toString()); - return id == null ? null : RegistryInfo.MENU.getValue(id); - } + Extra>> SUPPORTS_MENU_TYPE = Extra.registryKey(Registries.MENU, MenuType.class); EventGroup GROUP = EventGroup.of("PlayerEvents"); EventHandler LOGGED_IN = GROUP.server("loggedIn", () -> SimplePlayerKubeEvent.class); EventHandler LOGGED_OUT = GROUP.server("loggedOut", () -> SimplePlayerKubeEvent.class); + EventHandler CLONED = GROUP.server("cloned", () -> PlayerClonedKubeEvent.class); EventHandler RESPAWNED = GROUP.server("respawned", () -> PlayerRespawnedKubeEvent.class); EventHandler TICK = GROUP.common("tick", () -> SimplePlayerKubeEvent.class); - EventHandler CHAT = GROUP.server("chat", () -> PlayerChatDecorateKubeEvent.class).hasResult(); - EventHandler DECORATE_CHAT = GROUP.server("decorateChat", () -> PlayerChatDecorateKubeEvent.class); - EventHandler ADVANCEMENT = GROUP.server("advancement", () -> PlayerAdvancementKubeEvent.class).extra(Extra.ID).hasResult(); - EventHandler INVENTORY_OPENED = GROUP.common("inventoryOpened", () -> InventoryKubeEvent.class).extra(SUPPORTS_MENU_TYPE); - EventHandler INVENTORY_CLOSED = GROUP.common("inventoryClosed", () -> InventoryKubeEvent.class).extra(SUPPORTS_MENU_TYPE); - EventHandler INVENTORY_CHANGED = GROUP.common("inventoryChanged", () -> InventoryChangedKubeEvent.class).extra(ItemEvents.SUPPORTS_ITEM); - EventHandler CHEST_OPENED = GROUP.common("chestOpened", () -> ChestKubeEvent.class).extra(SUPPORTS_MENU_TYPE); - EventHandler CHEST_CLOSED = GROUP.common("chestClosed", () -> ChestKubeEvent.class).extra(SUPPORTS_MENU_TYPE); - EventHandler STAGE_ADDED = GROUP.common("stageAdded", () -> StageChangedEvent.class).extra(Extra.STRING); - EventHandler STAGE_REMOVED = GROUP.common("stageRemoved", () -> StageChangedEvent.class).extra(Extra.STRING); + EventHandler DECORATE_CHAT = GROUP.server("decorateChat", () -> PlayerChatReceivedKubeEvent.class).hasResult(); + EventHandler CHAT = GROUP.server("chat", () -> PlayerChatReceivedKubeEvent.class).hasResult(); + SpecializedEventHandler ADVANCEMENT = GROUP.server("advancement", Extra.ID, () -> PlayerAdvancementKubeEvent.class).hasResult(); + SpecializedEventHandler>> INVENTORY_OPENED = GROUP.common("inventoryOpened", SUPPORTS_MENU_TYPE, () -> InventoryKubeEvent.class); + SpecializedEventHandler>> INVENTORY_CLOSED = GROUP.common("inventoryClosed", SUPPORTS_MENU_TYPE, () -> InventoryKubeEvent.class); + SpecializedEventHandler> INVENTORY_CHANGED = GROUP.common("inventoryChanged", ItemEvents.SUPPORTS_ITEM, () -> InventoryChangedKubeEvent.class); + SpecializedEventHandler>> CHEST_OPENED = GROUP.common("chestOpened", SUPPORTS_MENU_TYPE, () -> ChestKubeEvent.class); + SpecializedEventHandler>> CHEST_CLOSED = GROUP.common("chestClosed", SUPPORTS_MENU_TYPE, () -> ChestKubeEvent.class); + SpecializedEventHandler STAGE_ADDED = GROUP.common("stageAdded", Extra.STRING, () -> StageChangedEvent.class); + SpecializedEventHandler STAGE_REMOVED = GROUP.common("stageRemoved", Extra.STRING, () -> StageChangedEvent.class); } diff --git a/src/main/java/dev/latvian/mods/kubejs/bindings/event/ServerEvents.java b/src/main/java/dev/latvian/mods/kubejs/bindings/event/ServerEvents.java index 393a27d6a..d3063aef3 100644 --- a/src/main/java/dev/latvian/mods/kubejs/bindings/event/ServerEvents.java +++ b/src/main/java/dev/latvian/mods/kubejs/bindings/event/ServerEvents.java @@ -4,6 +4,7 @@ import dev.latvian.mods.kubejs.event.EventGroup; import dev.latvian.mods.kubejs.event.EventHandler; import dev.latvian.mods.kubejs.event.Extra; +import dev.latvian.mods.kubejs.event.SpecializedEventHandler; import dev.latvian.mods.kubejs.recipe.AfterRecipesLoadedKubeEvent; import dev.latvian.mods.kubejs.recipe.CompostableRecipesKubeEvent; import dev.latvian.mods.kubejs.recipe.RecipesKubeEvent; @@ -13,18 +14,21 @@ import dev.latvian.mods.kubejs.server.CustomCommandKubeEvent; import dev.latvian.mods.kubejs.server.ServerKubeEvent; import dev.latvian.mods.kubejs.server.tag.TagKubeEvent; +import net.minecraft.core.Registry; +import net.minecraft.resources.ResourceKey; public interface ServerEvents { EventGroup GROUP = EventGroup.of("ServerEvents"); + EventHandler LOW_DATA = GROUP.server("lowPriorityData", () -> DataPackKubeEvent.class); EventHandler HIGH_DATA = GROUP.server("highPriorityData", () -> DataPackKubeEvent.class); EventHandler LOADED = GROUP.server("loaded", () -> ServerKubeEvent.class); EventHandler UNLOADED = GROUP.server("unloaded", () -> ServerKubeEvent.class); EventHandler TICK = GROUP.server("tick", () -> ServerKubeEvent.class); - EventHandler TAGS = GROUP.server("tags", () -> TagKubeEvent.class).extra(Extra.REQUIRES_REGISTRY); + SpecializedEventHandler>> TAGS = GROUP.server("tags", Extra.REGISTRY, () -> TagKubeEvent.class).required().exceptionHandler(TagKubeEvent.TAG_EVENT_HANDLER); EventHandler COMMAND_REGISTRY = GROUP.server("commandRegistry", () -> CommandRegistryKubeEvent.class); - EventHandler COMMAND = GROUP.server("command", () -> CommandKubeEvent.class).extra(Extra.STRING).hasResult(); - EventHandler CUSTOM_COMMAND = GROUP.server("customCommand", () -> CustomCommandKubeEvent.class).extra(Extra.STRING).hasResult(); + SpecializedEventHandler COMMAND = GROUP.server("command", Extra.STRING, () -> CommandKubeEvent.class).hasResult(); + SpecializedEventHandler CUSTOM_COMMAND = GROUP.server("customCommand", Extra.STRING, () -> CustomCommandKubeEvent.class).hasResult(); EventHandler RECIPES = GROUP.server("recipes", () -> RecipesKubeEvent.class); EventHandler RECIPES_AFTER_LOADED = GROUP.server("afterRecipes", () -> AfterRecipesLoadedKubeEvent.class); EventHandler SPECIAL_RECIPES = GROUP.server("specialRecipeSerializers", () -> SpecialRecipeSerializerManager.class); diff --git a/src/main/java/dev/latvian/mods/kubejs/bindings/event/StartupEvents.java b/src/main/java/dev/latvian/mods/kubejs/bindings/event/StartupEvents.java index 87d5b55c5..8c2c218ee 100644 --- a/src/main/java/dev/latvian/mods/kubejs/bindings/event/StartupEvents.java +++ b/src/main/java/dev/latvian/mods/kubejs/bindings/event/StartupEvents.java @@ -4,16 +4,20 @@ import dev.latvian.mods.kubejs.event.EventHandler; import dev.latvian.mods.kubejs.event.Extra; import dev.latvian.mods.kubejs.event.KubeStartupEvent; +import dev.latvian.mods.kubejs.event.SpecializedEventHandler; import dev.latvian.mods.kubejs.item.creativetab.CreativeTabKubeEvent; import dev.latvian.mods.kubejs.recipe.RecipeSchemaRegistryKubeEvent; import dev.latvian.mods.kubejs.registry.RegistryKubeEvent; +import net.minecraft.core.Registry; +import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; public interface StartupEvents { EventGroup GROUP = EventGroup.of("StartupEvents"); EventHandler INIT = GROUP.startup("init", () -> KubeStartupEvent.class); EventHandler POST_INIT = GROUP.startup("postInit", () -> KubeStartupEvent.class); - EventHandler REGISTRY = GROUP.startup("registry", () -> RegistryKubeEvent.class).extra(Extra.REQUIRES_REGISTRY); + SpecializedEventHandler>> REGISTRY = GROUP.startup("registry", Extra.REGISTRY, () -> RegistryKubeEvent.class).required(); EventHandler RECIPE_SCHEMA_REGISTRY = GROUP.startup("recipeSchemaRegistry", () -> RecipeSchemaRegistryKubeEvent.class); - EventHandler MODIFY_CREATIVE_TAB = GROUP.startup("modifyCreativeTab", () -> CreativeTabKubeEvent.class).extra(Extra.REQUIRES_ID); + SpecializedEventHandler MODIFY_CREATIVE_TAB = GROUP.startup("modifyCreativeTab", Extra.ID, () -> CreativeTabKubeEvent.class).required(); } diff --git a/src/main/java/dev/latvian/mods/kubejs/block/BlockBrokenKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/block/BlockBrokenKubeEvent.java index 2566d28c9..682ee093f 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/BlockBrokenKubeEvent.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/BlockBrokenKubeEvent.java @@ -1,62 +1,42 @@ package dev.latvian.mods.kubejs.block; -import dev.architectury.utils.value.IntValue; import dev.latvian.mods.kubejs.level.BlockContainerJS; import dev.latvian.mods.kubejs.player.KubePlayerEvent; import dev.latvian.mods.kubejs.typings.Info; -import net.minecraft.core.BlockPos; -import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.state.BlockState; -import org.jetbrains.annotations.Nullable; +import net.neoforged.neoforge.event.level.BlockEvent; @Info(value = """ Invoked when a block is destroyed by a player. """) public class BlockBrokenKubeEvent implements KubePlayerEvent { - private final ServerPlayer entity; - private final Level level; - private final BlockPos pos; - private final BlockState state; - @Nullable - private final IntValue xp; + private final BlockEvent.BreakEvent event; - public BlockBrokenKubeEvent(ServerPlayer entity, Level level, BlockPos pos, BlockState state, @Nullable IntValue xp) { - this.entity = entity; - this.level = level; - this.pos = pos; - this.state = state; - this.xp = xp; + public BlockBrokenKubeEvent(BlockEvent.BreakEvent event) { + this.event = event; } @Override @Info("The player that broke the block.") - public ServerPlayer getEntity() { - return entity; + public Player getEntity() { + return event.getPlayer(); } @Info("The block that was broken.") public BlockContainerJS getBlock() { - return new BlockContainerJS(level, pos) { - @Override - public BlockState getBlockState() { - return state; - } - }; + var block = new BlockContainerJS((Level) event.getLevel(), event.getPos()); + block.cachedState = event.getState(); + return block; } @Info("The experience dropped by the block. Always `0` on Fabric.") public int getXp() { - if (xp == null) { - return 0; - } - return xp.getAsInt(); + return event.getExpToDrop(); } @Info("Sets the experience dropped by the block. Only works on Forge.") public void setXp(int xp) { - if (this.xp != null) { - this.xp.accept(xp); - } + event.setExpToDrop(xp); } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/block/BlockBuilder.java b/src/main/java/dev/latvian/mods/kubejs/block/BlockBuilder.java index a59d634bf..d1c4c70c6 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/BlockBuilder.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/BlockBuilder.java @@ -23,8 +23,8 @@ import dev.latvian.mods.kubejs.registry.RegistryInfo; import dev.latvian.mods.kubejs.script.ScriptType; import dev.latvian.mods.kubejs.typings.Info; +import dev.latvian.mods.kubejs.util.Cast; import dev.latvian.mods.kubejs.util.ConsoleJS; -import dev.latvian.mods.kubejs.util.UtilsJS; import dev.latvian.mods.rhino.util.HideFromJS; import net.minecraft.core.Direction; import net.minecraft.core.Holder; @@ -830,7 +830,7 @@ public Block.Properties createProperties() { } if (noValidSpawns) { - properties.isValidSpawn(UtilsJS.cast(ALWAYS_FALSE_STATE_ARG_PREDICATE)); + properties.isValidSpawn(Cast.to(ALWAYS_FALSE_STATE_ARG_PREDICATE)); } if (!suffocating) { diff --git a/src/main/java/dev/latvian/mods/kubejs/block/BlockLeftClickedKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/block/BlockLeftClickedKubeEvent.java index 2147397fb..5e6549c6d 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/BlockLeftClickedKubeEvent.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/BlockLeftClickedKubeEvent.java @@ -3,48 +3,41 @@ import dev.latvian.mods.kubejs.level.BlockContainerJS; import dev.latvian.mods.kubejs.player.KubePlayerEvent; import dev.latvian.mods.kubejs.typings.Info; -import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; +import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent; import org.jetbrains.annotations.Nullable; @Info(value = """ Invoked when a player left clicks on a block. """) public class BlockLeftClickedKubeEvent implements KubePlayerEvent { - private final Player player; - private final InteractionHand hand; - private final BlockPos pos; - private final Direction direction; + private final PlayerInteractEvent.LeftClickBlock event; - public BlockLeftClickedKubeEvent(Player player, InteractionHand hand, BlockPos pos, Direction direction) { - this.player = player; - this.hand = hand; - this.pos = pos; - this.direction = direction; + public BlockLeftClickedKubeEvent(PlayerInteractEvent.LeftClickBlock event) { + this.event = event; } @Override @Info("The player that left clicked the block.") public Player getEntity() { - return player; + return event.getEntity(); } @Info("The block that was left clicked.") public BlockContainerJS getBlock() { - return new BlockContainerJS(player.level(), pos); + return new BlockContainerJS(event.getLevel(), event.getPos()); } @Info("The item that was used to left click the block.") public ItemStack getItem() { - return player.getItemInHand(hand); + return event.getEntity().getItemInHand(event.getHand()); } @Info("The face of the block that was left clicked.") @Nullable public Direction getFacing() { - return direction; + return event.getFace(); } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/block/BlockPlacedKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/block/BlockPlacedKubeEvent.java index 4bc7b8948..1bba03ed5 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/BlockPlacedKubeEvent.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/BlockPlacedKubeEvent.java @@ -3,47 +3,36 @@ import dev.latvian.mods.kubejs.entity.KubeEntityEvent; import dev.latvian.mods.kubejs.level.BlockContainerJS; import dev.latvian.mods.kubejs.typings.Info; -import net.minecraft.core.BlockPos; import net.minecraft.world.entity.Entity; import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.state.BlockState; -import org.jetbrains.annotations.Nullable; +import net.neoforged.neoforge.event.level.BlockEvent; @Info(value = """ Invoked when a block is placed. """) public class BlockPlacedKubeEvent implements KubeEntityEvent { - private final Entity entity; - private final Level level; - private final BlockPos pos; - private final BlockState state; + private final BlockEvent.EntityPlaceEvent event; - public BlockPlacedKubeEvent(@Nullable Entity entity, Level level, BlockPos pos, BlockState state) { - this.entity = entity; - this.level = level; - this.pos = pos; - this.state = state; + public BlockPlacedKubeEvent(BlockEvent.EntityPlaceEvent event) { + this.event = event; } @Override @Info("The level of the block that was placed.") public Level getLevel() { - return level; + return (Level) event.getLevel(); } @Override @Info("The entity that placed the block. Can be `null`, e.g. when a block is placed by a dispenser.") public Entity getEntity() { - return entity; + return event.getEntity(); } @Info("The block that is placed.") public BlockContainerJS getBlock() { - return new BlockContainerJS(level, pos) { - @Override - public BlockState getBlockState() { - return state; - } - }; + var block = new BlockContainerJS((Level) event.getLevel(), event.getPos()); + block.cachedState = event.getPlacedBlock(); + return block; } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/block/BlockRightClickedKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/block/BlockRightClickedKubeEvent.java index 2d678a901..ccb62ed08 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/BlockRightClickedKubeEvent.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/BlockRightClickedKubeEvent.java @@ -8,6 +8,8 @@ import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.phys.BlockHitResult; +import org.jetbrains.annotations.Nullable; @Info(""" Invoked when a player right clicks on a block. @@ -18,14 +20,16 @@ public class BlockRightClickedKubeEvent implements KubePlayerEvent { private final InteractionHand hand; private final BlockPos pos; private final Direction direction; + private final BlockHitResult hitResult; private BlockContainerJS block; - public BlockRightClickedKubeEvent(ItemStack item, Player player, InteractionHand hand, BlockPos pos, Direction direction) { + public BlockRightClickedKubeEvent(ItemStack item, Player player, InteractionHand hand, BlockPos pos, Direction direction, @Nullable BlockHitResult hitResult) { this.item = item; this.player = player; this.hand = hand; this.pos = pos; this.direction = direction; + this.hitResult = hitResult; } @Override @@ -61,4 +65,9 @@ public ItemStack getItem() { public Direction getFacing() { return direction; } + + @Nullable + public BlockHitResult getHitResult() { + return hitResult; + } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/block/FarmlandTrampledKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/block/FarmlandTrampledKubeEvent.java index 6b9f45d45..a13c920f8 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/FarmlandTrampledKubeEvent.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/FarmlandTrampledKubeEvent.java @@ -3,43 +3,38 @@ import dev.latvian.mods.kubejs.entity.KubeEntityEvent; import dev.latvian.mods.kubejs.level.BlockContainerJS; import dev.latvian.mods.kubejs.typings.Info; -import net.minecraft.core.BlockPos; import net.minecraft.world.entity.Entity; import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.state.BlockState; +import net.neoforged.neoforge.event.level.BlockEvent; @Info(value = """ Invoked when an entity attempts to trample farmland. """) public class FarmlandTrampledKubeEvent implements KubeEntityEvent { - private final Level level; + private final BlockEvent.FarmlandTrampleEvent event; private final BlockContainerJS block; - private final float distance; - private final Entity entity; - public FarmlandTrampledKubeEvent(Level l, BlockPos pos, BlockState state, float d, Entity e) { - level = l; - block = level.kjs$getBlock(pos); - block.cachedState = state; - distance = d; - entity = e; + public FarmlandTrampledKubeEvent(BlockEvent.FarmlandTrampleEvent event) { + this.event = event; + this.block = new BlockContainerJS((Level) event.getLevel(), event.getPos()); + this.block.cachedState = event.getState(); } @Info("The distance of the entity from the block.") public float getDistance() { - return distance; + return event.getFallDistance(); } @Override @Info("The entity that is attempting to trample the farmland.") public Entity getEntity() { - return entity; + return event.getEntity(); } @Override @Info("The level that the farmland and the entity are in.") public Level getLevel() { - return level; + return (Level) event.getLevel(); } @Info("The farmland block.") diff --git a/src/main/java/dev/latvian/mods/kubejs/block/KubeJSBlockEventHandler.java b/src/main/java/dev/latvian/mods/kubejs/block/KubeJSBlockEventHandler.java index e9b5c4acf..9b0c73a32 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/KubeJSBlockEventHandler.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/KubeJSBlockEventHandler.java @@ -1,51 +1,51 @@ package dev.latvian.mods.kubejs.block; -import dev.architectury.event.EventResult; -import dev.architectury.event.events.common.BlockEvent; -import dev.architectury.event.events.common.InteractionEvent; -import dev.architectury.utils.value.IntValue; +import dev.latvian.mods.kubejs.KubeJS; import dev.latvian.mods.kubejs.bindings.event.BlockEvents; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.state.BlockState; -import org.jetbrains.annotations.Nullable; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent; +import net.neoforged.neoforge.event.level.BlockEvent; +@EventBusSubscriber(modid = KubeJS.MOD_ID) public class KubeJSBlockEventHandler { + @SubscribeEvent + public static void rightClick(PlayerInteractEvent.RightClickBlock event) { + var state = event.getLevel().getBlockState(event.getPos()); - public static void init() { - InteractionEvent.RIGHT_CLICK_BLOCK.register(KubeJSBlockEventHandler::rightClick); - InteractionEvent.LEFT_CLICK_BLOCK.register(KubeJSBlockEventHandler::leftClick); - BlockEvent.BREAK.register(KubeJSBlockEventHandler::blockBreak); - BlockEvent.PLACE.register(KubeJSBlockEventHandler::blockPlace); - InteractionEvent.FARMLAND_TRAMPLE.register(KubeJSBlockEventHandler::farmlandTrample); - } - - private static EventResult rightClick(Player player, InteractionHand hand, BlockPos pos, Direction direction) { - if (BlockEvents.RIGHT_CLICKED.hasListeners() && !player.getCooldowns().isOnCooldown(player.getItemInHand(hand).getItem())) { - return BlockEvents.RIGHT_CLICKED.post(player, player.level().getBlockState(pos), new BlockRightClickedKubeEvent(null, player, hand, pos, direction)).arch(); + if (event.getLevel() instanceof Level level && BlockEvents.RIGHT_CLICKED.hasListeners(state.kjs$getRegistryKey()) && !event.getEntity().getCooldowns().isOnCooldown(event.getEntity().getItemInHand(event.getHand()).getItem())) { + BlockEvents.RIGHT_CLICKED.post(level, state.kjs$getRegistryKey(), new BlockRightClickedKubeEvent(null, event.getEntity(), event.getHand(), event.getPos(), event.getFace(), event.getHitVec())).applyCancel(event); } - - return EventResult.pass(); } - private static EventResult leftClick(Player player, InteractionHand hand, BlockPos pos, Direction direction) { - return BlockEvents.LEFT_CLICKED.hasListeners() ? BlockEvents.LEFT_CLICKED.post(player, player.level().getBlockState(pos), new BlockLeftClickedKubeEvent(player, hand, pos, direction)).arch() : EventResult.pass(); + @SubscribeEvent + public static void leftClick(PlayerInteractEvent.LeftClickBlock event) { + var state = event.getLevel().getBlockState(event.getPos()); + + if (event.getLevel() instanceof Level level && BlockEvents.LEFT_CLICKED.hasListeners(state.kjs$getRegistryKey())) { + BlockEvents.LEFT_CLICKED.post(level, state.kjs$getRegistryKey(), new BlockLeftClickedKubeEvent(event)).applyCancel(event); + } } - private static EventResult blockBreak(Level level, BlockPos pos, BlockState state, ServerPlayer player, @Nullable IntValue xp) { - return BlockEvents.BROKEN.hasListeners(state.getBlock()) ? BlockEvents.BROKEN.post(level, state.getBlock(), new BlockBrokenKubeEvent(player, level, pos, state, xp)).arch() : EventResult.pass(); + @SubscribeEvent + public static void blockBreak(BlockEvent.BreakEvent event) { + if (event.getLevel() instanceof Level level && BlockEvents.BROKEN.hasListeners(event.getState().kjs$getRegistryKey())) { + BlockEvents.BROKEN.post(level, event.getState().kjs$getRegistryKey(), new BlockBrokenKubeEvent(event)).applyCancel(event); + } } - private static EventResult blockPlace(Level level, BlockPos pos, BlockState state, @Nullable Entity placer) { - return BlockEvents.PLACED.hasListeners(state.getBlock()) ? BlockEvents.PLACED.post(level, state.getBlock(), new BlockPlacedKubeEvent(placer, level, pos, state)).arch() : EventResult.pass(); + @SubscribeEvent + public static void blockPlace(BlockEvent.EntityPlaceEvent event) { + if (event.getLevel() instanceof Level level && BlockEvents.PLACED.hasListeners(event.getPlacedBlock().kjs$getRegistryKey())) { + BlockEvents.PLACED.post(level, event.getPlacedBlock().kjs$getRegistryKey(), new BlockPlacedKubeEvent(event)).applyCancel(event); + } } - private static EventResult farmlandTrample(Level level, BlockPos pos, BlockState state, float distance, @Nullable Entity entity) { - return BlockEvents.FARMLAND_TRAMPLED.hasListeners(state.getBlock()) ? BlockEvents.FARMLAND_TRAMPLED.post(level, state.getBlock(), new FarmlandTrampledKubeEvent(level, pos, state, distance, entity)).arch() : EventResult.pass(); + @SubscribeEvent + public static void farmlandTrample(BlockEvent.FarmlandTrampleEvent event) { + if (event.getLevel() instanceof Level level && BlockEvents.FARMLAND_TRAMPLED.hasListeners(event.getState().kjs$getRegistryKey())) { + BlockEvents.FARMLAND_TRAMPLED.post(level, event.getState().kjs$getRegistryKey(), new FarmlandTrampledKubeEvent(event)).applyCancel(event); + } } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/block/custom/BasicBlockJS.java b/src/main/java/dev/latvian/mods/kubejs/block/custom/BasicBlockJS.java index ed8d0ce3d..889a8f9d0 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/custom/BasicBlockJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/custom/BasicBlockJS.java @@ -338,7 +338,7 @@ public BlockState mirror(BlockState blockState, Mirror mirror) { public ItemInteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { if (blockBuilder.rightClick != null) { if (!level.isClientSide()) { - blockBuilder.rightClick.accept(new BlockRightClickedKubeEvent(stack, player, hand, pos, hit.getDirection())); + blockBuilder.rightClick.accept(new BlockRightClickedKubeEvent(stack, player, hand, pos, hit.getDirection(), hit)); } return ItemInteractionResult.SUCCESS; diff --git a/src/main/java/dev/latvian/mods/kubejs/block/entity/InventoryAttachment.java b/src/main/java/dev/latvian/mods/kubejs/block/entity/InventoryAttachment.java index fb65a194f..8eafe9bcd 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/entity/InventoryAttachment.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/entity/InventoryAttachment.java @@ -57,9 +57,8 @@ public CompoundTag writeAttachment(HolderLookup.Provider registries) { var stack = getItem(i); if (!stack.isEmpty()) { - var itemTag = new CompoundTag(); + var itemTag = (CompoundTag) stack.save(registries, new CompoundTag()); itemTag.putByte("slot", (byte) i); - stack.save(registries, itemTag); list.add(itemTag); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/block/predicate/BlockIDPredicate.java b/src/main/java/dev/latvian/mods/kubejs/block/predicate/BlockIDPredicate.java index 60a1215bb..103152eb0 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/predicate/BlockIDPredicate.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/predicate/BlockIDPredicate.java @@ -2,7 +2,7 @@ import dev.latvian.mods.kubejs.level.BlockContainerJS; import dev.latvian.mods.kubejs.registry.RegistryInfo; -import dev.latvian.mods.kubejs.util.UtilsJS; +import dev.latvian.mods.kubejs.util.Cast; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; @@ -106,7 +106,7 @@ public BlockState getBlockState() { var state = getBlock().defaultBlockState(); for (var object : getBlockProperties()) { - state = state.setValue(object.property, UtilsJS.cast(object.value)); + state = state.setValue(object.property, Cast.to(object.value)); } return state; diff --git a/src/main/java/dev/latvian/mods/kubejs/block/state/BlockStatePredicate.java b/src/main/java/dev/latvian/mods/kubejs/block/state/BlockStatePredicate.java index ecef853e0..78b04e4b0 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/state/BlockStatePredicate.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/state/BlockStatePredicate.java @@ -1,6 +1,7 @@ package dev.latvian.mods.kubejs.block.state; import com.mojang.serialization.DataResult; +import dev.latvian.mods.kubejs.bindings.BlockWrapper; import dev.latvian.mods.kubejs.level.ruletest.AllMatchRuleTest; import dev.latvian.mods.kubejs.level.ruletest.AlwaysFalseRuleTest; import dev.latvian.mods.kubejs.level.ruletest.AnyMatchRuleTest; @@ -12,7 +13,6 @@ import dev.latvian.mods.kubejs.util.NBTUtils; import dev.latvian.mods.kubejs.util.RegExpJS; import dev.latvian.mods.kubejs.util.Tags; -import dev.latvian.mods.kubejs.util.UtilsJS; import dev.latvian.mods.rhino.Context; import net.minecraft.Util; import net.minecraft.core.registries.BuiltInRegistries; @@ -64,7 +64,7 @@ static BlockStatePredicate fromString(String s) { } else if (s.startsWith("#")) { return new TagMatch(Tags.block(new ResourceLocation(s.substring(1)))); } else if (s.indexOf('[') != -1) { - var state = UtilsJS.parseBlockState(s); + var state = BlockWrapper.parseBlockState(s); if (state != Blocks.AIR.defaultBlockState()) { return new StateMatch(state); @@ -159,7 +159,7 @@ private static BlockStatePredicate ofSingle(Object o) { default Collection getBlockStates() { var states = new HashSet(); - for (var state : UtilsJS.getAllBlockStates()) { + for (var state : BlockWrapper.getAllBlockStates()) { if (test(state)) { states.add(state); } @@ -226,7 +226,7 @@ public RuleTest asRuleTest() { @Override public Collection getBlockStates() { - return match ? UtilsJS.getAllBlockStates() : List.of(); + return match ? BlockWrapper.getAllBlockStates() : List.of(); } } @@ -329,9 +329,9 @@ final class RegexMatch implements BlockStatePredicate { public RegexMatch(Pattern p) { pattern = p; matchedBlocks = new LinkedHashSet<>(); - for (var state : UtilsJS.getAllBlockStates()) { + for (var state : BlockWrapper.getAllBlockStates()) { var block = state.getBlock(); - if (!matchedBlocks.contains(block) && pattern.matcher(RegistryInfo.BLOCK.getId(block).toString()).find()) { + if (!matchedBlocks.contains(block) && pattern.matcher(block.kjs$getId()).find()) { matchedBlocks.add(state.getBlock()); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/client/BuiltinKubeJSClientPlugin.java b/src/main/java/dev/latvian/mods/kubejs/client/BuiltinKubeJSClientPlugin.java index 66aec6e8d..86965ad91 100644 --- a/src/main/java/dev/latvian/mods/kubejs/client/BuiltinKubeJSClientPlugin.java +++ b/src/main/java/dev/latvian/mods/kubejs/client/BuiltinKubeJSClientPlugin.java @@ -8,7 +8,7 @@ import dev.latvian.mods.kubejs.util.ScheduledEvents; import net.minecraft.client.Minecraft; -public class BuiltinKubeJSClientPlugin extends KubeJSPlugin { +public class BuiltinKubeJSClientPlugin implements KubeJSPlugin { @Override public void clientInit() { Painter.INSTANCE.registerBuiltinObjects(); diff --git a/src/main/java/dev/latvian/mods/kubejs/client/KubeJSClient.java b/src/main/java/dev/latvian/mods/kubejs/client/KubeJSClient.java index 7eb4110fb..234fe0084 100644 --- a/src/main/java/dev/latvian/mods/kubejs/client/KubeJSClient.java +++ b/src/main/java/dev/latvian/mods/kubejs/client/KubeJSClient.java @@ -2,8 +2,6 @@ import dev.architectury.hooks.PackRepositoryHooks; import dev.architectury.platform.Platform; -import dev.architectury.registry.menu.MenuRegistry; -import dev.latvian.mods.kubejs.CommonProperties; import dev.latvian.mods.kubejs.KubeJS; import dev.latvian.mods.kubejs.KubeJSCommon; import dev.latvian.mods.kubejs.KubeJSPaths; @@ -13,8 +11,6 @@ import dev.latvian.mods.kubejs.bindings.event.NetworkEvents; import dev.latvian.mods.kubejs.client.painter.Painter; import dev.latvian.mods.kubejs.fluid.FluidBuilder; -import dev.latvian.mods.kubejs.gui.KubeJSMenu; -import dev.latvian.mods.kubejs.gui.KubeJSScreen; import dev.latvian.mods.kubejs.item.ItemModelPropertiesKubeEvent; import dev.latvian.mods.kubejs.net.NetworkKubeEvent; import dev.latvian.mods.kubejs.registry.RegistryInfo; @@ -33,6 +29,7 @@ import net.minecraft.util.profiling.InactiveProfiler; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.CreativeModeTabs; +import net.neoforged.bus.api.IEventBus; import org.jetbrains.annotations.Nullable; import java.io.File; @@ -43,7 +40,7 @@ public class KubeJSClient extends KubeJSCommon { @Override - public void init() { + public void init(IEventBus bus) { // You'd think that this is impossible, but not when you use runData gradle task if (Minecraft.getInstance() == null) { return; @@ -51,7 +48,7 @@ public void init() { reloadClientScripts(); - new KubeJSClientEventHandler().init(); + new KubeJSClientEventHandler().init(bus); var list = Minecraft.getInstance().getResourcePackRepository(); PackRepositoryHooks.addSource(list, new KubeJSResourcePackFinder()); @@ -108,10 +105,6 @@ public void clientSetup() { return null; }); - - if (!CommonProperties.get().serverOnly) { - MenuRegistry.registerScreenFactory(KubeJSMenu.KUBEJS_MENU.get(), KubeJSScreen::new); - } } @Override diff --git a/src/main/java/dev/latvian/mods/kubejs/client/KubeJSClientEventHandler.java b/src/main/java/dev/latvian/mods/kubejs/client/KubeJSClientEventHandler.java index 7e23a3473..b0d328cb2 100644 --- a/src/main/java/dev/latvian/mods/kubejs/client/KubeJSClientEventHandler.java +++ b/src/main/java/dev/latvian/mods/kubejs/client/KubeJSClientEventHandler.java @@ -10,6 +10,8 @@ import dev.latvian.mods.kubejs.bindings.event.ClientEvents; import dev.latvian.mods.kubejs.bindings.event.ItemEvents; import dev.latvian.mods.kubejs.client.painter.Painter; +import dev.latvian.mods.kubejs.gui.KubeJSMenus; +import dev.latvian.mods.kubejs.gui.KubeJSScreen; import dev.latvian.mods.kubejs.item.ItemTooltipKubeEvent; import dev.latvian.mods.kubejs.script.ScriptType; import dev.latvian.mods.kubejs.util.ConsoleJS; @@ -32,6 +34,8 @@ import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.material.Fluid; import net.minecraft.world.level.material.Fluids; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.neoforge.client.event.RegisterMenuScreensEvent; import org.jetbrains.annotations.Nullable; import java.util.HashMap; @@ -45,7 +49,7 @@ public class KubeJSClientEventHandler { public static Map> staticItemTooltips = null; private final Map tempTagNames = new LinkedHashMap<>(); - public void init() { + public void init(IEventBus bus) { ClientGuiEvent.DEBUG_TEXT_LEFT.register(this::debugInfoLeft); ClientGuiEvent.DEBUG_TEXT_RIGHT.register(this::debugInfoRight); ClientTooltipEvent.ITEM.register(this::itemTooltip); @@ -56,6 +60,8 @@ public void init() { ClientGuiEvent.RENDER_POST.register(Painter.INSTANCE::guiScreenDraw); ClientGuiEvent.INIT_PRE.register(this::guiPreInit); ClientGuiEvent.INIT_POST.register(this::guiPostInit); + bus.addListener(this::registerMenuScreens); + //ClientTextureStitchEvent.POST.register(this::postAtlasStitch); } @@ -218,4 +224,8 @@ private void guiPostInit(Screen screen, ScreenAccess access) { ex.printStackTrace(); } }*/ + + private void registerMenuScreens(RegisterMenuScreensEvent event) { + event.register(KubeJSMenus.MENU.get(), KubeJSScreen::new); + } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/client/KubeJSErrorScreen.java b/src/main/java/dev/latvian/mods/kubejs/client/KubeJSErrorScreen.java index 909fff88e..7efa8114f 100644 --- a/src/main/java/dev/latvian/mods/kubejs/client/KubeJSErrorScreen.java +++ b/src/main/java/dev/latvian/mods/kubejs/client/KubeJSErrorScreen.java @@ -5,7 +5,7 @@ import dev.latvian.mods.kubejs.script.ScriptType; import dev.latvian.mods.kubejs.util.ConsoleJS; import dev.latvian.mods.kubejs.util.LogType; -import dev.latvian.mods.kubejs.util.UtilsJS; +import dev.latvian.mods.kubejs.util.TimeJS; import net.minecraft.ChatFormatting; import net.minecraft.Util; import net.minecraft.client.Minecraft; @@ -191,7 +191,7 @@ public Entry(ErrorList errorList, Minecraft minecraft, int index, ConsoleLine li var sb = new StringBuilder(); calendar.setTimeInMillis(line.timestamp); - UtilsJS.appendTimestamp(sb, calendar); + TimeJS.appendTimestamp(sb, calendar); this.timestampText = Component.literal(sb.toString()).getVisualOrderText(); this.errorText = new ArrayList<>(minecraft.font.split(Component.literal(line.message), errorList.getRowWidth()).stream().limit(3L).toList()); diff --git a/src/main/java/dev/latvian/mods/kubejs/command/KubeJSCommands.java b/src/main/java/dev/latvian/mods/kubejs/command/KubeJSCommands.java index 67e8acd4e..59608a0ae 100644 --- a/src/main/java/dev/latvian/mods/kubejs/command/KubeJSCommands.java +++ b/src/main/java/dev/latvian/mods/kubejs/command/KubeJSCommands.java @@ -459,7 +459,7 @@ private static int dumpEvents(CommandSourceStack source) { builder.append("```js\n"); builder.append(fullName).append('('); if (handler.extra != null) { - builder.append(handler.extra.required ? "extra_id, " : "/* extra_id (optional), */ "); + builder.append(handler.extraRequired ? "extra_id, " : "/* extra_id (optional), */ "); } builder.append("(event) => {\n"); builder.append("\t// This space (un)intentionally left blank\n"); @@ -514,7 +514,7 @@ private static int help(CommandSourceStack source) { } private static int customCommand(CommandSourceStack source, String id) { - if (ServerEvents.CUSTOM_COMMAND.hasListeners()) { + if (ServerEvents.CUSTOM_COMMAND.hasListeners(id)) { var result = ServerEvents.CUSTOM_COMMAND.post(new CustomCommandKubeEvent(source.getLevel(), source.getEntity(), BlockPos.containing(source.getPosition()), id), id); if (result.type() == EventResult.Type.ERROR) { diff --git a/src/main/java/dev/latvian/mods/kubejs/core/AdvancementNodeKJS.java b/src/main/java/dev/latvian/mods/kubejs/core/AdvancementNodeKJS.java new file mode 100644 index 000000000..ddc123e6e --- /dev/null +++ b/src/main/java/dev/latvian/mods/kubejs/core/AdvancementNodeKJS.java @@ -0,0 +1,55 @@ +package dev.latvian.mods.kubejs.core; + +import dev.latvian.mods.rhino.util.RemapPrefixForJS; +import net.minecraft.advancements.AdvancementNode; +import net.minecraft.advancements.DisplayInfo; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; +import org.jetbrains.annotations.Nullable; + +import java.util.Set; + +@RemapPrefixForJS("kjs$") +public interface AdvancementNodeKJS { + default AdvancementNode kjs$self() { + return (AdvancementNode) this; + } + + default ResourceLocation kjs$getId() { + return kjs$self().holder().id(); + } + + @Nullable + default AdvancementNode kjs$getParent() { + return kjs$self().parent(); + } + + default Set kjs$getChildren() { + return (Set) kjs$self().children(); + } + + default void kjs$addChild(AdvancementNode a) { + kjs$self().addChild(a); + } + + default Component kjs$getDisplayText() { + return kjs$self().advancement().name().orElse(Component.empty()); + } + + default boolean kjs$hasDisplay() { + return kjs$self().advancement().display().isPresent(); + } + + default Component kjs$getTitle() { + return kjs$self().advancement().display().map(DisplayInfo::getTitle).orElse(Component.empty()); + } + + default Component kjs$getDescription() { + return kjs$self().advancement().display().map(DisplayInfo::getDescription).orElse(Component.empty()); + } + + @Nullable + default DisplayInfo kjs$getDisplay() { + return kjs$self().advancement().display().orElse(null); + } +} diff --git a/src/main/java/dev/latvian/mods/kubejs/core/BlockKJS.java b/src/main/java/dev/latvian/mods/kubejs/core/BlockKJS.java index a57a4dea2..6ce413b50 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/BlockKJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/BlockKJS.java @@ -2,9 +2,10 @@ import dev.latvian.mods.kubejs.block.BlockBuilder; import dev.latvian.mods.kubejs.block.RandomTickCallbackJS; -import dev.latvian.mods.kubejs.util.UtilsJS; +import dev.latvian.mods.kubejs.registry.RegistryInfo; import dev.latvian.mods.rhino.util.RemapPrefixForJS; import net.minecraft.nbt.CompoundTag; +import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.SoundType; @@ -14,13 +15,23 @@ import java.util.function.Consumer; @RemapPrefixForJS("kjs$") -public interface BlockKJS extends BlockBuilderProvider { +public interface BlockKJS extends BlockBuilderProvider, WithRegistryKeyKJS { default void kjs$setBlockBuilder(BlockBuilder b) { throw new NoMixinException(); } + @Override + default RegistryInfo kjs$getKubeRegistry() { + return RegistryInfo.BLOCK; + } + + @Override + default ResourceKey kjs$getRegistryKey() { + throw new NoMixinException(); + } + default ResourceLocation kjs$getIdLocation() { - return UtilsJS.UNKNOWN_ID; + return kjs$getRegistryKey().location(); } default String kjs$getId() { diff --git a/src/main/java/dev/latvian/mods/kubejs/core/BlockStateKJS.java b/src/main/java/dev/latvian/mods/kubejs/core/BlockStateKJS.java index f8e2219bd..eef6d6f3c 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/BlockStateKJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/BlockStateKJS.java @@ -1,9 +1,23 @@ package dev.latvian.mods.kubejs.core; +import dev.latvian.mods.kubejs.registry.RegistryInfo; import dev.latvian.mods.rhino.util.RemapPrefixForJS; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; @RemapPrefixForJS("kjs$") -public interface BlockStateKJS { +public interface BlockStateKJS extends WithRegistryKeyKJS { + @Override + default RegistryInfo kjs$getKubeRegistry() { + return RegistryInfo.BLOCK; + } + + @Override + default ResourceKey kjs$getRegistryKey() { + return ((BlockState) this).getBlock().kjs$getRegistryKey(); + } + default void kjs$setDestroySpeed(float v) { throw new NoMixinException(); } diff --git a/src/main/java/dev/latvian/mods/kubejs/core/EntityTypeKJS.java b/src/main/java/dev/latvian/mods/kubejs/core/EntityTypeKJS.java new file mode 100644 index 000000000..45fcb486c --- /dev/null +++ b/src/main/java/dev/latvian/mods/kubejs/core/EntityTypeKJS.java @@ -0,0 +1,11 @@ +package dev.latvian.mods.kubejs.core; + +import dev.latvian.mods.kubejs.registry.RegistryInfo; +import net.minecraft.world.entity.EntityType; + +public interface EntityTypeKJS extends WithRegistryKeyKJS> { + @Override + default RegistryInfo kjs$getKubeRegistry() { + return RegistryInfo.ENTITY_TYPE; + } +} diff --git a/src/main/java/dev/latvian/mods/kubejs/core/IngredientKJS.java b/src/main/java/dev/latvian/mods/kubejs/core/IngredientKJS.java index 2171c25f2..32f8237fd 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/IngredientKJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/IngredientKJS.java @@ -100,11 +100,11 @@ public interface IngredientKJS extends IngredientSupplierKJS, JsonSerializable { } default InputItem kjs$asStack() { - return InputItem.of(kjs$self(), 1); + return InputItem.create(kjs$self(), 1); } default InputItem kjs$withCount(int count) { - return InputItem.of(kjs$self(), count); + return InputItem.create(kjs$self(), count); } default boolean kjs$isWildcard() { diff --git a/src/main/java/dev/latvian/mods/kubejs/core/ItemKJS.java b/src/main/java/dev/latvian/mods/kubejs/core/ItemKJS.java index 58abb6c1e..0c66076c9 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/ItemKJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/ItemKJS.java @@ -4,7 +4,7 @@ import dev.latvian.mods.kubejs.item.ItemBuilder; import dev.latvian.mods.kubejs.item.ItemStackKey; import dev.latvian.mods.kubejs.item.MutableToolTier; -import dev.latvian.mods.kubejs.util.UtilsJS; +import dev.latvian.mods.kubejs.registry.RegistryInfo; import dev.latvian.mods.rhino.util.RemapPrefixForJS; import net.minecraft.Util; import net.minecraft.core.component.DataComponentType; @@ -18,7 +18,7 @@ import java.util.function.Consumer; @RemapPrefixForJS("kjs$") -public interface ItemKJS extends IngredientSupplierKJS { +public interface ItemKJS extends IngredientSupplierKJS, WithRegistryKeyKJS { @Nullable default ItemBuilder kjs$getItemBuilder() { throw new NoMixinException(); @@ -28,8 +28,13 @@ public interface ItemKJS extends IngredientSupplierKJS { throw new NoMixinException(); } + @Override + default RegistryInfo kjs$getKubeRegistry() { + return RegistryInfo.ITEM; + } + default ResourceLocation kjs$getIdLocation() { - return UtilsJS.UNKNOWN_ID; + return kjs$getRegistryKey().location(); } default String kjs$getId() { diff --git a/src/main/java/dev/latvian/mods/kubejs/core/ItemStackKJS.java b/src/main/java/dev/latvian/mods/kubejs/core/ItemStackKJS.java index dab5d8a41..b5a1f6665 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/ItemStackKJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/ItemStackKJS.java @@ -10,10 +10,10 @@ import dev.latvian.mods.kubejs.registry.RegistryInfo; import dev.latvian.mods.kubejs.script.KubeJSContext; import dev.latvian.mods.kubejs.util.ConsoleJS; +import dev.latvian.mods.kubejs.util.ID; import dev.latvian.mods.kubejs.util.JsonSerializable; import dev.latvian.mods.kubejs.util.NBTSerializable; import dev.latvian.mods.kubejs.util.Tags; -import dev.latvian.mods.kubejs.util.UtilsJS; import dev.latvian.mods.rhino.Context; import dev.latvian.mods.rhino.util.RemapForJS; import dev.latvian.mods.rhino.util.RemapPrefixForJS; @@ -51,7 +51,7 @@ public interface ItemStackKJS extends SpecialEquality, NBTSerializable, JsonSeri @Override default boolean specialEquals(Context cx, Object o, boolean shallow) { if (o instanceof CharSequence) { - return kjs$getId().equals(UtilsJS.getID(o.toString())); + return kjs$getId().equals(ID.string(o.toString())); } else if (o instanceof ItemStack s) { return kjs$equalsIgnoringCount(s); } @@ -147,7 +147,7 @@ default boolean specialEquals(Context cx, Object o, boolean shallow) { var is = kjs$self(); for (var entry : enchantments.entrySet()) { - var enchantment = RegistryInfo.ENCHANTMENT.getValue(UtilsJS.getMCID(null, entry.getKey())); + var enchantment = RegistryInfo.ENCHANTMENT.getValue(ID.mc(entry.getKey())); if (enchantment != null && entry.getValue() instanceof Number number) { is = is.kjs$enchantCopy(enchantment, number.intValue()); @@ -252,7 +252,7 @@ default JsonElement toJsonJS() { } default OutputItem kjs$withChance(double chance) { - return OutputItem.of(kjs$self(), chance); + return OutputItem.create(kjs$self(), chance); } default ItemStack kjs$withLore(Component[] lines) { diff --git a/src/main/java/dev/latvian/mods/kubejs/core/LivingEntityKJS.java b/src/main/java/dev/latvian/mods/kubejs/core/LivingEntityKJS.java index ed18debaf..fa5d7a94f 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/LivingEntityKJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/LivingEntityKJS.java @@ -40,8 +40,10 @@ public interface LivingEntityKJS extends EntityKJS { b.foodBuilder.eaten.accept(event); } - if (ItemEvents.FOOD_EATEN.hasListeners()) { - ItemEvents.FOOD_EATEN.post(entity, i, event); + var key = i.kjs$getRegistryKey(); + + if (ItemEvents.FOOD_EATEN.hasListeners(key)) { + ItemEvents.FOOD_EATEN.post(entity, key, event); } } } diff --git a/src/main/java/dev/latvian/mods/kubejs/core/MenuTypeKJS.java b/src/main/java/dev/latvian/mods/kubejs/core/MenuTypeKJS.java new file mode 100644 index 000000000..07c6ed924 --- /dev/null +++ b/src/main/java/dev/latvian/mods/kubejs/core/MenuTypeKJS.java @@ -0,0 +1,11 @@ +package dev.latvian.mods.kubejs.core; + +import dev.latvian.mods.kubejs.registry.RegistryInfo; +import net.minecraft.world.inventory.MenuType; + +public interface MenuTypeKJS extends WithRegistryKeyKJS> { + @Override + default RegistryInfo kjs$getKubeRegistry() { + return RegistryInfo.MENU; + } +} diff --git a/src/main/java/dev/latvian/mods/kubejs/core/MinecraftClientKJS.java b/src/main/java/dev/latvian/mods/kubejs/core/MinecraftClientKJS.java index acf4a609b..181cba5c3 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/MinecraftClientKJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/MinecraftClientKJS.java @@ -88,7 +88,11 @@ public interface MinecraftClientKJS extends MinecraftEnvironmentKJS { if (ItemEvents.FIRST_LEFT_CLICKED.hasListeners()) { var player = kjs$self().player; var stack = player.getItemInHand(InteractionHand.MAIN_HAND); - ItemEvents.FIRST_LEFT_CLICKED.post(ScriptType.CLIENT, stack.getItem(), new ItemClickedKubeEvent(player, InteractionHand.MAIN_HAND, stack)); + var key = stack.getItem().kjs$getRegistryKey(); + + if (ItemEvents.FIRST_LEFT_CLICKED.hasListeners(key)) { + ItemEvents.FIRST_LEFT_CLICKED.post(ScriptType.CLIENT, key, new ItemClickedKubeEvent(player, InteractionHand.MAIN_HAND, stack)); + } } PacketDistributor.sendToServer(new FirstClickPayload(0)); @@ -101,7 +105,11 @@ public interface MinecraftClientKJS extends MinecraftEnvironmentKJS { for (var hand : InteractionHand.values()) { var stack = player.getItemInHand(hand); - ItemEvents.FIRST_RIGHT_CLICKED.post(ScriptType.CLIENT, stack.getItem(), new ItemClickedKubeEvent(player, hand, stack)); + var key = stack.getItem().kjs$getRegistryKey(); + + if (ItemEvents.FIRST_RIGHT_CLICKED.hasListeners(key)) { + ItemEvents.FIRST_RIGHT_CLICKED.post(ScriptType.CLIENT, key, new ItemClickedKubeEvent(player, hand, stack)); + } } } diff --git a/src/main/java/dev/latvian/mods/kubejs/core/MinecraftServerKJS.java b/src/main/java/dev/latvian/mods/kubejs/core/MinecraftServerKJS.java index d14e12a38..759dffd8b 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/MinecraftServerKJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/MinecraftServerKJS.java @@ -2,13 +2,13 @@ import dev.latvian.mods.kubejs.CommonProperties; import dev.latvian.mods.kubejs.net.SendDataFromServerPayload; -import dev.latvian.mods.kubejs.player.AdvancementJS; import dev.latvian.mods.kubejs.player.EntityArrayList; import dev.latvian.mods.kubejs.server.DataExport; import dev.latvian.mods.kubejs.util.ConsoleJS; import dev.latvian.mods.rhino.util.HideFromJS; import dev.latvian.mods.rhino.util.RemapPrefixForJS; import net.minecraft.ChatFormatting; +import net.minecraft.advancements.AdvancementNode; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; @@ -87,9 +87,8 @@ public interface MinecraftServerKJS extends WithAttachedData, W } @Nullable - default AdvancementJS kjs$getAdvancement(ResourceLocation id) { - var a = kjs$self().getAdvancements().tree().get(id); - return a == null ? null : new AdvancementJS(a); + default AdvancementNode kjs$getAdvancement(ResourceLocation id) { + return kjs$self().getAdvancements().tree().get(id); } @Override diff --git a/src/main/java/dev/latvian/mods/kubejs/core/RecipeHolderKJS.java b/src/main/java/dev/latvian/mods/kubejs/core/RecipeHolderKJS.java index fbff32a94..c996c0b17 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/RecipeHolderKJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/RecipeHolderKJS.java @@ -18,7 +18,7 @@ @RemapPrefixForJS("kjs$") public interface RecipeHolderKJS extends RecipeLikeKJS { default RecipeHolder kjs$self() { - return UtilsJS.cast(this); + return (RecipeHolder) this; } default Recipe kjs$getRecipe() { diff --git a/src/main/java/dev/latvian/mods/kubejs/core/RecipeManagerKJS.java b/src/main/java/dev/latvian/mods/kubejs/core/RecipeManagerKJS.java new file mode 100644 index 000000000..d976cb20d --- /dev/null +++ b/src/main/java/dev/latvian/mods/kubejs/core/RecipeManagerKJS.java @@ -0,0 +1,4 @@ +package dev.latvian.mods.kubejs.core; + +public interface RecipeManagerKJS extends ReloadableServerResourceHolderKJS { +} \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/core/ReloadableServerResourceHolderKJS.java b/src/main/java/dev/latvian/mods/kubejs/core/ReloadableServerResourceHolderKJS.java new file mode 100644 index 000000000..80454221c --- /dev/null +++ b/src/main/java/dev/latvian/mods/kubejs/core/ReloadableServerResourceHolderKJS.java @@ -0,0 +1,7 @@ +package dev.latvian.mods.kubejs.core; + +public interface ReloadableServerResourceHolderKJS { + void kjs$setResources(ReloadableServerResourcesKJS resources); + + ReloadableServerResourcesKJS kjs$getResources(); +} \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/core/ServerPlayerKJS.java b/src/main/java/dev/latvian/mods/kubejs/core/ServerPlayerKJS.java index 370462ecd..df4d8b3a7 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/ServerPlayerKJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/ServerPlayerKJS.java @@ -96,17 +96,17 @@ public interface ServerPlayerKJS extends PlayerKJS { default boolean kjs$isAdvancementDone(ResourceLocation id) { var a = kjs$self().server.kjs$getAdvancement(id); - return a != null && kjs$self().getAdvancements().getOrStartProgress(a.holder).isDone(); + return a != null && kjs$self().getAdvancements().getOrStartProgress(a.holder()).isDone(); } default void kjs$unlockAdvancement(ResourceLocation id) { var a = kjs$self().server.kjs$getAdvancement(id); if (a != null) { - var advancementprogress = kjs$self().getAdvancements().getOrStartProgress(a.holder); + var advancementprogress = kjs$self().getAdvancements().getOrStartProgress(a.holder()); for (var s : advancementprogress.getRemainingCriteria()) { - kjs$self().getAdvancements().award(a.holder, s); + kjs$self().getAdvancements().award(a.holder(), s); } } } @@ -115,11 +115,11 @@ public interface ServerPlayerKJS extends PlayerKJS { var a = kjs$self().server.kjs$getAdvancement(id); if (a != null) { - var advancementprogress = kjs$self().getAdvancements().getOrStartProgress(a.holder); + var advancementprogress = kjs$self().getAdvancements().getOrStartProgress(a.holder()); if (advancementprogress.hasProgress()) { for (var s : advancementprogress.getCompletedCriteria()) { - kjs$self().getAdvancements().revoke(a.holder, s); + kjs$self().getAdvancements().revoke(a.holder(), s); } } } diff --git a/src/main/java/dev/latvian/mods/kubejs/core/TagLoaderKJS.java b/src/main/java/dev/latvian/mods/kubejs/core/TagLoaderKJS.java index d48e44a1d..13d8452a0 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/TagLoaderKJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/TagLoaderKJS.java @@ -29,7 +29,7 @@ public interface TagLoaderKJS { var regInfo = RegistryInfo.of(reg.key()); - if (regInfo.hasDefaultTags || ServerEvents.TAGS.hasListeners(reg.key())) { + if (regInfo.hasDefaultTags || ServerEvents.TAGS.hasListeners(regInfo.key)) { var preEvent = kjs$getResources().kjs$getServerScriptManager().preTagEvents.get(reg.key()); var event = new TagKubeEvent(regInfo, reg); @@ -50,7 +50,7 @@ public interface TagLoaderKJS { } if (preEvent == null) { - ServerEvents.TAGS.post(event, regInfo.key, TagKubeEvent.TAG_EVENT_HANDLER); + ServerEvents.TAGS.post(event, regInfo.key); } else { for (var a : preEvent.actions) { a.accept(event); diff --git a/src/main/java/dev/latvian/mods/kubejs/core/TagManagerKJS.java b/src/main/java/dev/latvian/mods/kubejs/core/TagManagerKJS.java index 2e7d3dfa2..8d7a1990f 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/TagManagerKJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/TagManagerKJS.java @@ -1,7 +1,4 @@ package dev.latvian.mods.kubejs.core; -public interface TagManagerKJS { - void kjs$setResources(ReloadableServerResourcesKJS resources); - - ReloadableServerResourcesKJS kjs$getResources(); +public interface TagManagerKJS extends ReloadableServerResourceHolderKJS { } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/core/WithRegistryKeyKJS.java b/src/main/java/dev/latvian/mods/kubejs/core/WithRegistryKeyKJS.java new file mode 100644 index 000000000..937b3d3c6 --- /dev/null +++ b/src/main/java/dev/latvian/mods/kubejs/core/WithRegistryKeyKJS.java @@ -0,0 +1,17 @@ +package dev.latvian.mods.kubejs.core; + +import dev.latvian.mods.kubejs.registry.RegistryInfo; +import dev.latvian.mods.kubejs.util.Cast; +import dev.latvian.mods.rhino.util.RemapPrefixForJS; +import net.minecraft.resources.ResourceKey; + +@RemapPrefixForJS("kjs$") +public interface WithRegistryKeyKJS { + default RegistryInfo kjs$getKubeRegistry() { + throw new NoMixinException(); + } + + default ResourceKey kjs$getRegistryKey() { + return kjs$getKubeRegistry().getKeyOf(Cast.to(this)); + } +} diff --git a/src/main/java/dev/latvian/mods/kubejs/core/mixin/AdvancementNodeMixin.java b/src/main/java/dev/latvian/mods/kubejs/core/mixin/AdvancementNodeMixin.java new file mode 100644 index 000000000..ec276d153 --- /dev/null +++ b/src/main/java/dev/latvian/mods/kubejs/core/mixin/AdvancementNodeMixin.java @@ -0,0 +1,11 @@ +package dev.latvian.mods.kubejs.core.mixin; + +import dev.latvian.mods.kubejs.core.AdvancementNodeKJS; +import dev.latvian.mods.rhino.util.RemapPrefixForJS; +import net.minecraft.advancements.AdvancementNode; +import org.spongepowered.asm.mixin.Mixin; + +@Mixin(AdvancementNode.class) +@RemapPrefixForJS("kjs$") +public abstract class AdvancementNodeMixin implements AdvancementNodeKJS { +} diff --git a/src/main/java/dev/latvian/mods/kubejs/core/mixin/BlockBehaviourMixin.java b/src/main/java/dev/latvian/mods/kubejs/core/mixin/BlockBehaviourMixin.java index 9c934a3e8..cf65829c6 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/mixin/BlockBehaviourMixin.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/mixin/BlockBehaviourMixin.java @@ -5,11 +5,11 @@ import dev.latvian.mods.kubejs.core.BlockKJS; import dev.latvian.mods.kubejs.level.BlockContainerJS; import dev.latvian.mods.kubejs.registry.RegistryInfo; -import dev.latvian.mods.kubejs.util.UtilsJS; import dev.latvian.mods.rhino.util.RemapPrefixForJS; import net.minecraft.core.BlockPos; +import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.ResourceKey; import net.minecraft.server.level.ServerLevel; import net.minecraft.util.RandomSource; import net.minecraft.world.level.block.Block; @@ -31,22 +31,26 @@ public abstract class BlockBehaviourMixin implements BlockKJS { private BlockBuilder kjs$blockBuilder; private CompoundTag kjs$typeData; - private ResourceLocation kjs$id; + private ResourceKey kjs$registryKey; private String kjs$idString; private Consumer kjs$randomTickCallback; @Override - public ResourceLocation kjs$getIdLocation() { - if (kjs$id == null) { + public ResourceKey kjs$getRegistryKey() { + if (kjs$registryKey == null) { if ((Object) this instanceof Block block) { - var id = RegistryInfo.BLOCK.getId(block); - kjs$id = id == null ? UtilsJS.UNKNOWN_ID : id; + try { + kjs$registryKey = block.builtInRegistryHolder().key(); + } catch (Exception ex) { + var id = RegistryInfo.BLOCK.getId(block); + kjs$registryKey = id == null ? RegistryInfo.BLOCK.unknownKey : ResourceKey.create(Registries.BLOCK, id); + } } else { - kjs$id = UtilsJS.UNKNOWN_ID; + kjs$registryKey = RegistryInfo.BLOCK.unknownKey; } } - return kjs$id; + return kjs$registryKey; } @Override diff --git a/src/main/java/dev/latvian/mods/kubejs/core/mixin/EntityTypeMixin.java b/src/main/java/dev/latvian/mods/kubejs/core/mixin/EntityTypeMixin.java new file mode 100644 index 000000000..c3496dcff --- /dev/null +++ b/src/main/java/dev/latvian/mods/kubejs/core/mixin/EntityTypeMixin.java @@ -0,0 +1,9 @@ +package dev.latvian.mods.kubejs.core.mixin; + +import dev.latvian.mods.kubejs.core.EntityTypeKJS; +import net.minecraft.world.entity.EntityType; +import org.spongepowered.asm.mixin.Mixin; + +@Mixin(EntityType.class) +public abstract class EntityTypeMixin implements EntityTypeKJS { +} diff --git a/src/main/java/dev/latvian/mods/kubejs/core/mixin/ItemMixin.java b/src/main/java/dev/latvian/mods/kubejs/core/mixin/ItemMixin.java index c0527c682..3674772fc 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/mixin/ItemMixin.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/mixin/ItemMixin.java @@ -4,14 +4,14 @@ import dev.latvian.mods.kubejs.item.ItemBuilder; import dev.latvian.mods.kubejs.item.ItemStackKey; import dev.latvian.mods.kubejs.registry.RegistryInfo; -import dev.latvian.mods.kubejs.util.UtilsJS; import dev.latvian.mods.rhino.util.RemapForJS; import dev.latvian.mods.rhino.util.RemapPrefixForJS; import net.minecraft.core.component.DataComponentMap; import net.minecraft.core.component.DataComponentType; +import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.ResourceKey; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.entity.LivingEntity; @@ -45,7 +45,7 @@ public abstract class ItemMixin implements ItemKJS { private CompoundTag kjs$typeData; private Ingredient kjs$asIngredient; private ItemStackKey kjs$typeItemStackKey; - private ResourceLocation kjs$id; + private ResourceKey kjs$registryKey; private String kjs$idString; @Override @@ -61,13 +61,17 @@ public abstract class ItemMixin implements ItemKJS { } @Override - public ResourceLocation kjs$getIdLocation() { - if (kjs$id == null) { - var id = RegistryInfo.ITEM.getId(kjs$self()); - kjs$id = id == null ? UtilsJS.UNKNOWN_ID : id; + public ResourceKey kjs$getRegistryKey() { + if (kjs$registryKey == null) { + try { + kjs$registryKey = kjs$self().builtInRegistryHolder().key(); + } catch (Exception ex) { + var id = RegistryInfo.ITEM.getId(kjs$self()); + kjs$registryKey = id == null ? RegistryInfo.ITEM.unknownKey : ResourceKey.create(Registries.ITEM, id); + } } - return kjs$id; + return kjs$registryKey; } @Override diff --git a/src/main/java/dev/latvian/mods/kubejs/core/mixin/MenuTypeMixin.java b/src/main/java/dev/latvian/mods/kubejs/core/mixin/MenuTypeMixin.java new file mode 100644 index 000000000..55fa1de73 --- /dev/null +++ b/src/main/java/dev/latvian/mods/kubejs/core/mixin/MenuTypeMixin.java @@ -0,0 +1,9 @@ +package dev.latvian.mods.kubejs.core.mixin; + +import dev.latvian.mods.kubejs.core.MenuTypeKJS; +import net.minecraft.world.inventory.MenuType; +import org.spongepowered.asm.mixin.Mixin; + +@Mixin(MenuType.class) +public abstract class MenuTypeMixin implements MenuTypeKJS { +} diff --git a/src/main/java/dev/latvian/mods/kubejs/core/mixin/PlayerListMixin.java b/src/main/java/dev/latvian/mods/kubejs/core/mixin/PlayerListMixin.java index e67b981b0..2b07b9ea9 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/mixin/PlayerListMixin.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/mixin/PlayerListMixin.java @@ -1,12 +1,7 @@ package dev.latvian.mods.kubejs.core.mixin; -import dev.latvian.mods.kubejs.player.KubeJSPlayerEventHandler; -import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.players.PlayerList; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(PlayerList.class) public abstract class PlayerListMixin { @@ -25,9 +20,4 @@ private void canPlayerLoginKJS(SocketAddress address, GameProfile gameProfile, C } } */ - - @Inject(method = "respawn", at = @At("RETURN")) - private void kjs$respawn(ServerPlayer serverPlayer, boolean keepData, CallbackInfoReturnable cir) { - KubeJSPlayerEventHandler.respawn(serverPlayer, cir.getReturnValue(), keepData); - } } diff --git a/src/main/java/dev/latvian/mods/kubejs/core/mixin/RecipeManagerMixin.java b/src/main/java/dev/latvian/mods/kubejs/core/mixin/RecipeManagerMixin.java index 1899ba5d5..f7cac7d99 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/mixin/RecipeManagerMixin.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/mixin/RecipeManagerMixin.java @@ -2,16 +2,19 @@ import com.google.gson.JsonElement; import dev.latvian.mods.kubejs.bindings.event.ServerEvents; +import dev.latvian.mods.kubejs.core.RecipeManagerKJS; +import dev.latvian.mods.kubejs.core.ReloadableServerResourcesKJS; import dev.latvian.mods.kubejs.recipe.CompostableRecipesKubeEvent; import dev.latvian.mods.kubejs.recipe.RecipesKubeEvent; import dev.latvian.mods.kubejs.script.ScriptType; +import dev.latvian.mods.kubejs.util.Cast; import dev.latvian.mods.kubejs.util.ConsoleJS; -import dev.latvian.mods.kubejs.util.UtilsJS; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.ResourceManager; import net.minecraft.util.profiling.ProfilerFiller; import net.minecraft.world.item.crafting.RecipeManager; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @@ -19,7 +22,10 @@ import java.util.Map; @Mixin(value = RecipeManager.class, priority = 1100) -public abstract class RecipeManagerMixin { +public abstract class RecipeManagerMixin implements RecipeManagerKJS { + @Unique + private ReloadableServerResourcesKJS kjs$resources; + @Inject(method = "apply*", at = @At("HEAD"), cancellable = true) private void customRecipesHead(Map map, ResourceManager resourceManager, ProfilerFiller profiler, CallbackInfo ci) { if (ServerEvents.COMPOSTABLE_RECIPES.hasListeners()) { @@ -28,7 +34,7 @@ private void customRecipesHead(Map map, ResourceM if (ServerEvents.RECIPES.hasListeners()) { if (RecipesKubeEvent.instance != null) { - RecipesKubeEvent.instance.post(UtilsJS.cast(this), map); + RecipesKubeEvent.instance.post(Cast.to(this), map); RecipesKubeEvent.instance = null; ci.cancel(); } else { @@ -36,4 +42,14 @@ private void customRecipesHead(Map map, ResourceM } } } + + @Override + public void kjs$setResources(ReloadableServerResourcesKJS resources) { + kjs$resources = resources; + } + + @Override + public ReloadableServerResourcesKJS kjs$getResources() { + return kjs$resources; + } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/core/mixin/ReloadableServerResourcesMixin.java b/src/main/java/dev/latvian/mods/kubejs/core/mixin/ReloadableServerResourcesMixin.java index 2366d4fcc..10c271180 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/mixin/ReloadableServerResourcesMixin.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/mixin/ReloadableServerResourcesMixin.java @@ -1,14 +1,17 @@ package dev.latvian.mods.kubejs.core.mixin; +import dev.latvian.mods.kubejs.core.RecipeManagerKJS; import dev.latvian.mods.kubejs.core.ReloadableServerResourcesKJS; import dev.latvian.mods.kubejs.core.TagManagerKJS; import dev.latvian.mods.kubejs.item.ingredient.TagContext; import dev.latvian.mods.kubejs.server.ServerScriptManager; +import dev.latvian.mods.kubejs.util.UtilsJS; import net.minecraft.commands.Commands; import net.minecraft.core.RegistryAccess; import net.minecraft.server.ReloadableServerResources; import net.minecraft.tags.TagManager; import net.minecraft.world.flag.FeatureFlagSet; +import net.minecraft.world.item.crafting.RecipeManager; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -26,11 +29,17 @@ public abstract class ReloadableServerResourcesMixin implements ReloadableServer @Final public TagManager tagManager; + @Shadow + @Final + private RecipeManager recipes; + @Inject(method = "", at = @At("RETURN")) private void init(RegistryAccess.Frozen registryAccess, FeatureFlagSet featureFlagSet, Commands.CommandSelection commandSelection, int functionCompilationLevel, CallbackInfo ci) { + UtilsJS.staticResources = (ReloadableServerResources) (Object) this; + UtilsJS.staticRegistryAccess = registryAccess; kjs$serverScriptManager = new ServerScriptManager((ReloadableServerResources) (Object) this, registryAccess); ((TagManagerKJS) tagManager).kjs$setResources(this); - kjs$serverScriptManager.updateResources((ReloadableServerResources) (Object) this, registryAccess); + ((RecipeManagerKJS) recipes).kjs$setResources(this); } @Inject(method = "updateRegistryTags(Lnet/minecraft/core/RegistryAccess;Lnet/minecraft/tags/TagManager$LoadResult;)V", at = @At("RETURN")) diff --git a/src/main/java/dev/latvian/mods/kubejs/entity/CheckLivingEntitySpawnKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/entity/CheckLivingEntitySpawnKubeEvent.java index 531c97cde..35eb4d832 100644 --- a/src/main/java/dev/latvian/mods/kubejs/entity/CheckLivingEntitySpawnKubeEvent.java +++ b/src/main/java/dev/latvian/mods/kubejs/entity/CheckLivingEntitySpawnKubeEvent.java @@ -1,12 +1,15 @@ package dev.latvian.mods.kubejs.entity; +import com.mojang.datafixers.util.Either; import dev.latvian.mods.kubejs.level.BlockContainerJS; +import dev.latvian.mods.kubejs.level.SpawnerJS; import dev.latvian.mods.kubejs.typings.Info; import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.MobSpawnType; -import net.minecraft.world.level.BaseSpawner; import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; import org.jetbrains.annotations.Nullable; @Info(""" @@ -19,19 +22,20 @@ public class CheckLivingEntitySpawnKubeEvent implements KubeLivingEntityEvent { private final Level level; public final double x, y, z; - public final MobSpawnType type; + public final transient MobSpawnType type; + private final Either spawnerEither; @Nullable - public final BaseSpawner spawner; + public transient SpawnerJS spawner; - public CheckLivingEntitySpawnKubeEvent(LivingEntity entity, Level level, double x, double y, double z, MobSpawnType type, @Nullable BaseSpawner spawner) { + public CheckLivingEntitySpawnKubeEvent(LivingEntity entity, Level level, double x, double y, double z, MobSpawnType type, Either spawnerEither) { this.entity = entity; this.level = level; this.x = x; this.y = y; this.z = z; this.type = type; - this.spawner = spawner; + this.spawnerEither = spawnerEither; } @Override @@ -58,7 +62,11 @@ public MobSpawnType getType() { @Info("The spawner that spawned the entity. Can be null if the entity was spawned by worldgen.") @Nullable - public BaseSpawner getSpawner() { + public SpawnerJS getSpawner() { + if (spawner == null) { + spawner = SpawnerJS.of(spawnerEither); + } + return spawner; } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/entity/KubeJSEntityEventHandler.java b/src/main/java/dev/latvian/mods/kubejs/entity/KubeJSEntityEventHandler.java index 875f33780..3fba6f983 100644 --- a/src/main/java/dev/latvian/mods/kubejs/entity/KubeJSEntityEventHandler.java +++ b/src/main/java/dev/latvian/mods/kubejs/entity/KubeJSEntityEventHandler.java @@ -1,47 +1,79 @@ package dev.latvian.mods.kubejs.entity; -import dev.architectury.event.EventResult; -import dev.architectury.event.events.common.EntityEvent; +import dev.latvian.mods.kubejs.KubeJS; import dev.latvian.mods.kubejs.bindings.event.EntityEvents; -import dev.latvian.mods.kubejs.util.UtilsJS; -import net.minecraft.world.damagesource.DamageSource; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.MobSpawnType; -import net.minecraft.world.level.BaseSpawner; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.LevelAccessor; -import org.jetbrains.annotations.Nullable; +import dev.latvian.mods.kubejs.core.EntityTypeKJS; +import net.minecraft.server.level.ServerLevel; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.event.entity.EntityJoinLevelEvent; +import net.neoforged.neoforge.event.entity.living.FinalizeSpawnEvent; +import net.neoforged.neoforge.event.entity.living.LivingDeathEvent; +import net.neoforged.neoforge.event.entity.living.LivingDropsEvent; +import net.neoforged.neoforge.event.entity.living.LivingHurtEvent; +@EventBusSubscriber(modid = KubeJS.MOD_ID) public class KubeJSEntityEventHandler { - public static void init() { - EntityEvent.LIVING_CHECK_SPAWN.register(KubeJSEntityEventHandler::checkSpawn); - EntityEvent.LIVING_DEATH.register(KubeJSEntityEventHandler::livingDeath); - EntityEvent.LIVING_HURT.register(KubeJSEntityEventHandler::livingHurt); - EntityEvent.ADD.register(KubeJSEntityEventHandler::entitySpawned); - } + @SubscribeEvent + public static void checkSpawn(FinalizeSpawnEvent event) { + var key = ((EntityTypeKJS) event.getEntity().getType()).kjs$getRegistryKey(); - private static EventResult checkSpawn(LivingEntity entity, LevelAccessor la, double x, double y, double z, MobSpawnType type, @Nullable BaseSpawner spawner) { - if (la instanceof Level level && (la.isClientSide() || UtilsJS.staticServer != null) && EntityEvents.CHECK_SPAWN.hasListeners()) { - return EntityEvents.CHECK_SPAWN.post(level, entity.getType(), new CheckLivingEntitySpawnKubeEvent(entity, level, x, y, z, type, spawner)).arch(); - } + if (event.getLevel() instanceof ServerLevel level && EntityEvents.CHECK_SPAWN.hasListeners(key)) { + var result = EntityEvents.CHECK_SPAWN.post(level, key, new CheckLivingEntitySpawnKubeEvent( + event.getEntity(), + level, + event.getX(), + event.getY(), + event.getZ(), + event.getSpawnType(), + event.getSpawner() + )); - return EventResult.pass(); + if (result.interruptFalse() || result.interruptTrue()) { + event.setSpawnCancelled(result.interruptFalse()); + event.setCanceled(true); + } + } } - private static EventResult livingDeath(LivingEntity entity, DamageSource source) { - return EntityEvents.DEATH.hasListeners() ? EntityEvents.DEATH.post(entity, entity.getType(), new LivingEntityDeathKubeEvent(entity, source)).arch() : EventResult.pass(); + @SubscribeEvent + public static void livingDeath(LivingDeathEvent event) { + var key = ((EntityTypeKJS) event.getEntity().getType()).kjs$getRegistryKey(); + + if (EntityEvents.DEATH.hasListeners(key)) { + EntityEvents.DEATH.post(event.getEntity(), key, new LivingEntityDeathKubeEvent(event.getEntity(), event.getSource())).applyCancel(event); + } } - private static EventResult livingHurt(LivingEntity entity, DamageSource source, float amount) { - return EntityEvents.HURT.hasListeners() ? EntityEvents.HURT.post(entity, entity.getType(), new LivingEntityHurtKubeEvent(entity, source, amount)).arch() : EventResult.pass(); + @SubscribeEvent + public static void livingHurt(LivingHurtEvent event) { + var key = ((EntityTypeKJS) event.getEntity().getType()).kjs$getRegistryKey(); + + if (EntityEvents.HURT.hasListeners(key)) { + EntityEvents.HURT.post(event.getEntity(), key, new LivingEntityHurtKubeEvent(event.getEntity(), event.getSource(), event.getAmount())).applyCancel(event); + } } - private static EventResult entitySpawned(Entity entity, Level level) { - if ((level.isClientSide() || UtilsJS.staticServer != null) && EntityEvents.SPAWNED.hasListeners()) { - return EntityEvents.SPAWNED.post(level, entity.getType(), new EntitySpawnedKubeEvent(entity, level)).arch(); + @SubscribeEvent + public static void entitySpawned(EntityJoinLevelEvent event) { + var key = ((EntityTypeKJS) event.getEntity().getType()).kjs$getRegistryKey(); + + if (EntityEvents.SPAWNED.hasListeners(key) && event.getLevel() instanceof ServerLevel level) { + EntityEvents.SPAWNED.post(level, key, new EntitySpawnedKubeEvent(event.getEntity(), level)).applyCancel(event); } + } - return EventResult.pass(); + @SubscribeEvent + public static void livingDrops(LivingDropsEvent event) { + var key = ((EntityTypeKJS) event.getEntity().getType()).kjs$getRegistryKey(); + + if (EntityEvents.ENTITY_DROPS.hasListeners(key)) { + var e = new LivingEntityDropsKubeEvent(event); + + if (!EntityEvents.ENTITY_DROPS.post(event.getEntity(), key, e).applyCancel(event) && e.eventDrops != null) { + event.getDrops().clear(); + event.getDrops().addAll(e.eventDrops); + } + } } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/event/EventGroup.java b/src/main/java/dev/latvian/mods/kubejs/event/EventGroup.java index cf92fab52..b7289f9f8 100644 --- a/src/main/java/dev/latvian/mods/kubejs/event/EventGroup.java +++ b/src/main/java/dev/latvian/mods/kubejs/event/EventGroup.java @@ -36,7 +36,7 @@ public boolean equals(Object obj) { } public EventHandler add(String name, ScriptTypePredicate scriptType, Supplier> eventType) { - EventHandler handler = new EventHandler(this, name, scriptType, eventType); + var handler = new EventHandler(this, name, scriptType, eventType); handlers.put(name, handler); return handler; } @@ -57,6 +57,28 @@ public EventHandler common(String name, Supplier> eve return add(name, ScriptTypePredicate.COMMON, eventType); } + public SpecializedEventHandler add(String name, ScriptTypePredicate scriptType, Extra extra, Supplier> eventType) { + var handler = new SpecializedEventHandler<>(this, name, scriptType, extra, eventType); + handlers.put(name, handler); + return handler; + } + + public SpecializedEventHandler startup(String name, Extra extra, Supplier> eventType) { + return add(name, ScriptType.STARTUP, extra, eventType); + } + + public SpecializedEventHandler server(String name, Extra extra, Supplier> eventType) { + return add(name, ScriptType.SERVER, extra, eventType); + } + + public SpecializedEventHandler client(String name, Extra extra, Supplier> eventType) { + return add(name, ScriptType.CLIENT, extra, eventType); + } + + public SpecializedEventHandler common(String name, Extra extra, Supplier> eventType) { + return add(name, ScriptTypePredicate.COMMON, extra, eventType); + } + public Map getHandlers() { return handlers; } diff --git a/src/main/java/dev/latvian/mods/kubejs/event/EventHandler.java b/src/main/java/dev/latvian/mods/kubejs/event/EventHandler.java index 19397fb4d..5b6f0c3ac 100644 --- a/src/main/java/dev/latvian/mods/kubejs/event/EventHandler.java +++ b/src/main/java/dev/latvian/mods/kubejs/event/EventHandler.java @@ -15,10 +15,7 @@ import dev.latvian.mods.rhino.util.HideFromJS; import org.jetbrains.annotations.Nullable; -import java.util.HashMap; import java.util.HashSet; -import java.util.IdentityHashMap; -import java.util.Map; import java.util.Set; import java.util.function.Consumer; import java.util.function.Supplier; @@ -27,7 +24,7 @@ *

Example

*

public static final EventHandler CLIENT_RIGHT_CLICKED = ItemEvents.GROUP.client("clientRightClicked", () -> ItemClickedEventJS.class).extra(ItemEvents.SUPPORTS_ITEM);

*/ -public final class EventHandler extends BaseFunction { +public class EventHandler extends BaseFunction { private static final TypeInfo EVENT_HANDLER_TYPE_INFO = TypeInfo.of(IEventHandler.class); public final EventGroup group; @@ -35,24 +32,26 @@ public final class EventHandler extends BaseFunction { public final ScriptTypePredicate scriptTypePredicate; public final Supplier> eventType; private boolean hasResult; - public transient Extra extra; - private EventHandlerContainer[] eventContainers; - private Map extraEventContainers; + public transient Extra extra; + public transient boolean extraRequired; + protected EventHandlerContainer[] eventContainers; + public transient EventExceptionHandler exceptionHandler; EventHandler(EventGroup g, String n, ScriptTypePredicate st, Supplier> e) { - group = g; - name = n; - scriptTypePredicate = st; - eventType = e; - hasResult = false; - extra = null; - eventContainers = null; - extraEventContainers = null; + this.group = g; + this.name = n; + this.scriptTypePredicate = st; + this.eventType = e; + this.hasResult = false; + this.extra = null; + this.eventContainers = null; + this.exceptionHandler = null; } /** * Allow event.cancel() to be called */ + @HideFromJS public EventHandler hasResult() { hasResult = true; return this; @@ -63,8 +62,8 @@ public boolean getHasResult() { } @HideFromJS - public EventHandler extra(Extra extra) { - this.extra = extra; + public EventHandler exceptionHandler(EventExceptionHandler handler) { + this.exceptionHandler = handler; return this; } @@ -77,34 +76,10 @@ public void clear(ScriptType type) { eventContainers = null; } } - - if (extraEventContainers != null) { - var entries = extraEventContainers.entrySet().iterator(); - - while (entries.hasNext()) { - var entry = entries.next(); - entry.getValue()[type.ordinal()] = null; - - if (EventHandlerContainer.isEmpty(entry.getValue())) { - entries.remove(); - } - } - - if (extraEventContainers.isEmpty()) { - extraEventContainers = null; - } - } } public boolean hasListeners() { - return eventContainers != null || extraEventContainers != null; - } - - /** - * Important! extraId won't be transformed for performance reasons. Only use this over {@link EventHandler#hasListeners()} if you think this will be more performant. Recommended only with identity extra IDs. - */ - public boolean hasListeners(Object extraId) { - return eventContainers != null || extraEventContainers != null && extraEventContainers.containsKey(extraId); + return eventContainers != null; } public void listen(@Nullable Context cx, ScriptType type, @Nullable Object extraId, IEventHandler handler) { @@ -121,7 +96,7 @@ public void listen(@Nullable Context cx, ScriptType type, @Nullable Object extra extraId = extra.transformer.transform(extraId); } - if (extra != null && extra.required && extraId == null) { + if (extra != null && extraRequired && extraId == null) { throw new IllegalArgumentException("Event handler '" + this + "' requires extra id!"); } @@ -136,28 +111,7 @@ public void listen(@Nullable Context cx, ScriptType type, @Nullable Object extra var line = new int[1]; var source = cx == null ? "java" : Context.getSourcePositionFromStack(cx, line); - EventHandlerContainer[] map; - - if (extraId == null) { - if (eventContainers == null) { - eventContainers = new EventHandlerContainer[ScriptType.VALUES.length]; - } - - map = eventContainers; - } else { - if (extraEventContainers == null) { - extraEventContainers = extra.identity ? new IdentityHashMap<>() : new HashMap<>(); - } - - map = extraEventContainers.get(extraId); - - //noinspection Java8MapApi - if (map == null) { - map = new EventHandlerContainer[ScriptType.VALUES.length]; - extraEventContainers.put(extraId, map); - } - } - + var map = createMap(extraId); var index = type.ordinal(); if (map[index] == null) { @@ -167,16 +121,24 @@ public void listen(@Nullable Context cx, ScriptType type, @Nullable Object extra } } + protected EventHandlerContainer[] createMap(@Nullable Object extraId) { + if (eventContainers == null) { + eventContainers = new EventHandlerContainer[ScriptType.VALUES.length]; + } + + return eventContainers; + } + @HideFromJS public void listenJava(ScriptType type, @Nullable Object extraId, IEventHandler handler) { var b = type.manager.get().canListenEvents; type.manager.get().canListenEvents = true; - listen(null, type, extraId, handler); + listen(type.manager.get().contextFactory.enter(), type, extraId, handler); type.manager.get().canListenEvents = b; } /** - * @see EventHandler#post(ScriptTypeHolder, Object, KubeEvent, EventExceptionHandler) + * @see EventHandler#post(ScriptTypeHolder, Object, KubeEvent) */ public EventResult post(KubeEvent event) { if (scriptTypePredicate instanceof ScriptTypeHolder type) { @@ -187,22 +149,14 @@ public EventResult post(KubeEvent event) { } /** - * @see EventHandler#post(ScriptTypeHolder, Object, KubeEvent, EventExceptionHandler) + * @see EventHandler#post(ScriptTypeHolder, Object, KubeEvent) */ public EventResult post(ScriptTypeHolder scriptType, KubeEvent event) { return post(scriptType, null, event); } /** - * @see EventHandler#post(ScriptTypeHolder, Object, KubeEvent, EventExceptionHandler) - */ - // sth, event, exh - public EventResult post(ScriptTypeHolder scriptType, KubeEvent event, EventExceptionHandler exh) { - return post(scriptType, null, event, exh); - } - - /** - * @see EventHandler#post(ScriptTypeHolder, Object, KubeEvent, EventExceptionHandler) + * @see EventHandler#post(ScriptTypeHolder, Object, KubeEvent) */ public EventResult post(KubeEvent event, @Nullable Object extraId) { if (scriptTypePredicate instanceof ScriptTypeHolder type) { @@ -212,24 +166,6 @@ public EventResult post(KubeEvent event, @Nullable Object extraId) { } } - /** - * @see EventHandler#post(ScriptTypeHolder, Object, KubeEvent, EventExceptionHandler) - */ - public EventResult post(KubeEvent event, @Nullable Object extraId, EventExceptionHandler exh) { - if (scriptTypePredicate instanceof ScriptTypeHolder type) { - return post(type, extraId, event, exh); - } else { - throw new IllegalStateException("You must specify which script type to post event to"); - } - } - - /** - * @see EventHandler#post(ScriptTypeHolder, Object, KubeEvent, EventExceptionHandler) - */ - public EventResult post(ScriptTypeHolder type, @Nullable Object extraId, KubeEvent event) { - return post(type, extraId, event, null); - } - /** * @return EventResult that can contain an object. What previously returned true on {@link KubeEvent#cancel()} now returns {@link EventResult#interruptFalse()} * @see KubeEvent#cancel() @@ -239,19 +175,14 @@ public EventResult post(ScriptTypeHolder type, @Nullable Object extraId, KubeEve * @see KubeEvent#success(Object) * @see KubeEvent#exit(Object) */ - public EventResult post(ScriptTypeHolder type, @Nullable Object extraId, KubeEvent event, EventExceptionHandler exh) { + public EventResult post(ScriptTypeHolder type, @Nullable Object extraId, KubeEvent event) { if (!hasListeners()) { return EventResult.PASS; } var scriptType = type.kjs$getScriptType(); - if (extraId != null && extra != null) { - extraId = Wrapper.unwrapped(extraId); - extraId = extra.transformer.transform(extraId); - } - - if (extra != null && extra.required && extraId == null) { + if (extra != null && extraRequired && extraId == null) { throw new IllegalArgumentException("Event handler '" + this + "' requires extra id!"); } @@ -262,21 +193,37 @@ public EventResult post(ScriptTypeHolder type, @Nullable Object extraId, KubeEve var eventResult = EventResult.PASS; try { - var extraContainers = extraEventContainers == null ? null : extraEventContainers.get(extraId); + var extraContainers = this instanceof SpecializedEventHandler h ? (h.extraEventContainers == null ? null : h.extraEventContainers.get(extraId)) : null; if (extraContainers != null) { - postToHandlers(scriptType, extraContainers, event, exh); + var handler = extraContainers[scriptType.ordinal()]; + + if (handler != null) { + handler.handle(event, exceptionHandler); + } if (!scriptType.isStartup()) { - postToHandlers(ScriptType.STARTUP, extraContainers, event, exh); + handler = extraContainers[ScriptType.STARTUP.ordinal()]; + + if (handler != null) { + handler.handle(event, exceptionHandler); + } } } if (eventContainers != null) { - postToHandlers(scriptType, eventContainers, event, exh); + var handler = eventContainers[scriptType.ordinal()]; + + if (handler != null) { + handler.handle(event, exceptionHandler); + } if (!scriptType.isStartup()) { - postToHandlers(ScriptType.STARTUP, eventContainers, event, exh); + handler = eventContainers[ScriptType.STARTUP.ordinal()]; + + if (handler != null) { + handler.handle(event, exceptionHandler); + } } } } catch (EventExit exit) { @@ -301,14 +248,6 @@ public EventResult post(ScriptTypeHolder type, @Nullable Object extraId, KubeEve return eventResult; } - private void postToHandlers(ScriptType type, EventHandlerContainer[] containers, KubeEvent event, @Nullable EventExceptionHandler exh) throws EventExit { - var handler = containers[type.ordinal()]; - - if (handler != null) { - handler.handle(event, exh); - } - } - @Override public String toString() { return group + "." + name; @@ -344,17 +283,6 @@ public void forEachListener(ScriptType type, Consumer cal c = c.child; } } - - if (extraEventContainers != null) { - for (var entry : extraEventContainers.entrySet()) { - var c = entry.getValue()[type.ordinal()]; - - while (c != null) { - callback.accept(c); - c = c.child; - } - } - } } public Set findUniqueExtraIds(ScriptType type) { diff --git a/src/main/java/dev/latvian/mods/kubejs/event/EventResult.java b/src/main/java/dev/latvian/mods/kubejs/event/EventResult.java index 7df38a56c..db9eb9a10 100644 --- a/src/main/java/dev/latvian/mods/kubejs/event/EventResult.java +++ b/src/main/java/dev/latvian/mods/kubejs/event/EventResult.java @@ -1,9 +1,13 @@ package dev.latvian.mods.kubejs.event; import dev.architectury.event.CompoundEventResult; -import dev.latvian.mods.kubejs.util.UtilsJS; +import dev.latvian.mods.kubejs.util.Cast; +import net.neoforged.bus.api.ICancellableEvent; +import net.neoforged.neoforge.common.util.TriState; import org.jetbrains.annotations.Nullable; +import java.util.function.Consumer; + public class EventResult { public enum Type { ERROR(dev.architectury.event.EventResult.pass()), @@ -75,10 +79,27 @@ public dev.architectury.event.EventResult arch() { public CompoundEventResult archCompound() { return switch (type) { - case INTERRUPT_DEFAULT -> CompoundEventResult.interruptDefault(UtilsJS.cast(value)); - case INTERRUPT_FALSE -> CompoundEventResult.interruptFalse(UtilsJS.cast(value)); - case INTERRUPT_TRUE -> CompoundEventResult.interruptTrue(UtilsJS.cast(value)); + case INTERRUPT_DEFAULT -> CompoundEventResult.interruptDefault(Cast.to(value)); + case INTERRUPT_FALSE -> CompoundEventResult.interruptFalse(Cast.to(value)); + case INTERRUPT_TRUE -> CompoundEventResult.interruptTrue(Cast.to(value)); default -> CompoundEventResult.pass(); }; } + + public boolean applyCancel(ICancellableEvent event) { + if (interruptFalse()) { + event.setCanceled(true); + return true; + } + + return false; + } + + public void applyTristate(Consumer consumer) { + if (interruptFalse()) { + consumer.accept(TriState.FALSE); + } else if (interruptTrue()) { + consumer.accept(TriState.TRUE); + } + } } diff --git a/src/main/java/dev/latvian/mods/kubejs/event/Extra.java b/src/main/java/dev/latvian/mods/kubejs/event/Extra.java index c4dad7a5f..fd2c5576e 100644 --- a/src/main/java/dev/latvian/mods/kubejs/event/Extra.java +++ b/src/main/java/dev/latvian/mods/kubejs/event/Extra.java @@ -1,17 +1,17 @@ package dev.latvian.mods.kubejs.event; -import dev.latvian.mods.kubejs.typings.desc.DescriptionContext; -import dev.latvian.mods.kubejs.typings.desc.TypeDescJS; +import dev.latvian.mods.kubejs.core.WithRegistryKeyKJS; +import dev.latvian.mods.kubejs.util.Cast; import dev.latvian.mods.kubejs.util.UtilsJS; +import dev.latvian.mods.rhino.type.TypeInfo; import net.minecraft.core.Registry; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import org.jetbrains.annotations.Nullable; -import java.util.function.Function; import java.util.function.Predicate; -public class Extra { +public class Extra { @FunctionalInterface public interface Transformer { Transformer IDENTITY = o -> o; @@ -20,12 +20,17 @@ public interface Transformer { Object transform(Object source); } - public static final Extra STRING = new Extra().transformer(Extra::toString); - public static final Extra REQUIRES_STRING = STRING.copy().required(); - public static final Extra ID = new Extra().transformer(Extra::toResourceLocation); - public static final Extra REQUIRES_ID = ID.copy().required(); - public static final Extra REGISTRY = new Extra().transformer(Extra::toRegistryKey).identity(); - public static final Extra REQUIRES_REGISTRY = REGISTRY.copy().required(); + public static Extra create(Class type) { + return new Extra<>(type); + } + + public static final Extra STRING = create(String.class).transformer(Extra::toString); + public static final Extra ID = create(ResourceLocation.class).transformer(Extra::toResourceLocation); + public static final Extra>> REGISTRY = Cast.to(create(ResourceKey.class).transformer(Extra::toRegistryKey).identity()); + + public static Extra> registryKey(ResourceKey> registry, Class type) { + return Cast.to(create(ResourceKey.class).identity().transformer(o -> toKey(registry, o)).describeType(TypeInfo.of(ResourceKey.class).withParams(TypeInfo.of(type)))); + } private static String toString(Object object) { if (object == null) { @@ -47,6 +52,21 @@ private static ResourceLocation toResourceLocation(Object object) { return s.isBlank() ? null : ResourceLocation.tryParse(s); } + private static ResourceKey toKey(ResourceKey registry, Object object) { + if (object == null) { + return null; + } else if (object instanceof ResourceKey rl) { + return rl; + } else if (object instanceof WithRegistryKeyKJS wrk) { + return wrk.kjs$getRegistryKey(); + } else if (object instanceof ResourceLocation rl) { + return ResourceKey.create(registry, rl); + } else { + var s = object.toString(); + return s.isBlank() ? null : ResourceKey.create(registry, new ResourceLocation(s)); + } + } + private static ResourceKey> toRegistryKey(Object object) { if (object == null) { return null; @@ -60,58 +80,43 @@ private static ResourceKey> toRegistryKey(Object object) { return s.isBlank() ? null : ResourceKey.createRegistryKey(new ResourceLocation(s)); } + public final Class type; public Transformer transformer; public boolean identity; - public boolean required; public Predicate validator; public Transformer toString; - public Function describeType; + public TypeInfo describeType; - public Extra() { + private Extra(Class type) { + this.type = type; this.transformer = Transformer.IDENTITY; this.identity = false; - this.required = false; this.validator = UtilsJS.ALWAYS_TRUE; this.toString = Transformer.IDENTITY; - this.describeType = context -> TypeDescJS.STRING; - } - - public Extra copy() { - Extra t = new Extra(); - t.transformer = transformer; - t.identity = identity; - t.required = required; - t.validator = validator; - t.toString = toString; - return t; + this.describeType = TypeInfo.STRING; } - public Extra transformer(Transformer factory) { + public Extra transformer(Transformer factory) { this.transformer = factory; return this; } - public Extra identity() { + public Extra identity() { this.identity = true; return this; } - public Extra required() { - this.required = true; - return this; - } - - public Extra validator(Predicate validator) { + public Extra validator(Predicate validator) { this.validator = validator; return this; } - public Extra describeType(Function describeType) { + public Extra describeType(TypeInfo describeType) { this.describeType = describeType; return this; } - public Extra toString(Transformer factory) { + public Extra toString(Transformer factory) { this.toString = factory; return this; } diff --git a/src/main/java/dev/latvian/mods/kubejs/event/KubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/event/KubeEvent.java index a8cb4dbf4..dcaa3bb28 100644 --- a/src/main/java/dev/latvian/mods/kubejs/event/KubeEvent.java +++ b/src/main/java/dev/latvian/mods/kubejs/event/KubeEvent.java @@ -1,19 +1,20 @@ package dev.latvian.mods.kubejs.event; import dev.latvian.mods.kubejs.typings.Info; +import dev.latvian.mods.rhino.Context; import dev.latvian.mods.rhino.util.HideFromJS; import org.jetbrains.annotations.Nullable; public interface KubeEvent { @Nullable @HideFromJS - default Object defaultExitValue() { + default Object defaultExitValue(Context cx) { return null; } @Nullable @HideFromJS - default Object mapExitValue(@Nullable Object value) { + default Object mapExitValue(Context cx, @Nullable Object value) { return value; } @@ -22,8 +23,8 @@ default Object mapExitValue(@Nullable Object value) { `cancel` denotes a `false` outcome. """) - default Object cancel() throws EventExit { - return cancel(defaultExitValue()); + default Object cancel(Context cx) throws EventExit { + return cancel(cx, defaultExitValue(cx)); } @Info(""" @@ -31,8 +32,8 @@ default Object cancel() throws EventExit { `success` denotes a `true` outcome. """) - default Object success() throws EventExit { - return success(defaultExitValue()); + default Object success(Context cx) throws EventExit { + return success(cx, defaultExitValue(cx)); } @Info(""" @@ -40,8 +41,8 @@ default Object success() throws EventExit { `exit` denotes a `default` outcome. """) - default Object exit() throws EventExit { - return exit(defaultExitValue()); + default Object exit(Context cx) throws EventExit { + return exit(cx, defaultExitValue(cx)); } @Info(""" @@ -49,8 +50,8 @@ default Object exit() throws EventExit { `cancel` denotes a `false` outcome. """) - default Object cancel(@Nullable Object value) throws EventExit { - throw EventResult.Type.INTERRUPT_FALSE.exit(mapExitValue(value)); + default Object cancel(Context cx, @Nullable Object value) throws EventExit { + throw EventResult.Type.INTERRUPT_FALSE.exit(mapExitValue(cx, value)); } @Info(""" @@ -58,8 +59,8 @@ default Object cancel(@Nullable Object value) throws EventExit { `success` denotes a `true` outcome. """) - default Object success(@Nullable Object value) throws EventExit { - throw EventResult.Type.INTERRUPT_TRUE.exit(mapExitValue(value)); + default Object success(Context cx, @Nullable Object value) throws EventExit { + throw EventResult.Type.INTERRUPT_TRUE.exit(mapExitValue(cx, value)); } @Info(""" @@ -67,8 +68,8 @@ default Object success(@Nullable Object value) throws EventExit { `exit` denotes a `default` outcome. """) - default Object exit(@Nullable Object value) throws EventExit { - throw EventResult.Type.INTERRUPT_DEFAULT.exit(mapExitValue(value)); + default Object exit(Context cx, @Nullable Object value) throws EventExit { + throw EventResult.Type.INTERRUPT_DEFAULT.exit(mapExitValue(cx, value)); } @HideFromJS diff --git a/src/main/java/dev/latvian/mods/kubejs/event/SpecializedEventHandler.java b/src/main/java/dev/latvian/mods/kubejs/event/SpecializedEventHandler.java new file mode 100644 index 000000000..f5ab21972 --- /dev/null +++ b/src/main/java/dev/latvian/mods/kubejs/event/SpecializedEventHandler.java @@ -0,0 +1,114 @@ +package dev.latvian.mods.kubejs.event; + +import dev.latvian.mods.kubejs.script.ScriptType; +import dev.latvian.mods.kubejs.script.ScriptTypePredicate; +import dev.latvian.mods.rhino.util.HideFromJS; +import org.jetbrains.annotations.Nullable; + +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.Map; +import java.util.function.Consumer; +import java.util.function.Supplier; + +public class SpecializedEventHandler extends EventHandler { + protected Map extraEventContainers; + + SpecializedEventHandler(EventGroup g, String n, ScriptTypePredicate st, Extra extra, Supplier> e) { + super(g, n, st, e); + this.extra = extra; + this.extraRequired = false; + this.extraEventContainers = null; + } + + /** + * Marks this event handler to require extra argument, usually needed for events related to registries + */ + public SpecializedEventHandler required() { + extraRequired = true; + return this; + } + + @Override + @HideFromJS + public SpecializedEventHandler hasResult() { + super.hasResult(); + return this; + } + + @Override + @HideFromJS + public SpecializedEventHandler exceptionHandler(EventExceptionHandler handler) { + this.exceptionHandler = handler; + return this; + } + + @Override + public boolean hasListeners() { + return eventContainers != null || extraEventContainers != null; + } + + public boolean hasListeners(Object extraId) { + return eventContainers != null || extraEventContainers != null && extraEventContainers.containsKey(extraId); + } + + @Override + @HideFromJS + public void clear(ScriptType type) { + super.clear(type); + + if (extraEventContainers != null) { + var entries = extraEventContainers.entrySet().iterator(); + + while (entries.hasNext()) { + var entry = entries.next(); + entry.getValue()[type.ordinal()] = null; + + if (EventHandlerContainer.isEmpty(entry.getValue())) { + entries.remove(); + } + } + + if (extraEventContainers.isEmpty()) { + extraEventContainers = null; + } + } + } + + @Override + protected EventHandlerContainer[] createMap(@Nullable Object extraId) { + if (extraId == null) { + return super.createMap(extraId); + } + + if (extraEventContainers == null) { + extraEventContainers = extra.identity ? new IdentityHashMap<>() : new HashMap<>(); + } + + var map = extraEventContainers.get(extraId); + + //noinspection Java8MapApi + if (map == null) { + map = new EventHandlerContainer[ScriptType.VALUES.length]; + extraEventContainers.put(extraId, map); + } + + return map; + } + + @Override + public void forEachListener(ScriptType type, Consumer callback) { + super.forEachListener(type, callback); + + if (extraEventContainers != null) { + for (var entry : extraEventContainers.entrySet()) { + var c = entry.getValue()[type.ordinal()]; + + while (c != null) { + callback.accept(c); + c = c.child; + } + } + } + } +} diff --git a/src/main/java/dev/latvian/mods/kubejs/fluid/FluidBuilder.java b/src/main/java/dev/latvian/mods/kubejs/fluid/FluidBuilder.java index 1a777f808..79817ed00 100644 --- a/src/main/java/dev/latvian/mods/kubejs/fluid/FluidBuilder.java +++ b/src/main/java/dev/latvian/mods/kubejs/fluid/FluidBuilder.java @@ -7,7 +7,7 @@ import dev.latvian.mods.kubejs.color.Color; import dev.latvian.mods.kubejs.registry.BuilderBase; import dev.latvian.mods.kubejs.registry.RegistryInfo; -import dev.latvian.mods.kubejs.util.UtilsJS; +import dev.latvian.mods.kubejs.util.Cast; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Rarity; @@ -82,7 +82,7 @@ public ArchitecturyFluidAttributes createAttributes() { .temperature(temperature) .lighterThanAir(isGaseous) .bucketItem(() -> Optional.ofNullable(bucketItem).map(Supplier::get)) - .block(() -> Optional.ofNullable(block).map(Supplier::get).map(UtilsJS::cast)); + .block(() -> Optional.ofNullable(block).map(Supplier::get).map(Cast::to)); this.attributes = attributes; return attributes; diff --git a/src/main/java/dev/latvian/mods/kubejs/gui/KubeJSMenu.java b/src/main/java/dev/latvian/mods/kubejs/gui/KubeJSMenu.java index f6b555edf..0e00e90bd 100644 --- a/src/main/java/dev/latvian/mods/kubejs/gui/KubeJSMenu.java +++ b/src/main/java/dev/latvian/mods/kubejs/gui/KubeJSMenu.java @@ -1,34 +1,18 @@ package dev.latvian.mods.kubejs.gui; -import dev.architectury.registry.registries.DeferredRegister; -import dev.latvian.mods.kubejs.CommonProperties; -import dev.latvian.mods.kubejs.helpers.MiscHelper; -import net.minecraft.core.registries.Registries; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.MenuType; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; -import java.util.function.Supplier; - public class KubeJSMenu extends AbstractContainerMenu { - public static final DeferredRegister> MENU_TYPES = DeferredRegister.create("kubejs", Registries.MENU); - public static final Supplier> KUBEJS_MENU = MENU_TYPES.register("menu", () -> MiscHelper.get().createMenuType()); - - public static void init() { - if (!CommonProperties.get().serverOnly) { - MENU_TYPES.register(); - } - } - public final Player player; public final KubeJSGUI guiData; public KubeJSMenu(int id, Inventory inventory, KubeJSGUI guiData) { - super(KUBEJS_MENU.get(), id); + super(KubeJSMenus.MENU.get(), id); this.player = inventory.player; this.guiData = guiData; diff --git a/src/main/java/dev/latvian/mods/kubejs/gui/KubeJSMenus.java b/src/main/java/dev/latvian/mods/kubejs/gui/KubeJSMenus.java new file mode 100644 index 000000000..1dc0c28da --- /dev/null +++ b/src/main/java/dev/latvian/mods/kubejs/gui/KubeJSMenus.java @@ -0,0 +1,15 @@ +package dev.latvian.mods.kubejs.gui; + +import dev.latvian.mods.kubejs.KubeJS; +import dev.latvian.mods.kubejs.helpers.MiscHelper; +import net.minecraft.core.registries.Registries; +import net.minecraft.world.inventory.MenuType; +import net.neoforged.neoforge.registries.DeferredRegister; + +import java.util.function.Supplier; + +public interface KubeJSMenus { + DeferredRegister> REGISTRY = DeferredRegister.create(Registries.MENU, KubeJS.MOD_ID); + + Supplier> MENU = REGISTRY.register("menu", () -> MiscHelper.get().createMenuType()); +} diff --git a/src/main/java/dev/latvian/mods/kubejs/helpers/IngredientHelper.java b/src/main/java/dev/latvian/mods/kubejs/helpers/IngredientHelper.java index b860142eb..ac9b38773 100644 --- a/src/main/java/dev/latvian/mods/kubejs/helpers/IngredientHelper.java +++ b/src/main/java/dev/latvian/mods/kubejs/helpers/IngredientHelper.java @@ -1,28 +1,22 @@ package dev.latvian.mods.kubejs.helpers; -import dev.latvian.mods.kubejs.KubeJS; +import dev.latvian.mods.kubejs.ingredient.CreativeTabIngredient; +import dev.latvian.mods.kubejs.ingredient.ModIngredient; +import dev.latvian.mods.kubejs.ingredient.RegExIngredient; +import dev.latvian.mods.kubejs.ingredient.WildcardIngredient; import dev.latvian.mods.kubejs.item.InputItem; -import dev.latvian.mods.kubejs.recipe.ingredient.CreativeTabIngredient; -import dev.latvian.mods.kubejs.recipe.ingredient.ModIngredient; -import dev.latvian.mods.kubejs.recipe.ingredient.RegExIngredient; -import dev.latvian.mods.kubejs.recipe.ingredient.WildcardIngredient; +import dev.latvian.mods.kubejs.util.ID; import dev.latvian.mods.kubejs.util.Tags; -import dev.latvian.mods.kubejs.util.UtilsJS; import net.minecraft.core.HolderSet; import net.minecraft.core.component.DataComponentPredicate; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; -import net.neoforged.bus.api.IEventBus; import net.neoforged.neoforge.common.crafting.CompoundIngredient; import net.neoforged.neoforge.common.crafting.DataComponentIngredient; import net.neoforged.neoforge.common.crafting.DifferenceIngredient; -import net.neoforged.neoforge.common.crafting.IngredientType; import net.neoforged.neoforge.common.crafting.IntersectionIngredient; -import net.neoforged.neoforge.registries.DeferredRegister; -import net.neoforged.neoforge.registries.NeoForgeRegistries; -import java.util.function.Supplier; import java.util.regex.Pattern; public enum IngredientHelper { @@ -32,18 +26,8 @@ public static IngredientHelper get() { return INSTANCE; } - public static final DeferredRegister> INGREDIENT_TYPES = DeferredRegister.create(NeoForgeRegistries.Keys.INGREDIENT_TYPES, KubeJS.MOD_ID); - public static final Supplier> WILDCARD = INGREDIENT_TYPES.register("wildcard", () -> new IngredientType<>(WildcardIngredient.CODEC)); - public static final Supplier> MOD = INGREDIENT_TYPES.register("mod", () -> new IngredientType<>(ModIngredient.CODEC)); - public static final Supplier> REGEX = INGREDIENT_TYPES.register("regex", () -> new IngredientType<>(RegExIngredient.CODEC)); - public static final Supplier> CREATIVE_TAB = INGREDIENT_TYPES.register("creative_tab", () -> new IngredientType<>(CreativeTabIngredient.CODEC)); - public InputItem stack(Ingredient ingredient, int count) { - return InputItem.of(ingredient, count); - } - - public static void register(IEventBus bus) { - INGREDIENT_TYPES.register(bus); + return InputItem.create(ingredient, count); } public Ingredient wildcard() { @@ -51,7 +35,7 @@ public Ingredient wildcard() { } public Ingredient tag(String tag) { - return Ingredient.of(Tags.item(UtilsJS.getMCID(null, tag))); + return Ingredient.of(Tags.item(ID.mc(tag))); } public Ingredient mod(String mod) { diff --git a/src/main/java/dev/latvian/mods/kubejs/helpers/MiscHelper.java b/src/main/java/dev/latvian/mods/kubejs/helpers/MiscHelper.java index 2291bfe36..1deb18c6a 100644 --- a/src/main/java/dev/latvian/mods/kubejs/helpers/MiscHelper.java +++ b/src/main/java/dev/latvian/mods/kubejs/helpers/MiscHelper.java @@ -9,7 +9,6 @@ import net.minecraft.world.item.ItemStack; import net.neoforged.fml.ModList; import net.neoforged.fml.loading.moddiscovery.ModInfo; -import net.neoforged.neoforge.data.loading.DatagenModLoader; import net.neoforged.neoforge.network.IContainerFactory; import java.util.function.Supplier; @@ -35,10 +34,6 @@ public void setModName(PlatformWrapper.ModInfo info, String name) { } } - public boolean isDataGen() { - return DatagenModLoader.isRunningDataGen(); - } - public long ingotFluidAmount() { return 90; } diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/ingredient/CreativeTabIngredient.java b/src/main/java/dev/latvian/mods/kubejs/ingredient/CreativeTabIngredient.java similarity index 85% rename from src/main/java/dev/latvian/mods/kubejs/recipe/ingredient/CreativeTabIngredient.java rename to src/main/java/dev/latvian/mods/kubejs/ingredient/CreativeTabIngredient.java index 550e6a1b9..d2e257fb0 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/ingredient/CreativeTabIngredient.java +++ b/src/main/java/dev/latvian/mods/kubejs/ingredient/CreativeTabIngredient.java @@ -1,8 +1,7 @@ -package dev.latvian.mods.kubejs.recipe.ingredient; +package dev.latvian.mods.kubejs.ingredient; import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; -import dev.latvian.mods.kubejs.helpers.IngredientHelper; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.ItemStack; @@ -16,7 +15,7 @@ public record CreativeTabIngredient(CreativeModeTab tab) implements KubeJSIngred @Override public IngredientType getType() { - return IngredientHelper.CREATIVE_TAB.get(); + return KubeJSIngredients.CREATIVE_TAB.get(); } @Override diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/ingredient/KubeJSIngredient.java b/src/main/java/dev/latvian/mods/kubejs/ingredient/KubeJSIngredient.java similarity index 91% rename from src/main/java/dev/latvian/mods/kubejs/recipe/ingredient/KubeJSIngredient.java rename to src/main/java/dev/latvian/mods/kubejs/ingredient/KubeJSIngredient.java index 34a14cb48..b924eba6c 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/ingredient/KubeJSIngredient.java +++ b/src/main/java/dev/latvian/mods/kubejs/ingredient/KubeJSIngredient.java @@ -1,4 +1,4 @@ -package dev.latvian.mods.kubejs.recipe.ingredient; +package dev.latvian.mods.kubejs.ingredient; import dev.latvian.mods.kubejs.item.ItemStackJS; import net.minecraft.world.item.ItemStack; diff --git a/src/main/java/dev/latvian/mods/kubejs/ingredient/KubeJSIngredients.java b/src/main/java/dev/latvian/mods/kubejs/ingredient/KubeJSIngredients.java new file mode 100644 index 000000000..f52885e95 --- /dev/null +++ b/src/main/java/dev/latvian/mods/kubejs/ingredient/KubeJSIngredients.java @@ -0,0 +1,17 @@ +package dev.latvian.mods.kubejs.ingredient; + +import dev.latvian.mods.kubejs.KubeJS; +import net.neoforged.neoforge.common.crafting.IngredientType; +import net.neoforged.neoforge.registries.DeferredRegister; +import net.neoforged.neoforge.registries.NeoForgeRegistries; + +import java.util.function.Supplier; + +public interface KubeJSIngredients { + DeferredRegister> REGISTRY = DeferredRegister.create(NeoForgeRegistries.Keys.INGREDIENT_TYPES, KubeJS.MOD_ID); + + Supplier> WILDCARD = REGISTRY.register("wildcard", () -> new IngredientType<>(WildcardIngredient.CODEC)); + Supplier> MOD = REGISTRY.register("mod", () -> new IngredientType<>(ModIngredient.CODEC)); + Supplier> REGEX = REGISTRY.register("regex", () -> new IngredientType<>(RegExIngredient.CODEC)); + Supplier> CREATIVE_TAB = REGISTRY.register("creative_tab", () -> new IngredientType<>(CreativeTabIngredient.CODEC)); +} diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/ingredient/ModIngredient.java b/src/main/java/dev/latvian/mods/kubejs/ingredient/ModIngredient.java similarity index 83% rename from src/main/java/dev/latvian/mods/kubejs/recipe/ingredient/ModIngredient.java rename to src/main/java/dev/latvian/mods/kubejs/ingredient/ModIngredient.java index 737636d22..8ea568b3a 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/ingredient/ModIngredient.java +++ b/src/main/java/dev/latvian/mods/kubejs/ingredient/ModIngredient.java @@ -1,9 +1,8 @@ -package dev.latvian.mods.kubejs.recipe.ingredient; +package dev.latvian.mods.kubejs.ingredient; import com.mojang.serialization.Codec; import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; -import dev.latvian.mods.kubejs.helpers.IngredientHelper; import net.minecraft.world.item.ItemStack; import net.neoforged.neoforge.common.crafting.IngredientType; import org.jetbrains.annotations.Nullable; @@ -15,7 +14,7 @@ public record ModIngredient(String mod) implements KubeJSIngredient { @Override public IngredientType getType() { - return IngredientHelper.MOD.get(); + return KubeJSIngredients.MOD.get(); } @Override diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/ingredient/RegExIngredient.java b/src/main/java/dev/latvian/mods/kubejs/ingredient/RegExIngredient.java similarity index 84% rename from src/main/java/dev/latvian/mods/kubejs/recipe/ingredient/RegExIngredient.java rename to src/main/java/dev/latvian/mods/kubejs/ingredient/RegExIngredient.java index b7828b698..fdd2204c6 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/ingredient/RegExIngredient.java +++ b/src/main/java/dev/latvian/mods/kubejs/ingredient/RegExIngredient.java @@ -1,8 +1,7 @@ -package dev.latvian.mods.kubejs.recipe.ingredient; +package dev.latvian.mods.kubejs.ingredient; import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; -import dev.latvian.mods.kubejs.helpers.IngredientHelper; import dev.latvian.mods.kubejs.util.RegExpJS; import net.minecraft.world.item.ItemStack; import net.neoforged.neoforge.common.crafting.IngredientType; @@ -17,7 +16,7 @@ public record RegExIngredient(Pattern pattern) implements KubeJSIngredient { @Override public IngredientType getType() { - return IngredientHelper.REGEX.get(); + return KubeJSIngredients.REGEX.get(); } @Override diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/ingredient/WildcardIngredient.java b/src/main/java/dev/latvian/mods/kubejs/ingredient/WildcardIngredient.java similarity index 83% rename from src/main/java/dev/latvian/mods/kubejs/recipe/ingredient/WildcardIngredient.java rename to src/main/java/dev/latvian/mods/kubejs/ingredient/WildcardIngredient.java index 6722fa2b3..9f0ed5e1f 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/ingredient/WildcardIngredient.java +++ b/src/main/java/dev/latvian/mods/kubejs/ingredient/WildcardIngredient.java @@ -1,7 +1,6 @@ -package dev.latvian.mods.kubejs.recipe.ingredient; +package dev.latvian.mods.kubejs.ingredient; import com.mojang.serialization.MapCodec; -import dev.latvian.mods.kubejs.helpers.IngredientHelper; import dev.latvian.mods.kubejs.item.ItemStackJS; import net.minecraft.world.item.ItemStack; import net.neoforged.neoforge.common.crafting.IngredientType; @@ -19,7 +18,7 @@ private WildcardIngredient() { @Override public IngredientType getType() { - return IngredientHelper.WILDCARD.get(); + return KubeJSIngredients.WILDCARD.get(); } @Override diff --git a/src/main/java/dev/latvian/mods/kubejs/integration/gamestages/GameStagesIntegration.java b/src/main/java/dev/latvian/mods/kubejs/integration/gamestages/GameStagesIntegration.java index 947308e65..b49b9cfcc 100644 --- a/src/main/java/dev/latvian/mods/kubejs/integration/gamestages/GameStagesIntegration.java +++ b/src/main/java/dev/latvian/mods/kubejs/integration/gamestages/GameStagesIntegration.java @@ -4,7 +4,7 @@ import dev.latvian.mods.kubejs.stages.StageCreationEvent; import dev.latvian.mods.kubejs.stages.StageEvents; -public class GameStagesIntegration extends KubeJSPlugin { +public class GameStagesIntegration implements KubeJSPlugin { @Override public void init() { StageEvents.overrideCreation(GameStagesIntegration::override); diff --git a/src/main/java/dev/latvian/mods/kubejs/integration/jei/JEIIntegration.java b/src/main/java/dev/latvian/mods/kubejs/integration/jei/JEIIntegration.java index 7255fcf49..4263d9614 100644 --- a/src/main/java/dev/latvian/mods/kubejs/integration/jei/JEIIntegration.java +++ b/src/main/java/dev/latvian/mods/kubejs/integration/jei/JEIIntegration.java @@ -3,7 +3,7 @@ import dev.latvian.mods.kubejs.KubeJSPlugin; import dev.latvian.mods.kubejs.event.EventGroupRegistry; -public class JEIIntegration extends KubeJSPlugin { +public class JEIIntegration implements KubeJSPlugin { @Override public void registerEvents(EventGroupRegistry registry) { registry.register(JEIEvents.GROUP); diff --git a/src/main/java/dev/latvian/mods/kubejs/integration/rei/GroupREIEntriesKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/integration/rei/GroupREIEntriesKubeEvent.java index fc0e017cc..2a334b2d6 100644 --- a/src/main/java/dev/latvian/mods/kubejs/integration/rei/GroupREIEntriesKubeEvent.java +++ b/src/main/java/dev/latvian/mods/kubejs/integration/rei/GroupREIEntriesKubeEvent.java @@ -2,8 +2,8 @@ import dev.latvian.mods.kubejs.event.KubeEvent; import dev.latvian.mods.kubejs.fluid.FluidWrapper; +import dev.latvian.mods.kubejs.util.Cast; import dev.latvian.mods.kubejs.util.Tags; -import dev.latvian.mods.kubejs.util.UtilsJS; import me.shedaniel.rei.api.client.registry.entry.CollapsibleEntryRegistry; import me.shedaniel.rei.api.common.entry.EntryStack; import me.shedaniel.rei.api.common.entry.type.VanillaEntryTypes; @@ -41,7 +41,7 @@ public void groupEntries(ResourceLocation groupId, Component description, Resour var entryType = KubeJSREIPlugin.getTypeOrThrow(entryTypeId); var wrapper = entryWrappers.getWrapper(entryType); var list = wrapper.entryList(entries); - group(groupId, description, UtilsJS.cast(list)); + group(groupId, description, Cast.to(list)); } public void groupSameItem(ResourceLocation group, Component description, ItemStack item) { diff --git a/src/main/java/dev/latvian/mods/kubejs/integration/rei/REIEvents.java b/src/main/java/dev/latvian/mods/kubejs/integration/rei/REIEvents.java index 370f398a2..7348f0779 100644 --- a/src/main/java/dev/latvian/mods/kubejs/integration/rei/REIEvents.java +++ b/src/main/java/dev/latvian/mods/kubejs/integration/rei/REIEvents.java @@ -3,12 +3,14 @@ import dev.latvian.mods.kubejs.event.EventGroup; import dev.latvian.mods.kubejs.event.EventHandler; import dev.latvian.mods.kubejs.event.Extra; +import dev.latvian.mods.kubejs.event.SpecializedEventHandler; +import net.minecraft.resources.ResourceLocation; public interface REIEvents { EventGroup GROUP = EventGroup.of("REIEvents"); - EventHandler HIDE = GROUP.client("hide", () -> HideREIKubeEvent.class).extra(Extra.REQUIRES_ID); - EventHandler ADD = GROUP.client("add", () -> AddREIKubeEvent.class).extra(Extra.REQUIRES_ID); + SpecializedEventHandler HIDE = GROUP.client("hide", Extra.ID, () -> HideREIKubeEvent.class).required(); + SpecializedEventHandler ADD = GROUP.client("add", Extra.ID, () -> AddREIKubeEvent.class).required(); EventHandler INFORMATION = GROUP.client("information", () -> InformationREIKubeEvent.class); EventHandler REMOVE_CATEGORIES = GROUP.client("removeCategories", () -> RemoveREICategoryKubeEvent.class); EventHandler REMOVE_RECIPES = GROUP.client("removeRecipes", () -> RemoveREIRecipeKubeEvent.class); diff --git a/src/main/java/dev/latvian/mods/kubejs/integration/rei/REIIntegration.java b/src/main/java/dev/latvian/mods/kubejs/integration/rei/REIIntegration.java index 34df246e9..dc5a28113 100644 --- a/src/main/java/dev/latvian/mods/kubejs/integration/rei/REIIntegration.java +++ b/src/main/java/dev/latvian/mods/kubejs/integration/rei/REIIntegration.java @@ -3,7 +3,7 @@ import dev.latvian.mods.kubejs.KubeJSPlugin; import dev.latvian.mods.kubejs.event.EventGroupRegistry; -public class REIIntegration extends KubeJSPlugin { +public class REIIntegration implements KubeJSPlugin { @Override public void registerEvents(EventGroupRegistry registry) { registry.register(REIEvents.GROUP); diff --git a/src/main/java/dev/latvian/mods/kubejs/item/ArmorMaterialBuilder.java b/src/main/java/dev/latvian/mods/kubejs/item/ArmorMaterialBuilder.java index 2d40b2be1..5323bee08 100644 --- a/src/main/java/dev/latvian/mods/kubejs/item/ArmorMaterialBuilder.java +++ b/src/main/java/dev/latvian/mods/kubejs/item/ArmorMaterialBuilder.java @@ -2,7 +2,6 @@ import dev.latvian.mods.kubejs.registry.BuilderBase; import dev.latvian.mods.kubejs.registry.RegistryInfo; -import dev.latvian.mods.kubejs.util.UtilsJS; import net.minecraft.core.Holder; import net.minecraft.resources.ResourceLocation; import net.minecraft.sounds.SoundEvent; @@ -60,8 +59,8 @@ public ArmorMaterial createObject() { ); } - public ArmorMaterialBuilder defense(Map v) { - defense = UtilsJS.remap(v, ArmorItem.Type.class, Integer.class, false); + public ArmorMaterialBuilder defense(Map v) { + defense = v; return this; } diff --git a/src/main/java/dev/latvian/mods/kubejs/item/InputItem.java b/src/main/java/dev/latvian/mods/kubejs/item/InputItem.java index ce4f71e5a..98070d255 100644 --- a/src/main/java/dev/latvian/mods/kubejs/item/InputItem.java +++ b/src/main/java/dev/latvian/mods/kubejs/item/InputItem.java @@ -24,7 +24,7 @@ public class InputItem implements IngredientSupplierKJS, InputReplacement, JsonS public static final InputItem EMPTY = new InputItem(Ingredient.EMPTY, 0); public static final Map PARSE_CACHE = new HashMap<>(); - public static InputItem of(Ingredient ingredient, int count) { + public static InputItem create(Ingredient ingredient, int count) { return count <= 0 || ingredient == Ingredient.EMPTY ? EMPTY : new InputItem(ingredient, count); } @@ -32,9 +32,9 @@ public static InputItem of(Object o) { if (o instanceof InputItem in) { return in; } else if (o instanceof ItemStack stack) { - return stack.isEmpty() ? EMPTY : of(Ingredient.of(stack), stack.getCount()); + return stack.isEmpty() ? EMPTY : create(Ingredient.of(stack), stack.getCount()); } else if (o instanceof OutputItem out) { - return out.isEmpty() ? EMPTY : of(Ingredient.of(out.item), out.getCount()); + return out.isEmpty() ? EMPTY : create(Ingredient.of(out.item), out.getCount()); } else if (o instanceof CharSequence) { var str = o.toString(); @@ -61,14 +61,14 @@ public static InputItem of(Object o) { } int count = Integer.parseInt(str.substring(0, x)); - cached = of(IngredientJS.of(str.substring(x + 2)), count); + cached = create(IngredientJS.of(str.substring(x + 2)), count); } catch (Exception ignore) { throw new RecipeExceptionJS("Invalid item input: " + str); } } if (cached == null) { - cached = of(IngredientJS.of(str), 1); + cached = create(IngredientJS.of(str), 1); } PARSE_CACHE.put(str, cached); @@ -77,7 +77,7 @@ public static InputItem of(Object o) { return ofJson(json); } - return of(IngredientJS.of(o), 1); + return create(IngredientJS.of(o), 1); } static InputItem ofJson(JsonElement json) { @@ -92,12 +92,12 @@ static InputItem ofJson(JsonElement json) { if (o.has("type")) { try { - return of(RecipeHelper.get().getCustomIngredient(o), count); + return create(RecipeHelper.get().getCustomIngredient(o), count); } catch (Exception ex) { throw new RecipeExceptionJS("Failed to parse custom ingredient (" + o.get("type") + ") from " + o + ": " + ex); } } else if (val || o.has("ingredient")) { - return of(IngredientJS.ofJson(val ? o.get("value") : o.get("ingredient")), count); + return create(IngredientJS.ofJson(val ? o.get("value") : o.get("ingredient")), count); } else if (o.has("tag")) { return IngredientHelper.get().tag(o.get("tag").getAsString()).kjs$withCount(count); } else if (o.has("item")) { @@ -106,7 +106,7 @@ static InputItem ofJson(JsonElement json) { return EMPTY; } else { - return of(IngredientJS.ofJson(json), 1); + return create(IngredientJS.ofJson(json), 1); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/item/ItemBuilder.java b/src/main/java/dev/latvian/mods/kubejs/item/ItemBuilder.java index 304046120..fd1219bd3 100644 --- a/src/main/java/dev/latvian/mods/kubejs/item/ItemBuilder.java +++ b/src/main/java/dev/latvian/mods/kubejs/item/ItemBuilder.java @@ -2,7 +2,6 @@ import com.google.gson.JsonObject; import dev.architectury.registry.fuel.FuelRegistry; -import dev.latvian.mods.kubejs.KubeJS; import dev.latvian.mods.kubejs.bindings.ItemWrapper; import dev.latvian.mods.kubejs.color.Color; import dev.latvian.mods.kubejs.generator.AssetJsonGenerator; @@ -11,6 +10,7 @@ import dev.latvian.mods.kubejs.registry.RegistryInfo; import dev.latvian.mods.kubejs.typings.Info; import dev.latvian.mods.kubejs.util.ConsoleJS; +import dev.latvian.mods.kubejs.util.ID; import net.minecraft.core.component.DataComponents; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; @@ -49,20 +49,19 @@ public abstract class ItemBuilder extends BuilderBase { } } - public static Tier toToolTier(Object o) { + public static Tier toolTierOf(Object o) { if (o instanceof Tier tier) { return tier; } - String asString = String.valueOf(o); + var asString = String.valueOf(o); + var toolTier = ItemBuilder.TOOL_TIERS.get(asString); - Tier toolTier = ItemBuilder.TOOL_TIERS.get(asString); if (toolTier != null) { return toolTier; } - String withKube = KubeJS.appendModId(asString); - return ItemBuilder.TOOL_TIERS.getOrDefault(withKube, Tiers.IRON); + return ItemBuilder.TOOL_TIERS.getOrDefault(ID.kjsString(asString), Tiers.IRON); } public transient int maxStackSize; diff --git a/src/main/java/dev/latvian/mods/kubejs/item/ItemClickedKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/item/ItemClickedKubeEvent.java index 343fef673..edfa4d7cd 100644 --- a/src/main/java/dev/latvian/mods/kubejs/item/ItemClickedKubeEvent.java +++ b/src/main/java/dev/latvian/mods/kubejs/item/ItemClickedKubeEvent.java @@ -3,6 +3,7 @@ import dev.latvian.mods.kubejs.entity.RayTraceResultJS; import dev.latvian.mods.kubejs.player.KubePlayerEvent; import dev.latvian.mods.kubejs.typings.Info; +import dev.latvian.mods.rhino.Context; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; @@ -53,13 +54,13 @@ public RayTraceResultJS getTarget() { @Override @Nullable - public Object defaultExitValue() { + public Object defaultExitValue(Context cx) { return item; } @Override @Nullable - public Object mapExitValue(@Nullable Object value) { - return ItemStackJS.of(value); + public Object mapExitValue(Context cx, @Nullable Object from) { + return cx.jsToJava(from, ItemStackJS.TYPE_INFO); } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/item/ItemEntityInteractedKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/item/ItemEntityInteractedKubeEvent.java index 9edc51d71..64827fadd 100644 --- a/src/main/java/dev/latvian/mods/kubejs/item/ItemEntityInteractedKubeEvent.java +++ b/src/main/java/dev/latvian/mods/kubejs/item/ItemEntityInteractedKubeEvent.java @@ -14,12 +14,13 @@ public class ItemEntityInteractedKubeEvent implements KubePlayerEvent { private final Player player; private final Entity entity; private final InteractionHand hand; + private final ItemStack item; - public ItemEntityInteractedKubeEvent(Player player, Entity entity, InteractionHand hand) { - + public ItemEntityInteractedKubeEvent(Player player, Entity entity, InteractionHand hand, ItemStack item) { this.player = player; this.entity = entity; this.hand = hand; + this.item = item; } @Override @@ -35,7 +36,7 @@ public InteractionHand getHand() { @Info("The item that was used to interact with the entity.") public ItemStack getItem() { - return player.getItemInHand(hand); + return item; } @Info("The entity that was interacted with.") diff --git a/src/main/java/dev/latvian/mods/kubejs/item/ItemModelPropertiesKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/item/ItemModelPropertiesKubeEvent.java index 90d2dd002..239a57177 100644 --- a/src/main/java/dev/latvian/mods/kubejs/item/ItemModelPropertiesKubeEvent.java +++ b/src/main/java/dev/latvian/mods/kubejs/item/ItemModelPropertiesKubeEvent.java @@ -1,11 +1,10 @@ package dev.latvian.mods.kubejs.item; import dev.architectury.registry.item.ItemPropertiesRegistry; -import dev.latvian.mods.kubejs.KubeJS; import dev.latvian.mods.kubejs.event.KubeStartupEvent; import dev.latvian.mods.kubejs.typings.Info; +import dev.latvian.mods.kubejs.util.ID; import net.minecraft.client.renderer.item.ClampedItemPropertyFunction; -import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.crafting.Ingredient; public class ItemModelPropertiesKubeEvent implements KubeStartupEvent { @@ -16,17 +15,20 @@ public class ItemModelPropertiesKubeEvent implements KubeStartupEvent { More about model properties: https://minecraft.fandom.com/wiki/Model#Item_predicates """) public void register(Ingredient ingredient, String overwriteId, ClampedItemPropertyFunction callback) { + var id = ID.kjs(overwriteId); + if (ingredient.kjs$isWildcard()) { - registerAll(overwriteId, callback); + ItemPropertiesRegistry.registerGeneric(id, callback); + } else { for (var stack : ingredient.kjs$getStacks()) { - ItemPropertiesRegistry.register(stack.getItem(), new ResourceLocation(KubeJS.appendModId(overwriteId)), callback); + ItemPropertiesRegistry.register(stack.getItem(), id, callback); } } } @Info("Register a model property for all items.") public void registerAll(String overwriteId, ClampedItemPropertyFunction callback) { - ItemPropertiesRegistry.registerGeneric(new ResourceLocation(KubeJS.appendModId(overwriteId)), callback); + ItemPropertiesRegistry.registerGeneric(ID.kjs(overwriteId), callback); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/item/ItemStackJS.java b/src/main/java/dev/latvian/mods/kubejs/item/ItemStackJS.java index 3f8811590..3ca5bb0f8 100644 --- a/src/main/java/dev/latvian/mods/kubejs/item/ItemStackJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/item/ItemStackJS.java @@ -7,6 +7,7 @@ import dev.latvian.mods.kubejs.recipe.KubeRecipe; import dev.latvian.mods.kubejs.recipe.RecipeExceptionJS; import dev.latvian.mods.kubejs.registry.RegistryInfo; +import dev.latvian.mods.kubejs.util.ID; import dev.latvian.mods.kubejs.util.Lazy; import dev.latvian.mods.kubejs.util.MapJS; import dev.latvian.mods.kubejs.util.NBTUtils; @@ -15,6 +16,7 @@ import dev.latvian.mods.rhino.Context; import dev.latvian.mods.rhino.Wrapper; import dev.latvian.mods.rhino.regexp.NativeRegExp; +import dev.latvian.mods.rhino.type.TypeInfo; import net.minecraft.core.HolderLookup; import net.minecraft.core.component.DataComponentPatch; import net.minecraft.nbt.CompoundTag; @@ -41,6 +43,7 @@ public interface ItemStackJS { Map PARSE_CACHE = new HashMap<>(); ItemStack[] EMPTY_ARRAY = new ItemStack[0]; + TypeInfo TYPE_INFO = TypeInfo.of(ItemStack.class); Lazy> CACHED_ITEM_TYPE_LIST = Lazy.of(() -> { var cachedItemTypeList = new ArrayList(); @@ -134,7 +137,7 @@ static ItemStack of(@Nullable Object o) { s = s.substring(spaceIndex + 1); } - cached = parse(s); + cached = ofString(s); cached.setCount(count); PARSE_CACHE.put(os, cached); return cached.copy(); @@ -144,7 +147,7 @@ static ItemStack of(@Nullable Object o) { if (map != null) { if (map.containsKey("item")) { - var id = UtilsJS.getMCID(null, map.get("item").toString()); + var id = ID.mc(map.get("item").toString()); var item = RegistryInfo.ITEM.getValue(id); if (item == Items.AIR) { @@ -180,7 +183,7 @@ static ItemStack of(@Nullable Object o) { return ItemStack.EMPTY; } - static ItemStack parse(String s) { + static ItemStack ofString(String s) { if (s.isEmpty() || s.equals("-") || s.equals("air") || s.equals("minecraft:air")) { return ItemStack.EMPTY; } else if (s.startsWith("#")) { @@ -243,7 +246,7 @@ static Item getRawItem(Context cx, @Nullable Object o) { if (s.isEmpty()) { return Items.AIR; } else if (s.charAt(0) != '#') { - return RegistryInfo.ITEM.getValue(UtilsJS.getMCID(cx, s)); + return RegistryInfo.ITEM.getValue(ID.mc(s)); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/item/KubeJSItemEventHandler.java b/src/main/java/dev/latvian/mods/kubejs/item/KubeJSItemEventHandler.java index d08a78a96..2f102e3bb 100644 --- a/src/main/java/dev/latvian/mods/kubejs/item/KubeJSItemEventHandler.java +++ b/src/main/java/dev/latvian/mods/kubejs/item/KubeJSItemEventHandler.java @@ -1,83 +1,107 @@ package dev.latvian.mods.kubejs.item; -import dev.architectury.event.CompoundEventResult; -import dev.architectury.event.EventResult; -import dev.architectury.event.events.common.InteractionEvent; -import dev.architectury.event.events.common.PlayerEvent; +import dev.latvian.mods.kubejs.KubeJS; import dev.latvian.mods.kubejs.bindings.event.ItemEvents; import dev.latvian.mods.kubejs.bindings.event.PlayerEvents; import dev.latvian.mods.kubejs.player.InventoryChangedKubeEvent; -import net.minecraft.world.Container; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.item.ItemEntity; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.ItemStack; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.event.entity.item.ItemTossEvent; +import net.neoforged.neoforge.event.entity.player.ItemEntityPickupEvent; +import net.neoforged.neoforge.event.entity.player.PlayerDestroyItemEvent; +import net.neoforged.neoforge.event.entity.player.PlayerEvent; +import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent; +@EventBusSubscriber(modid = KubeJS.MOD_ID) public class KubeJSItemEventHandler { - public static void init() { - InteractionEvent.RIGHT_CLICK_ITEM.register(KubeJSItemEventHandler::rightClick); - PlayerEvent.PICKUP_ITEM_PRE.register(KubeJSItemEventHandler::canPickUp); - PlayerEvent.PICKUP_ITEM_POST.register(KubeJSItemEventHandler::pickup); - PlayerEvent.DROP_ITEM.register(KubeJSItemEventHandler::drop); - InteractionEvent.INTERACT_ENTITY.register(KubeJSItemEventHandler::entityInteract); - PlayerEvent.CRAFT_ITEM.register(KubeJSItemEventHandler::crafted); - PlayerEvent.SMELT_ITEM.register(KubeJSItemEventHandler::smelted); - } + @SubscribeEvent + public static void rightClick(PlayerInteractEvent.RightClickItem event) { + var stack = event.getItemStack(); + var key = stack.getItem().kjs$getRegistryKey(); - private static CompoundEventResult rightClick(Player player, InteractionHand hand) { - if (!ItemEvents.RIGHT_CLICKED.hasListeners()) { - return CompoundEventResult.pass(); + if (ItemEvents.RIGHT_CLICKED.hasListeners(key) && !event.getEntity().getCooldowns().isOnCooldown(stack.getItem())) { + ItemEvents.RIGHT_CLICKED.post(event.getEntity(), key, new ItemClickedKubeEvent(event.getEntity(), event.getHand(), stack)).applyCancel(event); } + } - var stack = player.getItemInHand(hand); + @SubscribeEvent + public static void leftClickEmpty(PlayerInteractEvent.LeftClickEmpty event) { + // TODO: Implement me + } - if (!player.getCooldowns().isOnCooldown(stack.getItem())) { - return ItemEvents.RIGHT_CLICKED.post(player, stack.getItem(), new ItemClickedKubeEvent(player, hand, stack)).archCompound(); - } + @SubscribeEvent + public static void itemPickupPre(ItemEntityPickupEvent.Pre event) { + var key = event.getItemEntity().getItem().getItem().kjs$getRegistryKey(); - return CompoundEventResult.pass(); + if (ItemEvents.CAN_PICK_UP.hasListeners(key)) { + ItemEvents.CAN_PICK_UP.post(event.getPlayer(), key, new ItemPickedUpKubeEvent(event.getPlayer(), event.getItemEntity(), event.getItemEntity().getItem())).applyTristate(event::setCanPickup); + } } - private static EventResult canPickUp(Player player, ItemEntity entity, ItemStack stack) { - return ItemEvents.CAN_PICK_UP.hasListeners() ? ItemEvents.CAN_PICK_UP.post(player, stack.getItem(), new ItemPickedUpKubeEvent(player, entity, stack)).arch() : EventResult.pass(); - } + @SubscribeEvent + public static void itemPickupPost(ItemEntityPickupEvent.Post event) { + var key = event.getCurrentStack().getItem().kjs$getRegistryKey(); - private static void pickup(Player player, ItemEntity entity, ItemStack stack) { - if (ItemEvents.PICKED_UP.hasListeners()) { - ItemEvents.PICKED_UP.post(player, stack.getItem(), new ItemPickedUpKubeEvent(player, entity, stack)); + if (ItemEvents.PICKED_UP.hasListeners(key)) { + ItemEvents.PICKED_UP.post(event.getPlayer(), key, new ItemPickedUpKubeEvent(event.getPlayer(), event.getItemEntity(), event.getCurrentStack())); } } - private static EventResult drop(Player player, ItemEntity entity) { - return ItemEvents.DROPPED.hasListeners() ? ItemEvents.DROPPED.post(player, entity.getItem().getItem(), new ItemDroppedKubeEvent(player, entity)).arch() : EventResult.pass(); + @SubscribeEvent + public static void itemDrop(ItemTossEvent event) { + var key = event.getEntity().getItem().getItem().kjs$getRegistryKey(); + + if (ItemEvents.DROPPED.hasListeners(key)) { + ItemEvents.DROPPED.post(event.getPlayer(), key, new ItemDroppedKubeEvent(event.getPlayer(), event.getEntity())).applyCancel(event); + } } - private static EventResult entityInteract(Player player, Entity entity, InteractionHand hand) { - return ItemEvents.ENTITY_INTERACTED.hasListeners() ? ItemEvents.ENTITY_INTERACTED.post(player, player.getItemInHand(hand).getItem(), new ItemEntityInteractedKubeEvent(player, entity, hand)).arch() : EventResult.pass(); + @SubscribeEvent + public static void entityInteract(PlayerInteractEvent.EntityInteract event) { + var stack = event.getItemStack(); + var key = stack.getItem().kjs$getRegistryKey(); + + if (ItemEvents.ENTITY_INTERACTED.hasListeners(key)) { + ItemEvents.ENTITY_INTERACTED.post(event.getEntity(), key, new ItemEntityInteractedKubeEvent(event.getEntity(), event.getTarget(), event.getHand(), stack)).applyCancel(event); + } } - private static void crafted(Player player, ItemStack stack, Container grid) { - if (!stack.isEmpty()) { - if (ItemEvents.CRAFTED.hasListeners()) { - ItemEvents.CRAFTED.post(player, stack.getItem(), new ItemCraftedKubeEvent(player, stack, grid)); + @SubscribeEvent + public static void crafted(PlayerEvent.ItemCraftedEvent event) { + if (!event.getCrafting().isEmpty()) { + var key = event.getCrafting().getItem().kjs$getRegistryKey(); + + if (ItemEvents.CRAFTED.hasListeners(key)) { + ItemEvents.CRAFTED.post(event.getEntity(), key, new ItemCraftedKubeEvent(event.getEntity(), event.getCrafting(), event.getInventory())); } - if (PlayerEvents.INVENTORY_CHANGED.hasListeners()) { - PlayerEvents.INVENTORY_CHANGED.post(player, stack.getItem(), new InventoryChangedKubeEvent(player, stack, -1)); + if (PlayerEvents.INVENTORY_CHANGED.hasListeners(key)) { + PlayerEvents.INVENTORY_CHANGED.post(event.getEntity(), key, new InventoryChangedKubeEvent(event.getEntity(), event.getCrafting(), -1)); } } } - private static void smelted(Player player, ItemStack stack) { - if (!stack.isEmpty()) { - if (ItemEvents.SMELTED.hasListeners()) { - ItemEvents.SMELTED.post(player, stack.getItem(), new ItemSmeltedKubeEvent(player, stack)); + @SubscribeEvent + public static void smelted(PlayerEvent.ItemSmeltedEvent event) { + if (!event.getSmelting().isEmpty()) { + var key = event.getSmelting().getItem().kjs$getRegistryKey(); + + if (ItemEvents.SMELTED.hasListeners(key)) { + ItemEvents.SMELTED.post(event.getEntity(), key, new ItemSmeltedKubeEvent(event.getEntity(), event.getSmelting())); } - if (PlayerEvents.INVENTORY_CHANGED.hasListeners()) { - PlayerEvents.INVENTORY_CHANGED.post(player, stack.getItem(), new InventoryChangedKubeEvent(player, stack, -1)); + if (PlayerEvents.INVENTORY_CHANGED.hasListeners(key)) { + PlayerEvents.INVENTORY_CHANGED.post(event.getEntity(), key, new InventoryChangedKubeEvent(event.getEntity(), event.getSmelting(), -1)); } } } + + @SubscribeEvent + public static void itemDestroyed(PlayerDestroyItemEvent event) { + var key = event.getOriginal().getItem().kjs$getRegistryKey(); + + if (ItemEvents.ITEM_DESTROYED.hasListeners(key)) { + ItemEvents.ITEM_DESTROYED.post(event.getEntity(), key, new ItemDestroyedKubeEvent(event)); + } + } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/item/OutputItem.java b/src/main/java/dev/latvian/mods/kubejs/item/OutputItem.java index cf5c703e0..15d219fa2 100644 --- a/src/main/java/dev/latvian/mods/kubejs/item/OutputItem.java +++ b/src/main/java/dev/latvian/mods/kubejs/item/OutputItem.java @@ -14,7 +14,7 @@ public class OutputItem implements OutputReplacement { public static final OutputItem EMPTY = new OutputItem(ItemStack.EMPTY, Double.NaN, null); - public static OutputItem of(ItemStack item, double chance) { + public static OutputItem create(ItemStack item, double chance) { return item.isEmpty() ? EMPTY : new OutputItem(item, chance, null); } @@ -22,7 +22,7 @@ public static OutputItem of(Object from) { if (from instanceof OutputItem out) { return out; } else if (from instanceof ItemStack stack) { - return of(stack, Double.NaN); + return create(stack, Double.NaN); } var item = ItemStackJS.of(from); @@ -109,6 +109,6 @@ public Object replaceOutput(KubeRecipe recipe, ReplacementMatch match, OutputRep public InputItem ignoreNBT(Context cx) { var console = ConsoleJS.getCurrent(cx); console.warn("You don't need to call .ignoreNBT() anymore, all item ingredients ignore NBT by default!"); - return InputItem.of(item.getItem().kjs$asIngredient(), item.getCount()); + return InputItem.create(item.getItem().kjs$asIngredient(), item.getCount()); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/item/creativetab/KubeJSCreativeTabs.java b/src/main/java/dev/latvian/mods/kubejs/item/creativetab/KubeJSCreativeTabs.java index 349797bc2..a2e435b46 100644 --- a/src/main/java/dev/latvian/mods/kubejs/item/creativetab/KubeJSCreativeTabs.java +++ b/src/main/java/dev/latvian/mods/kubejs/item/creativetab/KubeJSCreativeTabs.java @@ -11,23 +11,21 @@ import net.minecraft.world.item.Items; import net.neoforged.neoforge.registries.DeferredRegister; -public class KubeJSCreativeTabs { - public static final DeferredRegister REGISTER = DeferredRegister.create(Registries.CREATIVE_MODE_TAB, KubeJS.MOD_ID); +import java.util.function.Supplier; - public static void init() { - if (!CommonProperties.get().serverOnly) { - REGISTER.register("tab", () -> MiscHelper.get().creativeModeTab( - Component.literal("KubeJS"), - () -> { - var is = ItemStackJS.of(CommonProperties.get().creativeModeTabIcon); - return is.isEmpty() ? Items.PURPLE_DYE.getDefaultInstance() : is; - }, - (params, output) -> { - for (var b : RegistryInfo.ITEM) { - output.accept(b.get().getDefaultInstance()); - } - } - )); +public interface KubeJSCreativeTabs { + DeferredRegister REGISTRY = DeferredRegister.create(Registries.CREATIVE_MODE_TAB, KubeJS.MOD_ID); + + Supplier TAB = REGISTRY.register("tab", () -> MiscHelper.get().creativeModeTab( + Component.literal("KubeJS"), + () -> { + var is = ItemStackJS.of(CommonProperties.get().creativeModeTabIcon); + return is.isEmpty() ? Items.PURPLE_DYE.getDefaultInstance() : is; + }, + (params, output) -> { + for (var b : RegistryInfo.ITEM) { + output.accept(b.get().getDefaultInstance()); + } } - } + )); } diff --git a/src/main/java/dev/latvian/mods/kubejs/item/ingredient/TagContext.java b/src/main/java/dev/latvian/mods/kubejs/item/ingredient/TagContext.java index 57d369dcc..2e6eb0df8 100644 --- a/src/main/java/dev/latvian/mods/kubejs/item/ingredient/TagContext.java +++ b/src/main/java/dev/latvian/mods/kubejs/item/ingredient/TagContext.java @@ -3,8 +3,8 @@ import com.google.common.collect.Iterables; import dev.architectury.extensions.injected.InjectedRegistryEntryExtension; import dev.latvian.mods.kubejs.KubeJS; +import dev.latvian.mods.kubejs.util.Cast; import dev.latvian.mods.kubejs.util.ConsoleJS; -import dev.latvian.mods.kubejs.util.UtilsJS; import net.minecraft.core.Holder; import net.minecraft.core.Registry; import net.minecraft.core.RegistryAccess; @@ -59,7 +59,7 @@ public Iterable> getTag(TagKey tag) { @Override public boolean contains(TagKey tag, T value) { if (value instanceof InjectedRegistryEntryExtension ext) { - Holder holder = UtilsJS.cast(ext.arch$holder()); + Holder holder = Cast.to(ext.arch$holder()); return holder.is(tag); } @@ -74,7 +74,7 @@ public boolean contains(TagKey tag, T value) { static TagContext fromLoadResult(List> results) { final Map>, Map>>> tags = results.stream() - .collect(Collectors.toMap(result -> UtilsJS.cast(result.key()), result -> UtilsJS.cast(result.tags()))); + .collect(Collectors.toMap(result -> Cast.to(result.key()), result -> Cast.to(result.tags()))); if (!tags.containsKey(Registries.ITEM)) { ConsoleJS.SERVER.warn("Failed to load item tags during recipe event! Using replaceInput etc. will not work!"); @@ -84,7 +84,7 @@ static TagContext fromLoadResult(List> results) { return new TagContext() { @Override public Iterable> getTag(TagKey tag) { - return UtilsJS.cast(tags.get(tag.registry()).getOrDefault(tag.location(), Set.of())); + return Cast.to(tags.get(tag.registry()).getOrDefault(tag.location(), Set.of())); } }; } diff --git a/src/main/java/dev/latvian/mods/kubejs/level/BlockContainerJS.java b/src/main/java/dev/latvian/mods/kubejs/level/BlockContainerJS.java index cbde3cf54..c684e2ab1 100644 --- a/src/main/java/dev/latvian/mods/kubejs/level/BlockContainerJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/level/BlockContainerJS.java @@ -3,8 +3,8 @@ import dev.latvian.mods.kubejs.core.InventoryKJS; import dev.latvian.mods.kubejs.player.EntityArrayList; import dev.latvian.mods.kubejs.registry.RegistryInfo; +import dev.latvian.mods.kubejs.util.Cast; import dev.latvian.mods.kubejs.util.Tags; -import dev.latvian.mods.kubejs.util.UtilsJS; import dev.latvian.mods.rhino.Context; import dev.latvian.mods.rhino.util.SpecialEquality; import net.minecraft.core.BlockPos; @@ -165,7 +165,7 @@ public void set(ResourceLocation id, Map properties, int flags) { var property = pmap.get(String.valueOf(entry.getKey())); if (property != null) { - state = state.setValue(property, UtilsJS.cast(property.getValue(String.valueOf(entry.getValue())).orElseThrow())); + state = state.setValue(property, Cast.to(property.getValue(String.valueOf(entry.getValue())).orElseThrow())); } } } diff --git a/src/main/java/dev/latvian/mods/kubejs/level/KubeJSWorldEventHandler.java b/src/main/java/dev/latvian/mods/kubejs/level/KubeJSWorldEventHandler.java index 20e3a9a02..d186b9ae3 100644 --- a/src/main/java/dev/latvian/mods/kubejs/level/KubeJSWorldEventHandler.java +++ b/src/main/java/dev/latvian/mods/kubejs/level/KubeJSWorldEventHandler.java @@ -1,52 +1,49 @@ package dev.latvian.mods.kubejs.level; -import dev.architectury.event.EventResult; -import dev.architectury.event.events.common.ExplosionEvent; -import dev.architectury.event.events.common.LifecycleEvent; -import dev.architectury.event.events.common.TickEvent; +import dev.latvian.mods.kubejs.KubeJS; import dev.latvian.mods.kubejs.bindings.event.LevelEvents; import dev.latvian.mods.kubejs.script.ScriptType; import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.level.Explosion; -import net.minecraft.world.level.Level; - -import java.util.List; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.event.level.ExplosionEvent; +import net.neoforged.neoforge.event.level.LevelEvent; +import net.neoforged.neoforge.event.tick.LevelTickEvent; +@EventBusSubscriber(modid = KubeJS.MOD_ID) public class KubeJSWorldEventHandler { - public static void init() { - LifecycleEvent.SERVER_LEVEL_LOAD.register(KubeJSWorldEventHandler::levelLoad); - LifecycleEvent.SERVER_LEVEL_UNLOAD.register(KubeJSWorldEventHandler::levelUnload); - TickEvent.SERVER_LEVEL_POST.register(KubeJSWorldEventHandler::levelPostTick); - ExplosionEvent.PRE.register(KubeJSWorldEventHandler::preExplosion); - ExplosionEvent.DETONATE.register(KubeJSWorldEventHandler::detonateExplosion); - } - - private static void levelLoad(ServerLevel level) { - if (LevelEvents.LOADED.hasListeners()) { - LevelEvents.LOADED.post(new SimpleLevelKubeEvent(level), level.dimension().location()); + @SubscribeEvent + public static void serverLevelLoad(LevelEvent.Load event) { + if (event.getLevel() instanceof ServerLevel level && LevelEvents.LOADED.hasListeners(level.dimension())) { + LevelEvents.LOADED.post(new SimpleLevelKubeEvent(level), level.dimension()); } } - private static void levelUnload(ServerLevel level) { - if (LevelEvents.UNLOADED.hasListeners()) { - LevelEvents.UNLOADED.post(new SimpleLevelKubeEvent(level), level.dimension().location()); + @SubscribeEvent + public static void serverLevelUnload(LevelEvent.Unload event) { + if (event.getLevel() instanceof ServerLevel level && LevelEvents.UNLOADED.hasListeners(level.dimension())) { + LevelEvents.UNLOADED.post(new SimpleLevelKubeEvent(level), level.dimension()); } } - private static void levelPostTick(ServerLevel level) { - if (LevelEvents.TICK.hasListeners()) { - LevelEvents.TICK.post(ScriptType.SERVER, level.dimension().location(), new SimpleLevelKubeEvent(level)); + @SubscribeEvent + public static void serverTickEvent(LevelTickEvent.Post event) { + if (event.getLevel() instanceof ServerLevel level && LevelEvents.TICK.hasListeners(level.dimension())) { + LevelEvents.TICK.post(ScriptType.SERVER, level.dimension(), new SimpleLevelKubeEvent(level)); } } - private static EventResult preExplosion(Level level, Explosion explosion) { - return LevelEvents.BEFORE_EXPLOSION.hasListeners() ? LevelEvents.BEFORE_EXPLOSION.post(level, new ExplosionKubeEvent.Before(level, explosion)).arch() : EventResult.pass(); + @SubscribeEvent + public static void preExplosion(ExplosionEvent.Start event) { + if (event.getLevel() instanceof ServerLevel level && LevelEvents.BEFORE_EXPLOSION.hasListeners(level.dimension())) { + LevelEvents.BEFORE_EXPLOSION.post(level, level.dimension(), new ExplosionKubeEvent.Before(level, event.getExplosion())).applyCancel(event); + } } - private static void detonateExplosion(Level level, Explosion explosion, List affectedEntities) { - if (LevelEvents.AFTER_EXPLOSION.hasListeners()) { - LevelEvents.AFTER_EXPLOSION.post(level, new ExplosionKubeEvent.After(level, explosion, affectedEntities)); + @SubscribeEvent + public static void detonateExplosion(ExplosionEvent.Detonate event) { + if (event.getLevel() instanceof ServerLevel level && LevelEvents.AFTER_EXPLOSION.hasListeners(level.dimension())) { + LevelEvents.AFTER_EXPLOSION.post(level, level.dimension(), new ExplosionKubeEvent.After(level, event.getExplosion(), event.getAffectedEntities())); } } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/level/SpawnerJS.java b/src/main/java/dev/latvian/mods/kubejs/level/SpawnerJS.java new file mode 100644 index 000000000..81ef01298 --- /dev/null +++ b/src/main/java/dev/latvian/mods/kubejs/level/SpawnerJS.java @@ -0,0 +1,24 @@ +package dev.latvian.mods.kubejs.level; + +import com.mojang.datafixers.util.Either; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.block.entity.BlockEntity; +import org.jetbrains.annotations.Nullable; + +public record SpawnerJS(@Nullable Entity entity, @Nullable BlockContainerJS block) { + public static SpawnerJS of(Either spawner) { + var e = spawner.right().orElse(null); + + if (e != null) { + return new SpawnerJS(e, null); + } + + var be = spawner.left().orElse(null); + + if (be != null) { + return new SpawnerJS(null, new BlockContainerJS(be)); + } + + return new SpawnerJS(null, null); + } +} diff --git a/src/main/java/dev/latvian/mods/kubejs/level/ruletest/AllMatchRuleTest.java b/src/main/java/dev/latvian/mods/kubejs/level/ruletest/AllMatchRuleTest.java index 2eb21d5e8..5092f316f 100644 --- a/src/main/java/dev/latvian/mods/kubejs/level/ruletest/AllMatchRuleTest.java +++ b/src/main/java/dev/latvian/mods/kubejs/level/ruletest/AllMatchRuleTest.java @@ -38,6 +38,6 @@ public boolean test(BlockState blockState, RandomSource random) { @Override protected RuleTestType getType() { - return KubeJSRuleTests.ALL_MATCH; + return KubeJSRuleTests.ALL_MATCH.get(); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/level/ruletest/AlwaysFalseRuleTest.java b/src/main/java/dev/latvian/mods/kubejs/level/ruletest/AlwaysFalseRuleTest.java index ee5ddaf1d..c78a137f8 100644 --- a/src/main/java/dev/latvian/mods/kubejs/level/ruletest/AlwaysFalseRuleTest.java +++ b/src/main/java/dev/latvian/mods/kubejs/level/ruletest/AlwaysFalseRuleTest.java @@ -21,7 +21,7 @@ public boolean test(BlockState blockState, RandomSource random) { @Override protected RuleTestType getType() { - return KubeJSRuleTests.ALWAYS_FALSE; + return KubeJSRuleTests.ALWAYS_FALSE.get(); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/level/ruletest/AnyMatchRuleTest.java b/src/main/java/dev/latvian/mods/kubejs/level/ruletest/AnyMatchRuleTest.java index 37c59fda2..0d7c97aaf 100644 --- a/src/main/java/dev/latvian/mods/kubejs/level/ruletest/AnyMatchRuleTest.java +++ b/src/main/java/dev/latvian/mods/kubejs/level/ruletest/AnyMatchRuleTest.java @@ -39,6 +39,6 @@ public boolean test(BlockState blockState, RandomSource random) { @Override protected RuleTestType getType() { - return KubeJSRuleTests.ANY_MATCH; + return KubeJSRuleTests.ANY_MATCH.get(); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/level/ruletest/InvertRuleTest.java b/src/main/java/dev/latvian/mods/kubejs/level/ruletest/InvertRuleTest.java index 8e32deac3..34362989c 100644 --- a/src/main/java/dev/latvian/mods/kubejs/level/ruletest/InvertRuleTest.java +++ b/src/main/java/dev/latvian/mods/kubejs/level/ruletest/InvertRuleTest.java @@ -25,6 +25,6 @@ public boolean test(BlockState blockState, RandomSource random) { @Override protected RuleTestType getType() { - return KubeJSRuleTests.INVERT; + return KubeJSRuleTests.INVERT.get(); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/level/ruletest/KubeJSRuleTests.java b/src/main/java/dev/latvian/mods/kubejs/level/ruletest/KubeJSRuleTests.java index 4daac1167..9deb47a30 100644 --- a/src/main/java/dev/latvian/mods/kubejs/level/ruletest/KubeJSRuleTests.java +++ b/src/main/java/dev/latvian/mods/kubejs/level/ruletest/KubeJSRuleTests.java @@ -1,27 +1,27 @@ package dev.latvian.mods.kubejs.level.ruletest; import com.mojang.serialization.MapCodec; -import dev.architectury.registry.registries.DeferredRegister; import dev.latvian.mods.kubejs.KubeJS; import net.minecraft.core.registries.Registries; import net.minecraft.world.level.levelgen.structure.templatesystem.RuleTest; import net.minecraft.world.level.levelgen.structure.templatesystem.RuleTestType; +import net.neoforged.neoforge.registries.DeferredRegister; + +import java.util.function.Supplier; public interface KubeJSRuleTests { - DeferredRegister> RULE_TEST_TYPES = DeferredRegister.create(KubeJS.MOD_ID, Registries.RULE_TEST); + DeferredRegister> RULE_TEST_TYPES = DeferredRegister.create(Registries.RULE_TEST, KubeJS.MOD_ID); - RuleTestType INVERT = register("invert", InvertRuleTest.CODEC); - RuleTestType ALWAYS_FALSE = register("always_false", AlwaysFalseRuleTest.CODEC); - RuleTestType ALL_MATCH = register("all_match", AllMatchRuleTest.CODEC); - RuleTestType ANY_MATCH = register("any_match", AnyMatchRuleTest.CODEC); + Supplier> INVERT = register("invert", InvertRuleTest.CODEC); + Supplier> ALWAYS_FALSE = register("always_false", AlwaysFalseRuleTest.CODEC); + Supplier> ALL_MATCH = register("all_match", AllMatchRuleTest.CODEC); + Supplier> ANY_MATCH = register("any_match", AnyMatchRuleTest.CODEC); - static

RuleTestType

register(String id, MapCodec

codec) { + static

Supplier> register(String id, MapCodec

codec) { var type = (RuleTestType

) () -> codec; - RULE_TEST_TYPES.register(id, () -> type); - return type; + return RULE_TEST_TYPES.register(id, () -> type); } static void init() { - RULE_TEST_TYPES.register(); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/neoforge/KubeJSEntryPoint.java b/src/main/java/dev/latvian/mods/kubejs/neoforge/KubeJSEntryPoint.java index b91899737..78a4add2d 100644 --- a/src/main/java/dev/latvian/mods/kubejs/neoforge/KubeJSEntryPoint.java +++ b/src/main/java/dev/latvian/mods/kubejs/neoforge/KubeJSEntryPoint.java @@ -2,17 +2,14 @@ import dev.latvian.mods.kubejs.CommonProperties; import dev.latvian.mods.kubejs.KubeJS; -import dev.latvian.mods.kubejs.KubeJSComponents; -import dev.latvian.mods.kubejs.bindings.event.EntityEvents; -import dev.latvian.mods.kubejs.bindings.event.ItemEvents; import dev.latvian.mods.kubejs.bindings.event.StartupEvents; -import dev.latvian.mods.kubejs.entity.LivingEntityDropsKubeEvent; -import dev.latvian.mods.kubejs.helpers.IngredientHelper; -import dev.latvian.mods.kubejs.item.ItemDestroyedKubeEvent; +import dev.latvian.mods.kubejs.gui.KubeJSMenus; +import dev.latvian.mods.kubejs.ingredient.KubeJSIngredients; import dev.latvian.mods.kubejs.item.creativetab.CreativeTabCallback; import dev.latvian.mods.kubejs.item.creativetab.CreativeTabKubeEvent; import dev.latvian.mods.kubejs.item.creativetab.KubeJSCreativeTabs; import dev.latvian.mods.kubejs.net.KubeJSNet; +import dev.latvian.mods.kubejs.recipe.KubeJSRecipeSerializers; import dev.latvian.mods.kubejs.registry.RegistryInfo; import dev.latvian.mods.kubejs.script.ScriptType; import dev.latvian.mods.kubejs.util.Cast; @@ -22,16 +19,11 @@ import net.neoforged.api.distmarker.Dist; import net.neoforged.bus.api.EventPriority; import net.neoforged.bus.api.IEventBus; -import net.neoforged.fml.ModContainer; import net.neoforged.fml.common.Mod; import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent; import net.neoforged.fml.event.lifecycle.FMLLoadCompleteEvent; -import net.neoforged.fml.loading.FMLEnvironment; -import net.neoforged.neoforge.common.NeoForge; import net.neoforged.neoforge.common.NeoForgeMod; import net.neoforged.neoforge.event.BuildCreativeModeTabContentsEvent; -import net.neoforged.neoforge.event.entity.living.LivingDropsEvent; -import net.neoforged.neoforge.event.entity.player.PlayerDestroyItemEvent; import net.neoforged.neoforge.registries.RegisterEvent; import java.util.AbstractMap; @@ -41,10 +33,9 @@ @Mod(KubeJS.MOD_ID) public class KubeJSEntryPoint { - private static final ThreadLocal BUS = new ThreadLocal<>(); - public KubeJSEntryPoint(IEventBus bus, Dist dist, ModContainer container) throws Throwable { + public KubeJSEntryPoint(IEventBus bus, Dist dist) throws Throwable { bus.addListener(EventPriority.LOW, KubeJSEntryPoint::loadComplete); bus.addListener(EventPriority.LOW, KubeJSEntryPoint::initRegistries); bus.addListener(EventPriority.LOW, KubeJSEntryPoint::commonSetup); @@ -53,25 +44,22 @@ public KubeJSEntryPoint(IEventBus bus, Dist dist, ModContainer container) throws BUS.set(bus); - KubeJS.instance = new KubeJS(); + KubeJS.instance = new KubeJS(bus); KubeJS.instance.setup(); if (CommonProperties.get().serverOnly) { // FIXME ModLoadingContext.get().registerExtensionPoint(DisplayTest.class, () -> new DisplayTest(() -> DisplayTest.IGNORESERVERONLY, (a, b) -> true)); - } - - NeoForge.EVENT_BUS.addListener(KubeJSEntryPoint::itemDestroyed); - NeoForge.EVENT_BUS.addListener(EventPriority.LOWEST, KubeJSEntryPoint::livingDrops); - - if (!CommonProperties.get().serverOnly) { + } else { NeoForgeMod.enableMilkFluid(); - IngredientHelper.register(bus); - KubeJSCreativeTabs.init(); - KubeJSComponents.init(); + KubeJSIngredients.REGISTRY.register(bus); + KubeJSCreativeTabs.REGISTRY.register(bus); + // KubeJSComponents.REGISTRY.register(bus); + KubeJSRecipeSerializers.REGISTRY.register(bus); + KubeJSMenus.REGISTRY.register(bus); } - if (FMLEnvironment.dist == Dist.CLIENT) { - new KubeJSNeoForgeClient(); + if (dist == Dist.CLIENT) { + new KubeJSNeoForgeClient(bus); } } @@ -144,25 +132,6 @@ private static void loadComplete(FMLLoadCompleteEvent event) { KubeJS.instance.loadComplete(); } - private static void itemDestroyed(PlayerDestroyItemEvent event) { - if (ItemEvents.ITEM_DESTROYED.hasListeners()) { - ItemEvents.ITEM_DESTROYED.post(event.getEntity(), event.getOriginal().getItem(), new ItemDestroyedKubeEvent(event)); - } - } - - private static void livingDrops(LivingDropsEvent event) { - if (EntityEvents.ENTITY_DROPS.hasListeners()) { - var e = new LivingEntityDropsKubeEvent(event); - - if (EntityEvents.ENTITY_DROPS.post(event.getEntity(), e.getEntity().getType(), e).interruptFalse()) { - event.setCanceled(true); - } else if (e.eventDrops != null) { - event.getDrops().clear(); - event.getDrops().addAll(e.eventDrops); - } - } - } - public static Optional eventBus() { return Optional.ofNullable(BUS.get()); } diff --git a/src/main/java/dev/latvian/mods/kubejs/neoforge/KubeJSNeoForgeClient.java b/src/main/java/dev/latvian/mods/kubejs/neoforge/KubeJSNeoForgeClient.java index 7ad31711a..4985e38fa 100644 --- a/src/main/java/dev/latvian/mods/kubejs/neoforge/KubeJSNeoForgeClient.java +++ b/src/main/java/dev/latvian/mods/kubejs/neoforge/KubeJSNeoForgeClient.java @@ -4,6 +4,7 @@ import dev.latvian.mods.kubejs.block.BlockBuilder; import dev.latvian.mods.kubejs.client.BlockTintFunctionWrapper; import dev.latvian.mods.kubejs.client.ItemTintFunctionWrapper; +import dev.latvian.mods.kubejs.client.KubeJSClientEventHandler; import dev.latvian.mods.kubejs.fluid.FluidBucketItemBuilder; import dev.latvian.mods.kubejs.fluid.FluidBuilder; import dev.latvian.mods.kubejs.item.ItemBuilder; @@ -11,16 +12,19 @@ import net.minecraft.client.renderer.ItemBlockRenderTypes; import net.minecraft.client.renderer.RenderType; import net.neoforged.bus.api.EventPriority; +import net.neoforged.bus.api.IEventBus; import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent; import net.neoforged.neoforge.client.event.RegisterColorHandlersEvent; +import net.neoforged.neoforge.client.event.ScreenEvent; +import net.neoforged.neoforge.common.NeoForge; public class KubeJSNeoForgeClient { - public KubeJSNeoForgeClient() { - var bus = KubeJSEntryPoint.eventBus().orElseThrow(); + public KubeJSNeoForgeClient(IEventBus bus) { bus.addListener(EventPriority.LOW, this::setupClient); bus.addListener(this::blockColors); bus.addListener(this::itemColors); //bus.addListener(this::textureStitch); + NeoForge.EVENT_BUS.addListener(EventPriority.LOW, this::openScreenEvent); } private void setupClient(FMLClientSetupEvent event) { @@ -80,4 +84,12 @@ private void itemColors(RegisterColorHandlersEvent.Item event) { /*private void textureStitch(TextureStitchEvent.Pre event) { ClientEvents.ATLAS_SPRITE_REGISTRY.post(new AtlasSpriteRegistryEventJS(event::addSprite), event.getAtlas().location()); }*/ + + private void openScreenEvent(ScreenEvent.Opening event) { + var s = KubeJSClientEventHandler.setScreen(event.getScreen()); + + if (s != null && event.getScreen() != s) { + event.setNewScreen(s); + } + } } diff --git a/src/main/java/dev/latvian/mods/kubejs/neoforge/NeoForgeKubeJSClientPlugin.java b/src/main/java/dev/latvian/mods/kubejs/neoforge/NeoForgeKubeJSClientPlugin.java deleted file mode 100644 index 7136deff4..000000000 --- a/src/main/java/dev/latvian/mods/kubejs/neoforge/NeoForgeKubeJSClientPlugin.java +++ /dev/null @@ -1,23 +0,0 @@ -package dev.latvian.mods.kubejs.neoforge; - -import dev.latvian.mods.kubejs.client.BuiltinKubeJSClientPlugin; -import dev.latvian.mods.kubejs.client.KubeJSClientEventHandler; -import net.neoforged.bus.api.EventPriority; -import net.neoforged.neoforge.client.event.ScreenEvent; -import net.neoforged.neoforge.common.NeoForge; - -public class NeoForgeKubeJSClientPlugin extends BuiltinKubeJSClientPlugin { - @Override - public void clientInit() { - super.clientInit(); - NeoForge.EVENT_BUS.addListener(EventPriority.LOW, this::openScreenEvent); - } - - private void openScreenEvent(ScreenEvent.Opening event) { - var s = KubeJSClientEventHandler.setScreen(event.getScreen()); - - if (s != null && event.getScreen() != s) { - event.setNewScreen(s); - } - } -} diff --git a/src/main/java/dev/latvian/mods/kubejs/neoforge/NeoForgeKubeJSPlugin.java b/src/main/java/dev/latvian/mods/kubejs/neoforge/NeoForgeKubeJSPlugin.java deleted file mode 100644 index 559b2a1c2..000000000 --- a/src/main/java/dev/latvian/mods/kubejs/neoforge/NeoForgeKubeJSPlugin.java +++ /dev/null @@ -1,32 +0,0 @@ -package dev.latvian.mods.kubejs.neoforge; - -import dev.latvian.mods.kubejs.BuiltinKubeJSPlugin; -import dev.latvian.mods.kubejs.script.BindingsEvent; -import dev.latvian.mods.kubejs.script.ScriptType; -import dev.latvian.mods.kubejs.util.ClassFilter; -import net.neoforged.neoforge.common.NeoForge; - -public class NeoForgeKubeJSPlugin extends BuiltinKubeJSPlugin { - @Override - public void registerClasses(ScriptType type, ClassFilter filter) { - super.registerClasses(type, filter); - - filter.allow("net.neoforged"); // Forge - filter.deny("net.neoforged.fml"); - filter.deny("net.neoforged.accesstransformer"); - filter.deny("net.neoforged.coremod"); - - filter.deny("cpw.mods.modlauncher"); // FML - filter.deny("cpw.mods.gross"); - } - - @Override - public void registerBindings(BindingsEvent event) { - super.registerBindings(event); - - if (event.type().isStartup()) { - event.add("NativeEvents", new NativeEventWrapper("NativeEvents", NeoForge.EVENT_BUS)); - KubeJSEntryPoint.eventBus().ifPresent(bus -> event.add("NativeModEvents", new NativeEventWrapper("NativeModEvents", bus))); - } - } -} diff --git a/src/main/java/dev/latvian/mods/kubejs/net/FirstClickPayload.java b/src/main/java/dev/latvian/mods/kubejs/net/FirstClickPayload.java index ba84b67aa..0755f8104 100644 --- a/src/main/java/dev/latvian/mods/kubejs/net/FirstClickPayload.java +++ b/src/main/java/dev/latvian/mods/kubejs/net/FirstClickPayload.java @@ -24,13 +24,21 @@ public void handle(IPayloadContext ctx) { if (clickType == 0 && ItemEvents.FIRST_LEFT_CLICKED.hasListeners()) { ctx.enqueueWork(() -> { var stack = serverPlayer.getItemInHand(InteractionHand.MAIN_HAND); - ItemEvents.FIRST_LEFT_CLICKED.post(ScriptType.SERVER, stack.getItem(), new ItemClickedKubeEvent(serverPlayer, InteractionHand.MAIN_HAND, stack)); + var key = stack.getItem().kjs$getRegistryKey(); + + if (ItemEvents.FIRST_LEFT_CLICKED.hasListeners(key)) { + ItemEvents.FIRST_LEFT_CLICKED.post(ScriptType.SERVER, key, new ItemClickedKubeEvent(serverPlayer, InteractionHand.MAIN_HAND, stack)); + } }); } else if (clickType == 1 && ItemEvents.FIRST_RIGHT_CLICKED.hasListeners()) { ctx.enqueueWork(() -> { for (var hand : InteractionHand.values()) { var stack = serverPlayer.getItemInHand(hand); - ItemEvents.FIRST_RIGHT_CLICKED.post(ScriptType.SERVER, stack.getItem(), new ItemClickedKubeEvent(serverPlayer, hand, stack)); + var key = stack.getItem().kjs$getRegistryKey(); + + if (ItemEvents.FIRST_RIGHT_CLICKED.hasListeners(key)) { + ItemEvents.FIRST_RIGHT_CLICKED.post(ScriptType.SERVER, key, new ItemClickedKubeEvent(serverPlayer, hand, stack)); + } } }); } diff --git a/src/main/java/dev/latvian/mods/kubejs/player/AdvancementJS.java b/src/main/java/dev/latvian/mods/kubejs/player/AdvancementJS.java deleted file mode 100644 index 95fc4cb9d..000000000 --- a/src/main/java/dev/latvian/mods/kubejs/player/AdvancementJS.java +++ /dev/null @@ -1,89 +0,0 @@ -package dev.latvian.mods.kubejs.player; - -import net.minecraft.advancements.Advancement; -import net.minecraft.advancements.AdvancementHolder; -import net.minecraft.advancements.AdvancementNode; -import net.minecraft.advancements.DisplayInfo; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; -import org.jetbrains.annotations.Nullable; - -import java.util.LinkedHashSet; -import java.util.Set; - -public class AdvancementJS { - public final AdvancementNode node; - - public final AdvancementHolder holder; - public final Advancement advancement; - - public AdvancementJS(AdvancementNode node) { - this.node = node; - this.holder = node.holder(); - this.advancement = node.advancement(); - } - - @Override - public boolean equals(Object o) { - return o == this || o instanceof AdvancementJS a && node.equals(a.node); - } - - @Override - public int hashCode() { - return node.hashCode(); - } - - @Override - public String toString() { - return getId().toString(); - } - - public ResourceLocation id() { - return getId(); - } - - public ResourceLocation getId() { - return node.holder().id(); - } - - @Nullable - public AdvancementJS getParent() { - var parent = node.parent(); - return parent == null ? null : new AdvancementJS(parent); - } - - public Set getChildren() { - Set set = new LinkedHashSet<>(); - - for (var a : node.children()) { - set.add(new AdvancementJS(a)); - } - - return set; - } - - public void addChild(AdvancementJS a) { - node.addChild(a.node); - } - - public Component getDisplayText() { - return advancement.name().orElse(Component.empty()); - } - - public boolean hasDisplay() { - return advancement.display().isPresent(); - } - - public Component getTitle() { - return advancement.display().map(DisplayInfo::getTitle).orElse(Component.empty()); - } - - public Component getDescription() { - return advancement.display().map(DisplayInfo::getDescription).orElse(Component.empty()); - } - - @Nullable - public DisplayInfo getDisplay() { - return advancement.display().orElse(null); - } -} \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/player/KubeJSInventoryListener.java b/src/main/java/dev/latvian/mods/kubejs/player/KubeJSInventoryListener.java index 411c758c5..58ad19bbc 100644 --- a/src/main/java/dev/latvian/mods/kubejs/player/KubeJSInventoryListener.java +++ b/src/main/java/dev/latvian/mods/kubejs/player/KubeJSInventoryListener.java @@ -15,8 +15,12 @@ public KubeJSInventoryListener(Player p) { @Override public void slotChanged(AbstractContainerMenu container, int index, ItemStack stack) { - if (PlayerEvents.INVENTORY_CHANGED.hasListeners() && !stack.isEmpty() && container.getSlot(index).container == player.getInventory()) { - PlayerEvents.INVENTORY_CHANGED.post(player, stack.getItem(), new InventoryChangedKubeEvent(player, stack, index)); + if (!stack.isEmpty() && container.getSlot(index).container == player.getInventory()) { + var key = stack.getItem().kjs$getRegistryKey(); + + if (PlayerEvents.INVENTORY_CHANGED.hasListeners(key)) { + PlayerEvents.INVENTORY_CHANGED.post(player, key, new InventoryChangedKubeEvent(player, stack, index)); + } } } diff --git a/src/main/java/dev/latvian/mods/kubejs/player/KubeJSPlayerEventHandler.java b/src/main/java/dev/latvian/mods/kubejs/player/KubeJSPlayerEventHandler.java index a9fe85ff6..6d232c194 100644 --- a/src/main/java/dev/latvian/mods/kubejs/player/KubeJSPlayerEventHandler.java +++ b/src/main/java/dev/latvian/mods/kubejs/player/KubeJSPlayerEventHandler.java @@ -1,97 +1,131 @@ package dev.latvian.mods.kubejs.player; -import dev.architectury.event.EventResult; -import dev.architectury.event.events.common.ChatEvent; -import dev.architectury.event.events.common.PlayerEvent; -import dev.architectury.event.events.common.TickEvent; import dev.latvian.mods.kubejs.CommonProperties; +import dev.latvian.mods.kubejs.KubeJS; import dev.latvian.mods.kubejs.bindings.event.PlayerEvents; +import dev.latvian.mods.kubejs.core.MenuTypeKJS; import dev.latvian.mods.kubejs.script.ScriptType; import dev.latvian.mods.kubejs.util.ConsoleJS; -import net.minecraft.advancements.AdvancementHolder; -import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.ChestMenu; import net.minecraft.world.inventory.InventoryMenu; - +import net.neoforged.bus.api.EventPriority; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.event.ServerChatEvent; +import net.neoforged.neoforge.event.entity.player.AdvancementEvent; +import net.neoforged.neoforge.event.entity.player.PlayerContainerEvent; +import net.neoforged.neoforge.event.entity.player.PlayerEvent; +import net.neoforged.neoforge.event.tick.PlayerTickEvent; + +@EventBusSubscriber(modid = KubeJS.MOD_ID) public class KubeJSPlayerEventHandler { - public static void init() { - PlayerEvent.PLAYER_JOIN.register(KubeJSPlayerEventHandler::loggedIn); - PlayerEvent.PLAYER_QUIT.register(KubeJSPlayerEventHandler::loggedOut); - TickEvent.PLAYER_POST.register(KubeJSPlayerEventHandler::tick); - ChatEvent.DECORATE.register(KubeJSPlayerEventHandler::chatDecorate); - ChatEvent.RECEIVED.register(KubeJSPlayerEventHandler::chatReceived); - PlayerEvent.PLAYER_ADVANCEMENT.register(KubeJSPlayerEventHandler::advancement); - PlayerEvent.OPEN_MENU.register(KubeJSPlayerEventHandler::inventoryOpened); - PlayerEvent.CLOSE_MENU.register(KubeJSPlayerEventHandler::inventoryClosed); - } + @SubscribeEvent + public static void loggedIn(PlayerEvent.PlayerLoggedInEvent event) { + if (PlayerEvents.LOGGED_IN.hasListeners() && event.getEntity() instanceof ServerPlayer player) { + PlayerEvents.LOGGED_IN.post(ScriptType.SERVER, new SimplePlayerKubeEvent(player)); + player.inventoryMenu.addSlotListener(player.kjs$getInventoryChangeListener()); - public static void loggedIn(ServerPlayer player) { - PlayerEvents.LOGGED_IN.post(ScriptType.SERVER, new SimplePlayerKubeEvent(player)); - player.inventoryMenu.addSlotListener(player.kjs$getInventoryChangeListener()); + if (!ConsoleJS.SERVER.errors.isEmpty() && !CommonProperties.get().hideServerScriptErrors) { + player.displayClientMessage(ConsoleJS.SERVER.errorsComponent("/kubejs errors server"), false); + } - if (!ConsoleJS.SERVER.errors.isEmpty() && !CommonProperties.get().hideServerScriptErrors) { - player.displayClientMessage(ConsoleJS.SERVER.errorsComponent("/kubejs errors server"), false); + player.kjs$getStages().sync(); } + } - player.kjs$getStages().sync(); + @SubscribeEvent + public static void cloned(PlayerEvent.Clone event) { + if (event.getOriginal() instanceof ServerPlayer oldPlayer && event.getEntity() instanceof ServerPlayer newPlayer) { + newPlayer.kjs$setRawPersistentData(oldPlayer.kjs$getRawPersistentData()); + newPlayer.inventoryMenu.addSlotListener(newPlayer.kjs$getInventoryChangeListener()); // move this to respawn? + PlayerEvents.CLONED.post(ScriptType.SERVER, new PlayerClonedKubeEvent(newPlayer, oldPlayer, !event.isWasDeath())); + } } - public static void respawn(ServerPlayer oldPlayer, ServerPlayer newPlayer, boolean keepData) { - newPlayer.kjs$setRawPersistentData(oldPlayer.kjs$getRawPersistentData()); - newPlayer.inventoryMenu.addSlotListener(newPlayer.kjs$getInventoryChangeListener()); - PlayerEvents.RESPAWNED.post(ScriptType.SERVER, new PlayerRespawnedKubeEvent(newPlayer, oldPlayer, keepData)); - newPlayer.kjs$getStages().sync(); + @SubscribeEvent + public static void respawn(PlayerEvent.PlayerRespawnEvent event) { + if (PlayerEvents.RESPAWNED.hasListeners() && event.getEntity() instanceof ServerPlayer player) { + PlayerEvents.RESPAWNED.post(ScriptType.SERVER, new PlayerRespawnedKubeEvent(player, event.isEndConquered())); + player.kjs$getStages().sync(); + } } - public static void loggedOut(ServerPlayer player) { - PlayerEvents.LOGGED_OUT.post(ScriptType.SERVER, new SimplePlayerKubeEvent(player)); + @SubscribeEvent + public static void loggedOut(net.neoforged.neoforge.event.entity.player.PlayerEvent.PlayerLoggedOutEvent event) { + if (PlayerEvents.LOGGED_OUT.hasListeners() && event.getEntity() instanceof ServerPlayer player) { + PlayerEvents.LOGGED_OUT.post(ScriptType.SERVER, new SimplePlayerKubeEvent(player)); + } } - public static void tick(Player player) { - if (PlayerEvents.TICK.hasListeners()) { + @SubscribeEvent + public static void tick(PlayerTickEvent.Post event) { + if (PlayerEvents.TICK.hasListeners() && event.getEntity() instanceof ServerPlayer player) { PlayerEvents.TICK.post(player, new SimplePlayerKubeEvent(player)); } } - public static void chatDecorate(ServerPlayer player, ChatEvent.ChatComponent component) { - PlayerEvents.DECORATE_CHAT.post(ScriptType.SERVER, new PlayerChatDecorateKubeEvent(player, component)); + @SubscribeEvent(priority = EventPriority.HIGHEST) + public static void chatDecorate(ServerChatEvent event) { + if (PlayerEvents.DECORATE_CHAT.hasListeners()) { + PlayerEvents.DECORATE_CHAT.post(ScriptType.SERVER, new PlayerChatReceivedKubeEvent(event)).applyCancel(event); + } } - public static EventResult chatReceived(ServerPlayer player, Component component) { - return PlayerEvents.CHAT.hasListeners() ? PlayerEvents.CHAT.post(ScriptType.SERVER, new PlayerChatReceivedKubeEvent(player, component)).arch() : EventResult.pass(); + @SubscribeEvent(priority = EventPriority.LOW) + public static void chatReceived(ServerChatEvent event) { + if (PlayerEvents.CHAT.hasListeners()) { + PlayerEvents.CHAT.post(ScriptType.SERVER, new PlayerChatReceivedKubeEvent(event)).applyCancel(event); + } } - public static void advancement(ServerPlayer player, AdvancementHolder advancement) { - if (PlayerEvents.ADVANCEMENT.hasListeners()) { - var id = advancement.id(); - PlayerEvents.ADVANCEMENT.post(new PlayerAdvancementKubeEvent(player, id), id); + @SubscribeEvent + public static void advancement(AdvancementEvent.AdvancementEarnEvent event) { + var id = event.getAdvancement().id(); + + if (PlayerEvents.ADVANCEMENT.hasListeners(id) && event.getEntity() instanceof ServerPlayer player) { + PlayerEvents.ADVANCEMENT.post(new PlayerAdvancementKubeEvent(player, player.server.kjs$getAdvancement(id)), id); } } - public static void inventoryOpened(Player player, AbstractContainerMenu menu) { - if (!(menu instanceof InventoryMenu)) { - menu.addSlotListener(player.kjs$getInventoryChangeListener()); - } + @SubscribeEvent + public static void inventoryOpened(PlayerContainerEvent.Open event) { + if (event.getEntity() instanceof ServerPlayer player) { + var menu = event.getContainer(); - if (PlayerEvents.INVENTORY_OPENED.hasListeners()) { - PlayerEvents.INVENTORY_OPENED.post(player, menu, new InventoryKubeEvent(player, menu)); - } + if (!(menu instanceof InventoryMenu)) { + menu.addSlotListener(player.kjs$getInventoryChangeListener()); + } - if (menu instanceof ChestMenu && PlayerEvents.CHEST_OPENED.hasListeners()) { - PlayerEvents.CHEST_OPENED.post(player, menu, new ChestKubeEvent(player, menu)); - } - } + var key = ((MenuTypeKJS) menu.getType()).kjs$getRegistryKey(); + + if (key != null) { + if (PlayerEvents.INVENTORY_OPENED.hasListeners(key)) { + PlayerEvents.INVENTORY_OPENED.post(player, key, new InventoryKubeEvent(player, menu)); + } - public static void inventoryClosed(Player player, AbstractContainerMenu menu) { - if (PlayerEvents.INVENTORY_CLOSED.hasListeners()) { - PlayerEvents.INVENTORY_CLOSED.post(player, menu, new InventoryKubeEvent(player, menu)); + if (menu instanceof ChestMenu && PlayerEvents.CHEST_OPENED.hasListeners(key)) { + PlayerEvents.CHEST_OPENED.post(player, key, new ChestKubeEvent(player, menu)); + } + } } + } - if (menu instanceof ChestMenu && PlayerEvents.CHEST_CLOSED.hasListeners()) { - PlayerEvents.CHEST_CLOSED.post(player, menu, new ChestKubeEvent(player, menu)); + @SubscribeEvent + public static void inventoryClosed(PlayerContainerEvent.Close event) { + if (event.getEntity() instanceof ServerPlayer player) { + var menu = event.getContainer(); + var key = ((MenuTypeKJS) menu.getType()).kjs$getRegistryKey(); + + if (key != null) { + if (PlayerEvents.INVENTORY_CLOSED.hasListeners(key)) { + PlayerEvents.INVENTORY_CLOSED.post(player, key, new InventoryKubeEvent(player, menu)); + } + + if (menu instanceof ChestMenu && PlayerEvents.CHEST_CLOSED.hasListeners(key)) { + PlayerEvents.CHEST_CLOSED.post(player, key, new ChestKubeEvent(player, menu)); + } + } } } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/player/PlayerAdvancementKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/player/PlayerAdvancementKubeEvent.java index 7deda6277..73e520c02 100644 --- a/src/main/java/dev/latvian/mods/kubejs/player/PlayerAdvancementKubeEvent.java +++ b/src/main/java/dev/latvian/mods/kubejs/player/PlayerAdvancementKubeEvent.java @@ -1,7 +1,7 @@ package dev.latvian.mods.kubejs.player; import dev.latvian.mods.kubejs.typings.Info; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.advancements.AdvancementNode; import net.minecraft.server.level.ServerPlayer; @Info(""" @@ -9,11 +9,11 @@ """) public class PlayerAdvancementKubeEvent implements KubePlayerEvent { private final ServerPlayer player; - private final ResourceLocation id; + private final AdvancementNode advancementNode; - public PlayerAdvancementKubeEvent(ServerPlayer player, ResourceLocation id) { + public PlayerAdvancementKubeEvent(ServerPlayer player, AdvancementNode advancementNode) { this.player = player; - this.id = id; + this.advancementNode = advancementNode; } @Override @@ -23,7 +23,7 @@ public ServerPlayer getEntity() { } @Info("Returns the advancement that was obtained.") - public AdvancementJS getAdvancement() { - return player.server.kjs$getAdvancement(id); + public AdvancementNode getAdvancement() { + return advancementNode; } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/player/PlayerChatDecorateKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/player/PlayerChatDecorateKubeEvent.java deleted file mode 100644 index 391d3b8a4..000000000 --- a/src/main/java/dev/latvian/mods/kubejs/player/PlayerChatDecorateKubeEvent.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.latvian.mods.kubejs.player; - -import dev.architectury.event.events.common.ChatEvent; -import dev.latvian.mods.kubejs.typings.Info; -import net.minecraft.network.chat.Component; -import net.minecraft.server.level.ServerPlayer; - -@Info(""" - Invoked when a player sends a chat message. - - If cancelled (`PlayerEvents.chat`), the message will not be sent. - """) -public class PlayerChatDecorateKubeEvent implements KubePlayerEvent { - private final ServerPlayer player; - public ChatEvent.ChatComponent chatComponent; - - public PlayerChatDecorateKubeEvent(ServerPlayer player, ChatEvent.ChatComponent chatComponent) { - this.player = player; - this.chatComponent = chatComponent; - } - - @Override - @Info("Gets the player that sent the message.") - public ServerPlayer getEntity() { - return player; - } - - @Info("Gets the username of the player that sent the message.") - public String getUsername() { - return player.getGameProfile().getName(); - } - - @Info("Gets the message that the player sent.") - public String getMessage() { - return chatComponent.get().getString(); - } - - @Info("Gets the message that the player sent.") - public Component getComponent() { - return chatComponent.get(); - } - - @Info("Sets the message that the player sent.") - public void setMessage(Component text) { - chatComponent.set(text); - } - - @Info("Sets the message that the player sent.") - public void setComponent(Component text) { - chatComponent.set(text); - } -} \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/player/PlayerChatReceivedKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/player/PlayerChatReceivedKubeEvent.java index 0c845a029..2abb42816 100644 --- a/src/main/java/dev/latvian/mods/kubejs/player/PlayerChatReceivedKubeEvent.java +++ b/src/main/java/dev/latvian/mods/kubejs/player/PlayerChatReceivedKubeEvent.java @@ -1,32 +1,34 @@ package dev.latvian.mods.kubejs.player; import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.MutableComponent; import net.minecraft.server.level.ServerPlayer; +import net.neoforged.neoforge.event.ServerChatEvent; public class PlayerChatReceivedKubeEvent implements KubePlayerEvent { - private final ServerPlayer player; - public final Component component; + private final ServerChatEvent event; - public PlayerChatReceivedKubeEvent(ServerPlayer player, Component component) { - this.player = player; - this.component = component; + public PlayerChatReceivedKubeEvent(ServerChatEvent event) { + this.event = event; } @Override public ServerPlayer getEntity() { - return player; + return event.getPlayer(); } public String getUsername() { - return player.getGameProfile().getName(); + return event.getPlayer().getGameProfile().getName(); } public String getMessage() { - return component.getString(); + return event.getRawText(); } - public MutableComponent getComponent() { - return component.copy(); + public Component getComponent() { + return event.getMessage(); + } + + public void setComponent(Component component) { + event.setMessage(component); } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/player/PlayerClonedKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/player/PlayerClonedKubeEvent.java new file mode 100644 index 000000000..d6d2e95b4 --- /dev/null +++ b/src/main/java/dev/latvian/mods/kubejs/player/PlayerClonedKubeEvent.java @@ -0,0 +1,37 @@ +package dev.latvian.mods.kubejs.player; + +import dev.latvian.mods.kubejs.typings.Info; +import net.minecraft.server.level.ServerPlayer; + +@Info(""" + Invoked when a player respawns. + + The reason of respawn can be either death or returning from the end. + """) +public class PlayerClonedKubeEvent implements KubePlayerEvent { + private final ServerPlayer player; + private final ServerPlayer oldPlayer; + private final boolean keepData; + + public PlayerClonedKubeEvent(ServerPlayer player, ServerPlayer oldPlayer, boolean keepData) { + this.player = player; + this.oldPlayer = oldPlayer; + this.keepData = keepData; + } + + @Override + @Info("Gets the player that respawned.") + public ServerPlayer getEntity() { + return player; + } + + @Info("Gets the player that was before respawn. Note that this entity is already removed from the world.") + public ServerPlayer getOldPlayer() { + return oldPlayer; + } + + @Info("Gets whether the player's data was kept, e.g. when returning from the end.") + public boolean getKeepData() { + return keepData; + } +} \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/player/PlayerRespawnedKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/player/PlayerRespawnedKubeEvent.java index 86a7bc758..03d79c6e5 100644 --- a/src/main/java/dev/latvian/mods/kubejs/player/PlayerRespawnedKubeEvent.java +++ b/src/main/java/dev/latvian/mods/kubejs/player/PlayerRespawnedKubeEvent.java @@ -10,13 +10,11 @@ """) public class PlayerRespawnedKubeEvent implements KubePlayerEvent { private final ServerPlayer player; - private final ServerPlayer oldPlayer; - private final boolean keepData; + private final boolean endConquered; - public PlayerRespawnedKubeEvent(ServerPlayer player, ServerPlayer oldPlayer, boolean keepData) { + public PlayerRespawnedKubeEvent(ServerPlayer player, boolean endConquered) { this.player = player; - this.oldPlayer = oldPlayer; - this.keepData = keepData; + this.endConquered = endConquered; } @Override @@ -25,13 +23,7 @@ public ServerPlayer getEntity() { return player; } - @Info("Gets the player that was before respawn. Note that this entity is already removed from the world.") - public ServerPlayer getOldPlayer() { - return oldPlayer; - } - - @Info("Gets whether the player's data was kept, e.g. when returning from the end.") - public boolean getKeepData() { - return keepData; + public boolean isEndConquered() { + return endConquered; } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/CompostableRecipesKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/recipe/CompostableRecipesKubeEvent.java index 013bc6774..8b07d378e 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/CompostableRecipesKubeEvent.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/CompostableRecipesKubeEvent.java @@ -8,6 +8,7 @@ import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.ComposterBlock; +// FIXME public class CompostableRecipesKubeEvent implements KubeEvent { public static Object2FloatMap originalMap = null; diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/KubeJSRecipeEventHandler.java b/src/main/java/dev/latvian/mods/kubejs/recipe/KubeJSRecipeEventHandler.java deleted file mode 100644 index 5d7c2e5df..000000000 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/KubeJSRecipeEventHandler.java +++ /dev/null @@ -1,30 +0,0 @@ -package dev.latvian.mods.kubejs.recipe; - -import dev.architectury.registry.registries.DeferredRegister; -import dev.latvian.mods.kubejs.CommonProperties; -import dev.latvian.mods.kubejs.KubeJS; -import dev.latvian.mods.kubejs.recipe.special.ShapedKubeJSRecipe; -import dev.latvian.mods.kubejs.recipe.special.ShapelessKubeJSRecipe; -import net.minecraft.core.registries.Registries; -import net.minecraft.world.item.crafting.RecipeSerializer; - -import java.util.function.Supplier; - -public class KubeJSRecipeEventHandler { - public static final DeferredRegister> REGISTER = DeferredRegister.create(KubeJS.MOD_ID, Registries.RECIPE_SERIALIZER); - - public static Supplier> SHAPED; - public static Supplier> SHAPELESS; - - public static void init() { - if (!CommonProperties.get().serverOnly) { - registry(); - } - } - - private static void registry() { - SHAPED = REGISTER.register("shaped", ShapedKubeJSRecipe.SerializerKJS::new); - SHAPELESS = REGISTER.register("shapeless", ShapelessKubeJSRecipe.SerializerKJS::new); - REGISTER.register(); - } -} diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/KubeJSRecipeSerializers.java b/src/main/java/dev/latvian/mods/kubejs/recipe/KubeJSRecipeSerializers.java new file mode 100644 index 000000000..0a8b27f9a --- /dev/null +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/KubeJSRecipeSerializers.java @@ -0,0 +1,17 @@ +package dev.latvian.mods.kubejs.recipe; + +import dev.latvian.mods.kubejs.KubeJS; +import dev.latvian.mods.kubejs.recipe.special.ShapedKubeJSRecipe; +import dev.latvian.mods.kubejs.recipe.special.ShapelessKubeJSRecipe; +import net.minecraft.core.registries.Registries; +import net.minecraft.world.item.crafting.RecipeSerializer; +import net.neoforged.neoforge.registries.DeferredRegister; + +import java.util.function.Supplier; + +public interface KubeJSRecipeSerializers { + DeferredRegister> REGISTRY = DeferredRegister.create(Registries.RECIPE_SERIALIZER, KubeJS.MOD_ID); + + Supplier> SHAPED = REGISTRY.register("shaped", ShapedKubeJSRecipe.SerializerKJS::new); + Supplier> SHAPELESS = REGISTRY.register("shapeless", ShapelessKubeJSRecipe.SerializerKJS::new); +} diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/KubeRecipe.java b/src/main/java/dev/latvian/mods/kubejs/recipe/KubeRecipe.java index a17cc621f..969814018 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/KubeRecipe.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/KubeRecipe.java @@ -22,6 +22,7 @@ import dev.latvian.mods.kubejs.recipe.ingredientaction.KeepAction; import dev.latvian.mods.kubejs.recipe.ingredientaction.ReplaceAction; import dev.latvian.mods.kubejs.recipe.schema.RecipeSchema; +import dev.latvian.mods.kubejs.util.Cast; import dev.latvian.mods.kubejs.util.ConsoleJS; import dev.latvian.mods.kubejs.util.UtilsJS; import dev.latvian.mods.rhino.Context; @@ -73,7 +74,7 @@ public final Scriptable convertJavaToJs(Context cx, Scriptable scope, TypeInfo s public void deserialize(boolean merge) { for (var v : valueMap.holders) { - v.key.component.readFromJson(this, UtilsJS.cast(v), json); + v.key.component.readFromJson(this, Cast.to(v), json); if (v.value != null) { if (merge) { @@ -92,7 +93,7 @@ public void serialize() { throw new RecipeExceptionJS("Value not set for " + v.key + " in recipe " + this); } - v.key.component.writeToJson(this, UtilsJS.cast(v), json); + v.key.component.writeToJson(this, Cast.to(v), json); } } } @@ -104,11 +105,11 @@ public T getValue(RecipeKey key) { throw new MissingComponentException(key.name, key, valueMap.keySet()); } - return UtilsJS.cast(v.value); + return Cast.to(v.value); } public KubeRecipe setValue(RecipeKey key, T value) { - RecipeComponentValue v = UtilsJS.cast(valueMap.getHolder(key)); + RecipeComponentValue v = Cast.to(valueMap.getHolder(key)); if (v == null) { throw new MissingComponentException(key.name, key, valueMap.keySet()); @@ -135,11 +136,11 @@ public Object get(String key) { } // intended for use by scripts - public KubeRecipe set(String key, Object value) { + public KubeRecipe set(Context cx, String key, Object value) { for (var h : valueMap.holders) { for (var name : h.key.names) { if (name.equals(key)) { - h.value = UtilsJS.cast(h.key.component.read(this, Wrapper.unwrapped(value))); + h.value = Cast.to(h.key.component.read(this, Wrapper.unwrapped(value))); h.write(); save(); return this; @@ -162,7 +163,7 @@ public void initValues(boolean created) { for (var v : valueMap.holders) { if (v.key.alwaysWrite || !v.key.optional()) { if (v.key.alwaysWrite) { - v.value = UtilsJS.cast(v.key.component.read(this, v.key.optional.getDefaultValue(type.schemaType))); + v.value = Cast.to(v.key.component.read(this, v.key.optional.getDefaultValue(type.schemaType))); } v.write(); @@ -294,7 +295,7 @@ public final boolean hasChanged() { public final RecipeComponentValue[] inputValues() { if (inputValues == null) { if (type.schemaType.schema.inputCount() == 0) { - inputValues = UtilsJS.cast(RecipeComponentValue.EMPTY_ARRAY); + inputValues = Cast.to(RecipeComponentValue.EMPTY_ARRAY); } else { var list = new ArrayList<>(type.schemaType.schema.inputCount()); @@ -315,7 +316,7 @@ public final RecipeComponentValue[] inputValues() { public final RecipeComponentValue[] outputValues() { if (outputValues == null) { if (type.schemaType.schema.outputCount() == 0) { - outputValues = UtilsJS.cast(RecipeComponentValue.EMPTY_ARRAY); + outputValues = Cast.to(RecipeComponentValue.EMPTY_ARRAY); } else { var list = new ArrayList<>(type.schemaType.schema.outputCount()); diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/RecipeKey.java b/src/main/java/dev/latvian/mods/kubejs/recipe/RecipeKey.java index 8bf3a3dfa..23af3b826 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/RecipeKey.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/RecipeKey.java @@ -3,7 +3,7 @@ import dev.latvian.mods.kubejs.recipe.component.RecipeComponent; import dev.latvian.mods.kubejs.recipe.schema.RecipeOptional; import dev.latvian.mods.kubejs.recipe.schema.RecipeSchema; -import dev.latvian.mods.kubejs.util.UtilsJS; +import dev.latvian.mods.kubejs.util.Cast; import java.util.LinkedHashSet; import java.util.List; @@ -114,7 +114,7 @@ public RecipeKey optional(RecipeOptional value) { * @see #optional(RecipeOptional) */ public RecipeKey defaultOptional() { - optional = UtilsJS.cast(RecipeOptional.DEFAULT); + optional = Cast.to(RecipeOptional.DEFAULT); return this; } diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/RecipeTypeFunction.java b/src/main/java/dev/latvian/mods/kubejs/recipe/RecipeTypeFunction.java index a16b8d47c..a1bc13f41 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/RecipeTypeFunction.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/RecipeTypeFunction.java @@ -34,7 +34,7 @@ public RecipeTypeFunction(RecipesKubeEvent event, RecipeSchemaType schemaType) { @Override public KubeRecipe call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args0) { try { - return createRecipe(args0); + return createRecipe(cx, args0); } catch (RecipeExceptionJS rex) { if (rex.error) { throw rex; @@ -44,7 +44,7 @@ public KubeRecipe call(Context cx, Scriptable scope, Scriptable thisObj, Object[ } } - public KubeRecipe createRecipe(Object[] args) { + public KubeRecipe createRecipe(Context cx, Object[] args) { try { for (int i = 0; i < args.length; i++) { args[i] = Wrapper.unwrapped(args[i]); @@ -81,7 +81,7 @@ public KubeRecipe createRecipe(Object[] args) { argMap.put(key, Wrapper.unwrapped(args[index++])); } - var recipe = constructor.factory().create(this, schemaType, constructor.keys(), argMap); + var recipe = constructor.factory().create(cx, this, schemaType, constructor.keys(), argMap); recipe.afterLoaded(); return event.addRecipe(recipe, false); } catch (RecipeExceptionJS rex) { diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/RecipesKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/recipe/RecipesKubeEvent.java index e385cc020..f1baf37b1 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/RecipesKubeEvent.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/RecipesKubeEvent.java @@ -9,6 +9,7 @@ import dev.latvian.mods.kubejs.DevProperties; import dev.latvian.mods.kubejs.bindings.event.ServerEvents; import dev.latvian.mods.kubejs.core.RecipeLikeKJS; +import dev.latvian.mods.kubejs.core.RecipeManagerKJS; import dev.latvian.mods.kubejs.event.EventExceptionHandler; import dev.latvian.mods.kubejs.event.KubeEvent; import dev.latvian.mods.kubejs.helpers.RecipeHelper; @@ -26,8 +27,8 @@ import dev.latvian.mods.kubejs.registry.RegistryInfo; import dev.latvian.mods.kubejs.script.ScriptType; import dev.latvian.mods.kubejs.server.DataExport; -import dev.latvian.mods.kubejs.server.KubeJSReloadListener; import dev.latvian.mods.kubejs.util.ConsoleJS; +import dev.latvian.mods.kubejs.util.ID; import dev.latvian.mods.kubejs.util.JsonIO; import dev.latvian.mods.kubejs.util.JsonUtils; import dev.latvian.mods.kubejs.util.KubeJSPlugins; @@ -38,6 +39,7 @@ import net.minecraft.core.HolderLookup; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.Bootstrap; +import net.minecraft.server.ReloadableServerResources; import net.minecraft.util.GsonHelper; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Recipe; @@ -269,8 +271,10 @@ public RecipesKubeEvent(HolderLookup.Provider registries) { public void post(RecipeManager recipeManager, Map datapackRecipeMap) { ConsoleJS.SERVER.info("Processing recipes..."); KubeRecipe.itemErrors = false; + var resources = ((RecipeManagerKJS) recipeManager).kjs$getResources(); + var cx = resources.kjs$getServerScriptManager().contextFactory.enter(); - TagContext.INSTANCE.setValue(TagContext.fromLoadResult(KubeJSReloadListener.resources.tagManager.getResult())); + TagContext.INSTANCE.setValue(TagContext.fromLoadResult(((ReloadableServerResources) resources).tagManager.getResult())); // clear recipe event specific maps RecipesKubeEvent.MODIFY_RESULT_CALLBACKS.clear(); @@ -619,7 +623,7 @@ public void replaceOutput(RecipeFilter filter, ReplacementMatch match, OutputRep public RecipeTypeFunction getRecipeFunction(@Nullable String id) { if (id == null || id.isEmpty()) { return null; - } else if (recipeFunctions.get(UtilsJS.getID(id)) instanceof RecipeTypeFunction fn) { + } else if (recipeFunctions.get(ID.string(id)) instanceof RecipeTypeFunction fn) { return fn; } else { return null; diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/component/BlockComponent.java b/src/main/java/dev/latvian/mods/kubejs/recipe/component/BlockComponent.java index 9cb87661b..3604c9197 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/component/BlockComponent.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/component/BlockComponent.java @@ -1,12 +1,12 @@ package dev.latvian.mods.kubejs.recipe.component; import com.google.gson.JsonPrimitive; +import dev.latvian.mods.kubejs.bindings.BlockWrapper; import dev.latvian.mods.kubejs.block.state.BlockStatePredicate; import dev.latvian.mods.kubejs.recipe.KubeRecipe; import dev.latvian.mods.kubejs.recipe.RecipeKey; import dev.latvian.mods.kubejs.recipe.ReplacementMatch; import dev.latvian.mods.kubejs.registry.RegistryInfo; -import dev.latvian.mods.kubejs.util.UtilsJS; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; @@ -43,9 +43,9 @@ public Block read(KubeRecipe recipe, Object from) { } else if (from instanceof BlockState s) { return s.getBlock(); } else if (from instanceof JsonPrimitive json) { - return UtilsJS.parseBlockState(json.getAsString()).getBlock(); + return BlockWrapper.parseBlockState(json.getAsString()).getBlock(); } else { - return UtilsJS.parseBlockState(String.valueOf(from)).getBlock(); + return BlockWrapper.parseBlockState(String.valueOf(from)).getBlock(); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/component/BlockStateComponent.java b/src/main/java/dev/latvian/mods/kubejs/recipe/component/BlockStateComponent.java index 4fd9a5c24..8946a236e 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/component/BlockStateComponent.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/component/BlockStateComponent.java @@ -4,13 +4,13 @@ import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import com.mojang.serialization.JsonOps; +import dev.latvian.mods.kubejs.bindings.BlockWrapper; import dev.latvian.mods.kubejs.block.state.BlockStatePredicate; import dev.latvian.mods.kubejs.recipe.KubeRecipe; import dev.latvian.mods.kubejs.recipe.RecipeExceptionJS; import dev.latvian.mods.kubejs.recipe.RecipeKey; import dev.latvian.mods.kubejs.recipe.ReplacementMatch; import dev.latvian.mods.kubejs.util.MapJS; -import dev.latvian.mods.kubejs.util.UtilsJS; import net.minecraft.commands.arguments.blocks.BlockStateParser; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; @@ -62,11 +62,11 @@ public BlockState read(KubeRecipe recipe, Object from) { } else if (from instanceof Block b) { return b.defaultBlockState(); } else if (from instanceof JsonPrimitive json) { - return UtilsJS.parseBlockState(json.getAsString()); + return BlockWrapper.parseBlockState(json.getAsString()); } else { Map map = MapJS.of(from); if (map == null) { - return UtilsJS.parseBlockState(String.valueOf(from)); + return BlockWrapper.parseBlockState(String.valueOf(from)); } else // this is formatted like so: // { Name: "blockid", Properties: {Property: "value"}} diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/component/EnumComponent.java b/src/main/java/dev/latvian/mods/kubejs/recipe/component/EnumComponent.java index 8258b1711..d72899b39 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/component/EnumComponent.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/component/EnumComponent.java @@ -6,7 +6,7 @@ import dev.latvian.mods.kubejs.recipe.schema.DynamicRecipeComponent; import dev.latvian.mods.kubejs.typings.desc.DescriptionContext; import dev.latvian.mods.kubejs.typings.desc.TypeDescJS; -import dev.latvian.mods.kubejs.util.UtilsJS; +import dev.latvian.mods.kubejs.util.Cast; import dev.latvian.mods.rhino.NativeJavaClass; import java.util.function.BiFunction; @@ -45,7 +45,7 @@ public record EnumComponent>(Class enumType, Function enumType) { - this(enumType, UtilsJS.cast(DEFAULT_TO_STRING), UtilsJS.cast(DEFAULT_TO_ENUM)); + this(enumType, Cast.to(DEFAULT_TO_STRING), Cast.to(DEFAULT_TO_ENUM)); } @Override diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/component/RecipeComponentBuilder.java b/src/main/java/dev/latvian/mods/kubejs/recipe/component/RecipeComponentBuilder.java index 0ae7e69a5..4f2e5a4ff 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/component/RecipeComponentBuilder.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/component/RecipeComponentBuilder.java @@ -9,7 +9,7 @@ import dev.latvian.mods.kubejs.recipe.ReplacementMatch; import dev.latvian.mods.kubejs.typings.desc.DescriptionContext; import dev.latvian.mods.kubejs.typings.desc.TypeDescJS; -import dev.latvian.mods.kubejs.util.UtilsJS; +import dev.latvian.mods.kubejs.util.Cast; import java.util.ArrayList; import java.util.List; @@ -88,8 +88,8 @@ public JsonElement write(KubeRecipe recipe, RecipeComponentBuilderMap value) { for (var val : value.holders) { if (val.value != null) { var vc = new RecipeComponentValue<>(val.key, val.getIndex()); - vc.value = UtilsJS.cast(val.value); - val.key.component.writeToJson(recipe, UtilsJS.cast(vc), json); + vc.value = Cast.to(val.value); + val.key.component.writeToJson(recipe, Cast.to(vc), json); } } @@ -102,7 +102,7 @@ public RecipeComponentBuilderMap read(KubeRecipe recipe, Object from) { if (from instanceof JsonObject json) { for (var holder : value.holders) { - holder.key.component.readFromJson(recipe, UtilsJS.cast(holder), json); + holder.key.component.readFromJson(recipe, Cast.to(holder), json); if (!holder.key.optional() && holder.value == null) { throw new IllegalArgumentException("Missing required key '" + holder.key + "'!"); @@ -110,7 +110,7 @@ public RecipeComponentBuilderMap read(KubeRecipe recipe, Object from) { } } else if (from instanceof Map map) { for (var holder : value.holders) { - holder.key.component.readFromMap(recipe, UtilsJS.cast(holder), map); + holder.key.component.readFromMap(recipe, Cast.to(holder), map); if (!holder.key.optional() && holder.value == null) { throw new IllegalArgumentException("Missing required key '" + holder.key + "'!"); diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/component/RecipeComponentBuilderMap.java b/src/main/java/dev/latvian/mods/kubejs/recipe/component/RecipeComponentBuilderMap.java index 4c3c5be02..d5511dc5a 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/component/RecipeComponentBuilderMap.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/component/RecipeComponentBuilderMap.java @@ -1,7 +1,7 @@ package dev.latvian.mods.kubejs.recipe.component; import dev.latvian.mods.kubejs.recipe.RecipeKey; -import dev.latvian.mods.kubejs.util.UtilsJS; +import dev.latvian.mods.kubejs.util.Cast; import dev.latvian.mods.rhino.Wrapper; import org.jetbrains.annotations.NotNull; @@ -47,7 +47,7 @@ public RecipeComponentBuilderMap(RecipeKey[] keys) { @Override public Set, Object>> entrySet() { if (holderSet == null) { - holderSet = UtilsJS.cast(Set.of(holders)); + holderSet = Cast.to(Set.of(holders)); } return holderSet; @@ -57,7 +57,7 @@ public Set, Object>> entrySet() { public Object put(RecipeKey key, Object value) { for (var holder : holders) { if (holder.key == key) { - return holder.setValue(UtilsJS.cast(Wrapper.unwrapped(value))); + return holder.setValue(Cast.to(Wrapper.unwrapped(value))); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/component/RecipeComponentValueFunction.java b/src/main/java/dev/latvian/mods/kubejs/recipe/component/RecipeComponentValueFunction.java index 846d5c21e..d3868e901 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/component/RecipeComponentValueFunction.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/component/RecipeComponentValueFunction.java @@ -1,7 +1,7 @@ package dev.latvian.mods.kubejs.recipe.component; import dev.latvian.mods.kubejs.recipe.KubeRecipe; -import dev.latvian.mods.kubejs.util.UtilsJS; +import dev.latvian.mods.kubejs.util.Cast; import dev.latvian.mods.rhino.BaseFunction; import dev.latvian.mods.rhino.Context; import dev.latvian.mods.rhino.Scriptable; @@ -18,6 +18,6 @@ public RecipeComponentValueFunction(KubeRecipe recipe, RecipeComponentValue c @Override public KubeRecipe call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { - return recipe.setValue(componentValue.key, UtilsJS.cast(componentValue.key.component.read(recipe, Wrapper.unwrapped(args[0])))); + return recipe.setValue(componentValue.key, Cast.to(componentValue.key.component.read(recipe, Wrapper.unwrapped(args[0])))); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/component/RegistryComponent.java b/src/main/java/dev/latvian/mods/kubejs/recipe/component/RegistryComponent.java index b489a3c0c..7f1bb8778 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/component/RegistryComponent.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/component/RegistryComponent.java @@ -7,7 +7,7 @@ import dev.latvian.mods.kubejs.registry.RegistryInfo; import dev.latvian.mods.kubejs.typings.desc.DescriptionContext; import dev.latvian.mods.kubejs.typings.desc.TypeDescJS; -import dev.latvian.mods.kubejs.util.UtilsJS; +import dev.latvian.mods.kubejs.util.ID; import net.minecraft.core.Registry; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; @@ -69,12 +69,12 @@ public T read(KubeRecipe recipe, Object from) { } } - return registry.getValue(UtilsJS.getMCID(null, from)); + return registry.getValue(ID.mc(from)); } @Override public boolean hasPriority(KubeRecipe recipe, Object from) { - return (registry.objectBaseClass != Object.class && registry.objectBaseClass.isInstance(from)) || (from instanceof CharSequence && UtilsJS.getMCID(null, from.toString()) != null) || (from instanceof JsonPrimitive json && json.isString() && UtilsJS.getMCID(null, json.getAsString()) != null); + return (registry.objectBaseClass != Object.class && registry.objectBaseClass.isInstance(from)) || (from instanceof CharSequence && ID.mc(from.toString()) != null) || (from instanceof JsonPrimitive json && json.isString() && ID.mc(json.getAsString()) != null); } @Override diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/component/TagKeyComponent.java b/src/main/java/dev/latvian/mods/kubejs/recipe/component/TagKeyComponent.java index 860d949fe..52df081a1 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/component/TagKeyComponent.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/component/TagKeyComponent.java @@ -5,7 +5,7 @@ import dev.latvian.mods.kubejs.recipe.schema.DynamicRecipeComponent; import dev.latvian.mods.kubejs.typings.desc.DescriptionContext; import dev.latvian.mods.kubejs.typings.desc.TypeDescJS; -import dev.latvian.mods.kubejs.util.UtilsJS; +import dev.latvian.mods.kubejs.util.ID; import dev.latvian.mods.rhino.Wrapper; import net.minecraft.core.Registry; import net.minecraft.core.registries.Registries; @@ -29,7 +29,7 @@ public record TagKeyComponent(ResourceKey> registry, Cl .add("registry", TypeDescJS.STRING) .add("class", TypeDescJS.STRING, true), (cx, scope, args) -> { - var registry = ResourceKey.createRegistryKey(UtilsJS.getMCID(cx, Wrapper.unwrapped(args.get("registry")))); + var registry = ResourceKey.createRegistryKey(ID.mc(Wrapper.unwrapped(args.get("registry")))); Class type = Object.class; if (args.containsKey("class")) { diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/component/TimeComponent.java b/src/main/java/dev/latvian/mods/kubejs/recipe/component/TimeComponent.java index bee7e55b4..d08e57ce7 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/component/TimeComponent.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/component/TimeComponent.java @@ -6,7 +6,7 @@ import dev.latvian.mods.kubejs.recipe.schema.DynamicRecipeComponent; import dev.latvian.mods.kubejs.typings.desc.DescriptionContext; import dev.latvian.mods.kubejs.typings.desc.TypeDescJS; -import dev.latvian.mods.kubejs.util.UtilsJS; +import dev.latvian.mods.kubejs.util.TimeJS; import dev.latvian.mods.rhino.ScriptRuntime; import dev.latvian.mods.rhino.Wrapper; @@ -55,7 +55,7 @@ public Long read(KubeRecipe recipe, Object from) { return ((Number) from).longValue() * scale; } - return UtilsJS.getTickDuration(from); + return TimeJS.tickDurationOf(from); } @Override diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/filter/RecipeFilter.java b/src/main/java/dev/latvian/mods/kubejs/recipe/filter/RecipeFilter.java index 429d5f5ce..ff4c74f7a 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/filter/RecipeFilter.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/filter/RecipeFilter.java @@ -6,10 +6,10 @@ import dev.latvian.mods.kubejs.recipe.RecipeExceptionJS; import dev.latvian.mods.kubejs.recipe.ReplacementMatch; import dev.latvian.mods.kubejs.util.ConsoleJS; +import dev.latvian.mods.kubejs.util.ID; import dev.latvian.mods.kubejs.util.ListJS; import dev.latvian.mods.kubejs.util.MapJS; import dev.latvian.mods.kubejs.util.RegExpJS; -import dev.latvian.mods.kubejs.util.UtilsJS; import dev.latvian.mods.rhino.Context; import dev.latvian.mods.rhino.regexp.NativeRegExp; import org.jetbrains.annotations.Nullable; @@ -38,7 +38,7 @@ static RecipeFilter of(Context cx, @Nullable Object o) { return ConstantFilter.FALSE; } else { var r = RegExpJS.of(s); - return r == null ? new IDFilter(UtilsJS.getMCID(cx, s)) : RegexIDFilter.of(r); + return r == null ? new IDFilter(ID.mc(s)) : RegexIDFilter.of(r); } } @@ -83,13 +83,13 @@ static RecipeFilter of(Context cx, @Nullable Object o) { if (id != null) { var pattern = RegExpJS.of(id); - predicate.list.add(pattern == null ? new IDFilter(UtilsJS.getMCID(cx, id)) : RegexIDFilter.of(pattern)); + predicate.list.add(pattern == null ? new IDFilter(ID.mc(id)) : RegexIDFilter.of(pattern)); } var type = map.get("type"); if (type != null) { - predicate.list.add(new TypeFilter(UtilsJS.getMCID(cx, type))); + predicate.list.add(new TypeFilter(ID.mc(type))); } var group = map.get("group"); diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/schema/RecipeConstructor.java b/src/main/java/dev/latvian/mods/kubejs/recipe/schema/RecipeConstructor.java index fc85f27d1..4e62636a7 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/schema/RecipeConstructor.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/schema/RecipeConstructor.java @@ -5,7 +5,8 @@ import dev.latvian.mods.kubejs.recipe.RecipeKey; import dev.latvian.mods.kubejs.recipe.RecipeTypeFunction; import dev.latvian.mods.kubejs.recipe.component.ComponentValueMap; -import dev.latvian.mods.kubejs.util.UtilsJS; +import dev.latvian.mods.kubejs.util.Cast; +import dev.latvian.mods.rhino.Context; import java.util.Arrays; import java.util.function.BiFunction; @@ -16,7 +17,7 @@ public record RecipeConstructor(RecipeSchema schema, RecipeKey[] keys, Factor public interface Factory { Factory DEFAULT = (recipe, schemaType, keys, from) -> { for (var key : keys) { - recipe.setValue(key, UtilsJS.cast(from.getValue(recipe, key))); + recipe.setValue(key, Cast.to(from.getValue(recipe, key))); } }; @@ -28,13 +29,13 @@ static Factory defaultWith(BiFunction, Object> valueSup var v = valueSupplier.apply(recipe, key); if (v != null) { - recipe.setValue(key, UtilsJS.cast(v)); + recipe.setValue(key, Cast.to(v)); } } }; } - default KubeRecipe create(RecipeTypeFunction type, RecipeSchemaType schemaType, RecipeKey[] keys, ComponentValueMap from) { + default KubeRecipe create(Context cx, RecipeTypeFunction type, RecipeSchemaType schemaType, RecipeKey[] keys, ComponentValueMap from) { var r = schemaType.schema.factory.get(); r.type = type; r.json = new JsonObject(); diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/schema/minecraft/SmithingTransformRecipeSchema.java b/src/main/java/dev/latvian/mods/kubejs/recipe/schema/minecraft/SmithingTransformRecipeSchema.java index be6aa5b18..8ba98e6ba 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/schema/minecraft/SmithingTransformRecipeSchema.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/schema/minecraft/SmithingTransformRecipeSchema.java @@ -20,7 +20,7 @@ public interface SmithingTransformRecipeSchema { .constructor(RESULT, TEMPLATE, BASE, ADDITION) .constructor(RecipeConstructor.Factory.defaultWith((recipe, key) -> { if (key == TEMPLATE) { - return InputItem.of(Ingredient.of(Items.NETHERITE_UPGRADE_SMITHING_TEMPLATE), 1); + return InputItem.create(Ingredient.of(Items.NETHERITE_UPGRADE_SMITHING_TEMPLATE), 1); } else { return null; } diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/special/ShapedKubeJSRecipe.java b/src/main/java/dev/latvian/mods/kubejs/recipe/special/ShapedKubeJSRecipe.java index fc9b1f2cb..a6097de13 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/special/ShapedKubeJSRecipe.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/special/ShapedKubeJSRecipe.java @@ -7,7 +7,7 @@ import com.mojang.serialization.MapLike; import com.mojang.serialization.RecordBuilder; import com.mojang.serialization.codecs.RecordCodecBuilder; -import dev.latvian.mods.kubejs.recipe.KubeJSRecipeEventHandler; +import dev.latvian.mods.kubejs.recipe.KubeJSRecipeSerializers; import dev.latvian.mods.kubejs.recipe.ModifyRecipeResultCallback; import dev.latvian.mods.kubejs.recipe.ingredientaction.IngredientAction; import it.unimi.dsi.fastutil.chars.CharArraySet; @@ -78,7 +78,7 @@ public ShapedKubeJSRecipe(String group, CraftingBookCategory category, ShapedRec @Override public RecipeSerializer getSerializer() { - return KubeJSRecipeEventHandler.SHAPED.get(); + return KubeJSRecipeSerializers.SHAPED.get(); } @Override diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/special/ShapelessKubeJSRecipe.java b/src/main/java/dev/latvian/mods/kubejs/recipe/special/ShapelessKubeJSRecipe.java index 2bef4ec91..9e3b7c407 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/special/ShapelessKubeJSRecipe.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/special/ShapelessKubeJSRecipe.java @@ -3,7 +3,7 @@ import com.mojang.serialization.Codec; import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; -import dev.latvian.mods.kubejs.recipe.KubeJSRecipeEventHandler; +import dev.latvian.mods.kubejs.recipe.KubeJSRecipeSerializers; import dev.latvian.mods.kubejs.recipe.ModifyRecipeResultCallback; import dev.latvian.mods.kubejs.recipe.ingredientaction.IngredientAction; import net.minecraft.core.HolderLookup; @@ -34,7 +34,7 @@ public ShapelessKubeJSRecipe(ShapelessRecipe original, List in @Override public RecipeSerializer getSerializer() { - return KubeJSRecipeEventHandler.SHAPELESS.get(); + return KubeJSRecipeSerializers.SHAPELESS.get(); } @Override diff --git a/src/main/java/dev/latvian/mods/kubejs/registry/RegistryInfo.java b/src/main/java/dev/latvian/mods/kubejs/registry/RegistryInfo.java index 849ff3b4e..10f8191b5 100644 --- a/src/main/java/dev/latvian/mods/kubejs/registry/RegistryInfo.java +++ b/src/main/java/dev/latvian/mods/kubejs/registry/RegistryInfo.java @@ -10,6 +10,7 @@ import dev.latvian.mods.kubejs.typings.Info; import dev.latvian.mods.kubejs.util.Cast; import dev.latvian.mods.kubejs.util.ConsoleJS; +import dev.latvian.mods.kubejs.util.ID; import dev.latvian.mods.kubejs.util.UtilsJS; import dev.latvian.mods.rhino.Context; import dev.latvian.mods.rhino.type.TypeInfo; @@ -265,6 +266,7 @@ public static List> allOfClass(Class type) { public final Class objectBaseClass; public final Map> types; public final Map> objects; + public final ResourceKey unknownKey; public boolean hasDefaultTags = false; private BuilderType defaultType; public boolean bypassServerOnly; @@ -277,6 +279,7 @@ private RegistryInfo(ResourceKey> key, Class objectBase this.objectBaseClass = objectBaseClass; this.types = new LinkedHashMap<>(); this.objects = new LinkedHashMap<>(); + this.unknownKey = ResourceKey.create(key, UtilsJS.UNKNOWN_ID); this.bypassServerOnly = false; this.autoWrap = objectBaseClass != Codec.class && objectBaseClass != ResourceLocation.class && objectBaseClass != String.class; this.languageKeyPrefix = key.location().getPath().replace('/', '.'); @@ -438,6 +441,11 @@ public boolean hasValue(ResourceLocation id) { return getArchitecturyRegistrar().contains(id); } + @Nullable + public ResourceKey getKeyOf(T value) { + return getVanillaRegistry().getResourceKey(value).orElse(null); + } + @Override public T wrap(Context cx, Object o, TypeInfo target) { if (o == null) { @@ -446,7 +454,7 @@ public T wrap(Context cx, Object o, TypeInfo target) { return (T) o; } - var id = UtilsJS.getMCID(cx, o); + var id = ID.mc(o); var value = getValue(id); if (value == null) { diff --git a/src/main/java/dev/latvian/mods/kubejs/registry/RegistryKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/registry/RegistryKubeEvent.java index 66816138d..e4a7856c7 100644 --- a/src/main/java/dev/latvian/mods/kubejs/registry/RegistryKubeEvent.java +++ b/src/main/java/dev/latvian/mods/kubejs/registry/RegistryKubeEvent.java @@ -1,9 +1,7 @@ package dev.latvian.mods.kubejs.registry; -import dev.latvian.mods.kubejs.KubeJS; import dev.latvian.mods.kubejs.event.KubeStartupEvent; -import dev.latvian.mods.kubejs.util.StringWithContext; -import dev.latvian.mods.kubejs.util.UtilsJS; +import dev.latvian.mods.kubejs.util.ID; import java.util.LinkedList; import java.util.List; @@ -18,14 +16,14 @@ public RegistryKubeEvent(RegistryInfo r) { this.created = new LinkedList<>(); } - public BuilderBase create(StringWithContext id, String type) { + public BuilderBase create(String id, String type) { var t = registry.types.get(type); if (t == null) { throw new IllegalArgumentException("Unknown type '" + type + "' for object '" + id + "'!"); } - var b = t.factory().createBuilder(UtilsJS.getMCID(id.cx(), KubeJS.appendModId(id.string()))); + var b = t.factory().createBuilder(ID.kjs(id)); if (b == null) { throw new IllegalArgumentException("Unknown type '" + type + "' for object '" + id + "'!"); @@ -37,14 +35,14 @@ public BuilderBase create(StringWithContext id, String type) { return b; } - public BuilderBase create(StringWithContext id) { + public BuilderBase create(String id) { var t = registry.getDefaultType(); if (t == null) { throw new IllegalArgumentException("Registry for type '" + registry.key.location() + "' doesn't have any builders registered!"); } - var b = t.factory().createBuilder(UtilsJS.getMCID(id.cx(), KubeJS.appendModId(id.string()))); + var b = t.factory().createBuilder(ID.kjs(id)); if (b == null) { throw new IllegalArgumentException("Unknown type '" + t.type() + "' for object '" + id + "'!"); @@ -56,12 +54,12 @@ public BuilderBase create(StringWithContext id) { return b; } - public CustomBuilderObject createCustom(StringWithContext id, Supplier object) { + public CustomBuilderObject createCustom(String id, Supplier object) { if (object == null) { throw new IllegalArgumentException("Tried to register a null object with id: " + id); } - var rl = UtilsJS.getMCID(id.cx(), KubeJS.appendModId(id.string())); + var rl = ID.kjs(id); var b = new CustomBuilderObject(rl, object, registry); registry.addBuilder(b); created.add(b); diff --git a/src/main/java/dev/latvian/mods/kubejs/script/CodecTypeWrapper.java b/src/main/java/dev/latvian/mods/kubejs/script/CodecTypeWrapper.java index 0f971760e..6733bef74 100644 --- a/src/main/java/dev/latvian/mods/kubejs/script/CodecTypeWrapper.java +++ b/src/main/java/dev/latvian/mods/kubejs/script/CodecTypeWrapper.java @@ -3,8 +3,8 @@ import com.mojang.serialization.Codec; import com.mojang.serialization.JavaOps; import com.mojang.serialization.JsonOps; +import dev.latvian.mods.kubejs.util.Cast; import dev.latvian.mods.kubejs.util.MapJS; -import dev.latvian.mods.kubejs.util.UtilsJS; import dev.latvian.mods.rhino.Context; import dev.latvian.mods.rhino.Wrapper; import dev.latvian.mods.rhino.type.TypeInfo; @@ -22,7 +22,7 @@ public T wrap(Context cx, Object o, TypeInfo target) { if (o == null) { return defaultValue; } else if (target.asClass().isInstance(o)) { - return UtilsJS.cast(o); + return Cast.to(o); } else if (o instanceof Tag tag) { return codec.decode(NbtOps.INSTANCE, tag).result().get().getFirst(); } else if (o instanceof Map map) { diff --git a/src/main/java/dev/latvian/mods/kubejs/script/KubeJSContext.java b/src/main/java/dev/latvian/mods/kubejs/script/KubeJSContext.java index ec347d31a..4ef3a6cd7 100644 --- a/src/main/java/dev/latvian/mods/kubejs/script/KubeJSContext.java +++ b/src/main/java/dev/latvian/mods/kubejs/script/KubeJSContext.java @@ -4,7 +4,6 @@ import dev.latvian.mods.kubejs.KubeJS; import dev.latvian.mods.kubejs.util.ConsoleJS; import dev.latvian.mods.kubejs.util.KubeJSPlugins; -import dev.latvian.mods.kubejs.util.WithContext; import dev.latvian.mods.rhino.Context; import dev.latvian.mods.rhino.NativeJavaClass; import dev.latvian.mods.rhino.Scriptable; @@ -16,14 +15,12 @@ public class KubeJSContext extends Context { public final KubeJSContextFactory kjsFactory; - public final WithContext nullWithContext; public final Scriptable topLevelScope; private Map> javaClassCache; public KubeJSContext(KubeJSContextFactory factory) { super(factory); this.kjsFactory = factory; - this.nullWithContext = new WithContext<>(this, null); setApplicationClassLoader(KubeJS.class.getClassLoader()); this.topLevelScope = initSafeStandardObjects(); diff --git a/src/main/java/dev/latvian/mods/kubejs/script/MapCodecTypeWrapper.java b/src/main/java/dev/latvian/mods/kubejs/script/MapCodecTypeWrapper.java index cd596e1c0..5aaee2003 100644 --- a/src/main/java/dev/latvian/mods/kubejs/script/MapCodecTypeWrapper.java +++ b/src/main/java/dev/latvian/mods/kubejs/script/MapCodecTypeWrapper.java @@ -3,8 +3,8 @@ import com.mojang.serialization.JavaOps; import com.mojang.serialization.JsonOps; import com.mojang.serialization.MapCodec; +import dev.latvian.mods.kubejs.util.Cast; import dev.latvian.mods.kubejs.util.MapJS; -import dev.latvian.mods.kubejs.util.UtilsJS; import dev.latvian.mods.rhino.Context; import dev.latvian.mods.rhino.Wrapper; import dev.latvian.mods.rhino.type.TypeInfo; @@ -22,7 +22,7 @@ public T wrap(Context cx, Object o, TypeInfo target) { if (o == null) { return defaultValue; } else if (target.asClass().isInstance(o)) { - return UtilsJS.cast(o); + return Cast.to(o); } else if (o instanceof Tag tag) { return codec.decode(NbtOps.INSTANCE, NbtOps.INSTANCE.getMap(tag).getOrThrow()).result().get(); } else if (o instanceof Map map) { diff --git a/src/main/java/dev/latvian/mods/kubejs/script/PlatformWrapper.java b/src/main/java/dev/latvian/mods/kubejs/script/PlatformWrapper.java index 817632a36..62304d6e4 100644 --- a/src/main/java/dev/latvian/mods/kubejs/script/PlatformWrapper.java +++ b/src/main/java/dev/latvian/mods/kubejs/script/PlatformWrapper.java @@ -4,6 +4,7 @@ import dev.architectury.utils.Env; import dev.latvian.mods.kubejs.KubeJS; import dev.latvian.mods.kubejs.helpers.MiscHelper; +import net.neoforged.neoforge.data.loading.DatagenModLoader; import java.util.Arrays; import java.util.LinkedHashMap; @@ -124,7 +125,7 @@ public static String getMinecraftVersionString() { } public static boolean isGeneratingData() { - return MiscHelper.get().isDataGen(); + return DatagenModLoader.isRunningDataGen(); } public static void breakpoint(Object... args) { diff --git a/src/main/java/dev/latvian/mods/kubejs/script/ScriptFileInfo.java b/src/main/java/dev/latvian/mods/kubejs/script/ScriptFileInfo.java index 1ae4709bf..6ad3d84d9 100644 --- a/src/main/java/dev/latvian/mods/kubejs/script/ScriptFileInfo.java +++ b/src/main/java/dev/latvian/mods/kubejs/script/ScriptFileInfo.java @@ -2,6 +2,7 @@ import dev.architectury.platform.Platform; import dev.latvian.mods.kubejs.CommonProperties; +import dev.latvian.mods.kubejs.util.ID; import dev.latvian.mods.kubejs.util.UtilsJS; import net.minecraft.resources.ResourceLocation; @@ -32,7 +33,7 @@ public ScriptFileInfo(ScriptPackInfo p, String f) { pack = p; file = f; id = new ResourceLocation(pack.namespace, FILE_FIXER.matcher(pack.pathStart + file).replaceAll("_").toLowerCase()); - location = UtilsJS.getID(pack.namespace + ":" + pack.pathStart + file); + location = ID.string(pack.namespace + ":" + pack.pathStart + file); properties = new HashMap<>(); priority = 0; ignored = false; diff --git a/src/main/java/dev/latvian/mods/kubejs/script/ScriptManager.java b/src/main/java/dev/latvian/mods/kubejs/script/ScriptManager.java index 59ccd52f2..3883b1a98 100644 --- a/src/main/java/dev/latvian/mods/kubejs/script/ScriptManager.java +++ b/src/main/java/dev/latvian/mods/kubejs/script/ScriptManager.java @@ -2,12 +2,12 @@ import dev.latvian.mods.kubejs.KubeJS; import dev.latvian.mods.kubejs.KubeJSPlugin; -import dev.latvian.mods.kubejs.helpers.MiscHelper; import dev.latvian.mods.kubejs.registry.RegistryInfo; import dev.latvian.mods.kubejs.util.ClassFilter; import dev.latvian.mods.kubejs.util.KubeJSPlugins; import dev.latvian.mods.kubejs.util.LogType; import dev.latvian.mods.kubejs.util.UtilsJS; +import dev.latvian.mods.rhino.util.wrap.TypeWrapperFactory; import net.minecraft.core.HolderLookup; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceLocation; @@ -148,7 +148,7 @@ public void load() { contextFactory = new KubeJSContextFactory(this); scriptType.console.contextFactory = new WeakReference<>(contextFactory); - if (MiscHelper.get().isDataGen()) { + if (PlatformWrapper.isGeneratingData()) { firstLoad = false; scriptType.console.info("Skipping KubeJS script loading (DataGen)"); return; @@ -168,7 +168,7 @@ public void load() { if (info.autoWrap && info.objectBaseClass != Object.class && info.objectBaseClass != null) { try { - typeWrappers.register(info.objectBaseClass, UtilsJS.cast(info)); + typeWrappers.register(info.objectBaseClass, (TypeWrapperFactory) info); } catch (IllegalArgumentException ignored) { scriptType.console.info("Skipped registry type wrapper for " + info.key.location()); } diff --git a/src/main/java/dev/latvian/mods/kubejs/script/WrapperRegistry.java b/src/main/java/dev/latvian/mods/kubejs/script/WrapperRegistry.java index 8b321f8d8..a706ce737 100644 --- a/src/main/java/dev/latvian/mods/kubejs/script/WrapperRegistry.java +++ b/src/main/java/dev/latvian/mods/kubejs/script/WrapperRegistry.java @@ -3,7 +3,8 @@ import com.mojang.serialization.Codec; import com.mojang.serialization.MapCodec; import dev.latvian.mods.kubejs.KubeJSCodecs; -import dev.latvian.mods.kubejs.util.UtilsJS; +import dev.latvian.mods.kubejs.util.Cast; +import dev.latvian.mods.rhino.Context; import dev.latvian.mods.rhino.Wrapper; import dev.latvian.mods.rhino.util.wrap.DirectTypeWrapperFactory; import dev.latvian.mods.rhino.util.wrap.TypeWrapperFactory; @@ -11,6 +12,8 @@ import dev.latvian.mods.rhino.util.wrap.TypeWrappers; import net.minecraft.util.StringRepresentable; +import java.util.function.BiFunction; + public class WrapperRegistry { public final ScriptType type; public final TypeWrappers typeWrappers; @@ -28,22 +31,30 @@ public void register(Class target, TypeWrapperFactory factory) { typeWrappers.register(target, factory); } - public void registerSimple(Class target, TypeWrapperValidator validator, DirectTypeWrapperFactory factory) { + public void register(Class target, TypeWrapperValidator validator, BiFunction factory) { + typeWrappers.register(target, validator, (cx, from, t) -> factory.apply(cx, from)); + } + + public void register(Class target, BiFunction factory) { + typeWrappers.register(target, (cx, from, t) -> factory.apply(cx, from)); + } + + public void register(Class target, TypeWrapperValidator validator, DirectTypeWrapperFactory factory) { typeWrappers.registerDirect(target, validator, factory); } - public void registerSimple(Class target, DirectTypeWrapperFactory factory) { + public void register(Class target, DirectTypeWrapperFactory factory) { typeWrappers.registerDirect(target, factory); } public & StringRepresentable> void registerEnumFromStringCodec(Class target, Codec codec, T defaultValue, boolean forceLowerCase) { - registerSimple(target, o -> { + register(target, o -> { o = Wrapper.unwrapped(o); if (o == null) { return defaultValue; } else if (target.isInstance(o)) { - return UtilsJS.cast(o); + return Cast.to(o); } else { var s = o.toString(); return s.isEmpty() ? defaultValue : KubeJSCodecs.byName(codec, forceLowerCase ? s.toLowerCase() : s); diff --git a/src/main/java/dev/latvian/mods/kubejs/server/CommandKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/server/CommandKubeEvent.java index 20e073d0e..8c5fd7c8e 100644 --- a/src/main/java/dev/latvian/mods/kubejs/server/CommandKubeEvent.java +++ b/src/main/java/dev/latvian/mods/kubejs/server/CommandKubeEvent.java @@ -1,17 +1,17 @@ package dev.latvian.mods.kubejs.server; import com.mojang.brigadier.ParseResults; -import dev.architectury.event.events.common.CommandPerformEvent; import net.minecraft.commands.CommandSourceStack; +import net.neoforged.neoforge.event.CommandEvent; public class CommandKubeEvent extends ServerKubeEvent { - private final CommandPerformEvent event; + private final CommandEvent event; private final String commandName; - public CommandKubeEvent(CommandPerformEvent e) { - super(e.getResults().getContext().getSource().getServer()); - event = e; - commandName = event.getResults().getContext().getNodes().isEmpty() ? "" : event.getResults().getContext().getNodes().get(0).getNode().getName(); + public CommandKubeEvent(CommandEvent event) { + super(event.getParseResults().getContext().getSource().getServer()); + this.event = event; + this.commandName = event.getParseResults().getContext().getNodes().isEmpty() ? "" : event.getParseResults().getContext().getNodes().get(0).getNode().getName(); } public String getCommandName() { @@ -19,22 +19,22 @@ public String getCommandName() { } public String getInput() { - return event.getResults().getReader().getString(); + return event.getParseResults().getReader().getString(); } public ParseResults getParseResults() { - return event.getResults(); + return event.getParseResults(); } public void setParseResults(ParseResults parse) { - event.setResults(parse); + event.setParseResults(parse); } public Throwable getException() { - return event.getThrowable(); + return event.getException(); } public void setException(Throwable exception) { - event.setThrowable(exception); + event.setException(exception); } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/server/DataExport.java b/src/main/java/dev/latvian/mods/kubejs/server/DataExport.java index d5d7df55a..ab6a21be9 100644 --- a/src/main/java/dev/latvian/mods/kubejs/server/DataExport.java +++ b/src/main/java/dev/latvian/mods/kubejs/server/DataExport.java @@ -12,7 +12,8 @@ import dev.latvian.mods.kubejs.util.ConsoleJS; import dev.latvian.mods.kubejs.util.JsonUtils; import dev.latvian.mods.kubejs.util.KubeJSPlugins; -import dev.latvian.mods.kubejs.util.UtilsJS; +import dev.latvian.mods.kubejs.util.LogType; +import dev.latvian.mods.kubejs.util.TimeJS; import dev.latvian.mods.rhino.util.HideFromJS; import net.minecraft.Util; import net.minecraft.commands.CommandSourceStack; @@ -78,7 +79,7 @@ public void addJson(String path, JsonElement json) { private void appendLine(StringBuilder sb, Calendar calendar, ConsoleLine line) { calendar.setTimeInMillis(line.timestamp); sb.append('['); - UtilsJS.appendTimestamp(sb, calendar); + TimeJS.appendTimestamp(sb, calendar); sb.append(']'); sb.append(' '); sb.append('['); @@ -86,7 +87,7 @@ private void appendLine(StringBuilder sb, Calendar calendar, ConsoleLine line) { sb.append(']'); sb.append(' '); - if (line.type.equals("ERROR")) { + if (line.type == LogType.ERROR) { sb.append('!'); sb.append(' '); } diff --git a/src/main/java/dev/latvian/mods/kubejs/server/KubeJSReloadListener.java b/src/main/java/dev/latvian/mods/kubejs/server/KubeJSReloadListener.java index b961e2a75..d627e87ac 100644 --- a/src/main/java/dev/latvian/mods/kubejs/server/KubeJSReloadListener.java +++ b/src/main/java/dev/latvian/mods/kubejs/server/KubeJSReloadListener.java @@ -3,16 +3,14 @@ import dev.latvian.mods.kubejs.bindings.event.ServerEvents; import dev.latvian.mods.kubejs.recipe.AfterRecipesLoadedKubeEvent; import dev.latvian.mods.kubejs.script.ScriptType; -import net.minecraft.server.ReloadableServerResources; +import dev.latvian.mods.kubejs.util.UtilsJS; import net.minecraft.server.packs.resources.ResourceManager; import net.minecraft.server.packs.resources.ResourceManagerReloadListener; public class KubeJSReloadListener implements ResourceManagerReloadListener { - public static ReloadableServerResources resources; - @Override public void onResourceManagerReload(ResourceManager resourceManager) { - var recipeManager = resources == null ? null : resources.getRecipeManager(); + var recipeManager = UtilsJS.staticResources == null ? null : UtilsJS.staticResources.getRecipeManager(); if (recipeManager != null && ServerEvents.RECIPES_AFTER_LOADED.hasListeners()) { ServerEvents.RECIPES_AFTER_LOADED.post(ScriptType.SERVER, new AfterRecipesLoadedKubeEvent(recipeManager.byType, recipeManager.byName)); diff --git a/src/main/java/dev/latvian/mods/kubejs/server/KubeJSServerEventHandler.java b/src/main/java/dev/latvian/mods/kubejs/server/KubeJSServerEventHandler.java index cb64d95b5..71e8b8813 100644 --- a/src/main/java/dev/latvian/mods/kubejs/server/KubeJSServerEventHandler.java +++ b/src/main/java/dev/latvian/mods/kubejs/server/KubeJSServerEventHandler.java @@ -1,10 +1,6 @@ package dev.latvian.mods.kubejs.server; -import com.mojang.brigadier.CommandDispatcher; -import dev.architectury.event.EventResult; -import dev.architectury.event.events.common.CommandPerformEvent; -import dev.architectury.event.events.common.CommandRegistrationEvent; -import dev.architectury.event.events.common.LifecycleEvent; +import dev.latvian.mods.kubejs.KubeJS; import dev.latvian.mods.kubejs.bindings.event.LevelEvents; import dev.latvian.mods.kubejs.bindings.event.ServerEvents; import dev.latvian.mods.kubejs.command.CommandRegistryKubeEvent; @@ -13,39 +9,46 @@ import dev.latvian.mods.kubejs.script.ScriptType; import dev.latvian.mods.kubejs.util.UtilsJS; import net.minecraft.Util; -import net.minecraft.commands.CommandBuildContext; -import net.minecraft.commands.CommandSourceStack; -import net.minecraft.commands.Commands; import net.minecraft.core.RegistryAccess; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.nbt.NbtAccounter; import net.minecraft.nbt.NbtIo; -import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.storage.LevelResource; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.event.CommandEvent; +import net.neoforged.neoforge.event.RegisterCommandsEvent; +import net.neoforged.neoforge.event.level.LevelEvent; +import net.neoforged.neoforge.event.server.ServerAboutToStartEvent; +import net.neoforged.neoforge.event.server.ServerStartingEvent; +import net.neoforged.neoforge.event.server.ServerStoppedEvent; +import net.neoforged.neoforge.event.server.ServerStoppingEvent; import java.nio.file.Files; import java.util.HashMap; import java.util.UUID; +@EventBusSubscriber(modid = KubeJS.MOD_ID) public class KubeJSServerEventHandler { private static final LevelResource PERSISTENT_DATA = new LevelResource("kubejs_persistent_data.nbt"); - public static void init() { - LifecycleEvent.SERVER_BEFORE_START.register(KubeJSServerEventHandler::serverBeforeStart); - CommandRegistrationEvent.EVENT.register(KubeJSServerEventHandler::registerCommands); - LifecycleEvent.SERVER_STARTING.register(KubeJSServerEventHandler::serverStarting); - LifecycleEvent.SERVER_STOPPING.register(KubeJSServerEventHandler::serverStopping); - LifecycleEvent.SERVER_STOPPED.register(KubeJSServerEventHandler::serverStopped); - LifecycleEvent.SERVER_LEVEL_SAVE.register(KubeJSServerEventHandler::serverLevelSaved); - LifecycleEvent.SERVER_LEVEL_LOAD.register(KubeJSServerEventHandler::serverLevelLoaded); - CommandPerformEvent.EVENT.register(KubeJSServerEventHandler::command); + @SubscribeEvent + public static void registerCommands(RegisterCommandsEvent event) { + KubeJSCommands.register(event.getDispatcher()); + + if (ServerEvents.COMMAND_REGISTRY.hasListeners()) { + ServerEvents.COMMAND_REGISTRY.post(ScriptType.SERVER, new CommandRegistryKubeEvent(event.getDispatcher(), event.getBuildContext(), event.getCommandSelection())); + } } - public static void serverBeforeStart(MinecraftServer server) { + @SubscribeEvent + public static void serverBeforeStart(ServerAboutToStartEvent event) { + var server = event.getServer(); + UtilsJS.staticServer = server; UtilsJS.staticRegistryAccess = server.registryAccess(); @@ -86,35 +89,36 @@ public static void serverBeforeStart(MinecraftServer server) { } } - public static void registerCommands(CommandDispatcher dispatcher, CommandBuildContext registry, Commands.CommandSelection selection) { - KubeJSCommands.register(dispatcher); - - if (ServerEvents.COMMAND_REGISTRY.hasListeners()) { - ServerEvents.COMMAND_REGISTRY.post(ScriptType.SERVER, new CommandRegistryKubeEvent(dispatcher, registry, selection)); - } - } - - private static void serverStarting(MinecraftServer server) { - ServerEvents.LOADED.post(ScriptType.SERVER, new ServerKubeEvent(server)); + @SubscribeEvent + public static void serverStarting(ServerStartingEvent event) { + ServerEvents.LOADED.post(ScriptType.SERVER, new ServerKubeEvent(event.getServer())); } - private static void serverStopping(MinecraftServer server) { - ServerEvents.UNLOADED.post(ScriptType.SERVER, new ServerKubeEvent(server)); + @SubscribeEvent + public static void serverStopping(ServerStoppingEvent event) { + ServerEvents.UNLOADED.post(ScriptType.SERVER, new ServerKubeEvent(event.getServer())); } - private static void serverStopped(MinecraftServer server) { + @SubscribeEvent + public static void serverStopped(ServerStoppedEvent event) { UtilsJS.staticServer = null; UtilsJS.staticRegistryAccess = RegistryAccess.EMPTY; } - private static void serverLevelLoaded(ServerLevel level) { - if (LevelEvents.LOADED.hasListeners()) { - LevelEvents.LOADED.post(new SimpleLevelKubeEvent(level), level.dimension().location()); + @SubscribeEvent + public static void serverLevelLoaded(LevelEvent.Load event) { + if (event.getLevel() instanceof ServerLevel level && LevelEvents.LOADED.hasListeners(level.dimension())) { + LevelEvents.LOADED.post(new SimpleLevelKubeEvent(level), level.dimension()); } } - private static void serverLevelSaved(ServerLevel level) { - if (level.dimension() == Level.OVERWORLD) { + @SubscribeEvent + public static void serverLevelSaved(LevelEvent.Save event) { + if (event.getLevel() instanceof ServerLevel level && LevelEvents.SAVED.hasListeners(level.dimension())) { + LevelEvents.SAVED.post(new SimpleLevelKubeEvent(level), level.dimension()); + } + + if (event.getLevel() instanceof ServerLevel level && level.dimension() == Level.OVERWORLD) { var serverData = level.getServer().kjs$getPersistentData().copy(); var p = level.getServer().getWorldPath(PERSISTENT_DATA); @@ -149,12 +153,14 @@ private static void serverLevelSaved(ServerLevel level) { } } - public static EventResult command(CommandPerformEvent event) { + @SubscribeEvent + public static void command(CommandEvent event) { if (ServerEvents.COMMAND.hasListeners()) { var e = new CommandKubeEvent(event); - return ServerEvents.COMMAND.post(e, e.getCommandName()).arch(); - } - return EventResult.pass(); + if (ServerEvents.COMMAND.hasListeners(e.getCommandName())) { + ServerEvents.COMMAND.post(e, e.getCommandName()).applyCancel(event); + } + } } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/server/ServerScriptManager.java b/src/main/java/dev/latvian/mods/kubejs/server/ServerScriptManager.java index c7bde8be7..cefa0242d 100644 --- a/src/main/java/dev/latvian/mods/kubejs/server/ServerScriptManager.java +++ b/src/main/java/dev/latvian/mods/kubejs/server/ServerScriptManager.java @@ -13,7 +13,6 @@ import dev.latvian.mods.kubejs.server.tag.PreTagKubeEvent; import dev.latvian.mods.kubejs.util.ConsoleJS; import dev.latvian.mods.kubejs.util.KubeJSPlugins; -import dev.latvian.mods.kubejs.util.UtilsJS; import net.minecraft.core.HolderLookup; import net.minecraft.core.RegistryAccess; import net.minecraft.network.chat.Component; @@ -69,11 +68,6 @@ public HolderLookup.Provider getRegistries() { return registries; } - public void updateResources(ReloadableServerResources serverResources, RegistryAccess registryAccess) { - KubeJSReloadListener.resources = serverResources; - UtilsJS.staticRegistryAccess = registryAccess; - } - public MultiPackResourceManager wrapResourceManager(HolderLookup.Provider registries, CloseableResourceManager original) { var virtualDataPackLow = new VirtualKubeJSDataPack(false); var virtualDataPackHigh = new VirtualKubeJSDataPack(true); diff --git a/src/main/java/dev/latvian/mods/kubejs/server/tag/TagKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/server/tag/TagKubeEvent.java index 2c92fe6fb..c2482966f 100644 --- a/src/main/java/dev/latvian/mods/kubejs/server/tag/TagKubeEvent.java +++ b/src/main/java/dev/latvian/mods/kubejs/server/tag/TagKubeEvent.java @@ -3,8 +3,8 @@ import dev.latvian.mods.kubejs.event.EventExceptionHandler; import dev.latvian.mods.kubejs.event.KubeEvent; import dev.latvian.mods.kubejs.registry.RegistryInfo; +import dev.latvian.mods.kubejs.util.Cast; import dev.latvian.mods.kubejs.util.ConsoleJS; -import dev.latvian.mods.kubejs.util.UtilsJS; import net.minecraft.core.Holder; import net.minecraft.core.Registry; import net.minecraft.resources.ResourceKey; @@ -87,7 +87,7 @@ public void removeAllTagsFrom(Object... ids) { public Set getElementIds() { if (elementIds == null) { - elementIds = UtilsJS.cast(vanillaRegistry.holders().map(Holder.Reference::key).map(ResourceKey::location).collect(Collectors.toSet())); + elementIds = Cast.to(vanillaRegistry.holders().map(Holder.Reference::key).map(ResourceKey::location).collect(Collectors.toSet())); } return elementIds; diff --git a/src/main/java/dev/latvian/mods/kubejs/stages/Stages.java b/src/main/java/dev/latvian/mods/kubejs/stages/Stages.java index 044809a5d..f887e0995 100644 --- a/src/main/java/dev/latvian/mods/kubejs/stages/Stages.java +++ b/src/main/java/dev/latvian/mods/kubejs/stages/Stages.java @@ -31,7 +31,10 @@ default boolean add(String stage) { PacketDistributor.sendToAllPlayers(new AddStagePayload(player.getUUID(), stage)); } - PlayerEvents.STAGE_ADDED.post(new StageChangedEvent(getPlayer(), this, stage), stage); + if (PlayerEvents.STAGE_ADDED.hasListeners(stage)) { + PlayerEvents.STAGE_ADDED.post(new StageChangedEvent(getPlayer(), this, stage), stage); + } + return true; } @@ -44,7 +47,10 @@ default boolean remove(String stage) { PacketDistributor.sendToAllPlayers(new RemoveStagePayload(player.getUUID(), stage)); } - PlayerEvents.STAGE_REMOVED.post(new StageChangedEvent(getPlayer(), this, stage), stage); + if (PlayerEvents.STAGE_REMOVED.hasListeners(stage)) { + PlayerEvents.STAGE_REMOVED.post(new StageChangedEvent(getPlayer(), this, stage), stage); + } + return true; } diff --git a/src/main/java/dev/latvian/mods/kubejs/util/ConsoleJS.java b/src/main/java/dev/latvian/mods/kubejs/util/ConsoleJS.java index f7bc9fdfe..0fa3b08cf 100644 --- a/src/main/java/dev/latvian/mods/kubejs/util/ConsoleJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/util/ConsoleJS.java @@ -1,9 +1,9 @@ package dev.latvian.mods.kubejs.util; import dev.latvian.mods.kubejs.DevProperties; -import dev.latvian.mods.kubejs.helpers.MiscHelper; import dev.latvian.mods.kubejs.script.ConsoleLine; import dev.latvian.mods.kubejs.script.KubeJSContext; +import dev.latvian.mods.kubejs.script.PlatformWrapper; import dev.latvian.mods.kubejs.script.ScriptType; import dev.latvian.mods.rhino.Context; import dev.latvian.mods.rhino.ContextFactory; @@ -229,7 +229,7 @@ public synchronized void writeToFile(LogType type, String line) { } public synchronized void writeToFile(LogType type, long timestamp, String line) { - if (!writeToFile || MiscHelper.get().isDataGen()) { + if (!writeToFile || PlatformWrapper.isGeneratingData()) { return; } @@ -237,7 +237,7 @@ public synchronized void writeToFile(LogType type, long timestamp, String line) var sb = new StringBuilder(); sb.append('['); - UtilsJS.appendTimestamp(sb, calendar); + TimeJS.appendTimestamp(sb, calendar); sb.append(']'); sb.append(' '); sb.append('['); diff --git a/src/main/java/dev/latvian/mods/kubejs/util/ID.java b/src/main/java/dev/latvian/mods/kubejs/util/ID.java new file mode 100644 index 000000000..a765c3423 --- /dev/null +++ b/src/main/java/dev/latvian/mods/kubejs/util/ID.java @@ -0,0 +1,85 @@ +package dev.latvian.mods.kubejs.util; + +import com.google.gson.JsonPrimitive; +import dev.latvian.mods.kubejs.KubeJS; +import net.minecraft.ResourceLocationException; +import net.minecraft.core.Holder; +import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; +import org.jetbrains.annotations.Nullable; + +public interface ID { + static String string(@Nullable String id) { + if (id == null || id.isEmpty()) { + return ""; + } + + if (id.indexOf(':') == -1) { + return "minecraft:" + id; + } + + return id; + } + + static String kjsString(String id) { + if (id == null || id.isEmpty()) { + return ""; + } + + if (id.indexOf(':') == -1) { + return KubeJS.MOD_ID + ":" + id; + } + + return id; + } + + static String namespace(@Nullable String s) { + if (s == null || s.isEmpty()) { + return "minecraft"; + } + + var i = s.indexOf(':'); + return i == -1 ? "minecraft" : s.substring(0, i); + } + + static String path(@Nullable String s) { + if (s == null || s.isEmpty()) { + return "air"; + } + + var i = s.indexOf(':'); + return i == -1 ? s : s.substring(i + 1); + } + + static ResourceLocation of(@Nullable Object o, boolean preferKJS) { + if (o == null) { + return null; + } else if (o instanceof ResourceLocation id) { + return id; + } else if (o instanceof ResourceKey key) { + return key.location(); + } else if (o instanceof Holder holder) { + return holder.unwrapKey().get().location(); + } + + var s = o instanceof JsonPrimitive p ? p.getAsString() : o.toString(); + + if (s.indexOf(':') == -1 && preferKJS) { + s = "kubejs:" + s; + } + + try { + return new ResourceLocation(s); + } catch (ResourceLocationException ex) { + throw new IllegalArgumentException("Could not create ID from '%s'!".formatted(s)); + } + } + + static ResourceLocation mc(@Nullable Object o) { + return of(o, false); + } + + static ResourceLocation kjs(@Nullable Object o) { + return of(o, true); + } +} diff --git a/src/main/java/dev/latvian/mods/kubejs/util/NotificationToastData.java b/src/main/java/dev/latvian/mods/kubejs/util/NotificationToastData.java index da03d19bb..3326e4525 100644 --- a/src/main/java/dev/latvian/mods/kubejs/util/NotificationToastData.java +++ b/src/main/java/dev/latvian/mods/kubejs/util/NotificationToastData.java @@ -3,7 +3,6 @@ import com.mojang.serialization.Codec; import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; -import dev.latvian.mods.kubejs.KubeJSCodecs; import dev.latvian.mods.kubejs.client.NotificationToast; import dev.latvian.mods.kubejs.color.Color; import dev.latvian.mods.kubejs.color.SimpleColor; @@ -34,7 +33,7 @@ public record NotificationToastData( public static final Color DEFAULT_BACKGROUND_COLOR = new SimpleColor(0x241335); public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(instance -> instance.group( - KubeJSCodecs.DURATION.optionalFieldOf("duration", DEFAULT_DURATION).forGetter(NotificationToastData::duration), + TimeJS.DURATION.optionalFieldOf("duration", DEFAULT_DURATION).forGetter(NotificationToastData::duration), ComponentSerialization.CODEC.optionalFieldOf("text", Component.empty()).forGetter(NotificationToastData::text), IconKJS.CODEC.optionalFieldOf("icon", IconKJS.NONE).forGetter(NotificationToastData::icon), Codec.INT.optionalFieldOf("icon_size", 16).forGetter(NotificationToastData::iconSize), @@ -47,7 +46,7 @@ public record NotificationToastData( public static final StreamCodec STREAM_CODEC = new StreamCodec<>() { @Override public NotificationToastData decode(RegistryFriendlyByteBuf buf) { - var duration = KubeJSCodecs.DURATION_STREAM.decode(buf); + var duration = TimeJS.DURATION_STREAM.decode(buf); var text = ComponentSerialization.STREAM_CODEC.decode(buf); var icon = IconKJS.STREAM_CODEC.decode(buf); var iconSize = ByteBufCodecs.VAR_INT.decode(buf); @@ -60,7 +59,7 @@ public NotificationToastData decode(RegistryFriendlyByteBuf buf) { @Override public void encode(RegistryFriendlyByteBuf buf, NotificationToastData data) { - KubeJSCodecs.DURATION_STREAM.encode(buf, data.duration()); + TimeJS.DURATION_STREAM.encode(buf, data.duration()); ComponentSerialization.STREAM_CODEC.encode(buf, data.text()); IconKJS.STREAM_CODEC.encode(buf, data.icon()); ByteBufCodecs.VAR_INT.encode(buf, data.iconSize()); diff --git a/src/main/java/dev/latvian/mods/kubejs/util/StringWithContext.java b/src/main/java/dev/latvian/mods/kubejs/util/StringWithContext.java deleted file mode 100644 index 9d56f84e3..000000000 --- a/src/main/java/dev/latvian/mods/kubejs/util/StringWithContext.java +++ /dev/null @@ -1,29 +0,0 @@ -package dev.latvian.mods.kubejs.util; - -import dev.latvian.mods.kubejs.script.KubeJSContext; -import dev.latvian.mods.rhino.Context; - -public record StringWithContext(KubeJSContext cx, String string) { - public static StringWithContext of(Context cx, Object o) { - if (cx instanceof KubeJSContext kcx) { - return new StringWithContext(kcx, o.toString()); - } else { - throw new IllegalArgumentException("Context is not a KubeJSContext"); - } - } - - @Override - public int hashCode() { - return string.hashCode(); - } - - @Override - public boolean equals(Object o) { - return o != null && toString().equals(o.toString()); - } - - @Override - public String toString() { - return string; - } -} diff --git a/src/main/java/dev/latvian/mods/kubejs/util/TimeJS.java b/src/main/java/dev/latvian/mods/kubejs/util/TimeJS.java new file mode 100644 index 000000000..12c82c5b6 --- /dev/null +++ b/src/main/java/dev/latvian/mods/kubejs/util/TimeJS.java @@ -0,0 +1,128 @@ +package dev.latvian.mods.kubejs.util; + +import com.google.gson.JsonPrimitive; +import com.mojang.serialization.Codec; +import dev.latvian.mods.kubejs.KubeJSCodecs; +import io.netty.buffer.ByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; + +import java.time.Duration; +import java.time.temporal.TemporalAmount; +import java.util.Calendar; +import java.util.regex.Pattern; + +public interface TimeJS { + Pattern TEMPORAL_AMOUNT_PATTERN = Pattern.compile("(\\d+)\\s*(y|M|d|w|h|m|s|ms|ns|t)\\b"); + Codec DURATION = KubeJSCodecs.stringResolverCodec(Duration::toString, TimeJS::durationOf); + StreamCodec DURATION_STREAM = ByteBufCodecs.STRING_UTF8.map(TimeJS::durationOf, Duration::toString); + + static TemporalAmount temporalAmountOf(Object o) { + if (o instanceof TemporalAmount d) { + return d; + } else if (o instanceof Number n) { + return Duration.ofMillis(n.longValue()); + } else if (o instanceof CharSequence) { + var matcher = TEMPORAL_AMOUNT_PATTERN.matcher(o.toString()); + + var millis = 0L; + var nanos = 0L; + var ticks = -1L; + + while (matcher.find()) { + var amount = Double.parseDouble(matcher.group(1)); + + switch (matcher.group(2)) { + case "t" -> { + if (ticks == -1L) { + ticks = 0L; + } + + ticks += amount; + } + + case "ns" -> nanos += (long) amount; + case "ms" -> millis += (long) amount; + case "s" -> millis = (long) (amount * 1000D); + case "m" -> millis = (long) (amount * 60000D); + case "h" -> millis = (long) (amount * 60000D) * 60L; + case "d" -> millis = (long) (amount * 24D * 86400L) * 1000L; + case "w" -> millis = (long) (amount * 24D * 86400L) * 7000L; + case "M" -> millis = (long) (amount * 31556952D / 12D) * 1000L; + case "y" -> millis = (long) (amount * 31556952D) * 1000L; + default -> throw new IllegalArgumentException("Invalid temporal unit: " + matcher.group(2)); + } + } + + if (ticks != -1L) { + return new TickDuration(ticks + millis / 50L); + } + + return Duration.ofMillis(millis).plusNanos(nanos); + } else { + throw new IllegalArgumentException("Invalid temporal amount: " + o); + } + } + + static long tickDurationOf(Object o) { + if (o instanceof Number n) { + return n.longValue(); + } else if (o instanceof JsonPrimitive json) { + return json.getAsLong(); + } + + var t = temporalAmountOf(o); + + if (t instanceof TickDuration d) { + return d.ticks(); + } else if (t instanceof Duration d) { + return d.toMillis() / 50L; + } else { + return 0L; + } + } + + static Duration durationOf(Object o) { + var t = temporalAmountOf(o); + + if (t instanceof Duration d) { + return d; + } else if (t instanceof TickDuration d) { + return Duration.ofMillis(d.ticks() * 50L); + } else { + var d = Duration.ZERO; + + for (var unit : t.getUnits()) { + d = d.plus(t.get(unit), unit); + } + + return d; + } + } + + static void appendTimestamp(StringBuilder builder, Calendar calendar) { + int h = calendar.get(Calendar.HOUR_OF_DAY); + int m = calendar.get(Calendar.MINUTE); + int s = calendar.get(Calendar.SECOND); + + if (h < 10) { + builder.append('0'); + } + + builder.append(h); + builder.append(':'); + + if (m < 10) { + builder.append('0'); + } + + builder.append(m); + builder.append(':'); + + if (s < 10) { + builder.append('0'); + } + + builder.append(s); + } +} diff --git a/src/main/java/dev/latvian/mods/kubejs/util/UtilsJS.java b/src/main/java/dev/latvian/mods/kubejs/util/UtilsJS.java index 636266055..30b802aa6 100644 --- a/src/main/java/dev/latvian/mods/kubejs/util/UtilsJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/util/UtilsJS.java @@ -5,52 +5,31 @@ import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import com.mojang.brigadier.StringReader; -import dev.latvian.mods.kubejs.KubeJS; import dev.latvian.mods.kubejs.bindings.event.BlockEvents; import dev.latvian.mods.kubejs.bindings.event.ItemEvents; import dev.latvian.mods.kubejs.block.BlockModificationKubeEvent; import dev.latvian.mods.kubejs.item.ItemModificationKubeEvent; -import dev.latvian.mods.kubejs.level.BlockContainerJS; import dev.latvian.mods.kubejs.registry.RegistryInfo; import dev.latvian.mods.kubejs.script.ScriptType; import dev.latvian.mods.rhino.BaseFunction; import dev.latvian.mods.rhino.Context; import dev.latvian.mods.rhino.Wrapper; import dev.latvian.mods.rhino.type.TypeInfo; -import net.minecraft.ResourceLocationException; import net.minecraft.advancements.critereon.MinMaxBounds; import net.minecraft.commands.arguments.selector.EntitySelector; import net.minecraft.commands.arguments.selector.EntitySelectorParser; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Holder; import net.minecraft.core.HolderLookup; import net.minecraft.core.RegistryAccess; -import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.EndTag; -import net.minecraft.nbt.NbtOps; import net.minecraft.nbt.NumericTag; import net.minecraft.nbt.StringTag; import net.minecraft.nbt.Tag; -import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; -import net.minecraft.util.valueproviders.ClampedInt; -import net.minecraft.util.valueproviders.ClampedNormalInt; -import net.minecraft.util.valueproviders.ConstantInt; -import net.minecraft.util.valueproviders.IntProvider; -import net.minecraft.util.valueproviders.UniformInt; -import net.minecraft.world.entity.Entity; +import net.minecraft.server.ReloadableServerResources; import net.minecraft.world.item.CreativeModeTab; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.storage.loot.providers.number.BinomialDistributionGenerator; -import net.minecraft.world.level.storage.loot.providers.number.ConstantValue; -import net.minecraft.world.level.storage.loot.providers.number.NumberProvider; -import net.minecraft.world.level.storage.loot.providers.number.UniformGenerator; -import net.minecraft.world.phys.Vec3; import org.jetbrains.annotations.Nullable; -import java.io.File; import java.io.IOException; import java.lang.reflect.Array; import java.lang.reflect.GenericArrayType; @@ -58,20 +37,11 @@ import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; -import java.nio.file.Path; -import java.time.Duration; -import java.time.temporal.TemporalAmount; import java.util.ArrayList; import java.util.Arrays; -import java.util.Calendar; -import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; import java.util.Map; -import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.StringJoiner; @@ -89,11 +59,10 @@ public class UtilsJS { public static final String[] EMPTY_STRING_ARRAY = new String[0]; public static MinecraftServer staticServer = null; public static HolderLookup.Provider staticRegistryAccess = RegistryAccess.EMPTY; // FIXME + public static ReloadableServerResources staticResources = null; public static final ResourceLocation UNKNOWN_ID = new ResourceLocation("unknown", "unknown"); public static final Predicate ALWAYS_TRUE = o -> true; - public static final Pattern TEMPORAL_AMOUNT_PATTERN = Pattern.compile("(\\d+)\\s*(y|M|d|w|h|m|s|ms|ns|t)\\b"); - private static Collection ALL_STATE_CACHE = null; private static final Map ENTITY_SELECTOR_CACHE = new HashMap<>(); private static final EntitySelector ALL_ENTITIES_SELECTOR = new EntitySelector(EntitySelector.INFINITE, true, false, e -> true, MinMaxBounds.Doubles.ANY, Function.identity(), null, EntitySelectorParser.ORDER_RANDOM, false, null, null, null, true); @@ -110,15 +79,6 @@ public static void tryIO(TryIO tryIO) { } } - /** - * Use {@link Cast#to(Object)} - */ - @Deprecated(forRemoval = true) - @SuppressWarnings("unchecked") - public static T cast(Object o) { - return (T) o; - } - public static void queueIO(Runnable runnable) { try { runnable.run(); @@ -127,36 +87,6 @@ public static void queueIO(Runnable runnable) { } } - @Nullable - public static Path getPath(Object o) { - try { - if (o instanceof Path) { - return KubeJS.verifyFilePath((Path) o); - } else if (o == null || o.toString().isEmpty()) { - return null; - } - - return KubeJS.verifyFilePath(KubeJS.getGameDirectory().resolve(o.toString())); - } catch (Exception ex) { - return null; - } - } - - @Nullable - public static File getFileFromPath(Object o) { - try { - if (o instanceof File) { - return KubeJS.verifyFilePath(((File) o).toPath()).toFile(); - } else if (o == null || o.toString().isEmpty()) { - return null; - } - - return KubeJS.verifyFilePath(KubeJS.getGameDirectory().resolve(o.toString())).toFile(); - } catch (Exception ex) { - return null; - } - } - @Nullable public static Object copy(@Nullable Object o) { if (o instanceof Copyable copyable) { @@ -172,12 +102,20 @@ public static Object copy(@Nullable Object o) { @Nullable public static Object wrap(@Nullable Object o, JSObjectType type) { //Primitives and already normalized objects - if (o == null || o instanceof WrappedJS || o instanceof Tag || o instanceof Number || o instanceof Character || o instanceof String || o instanceof Enum || o.getClass().isPrimitive() && !o.getClass().isArray()) { + if (o == null || o instanceof WrappedJS || o instanceof Number || o instanceof Character || o instanceof String || o instanceof Enum || o.getClass().isPrimitive() && !o.getClass().isArray()) { return o; } else if (o instanceof CharSequence || o instanceof ResourceLocation) { return o.toString(); + } else if (o instanceof EndTag || o instanceof JsonNull) { + return null; } else if (o instanceof Wrapper w) { return wrap(w.unwrap(), type); + } else if (o instanceof NumericTag tag) { + return tag.getAsNumber(); + } else if (o instanceof StringTag tag) { + return tag.getAsString(); + } else if (o instanceof Tag) { + return o; } // Maps else if (o instanceof Map) { @@ -223,28 +161,6 @@ else if (o instanceof JsonObject json) { return map; } - // GSON and NBT Null - else if (o instanceof JsonNull || o instanceof EndTag) { - return null; - } - // NBT - else if (o instanceof CompoundTag tag) { - if (!type.checkMap()) { - return null; - } - - var map = new HashMap(tag.size()); - - for (var s : tag.getAllKeys()) { - map.put(s, tag.get(s)); - } - - return map; - } else if (o instanceof NumericTag tag) { - return tag.getAsNumber(); - } else if (o instanceof StringTag tag) { - return tag.getAsString(); - } return o; } @@ -309,96 +225,6 @@ public static double parseDouble(@Nullable Object object, double def) { } } - public static String getID(@Nullable String s) { - if (s == null || s.isEmpty()) { - return "minecraft:air"; - } - - if (s.indexOf(':') == -1) { - return "minecraft:" + s; - } - - return s; - } - - public static ResourceLocation getMCID(@Nullable Context cx, @Nullable Object o, boolean preferKJS) { - if (o == null) { - return null; - } else if (o instanceof ResourceLocation id) { - return id; - } else if (o instanceof ResourceKey key) { - return key.location(); - } else if (o instanceof Holder holder) { - return holder.unwrapKey().get().location(); - } - - var s = o instanceof JsonPrimitive p ? p.getAsString() : o.toString(); - - if (s.indexOf(':') == -1 && preferKJS) { - s = "kubejs:" + s; - } - - try { - return new ResourceLocation(s); - } catch (ResourceLocationException ex) { - ConsoleJS.getCurrent(cx).error("Could not create ID from '%s'!".formatted(s), ex); - } - - return null; - } - - public static ResourceLocation getMCID(@Nullable Context cx, @Nullable Object o) { - return getMCID(cx, o, false); - } - - public static String getNamespace(@Nullable String s) { - if (s == null || s.isEmpty()) { - return "minecraft"; - } - - var i = s.indexOf(':'); - return i == -1 ? "minecraft" : s.substring(0, i); - } - - public static String getPath(@Nullable String s) { - if (s == null || s.isEmpty()) { - return "air"; - } - - var i = s.indexOf(':'); - return i == -1 ? s : s.substring(i + 1); - } - - public static BlockState parseBlockState(String string) { - if (string.isEmpty()) { - return Blocks.AIR.defaultBlockState(); - } - - var i = string.indexOf('['); - var hasProperties = i >= 0 && string.indexOf(']') == string.length() - 1; - var state = RegistryInfo.BLOCK.getValue(new ResourceLocation(hasProperties ? string.substring(0, i) : string)).defaultBlockState(); - - if (hasProperties) { - for (var s : string.substring(i + 1, string.length() - 1).split(",")) { - var s1 = s.split("=", 2); - - if (s1.length == 2 && !s1[0].isEmpty() && !s1[1].isEmpty()) { - var p = state.getBlock().getStateDefinition().getProperty(s1[0]); - - if (p != null) { - Optional o = p.getValue(s1[1]); - - if (o.isPresent()) { - state = state.setValue(p, UtilsJS.cast(o.get())); - } - } - } - } - } - - return state; - } - public static Predicate onMatchDo(Predicate predicate, Consumer onMatch) { return t -> { var match = predicate.test(t); @@ -550,126 +376,6 @@ public static String snakeCaseToTitleCase(String string) { return joiner.toString(); } - @SuppressWarnings("unchecked") - public static IntProvider intProviderOf(Context cx, Object o) { - if (o instanceof Number n) { - return ConstantInt.of(n.intValue()); - } else if (o instanceof List l && !l.isEmpty()) { - var min = (Number) l.get(0); - var max = l.size() >= 2 ? (Number) l.get(1) : min; - return UniformInt.of(min.intValue(), max.intValue()); - } else if (o instanceof Map) { - var m = (Map) o; - - var intBounds = parseIntBounds(m); - if (intBounds != null) { - return intBounds; - } else if (m.containsKey("clamped")) { - var source = intProviderOf(cx, m.get("clamped")); - var clampTo = parseIntBounds(m); - if (clampTo != null) { - return ClampedInt.of(source, clampTo.getMinValue(), clampTo.getMaxValue()); - } - } else if (m.containsKey("clamped_normal")) { - var clampTo = parseIntBounds(m); - var mean = ((Number) m.get("mean")).intValue(); - var deviation = ((Number) m.get("deviation")).intValue(); - if (clampTo != null) { - return ClampedNormalInt.of(mean, deviation, clampTo.getMinValue(), clampTo.getMaxValue()); - } - } - - var decoded = IntProvider.CODEC.parse(NbtOps.INSTANCE, NBTUtils.toTagCompound(cx, m)).result(); - if (decoded.isPresent()) { - return decoded.get(); - } - } - - return ConstantInt.of(0); - } - - private static UniformInt parseIntBounds(Map m) { - if (m.get("bounds") instanceof List bounds) { - return UniformInt.of(UtilsJS.parseInt(bounds.get(0), 0), UtilsJS.parseInt(bounds.get(1), 0)); - } else if (m.containsKey("min") && m.containsKey("max")) { - return UniformInt.of(((Number) m.get("min")).intValue(), ((Number) m.get("max")).intValue()); - } else if (m.containsKey("min_inclusive") && m.containsKey("max_inclusive")) { - return UniformInt.of(((Number) m.get("min_inclusive")).intValue(), ((Number) m.get("max_inclusive")).intValue()); - } else if (m.containsKey("value")) { - var f = ((Number) m.get("value")).intValue(); - return UniformInt.of(f, f); - } - return null; - } - - @SuppressWarnings("unchecked") - public static NumberProvider numberProviderOf(Object o) { - if (o instanceof Number n) { - var f = n.floatValue(); - return UniformGenerator.between(f, f); - } else if (o instanceof List l && !l.isEmpty()) { - var min = (Number) l.get(0); - var max = l.size() >= 2 ? (Number) l.get(1) : min; - return UniformGenerator.between(min.floatValue(), max.floatValue()); - } else if (o instanceof Map) { - var m = (Map) o; - if (m.containsKey("min") && m.containsKey("max")) { - return UniformGenerator.between(((Number) m.get("min")).intValue(), ((Number) m.get("max")).floatValue()); - } else if (m.containsKey("n") && m.containsKey("p")) { - return BinomialDistributionGenerator.binomial(((Number) m.get("n")).intValue(), ((Number) m.get("p")).floatValue()); - } else if (m.containsKey("value")) { - var f = ((Number) m.get("value")).floatValue(); - return UniformGenerator.between(f, f); - } - } - - return ConstantValue.exactly(0); - } - - public static Vec3 vec3Of(@Nullable Object o) { - if (o instanceof Vec3 vec) { - return vec; - } else if (o instanceof Entity entity) { - return entity.position(); - } else if (o instanceof List list && list.size() >= 3) { - return new Vec3(UtilsJS.parseDouble(list.get(0), 0), UtilsJS.parseDouble(list.get(1), 0), UtilsJS.parseDouble(list.get(2), 0)); - } else if (o instanceof BlockPos pos) { - return new Vec3(pos.getX() + 0.5D, pos.getY() + 0.5D, pos.getZ() + 0.5D); - } else if (o instanceof BlockContainerJS block) { - return new Vec3(block.getPos().getX() + 0.5D, block.getPos().getY() + 0.5D, block.getPos().getZ() + 0.5D); - } - - return Vec3.ZERO; - } - - public static BlockPos blockPosOf(@Nullable Object o) { - if (o instanceof BlockPos pos) { - return pos; - } else if (o instanceof List list && list.size() >= 3) { - return new BlockPos(UtilsJS.parseInt(list.get(0), 0), UtilsJS.parseInt(list.get(1), 0), UtilsJS.parseInt(list.get(2), 0)); - } else if (o instanceof BlockContainerJS block) { - return block.getPos(); - } else if (o instanceof Vec3 vec) { - return BlockPos.containing(vec.x, vec.y, vec.z); - } - - return BlockPos.ZERO; - } - - public static Collection getAllBlockStates() { - if (ALL_STATE_CACHE != null) { - return ALL_STATE_CACHE; - } - - var states = new HashSet(); - for (var block : RegistryInfo.BLOCK.getArchitecturyRegistrar()) { - states.addAll(block.getStateDefinition().getPossibleStates()); - } - - ALL_STATE_CACHE = Collections.unmodifiableCollection(states); - return ALL_STATE_CACHE; - } - public static String toTitleCase(String s) { return toTitleCase(s, false); } @@ -739,149 +445,6 @@ public static CreativeModeTab findCreativeTab(ResourceLocation id) { } public static T makeFunctionProxy(Context cx, TypeInfo targetClass, BaseFunction function) { - return cast(cx.createInterfaceAdapter(targetClass, function)); - } - - public static TemporalAmount getTemporalAmount(Object o) { - if (o instanceof TemporalAmount d) { - return d; - } else if (o instanceof Number n) { - return Duration.ofMillis(n.longValue()); - } else if (o instanceof CharSequence) { - var matcher = TEMPORAL_AMOUNT_PATTERN.matcher(o.toString()); - - var millis = 0L; - var nanos = 0L; - var ticks = -1L; - - while (matcher.find()) { - var amount = Double.parseDouble(matcher.group(1)); - - switch (matcher.group(2)) { - case "t" -> { - if (ticks == -1L) { - ticks = 0L; - } - - ticks += amount; - } - - case "ns" -> nanos += (long) amount; - case "ms" -> millis += (long) amount; - case "s" -> millis = (long) (amount * 1000D); - case "m" -> millis = (long) (amount * 60000D); - case "h" -> millis = (long) (amount * 60000D) * 60L; - case "d" -> millis = (long) (amount * 24D * 86400L) * 1000L; - case "w" -> millis = (long) (amount * 24D * 86400L) * 7000L; - case "M" -> millis = (long) (amount * 31556952D / 12D) * 1000L; - case "y" -> millis = (long) (amount * 31556952D) * 1000L; - default -> throw new IllegalArgumentException("Invalid temporal unit: " + matcher.group(2)); - } - } - - if (ticks != -1L) { - return new TickDuration(ticks + millis / 50L); - } - - return Duration.ofMillis(millis).plusNanos(nanos); - } else { - throw new IllegalArgumentException("Invalid temporal amount: " + o); - } - } - - public static long getTickDuration(Object o) { - if (o instanceof Number n) { - return n.longValue(); - } else if (o instanceof JsonPrimitive json) { - return json.getAsLong(); - } - - var t = getTemporalAmount(o); - - if (t instanceof TickDuration d) { - return d.ticks(); - } else if (t instanceof Duration d) { - return d.toMillis() / 50L; - } else { - return 0L; - } - } - - public static Duration getDuration(Object o) { - var t = getTemporalAmount(o); - - if (t instanceof Duration d) { - return d; - } else if (t instanceof TickDuration d) { - return Duration.ofMillis(d.ticks() * 50L); - } else { - var d = Duration.ZERO; - - for (var unit : t.getUnits()) { - d = d.plus(t.get(unit), unit); - } - - return d; - } - } - - public static void appendTimestamp(StringBuilder builder, Calendar calendar) { - int h = calendar.get(Calendar.HOUR_OF_DAY); - int m = calendar.get(Calendar.MINUTE); - int s = calendar.get(Calendar.SECOND); - - if (h < 10) { - builder.append('0'); - } - - builder.append(h); - builder.append(':'); - - if (m < 10) { - builder.append('0'); - } - - builder.append(m); - builder.append(':'); - - if (s < 10) { - builder.append('0'); - } - - builder.append(s); - } - - public static Map remap(Map original, Class keyClass, Class valueClass, boolean linked) { - if (original.isEmpty()) { - return Map.of(); - } - - var map = linked ? new LinkedHashMap() : new HashMap(); - - for (var entry : original.entrySet()) { - var okey = entry.getKey(); - var ovalue = entry.getValue(); - - if (okey == null || ovalue == null) { - continue; - } - - Object key = null; - Object value = null; - - if (keyClass.isInstance(okey)) { - key = okey; - } - - if (valueClass.isInstance(ovalue)) { - value = ovalue; - } - - if (key != null && value != null) { - map.put(keyClass.cast(key), valueClass.cast(value)); - } - } - - return map; + return Cast.to(cx.createInterfaceAdapter(targetClass, function)); } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/util/WithContext.java b/src/main/java/dev/latvian/mods/kubejs/util/WithContext.java deleted file mode 100644 index 57a05a563..000000000 --- a/src/main/java/dev/latvian/mods/kubejs/util/WithContext.java +++ /dev/null @@ -1,38 +0,0 @@ -package dev.latvian.mods.kubejs.util; - -import dev.latvian.mods.kubejs.script.KubeJSContext; -import dev.latvian.mods.rhino.Context; -import dev.latvian.mods.rhino.type.TypeInfo; - -import java.util.Objects; - -public record WithContext(KubeJSContext cx, T value) { - public static WithContext of(Context cx, Object o, TypeInfo target) { - if (cx instanceof KubeJSContext kcx) { - var type = target.param(0); - - if (type.shouldConvert()) { - return new WithContext(kcx, cx.jsToJava(o, type)); - } else { - return new WithContext(kcx, o); - } - } - - throw new IllegalArgumentException("Context is not a KubeJSContext"); - } - - @Override - public int hashCode() { - return value == null ? 0 : value.hashCode(); - } - - @Override - public boolean equals(Object o) { - return o instanceof WithContext wc && Objects.equals(value, wc.value); - } - - @Override - public String toString() { - return "WithContext[" + value + ']'; - } -} diff --git a/src/main/java/dev/latvian/mods/kubejs/util/registrypredicate/RegistryPredicate.java b/src/main/java/dev/latvian/mods/kubejs/util/registrypredicate/RegistryPredicate.java index 3b34d7503..b14941a92 100644 --- a/src/main/java/dev/latvian/mods/kubejs/util/registrypredicate/RegistryPredicate.java +++ b/src/main/java/dev/latvian/mods/kubejs/util/registrypredicate/RegistryPredicate.java @@ -2,8 +2,8 @@ import com.google.gson.JsonPrimitive; import dev.latvian.mods.kubejs.registry.RegistryInfo; +import dev.latvian.mods.kubejs.util.ID; import dev.latvian.mods.kubejs.util.RegExpJS; -import dev.latvian.mods.kubejs.util.UtilsJS; import dev.latvian.mods.rhino.BaseFunction; import dev.latvian.mods.rhino.Context; import dev.latvian.mods.rhino.regexp.NativeRegExp; @@ -34,7 +34,7 @@ static RegistryPredicate of(Context cx, Object from, TypeInfo target) { return EntireRegistryPredicate.FALSE; } else if (s.startsWith("#")) { var reg = RegistryInfo.ofClass(target.param(0).asClass()); - var tag = UtilsJS.getMCID(cx, s.substring(1)); + var tag = ID.mc(s.substring(1)); if (reg != null) { return new RegistryTagKeyPredicate<>(TagKey.create(reg.key, tag)); @@ -50,7 +50,7 @@ static RegistryPredicate of(Context cx, Object from, TypeInfo target) { return new RegistryRegExpPredicate<>(pattern); } else { var reg = RegistryInfo.ofClass(target.param(0).asClass()); - var id = UtilsJS.getMCID(cx, s); + var id = ID.mc(s); if (reg != null) { return new RegistryHolderPredicate<>(reg.getHolder(id)); diff --git a/src/main/resources/kubejs.mixins.json b/src/main/resources/kubejs.mixins.json index 343da51b9..da1650599 100644 --- a/src/main/resources/kubejs.mixins.json +++ b/src/main/resources/kubejs.mixins.json @@ -3,6 +3,7 @@ "package": "dev.latvian.mods.kubejs.core.mixin", "compatibilityLevel": "JAVA_17", "mixins": [ + "AdvancementNodeMixin", "BlockBehaviourMixin", "BlockMixin", "BlockStateBaseMixin", @@ -20,6 +21,7 @@ "DirectionMixin", "DyeColorMixin", "EntityMixin", + "EntityTypeMixin", "EventHandlerBridgeMixin", "EventHandlerInvoker", "FireworkRocketEntityMixin", @@ -34,6 +36,7 @@ "LevelMixin", "LivingEntityMixin", "LootDataTypeMixin", + "MenuTypeMixin", "MinecraftServerMixin", "MutableComponentMixin", "NumericTagMixin", diff --git a/src/main/resources/kubejs.plugins.txt b/src/main/resources/kubejs.plugins.txt index d51c2cb5b..a182489a4 100644 --- a/src/main/resources/kubejs.plugins.txt +++ b/src/main/resources/kubejs.plugins.txt @@ -1,5 +1,5 @@ -dev.latvian.mods.kubejs.neoforge.NeoForgeKubeJSPlugin -dev.latvian.mods.kubejs.neoforge.NeoForgeKubeJSClientPlugin client +dev.latvian.mods.kubejs.BuiltinKubeJSPlugin +dev.latvian.mods.kubejs.client.BuiltinKubeJSClientPlugin client dev.latvian.mods.kubejs.integration.gamestages.GameStagesIntegration gamestages dev.latvian.mods.kubejs.integration.jei.JEIIntegration jei dev.latvian.mods.kubejs.integration.rei.REIIntegration roughlyenoughitems \ No newline at end of file