From d631de54c2ba074e2cf19d9a9e29129ff7829d92 Mon Sep 17 00:00:00 2001 From: LatvianModder Date: Fri, 14 Jun 2024 22:09:40 +0300 Subject: [PATCH] Ported to 1.21, added few new icons, replaced custom ingredient action callbacks with an event --- .kubejs/meta.json | 2 +- build.gradle | 2 +- gradle.properties | 12 +- settings.gradle | 2 +- .../mods/kubejs/BuiltinKubeJSPlugin.java | 40 +- .../java/dev/latvian/mods/kubejs/KubeJS.java | 10 +- .../dev/latvian/mods/kubejs/KubeJSCommon.java | 3 - .../dev/latvian/mods/kubejs/KubeJSPlugin.java | 10 +- .../mods/kubejs/bindings/BlockWrapper.java | 44 +- .../kubejs/bindings/IngredientWrapper.java | 7 - .../mods/kubejs/bindings/ItemWrapper.java | 18 +- .../mods/kubejs/bindings/TextWrapper.java | 24 +- .../mods/kubejs/bindings/UtilsWrapper.java | 5 - .../kubejs/bindings/event/ServerEvents.java | 5 +- .../mods/kubejs/block/BlockBuilder.java | 8 +- .../block/custom/ButtonBlockBuilder.java | 23 +- .../block/custom/CarpetBlockBuilder.java | 6 +- .../kubejs/block/custom/CropBlockBuilder.java | 13 +- .../block/custom/FenceBlockBuilder.java | 10 +- .../block/custom/FenceGateBlockBuilder.java | 9 +- .../custom/PressurePlateBlockBuilder.java | 6 +- .../kubejs/block/custom/SlabBlockBuilder.java | 6 +- .../block/custom/StairBlockBuilder.java | 6 +- .../kubejs/block/custom/WallBlockBuilder.java | 6 +- .../block/state/BlockStatePredicate.java | 6 +- .../client/BuiltinKubeJSClientPlugin.java | 14 +- .../client/GenerateClientAssetsKubeEvent.java | 6 +- .../client/GeneratedClientResourcePack.java | 2 +- .../mods/kubejs/client/KubeJSClient.java | 33 +- .../client/KubeJSClientEventHandler.java | 38 +- .../mods/kubejs/client/NotificationToast.java | 13 +- .../mods/kubejs/client/TagInstance.java | 52 +- .../kubejs/client/painter/PaintKubeEvent.java | 33 +- .../mods/kubejs/client/painter/Painter.java | 21 +- .../painter/PainterObjectProperties.java | 2 +- .../painter/screen/AtlasTextureObject.java | 4 +- .../client/painter/screen/GradientObject.java | 30 +- .../client/painter/screen/ItemObject.java | 20 +- .../client/painter/screen/LineObject.java | 2 - .../painter/screen/PaintScreenKubeEvent.java | 23 +- .../painter/screen/RectangleObject.java | 6 +- .../mods/kubejs/command/DumpCommands.java | 265 ++++++++ .../kubejs/command/InformationCommands.java | 109 +++ .../mods/kubejs/command/KubeJSCommands.java | 636 ++---------------- .../command/PersistentDataCommands.java | 175 +++++ .../mods/kubejs/command/StageCommands.java | 48 ++ .../kubejs/core/CraftingContainerKJS.java | 13 - .../mods/kubejs/core/EnchantmentKJS.java | 13 - .../mods/kubejs/core/ItemStackKJS.java | 6 +- .../mods/kubejs/core/LivingEntityKJS.java | 24 +- .../mods/kubejs/core/RecipeInputKJS.java | 51 ++ .../mixin/AbstractSelectionListMixin.java | 1 + .../kubejs/core/mixin/ClickEventMixin.java | 3 - .../kubejs/core/mixin/CompoundTagMixin.java | 7 +- .../core/mixin/CraftingContainerMixin.java | 17 - .../kubejs/core/mixin/EnchantmentMixin.java | 46 -- .../mods/kubejs/core/mixin/ItemMixin.java | 4 +- .../kubejs/core/mixin/ItemStackMixin.java | 3 +- .../core/mixin/KeyboardHandlerMixin.java | 9 +- .../mods/kubejs/core/mixin/LevelMixin.java | 2 + .../kubejs/core/mixin/LivingEntityMixin.java | 7 +- .../core/mixin/LoadingOverlayMixin.java | 1 + .../kubejs/core/mixin/LootDataTypeMixin.java | 6 +- .../mods/kubejs/core/mixin/OptionsMixin.java | 2 +- .../kubejs/core/mixin/PlayerListMixin.java | 1 + .../kubejs/core/mixin/RecipeInputMixin.java | 9 + .../kubejs/core/mixin/ResourceKeyMixin.java | 3 - .../mods/kubejs/core/mixin/ScreenMixin.java | 1 + .../kubejs/core/mixin/ServerLevelMixin.java | 4 +- .../mixin/WorldLoaderPackConfigMixin.java | 1 + .../entity/LivingEntityDropsKubeEvent.java | 4 - .../dev/latvian/mods/kubejs/event/Extra.java | 4 +- .../mods/kubejs/fluid/FluidBuilder.java | 2 +- .../kubejs/generator/AssetJsonGenerator.java | 12 +- .../kubejs/generator/ResourceGenerator.java | 2 +- .../latvian/mods/kubejs/gui/KubeJSScreen.java | 2 +- .../kubejs/integration/jei/JEIPlugin.java | 2 +- .../latvian/mods/kubejs/item/FoodBuilder.java | 11 +- .../latvian/mods/kubejs/item/ItemBuilder.java | 125 ++-- .../kubejs/item/ItemEnchantmentsWrapper.java | 5 +- .../latvian/mods/kubejs/item/ItemStackJS.java | 2 +- .../mods/kubejs/item/JukeboxSongBuilder.java | 54 ++ .../mods/kubejs/item/custom/RecordItemJS.java | 86 --- .../kubejs/item/custom/ShearsItemBuilder.java | 9 +- .../kubejs/item/ingredient/IngredientJS.java | 4 +- .../mods/kubejs/level/BlockContainerJS.java | 2 - .../mods/kubejs/misc/BasicEnchantment.java | 3 +- .../mods/kubejs/misc/BasicMobEffect.java | 4 +- .../mods/kubejs/misc/EnchantmentBuilder.java | 3 +- .../mods/kubejs/misc/MobEffectBuilder.java | 7 +- .../kubejs/misc/PaintingVariantBuilder.java | 16 +- .../kubejs/neoforge/KubeJSNeoForgeClient.java | 11 + .../mods/kubejs/player/EntityArrayList.java | 13 +- .../mods/kubejs/player/PlayerStatsJS.java | 2 +- .../ContainerModifyRecipeCraftingGrid.java | 50 -- .../recipe/ModifyCraftingItemKubeEvent.java | 41 ++ .../recipe/ModifyRecipeCraftingGrid.java | 45 -- .../recipe/ModifyRecipeResultKubeEvent.java | 33 - .../mods/kubejs/recipe/RecipesKubeEvent.java | 9 +- .../recipe/component/StringComponent.java | 8 +- .../recipe/component/TagKeyComponent.java | 2 +- .../ingredientaction/ConsumeAction.java | 4 +- .../CustomIngredientAction.java | 15 +- .../CustomIngredientActionCallback.java | 9 - .../recipe/ingredientaction/DamageAction.java | 4 +- .../ingredientaction/IngredientAction.java | 10 +- .../recipe/ingredientaction/KeepAction.java | 4 +- .../ingredientaction/ReplaceAction.java | 4 +- .../recipe/schema/JsonRecipeSchemaLoader.java | 6 +- .../recipe/schema/RecipeMappingRegistry.java | 2 +- .../kubejs/recipe/schema/RecipeNamespace.java | 2 +- .../recipe/schema/RecipeSchemaStorage.java | 2 +- .../schema/minecraft/ShapedKubeRecipe.java | 1 - .../recipe/special/KubeJSCraftingRecipe.java | 23 +- .../recipe/special/ShapedKubeJSRecipe.java | 67 +- .../recipe/special/ShapelessKubeJSRecipe.java | 10 +- .../mods/kubejs/registry/BuilderBase.java | 7 +- .../mods/kubejs/registry/RegistryInfo.java | 4 +- .../mods/kubejs/script/KubeJSContext.java | 136 ++-- .../mods/kubejs/script/ScriptFileInfo.java | 2 +- .../kubejs/script/data/DataPackKubeEvent.java | 2 +- .../script/data/GeneratedResourcePack.java | 2 +- .../kubejs/server/ServerScriptManager.java | 2 - .../kubejs/server/tag/TagEventFilter.java | 4 +- .../java/dev/latvian/mods/kubejs/util/ID.java | 4 +- .../dev/latvian/mods/kubejs/util/IconKJS.java | 26 +- .../latvian/mods/kubejs/util/NBTUtils.java | 3 + .../dev/latvian/mods/kubejs/util/UtilsJS.java | 5 +- src/main/resources/architectury.common.json | 6 - .../resources/assets/kubejs/font/icons.json | 46 +- .../kubejs/textures/font/icons/block_tag.png | Bin 0 -> 249 bytes .../textures/font/icons/entity_type_tag.png | Bin 0 -> 216 bytes .../kubejs/textures/font/icons/fluid_tag.png | Bin 0 -> 220 bytes .../textures/font/icons/{i.png => info.png} | Bin .../kubejs/textures/font/icons/item_tag.png | Bin 0 -> 191 bytes .../textures/font/icons/{k.png => kube.png} | Bin .../textures/font/icons/{n.png => no.png} | Bin .../assets/kubejs/textures/font/icons/tag.png | Bin 0 -> 223 bytes .../textures/font/icons/{w.png => warn.png} | Bin .../textures/font/icons/{y.png => yes.png} | Bin src/main/resources/kubejs.accesswidener | 4 +- src/main/resources/kubejs.mixins.json | 3 +- 142 files changed, 1485 insertions(+), 1556 deletions(-) create mode 100644 src/main/java/dev/latvian/mods/kubejs/command/DumpCommands.java create mode 100644 src/main/java/dev/latvian/mods/kubejs/command/InformationCommands.java create mode 100644 src/main/java/dev/latvian/mods/kubejs/command/PersistentDataCommands.java create mode 100644 src/main/java/dev/latvian/mods/kubejs/command/StageCommands.java delete mode 100644 src/main/java/dev/latvian/mods/kubejs/core/CraftingContainerKJS.java delete mode 100644 src/main/java/dev/latvian/mods/kubejs/core/EnchantmentKJS.java create mode 100644 src/main/java/dev/latvian/mods/kubejs/core/RecipeInputKJS.java delete mode 100644 src/main/java/dev/latvian/mods/kubejs/core/mixin/CraftingContainerMixin.java delete mode 100644 src/main/java/dev/latvian/mods/kubejs/core/mixin/EnchantmentMixin.java create mode 100644 src/main/java/dev/latvian/mods/kubejs/core/mixin/RecipeInputMixin.java create mode 100644 src/main/java/dev/latvian/mods/kubejs/item/JukeboxSongBuilder.java delete mode 100644 src/main/java/dev/latvian/mods/kubejs/item/custom/RecordItemJS.java delete mode 100644 src/main/java/dev/latvian/mods/kubejs/recipe/ContainerModifyRecipeCraftingGrid.java create mode 100644 src/main/java/dev/latvian/mods/kubejs/recipe/ModifyCraftingItemKubeEvent.java delete mode 100644 src/main/java/dev/latvian/mods/kubejs/recipe/ModifyRecipeCraftingGrid.java delete mode 100644 src/main/java/dev/latvian/mods/kubejs/recipe/ModifyRecipeResultKubeEvent.java delete mode 100644 src/main/java/dev/latvian/mods/kubejs/recipe/ingredientaction/CustomIngredientActionCallback.java create mode 100644 src/main/resources/assets/kubejs/textures/font/icons/block_tag.png create mode 100644 src/main/resources/assets/kubejs/textures/font/icons/entity_type_tag.png create mode 100644 src/main/resources/assets/kubejs/textures/font/icons/fluid_tag.png rename src/main/resources/assets/kubejs/textures/font/icons/{i.png => info.png} (100%) create mode 100644 src/main/resources/assets/kubejs/textures/font/icons/item_tag.png rename src/main/resources/assets/kubejs/textures/font/icons/{k.png => kube.png} (100%) rename src/main/resources/assets/kubejs/textures/font/icons/{n.png => no.png} (100%) create mode 100644 src/main/resources/assets/kubejs/textures/font/icons/tag.png rename src/main/resources/assets/kubejs/textures/font/icons/{w.png => warn.png} (100%) rename src/main/resources/assets/kubejs/textures/font/icons/{y.png => yes.png} (100%) diff --git a/.kubejs/meta.json b/.kubejs/meta.json index 32d3bcec3..f36f92a81 100644 --- a/.kubejs/meta.json +++ b/.kubejs/meta.json @@ -1,5 +1,5 @@ { - "minecraft": 2006, + "minecraft": 2100, "type": "neoforge", "version": { "file": "gradle.properties", diff --git a/build.gradle b/build.gradle index 4dfb9fe3f..caa6b7863 100644 --- a/build.gradle +++ b/build.gradle @@ -87,7 +87,7 @@ dependencies { minecraft "com.mojang:minecraft:$minecraft_version" mappings loom.layered() { officialMojangMappings() - parchment("org.parchmentmc.data:parchment-$minecraft_version:$parchment_version@zip") + parchment("org.parchmentmc.data:parchment-1.20.6:$parchment_version@zip") } neoForge("net.neoforged:neoforge:$neoforge_version") diff --git a/gradle.properties b/gradle.properties index ca7a0377b..82c838641 100644 --- a/gradle.properties +++ b/gradle.properties @@ -10,13 +10,13 @@ mod_author=latvian.dev curseforge_id=238086 modrinth_id=umyGl7zF -minecraft_version=1.20.6 -mod_version=2006.7.0 +minecraft_version=1.21 +mod_version=2100.7.0 -neoforge_version=20.6.115 -parchment_version=2024.05.01 -rhino_version=2006.2.5-build.25 -architectury_version=12.1.3 +neoforge_version=21.0.6-beta +parchment_version=2024.06.02 +rhino_version=2100.2.5-build.28 +architectury_version=13.0.1 rei_version=15.0.728 #rei_comp_version=9.0.16 diff --git a/settings.gradle b/settings.gradle index b86423b67..40cb18496 100644 --- a/settings.gradle +++ b/settings.gradle @@ -7,4 +7,4 @@ pluginManagement { } } -rootProject.name = 'KubeJS-1.20.6' +rootProject.name = 'KubeJS-1.21' diff --git a/src/main/java/dev/latvian/mods/kubejs/BuiltinKubeJSPlugin.java b/src/main/java/dev/latvian/mods/kubejs/BuiltinKubeJSPlugin.java index e9bcfb4bc..5a7d30217 100644 --- a/src/main/java/dev/latvian/mods/kubejs/BuiltinKubeJSPlugin.java +++ b/src/main/java/dev/latvian/mods/kubejs/BuiltinKubeJSPlugin.java @@ -46,6 +46,13 @@ import dev.latvian.mods.kubejs.block.entity.InventoryAttachment; import dev.latvian.mods.kubejs.block.state.BlockStatePredicate; import dev.latvian.mods.kubejs.client.painter.Painter; +import dev.latvian.mods.kubejs.client.painter.screen.AtlasTextureObject; +import dev.latvian.mods.kubejs.client.painter.screen.GradientObject; +import dev.latvian.mods.kubejs.client.painter.screen.ItemObject; +import dev.latvian.mods.kubejs.client.painter.screen.LineObject; +import dev.latvian.mods.kubejs.client.painter.screen.RectangleObject; +import dev.latvian.mods.kubejs.client.painter.screen.ScreenGroup; +import dev.latvian.mods.kubejs.client.painter.screen.TextObject; import dev.latvian.mods.kubejs.color.Color; import dev.latvian.mods.kubejs.core.PlayerSelector; import dev.latvian.mods.kubejs.event.EventGroupRegistry; @@ -61,12 +68,12 @@ import dev.latvian.mods.kubejs.item.ItemEnchantmentsWrapper; import dev.latvian.mods.kubejs.item.ItemStackJS; import dev.latvian.mods.kubejs.item.ItemTintFunction; +import dev.latvian.mods.kubejs.item.JukeboxSongBuilder; import dev.latvian.mods.kubejs.item.creativetab.CreativeTabBuilder; import dev.latvian.mods.kubejs.item.custom.ArmorItemBuilder; import dev.latvian.mods.kubejs.item.custom.BasicItemJS; import dev.latvian.mods.kubejs.item.custom.DiggerItemBuilder; import dev.latvian.mods.kubejs.item.custom.ItemToolTierRegistryKubeEvent; -import dev.latvian.mods.kubejs.item.custom.RecordItemJS; import dev.latvian.mods.kubejs.item.custom.ShearsItemBuilder; import dev.latvian.mods.kubejs.item.custom.SmithingTemplateItemBuilder; import dev.latvian.mods.kubejs.item.custom.SwordItemBuilder; @@ -74,7 +81,6 @@ import dev.latvian.mods.kubejs.level.ruletest.KubeJSRuleTests; import dev.latvian.mods.kubejs.misc.BasicMobEffect; import dev.latvian.mods.kubejs.misc.CustomStatBuilder; -import dev.latvian.mods.kubejs.misc.EnchantmentBuilder; import dev.latvian.mods.kubejs.misc.PaintingVariantBuilder; import dev.latvian.mods.kubejs.misc.ParticleTypeBuilder; import dev.latvian.mods.kubejs.misc.PoiTypeBuilder; @@ -145,7 +151,6 @@ import dev.latvian.mods.kubejs.util.registrypredicate.RegistryPredicate; import dev.latvian.mods.rhino.type.RecordTypeInfo; import dev.latvian.mods.rhino.type.TypeInfo; -import dev.latvian.mods.unit.Unit; import net.minecraft.commands.arguments.selector.EntitySelector; import net.minecraft.core.BlockPos; import net.minecraft.core.Vec3i; @@ -176,11 +181,11 @@ import net.minecraft.world.item.Tier; import net.minecraft.world.item.component.Fireworks; import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.world.item.enchantment.Enchantment; import net.minecraft.world.item.enchantment.ItemEnchantments; import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.SoundType; +import net.minecraft.world.level.block.state.properties.BlockSetType; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.levelgen.structure.templatesystem.RuleTest; import net.minecraft.world.level.material.MapColor; @@ -189,7 +194,10 @@ 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.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.common.ToolAction; import net.neoforged.neoforge.common.crafting.SizedIngredient; import net.neoforged.neoforge.fluids.FluidStack; import net.neoforged.neoforge.fluids.crafting.FluidIngredient; @@ -261,12 +269,11 @@ public void registerBuilderTypes(BuilderTypeRegistry registry) { reg.add("leggings", ArmorItemBuilder.Leggings.class, ArmorItemBuilder.Leggings::new); reg.add("boots", ArmorItemBuilder.Boots.class, ArmorItemBuilder.Boots::new); reg.add("animal_armor", ArmorItemBuilder.AnimalArmor.class, ArmorItemBuilder.AnimalArmor::new); - reg.add("music_disc", RecordItemJS.Builder.class, RecordItemJS.Builder::new); reg.add("smithing_template", SmithingTemplateItemBuilder.class, SmithingTemplateItemBuilder::new); }); registry.addDefault(Registries.FLUID, FluidBuilder.class, FluidBuilder::new); - registry.addDefault(Registries.ENCHANTMENT, EnchantmentBuilder.class, EnchantmentBuilder::new); + // FIXME registry.addDefault(Registries.ENCHANTMENT, EnchantmentBuilder.class, EnchantmentBuilder::new); registry.addDefault(Registries.MOB_EFFECT, BasicMobEffect.Builder.class, BasicMobEffect.Builder::new); registry.addDefault(Registries.POTION, PotionBuilder.class, PotionBuilder::new); registry.addDefault(Registries.PARTICLE_TYPE, ParticleTypeBuilder.class, ParticleTypeBuilder::new); @@ -277,6 +284,7 @@ public void registerBuilderTypes(BuilderTypeRegistry registry) { registry.addDefault(Registries.VILLAGER_PROFESSION, VillagerProfessionBuilder.class, VillagerProfessionBuilder::new); registry.addDefault(Registries.CREATIVE_MODE_TAB, CreativeTabBuilder.class, CreativeTabBuilder::new); registry.addDefault(Registries.ARMOR_MATERIAL, ArmorMaterialBuilder.class, ArmorMaterialBuilder::new); + registry.addDefault(Registries.JUKEBOX_SONG, JukeboxSongBuilder.class, JukeboxSongBuilder::new); } @Override @@ -383,7 +391,8 @@ public void registerBindings(BindingRegistry bindings) { } bindings.add("JavaMath", Math.class); - bindings.add("ResourceLocation", ResourceLocation.class); + bindings.add("ID", ID.class); + bindings.add("Duration", Duration.class); // event.add("onEvent", new LegacyCodeHandler("onEvent()")); @@ -472,7 +481,6 @@ public void registerTypeWrappers(TypeWrapperRegistry registry) { registry.register(JsonPrimitive.class, JsonUtils::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); @@ -499,8 +507,10 @@ public void registerTypeWrappers(TypeWrapperRegistry registry) { registry.register(NumberProvider.class, KubeJSTypeWrappers::numberProviderOf); registry.registerEnumFromStringCodec(LootContext.EntityTarget.class, LootContext.EntityTarget.CODEC); registry.registerEnumFromStringCodec(CopyNameFunction.NameSource.class, CopyNameFunction.NameSource.CODEC); - registry.register(Enchantment.Cost.class, EnchantmentBuilder::costOf); + // FIXME registry.register(Enchantment.Cost.class, EnchantmentBuilder::costOf); registry.registerEnumFromStringCodec(ArmorItem.Type.class, ArmorItem.Type.CODEC); + registry.register(BlockSetType.class, BlockWrapper::setTypeOf); + registry.register(ToolAction.class, ItemWrapper::toolActionOf); // KubeJS // registry.register(Map.class, MapJS::of); @@ -621,6 +631,18 @@ public void registerIngredientActionTypes(IngredientActionTypeRegistry registry) registry.register(ReplaceAction.TYPE); } + @Override + @OnlyIn(Dist.CLIENT) + public void painterRegistry(Painter painter) { + painter.registerObject("screen_group", ScreenGroup::new); + painter.registerObject("rectangle", RectangleObject::new); + painter.registerObject("text", TextObject::new); + painter.registerObject("atlas_texture", AtlasTextureObject::new); + painter.registerObject("gradient", GradientObject::new); + painter.registerObject("item", ItemObject::new); + painter.registerObject("line", LineObject::new); + } + @Override public void clearCaches() { ItemStackJS.CACHED_ITEM_MAP.forget(); diff --git a/src/main/java/dev/latvian/mods/kubejs/KubeJS.java b/src/main/java/dev/latvian/mods/kubejs/KubeJS.java index 664fce6e6..c2d0b073f 100644 --- a/src/main/java/dev/latvian/mods/kubejs/KubeJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/KubeJS.java @@ -35,7 +35,6 @@ import net.neoforged.bus.api.EventPriority; import net.neoforged.bus.api.IEventBus; import net.neoforged.bus.api.SubscribeEvent; -import net.neoforged.fml.DistExecutor; import net.neoforged.fml.ModContainer; import net.neoforged.fml.ModList; import net.neoforged.fml.common.EventBusSubscriber; @@ -80,12 +79,12 @@ public class KubeJS { public static String VERSION = "0"; public static ResourceLocation id(String path) { - return new ResourceLocation(MOD_ID, path); + return ResourceLocation.fromNamespaceAndPath(MOD_ID, path); } public static ModContainer thisMod; - public static KubeJSCommon PROXY; + public static KubeJSCommon PROXY = new KubeJSCommon(); private static ScriptManager startupScriptManager, clientScriptManager; @@ -126,8 +125,7 @@ public KubeJS(IEventBus bus, Dist dist, ModContainer mod) throws Throwable { } } - //noinspection removal - PROXY = DistExecutor.safeRunForDist(() -> KubeJSClient::new, () -> KubeJSCommon::new); + PROXY = new KubeJSClient(); if (!PlatformWrapper.isGeneratingData()) { new KubeJSBackgroundThread().start(); @@ -156,8 +154,6 @@ public KubeJS(IEventBus bus, Dist dist, ModContainer mod) throws Throwable { KubeJSPlugins.forEachPlugin(KubeJSPlugin::initStartup); - PROXY.init(); - for (var key : StartupEvents.REGISTRY.findUniqueExtraIds(ScriptType.STARTUP)) { StartupEvents.REGISTRY.post(new RegistryKubeEvent<>((ResourceKey) key), key); } diff --git a/src/main/java/dev/latvian/mods/kubejs/KubeJSCommon.java b/src/main/java/dev/latvian/mods/kubejs/KubeJSCommon.java index bf99989f1..b3ca4af5e 100644 --- a/src/main/java/dev/latvian/mods/kubejs/KubeJSCommon.java +++ b/src/main/java/dev/latvian/mods/kubejs/KubeJSCommon.java @@ -11,9 +11,6 @@ import java.util.List; public class KubeJSCommon { - public void init() { - } - public void reloadClientInternal() { } diff --git a/src/main/java/dev/latvian/mods/kubejs/KubeJSPlugin.java b/src/main/java/dev/latvian/mods/kubejs/KubeJSPlugin.java index 874db10ab..3b259d46a 100644 --- a/src/main/java/dev/latvian/mods/kubejs/KubeJSPlugin.java +++ b/src/main/java/dev/latvian/mods/kubejs/KubeJSPlugin.java @@ -2,6 +2,7 @@ import dev.latvian.mods.kubejs.block.entity.BlockEntityAttachmentType; import dev.latvian.mods.kubejs.client.LangKubeEvent; +import dev.latvian.mods.kubejs.client.painter.Painter; import dev.latvian.mods.kubejs.core.RecipeManagerKJS; import dev.latvian.mods.kubejs.event.EventGroup; import dev.latvian.mods.kubejs.event.EventGroupRegistry; @@ -26,6 +27,8 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.crafting.RecipeHolder; import net.minecraft.world.level.Level; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; import java.util.List; import java.util.Map; @@ -37,9 +40,6 @@ default void init() { default void initStartup() { } - default void clientInit() { - } - default void afterInit() { } @@ -82,6 +82,10 @@ default void registerBlockEntityAttachments(List type default void registerIngredientActionTypes(IngredientActionTypeRegistry registry) { } + @OnlyIn(Dist.CLIENT) + default void painterRegistry(Painter painter) { + } + default void attachServerData(AttachedData event) { } 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 f7fd5e694..043aa6dcb 100644 --- a/src/main/java/dev/latvian/mods/kubejs/bindings/BlockWrapper.java +++ b/src/main/java/dev/latvian/mods/kubejs/bindings/BlockWrapper.java @@ -5,9 +5,12 @@ 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 dev.latvian.mods.rhino.Context; +import dev.latvian.mods.rhino.type.RecordTypeInfo; +import dev.latvian.mods.rhino.type.TypeInfo; import net.minecraft.Util; +import net.minecraft.commands.arguments.blocks.BlockStateParser; import net.minecraft.core.Direction; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceKey; @@ -15,6 +18,7 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.properties.BlockSetType; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; @@ -25,7 +29,6 @@ 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 { @@ -118,28 +121,29 @@ public static BlockState parseBlockState(String string) { 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]); + try { + return BlockStateParser.parseForBlock(BuiltInRegistries.BLOCK.asLookup(), string, false).blockState(); + } catch (Exception ex) { + return Blocks.AIR.defaultBlockState(); + } + } - if (p != null) { - Optional o = p.getValue(s1[1]); + public static BlockSetType setTypeOf(Context cx, Object from, TypeInfo target) { + return switch (from) { + case null -> null; + case BlockSetType type -> type; + case CharSequence charSequence -> { + var str = charSequence.toString(); - if (o.isPresent()) { - state = state.setValue(p, Cast.to(o.get())); - } + for (var type : BlockSetType.values().toList()) { + if (type.name().equalsIgnoreCase(str)) { + yield type; } } - } - } - return state; + yield null; + } + default -> (BlockSetType) ((RecordTypeInfo) target).wrap(cx, from, target); + }; } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/bindings/IngredientWrapper.java b/src/main/java/dev/latvian/mods/kubejs/bindings/IngredientWrapper.java index c1dc7dfac..c8f0bcb1b 100644 --- a/src/main/java/dev/latvian/mods/kubejs/bindings/IngredientWrapper.java +++ b/src/main/java/dev/latvian/mods/kubejs/bindings/IngredientWrapper.java @@ -1,8 +1,6 @@ package dev.latvian.mods.kubejs.bindings; import dev.latvian.mods.kubejs.helpers.IngredientHelper; -import dev.latvian.mods.kubejs.recipe.ingredientaction.CustomIngredientAction; -import dev.latvian.mods.kubejs.recipe.ingredientaction.CustomIngredientActionCallback; import dev.latvian.mods.kubejs.typings.Info; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; @@ -26,11 +24,6 @@ static SizedIngredient of(Ingredient ingredient, int count) { return ingredient.kjs$withCount(count); } - @Info("Register a custom ingredient action for use in recipes with Recipe#customIngredientAction") - static void registerCustomIngredientAction(String id, CustomIngredientActionCallback callback) { - CustomIngredientAction.MAP.put(id, callback); - } - @Info(""" Checks if the passed in object is an Ingredient. Note that this does not mean it will not function as an Ingredient if passed to something that requests one. diff --git a/src/main/java/dev/latvian/mods/kubejs/bindings/ItemWrapper.java b/src/main/java/dev/latvian/mods/kubejs/bindings/ItemWrapper.java index e8ece7e62..341826909 100644 --- a/src/main/java/dev/latvian/mods/kubejs/bindings/ItemWrapper.java +++ b/src/main/java/dev/latvian/mods/kubejs/bindings/ItemWrapper.java @@ -4,18 +4,22 @@ import com.mojang.authlib.GameProfile; import com.mojang.authlib.properties.Property; import com.mojang.authlib.properties.PropertyMap; +import com.mojang.serialization.MapCodec; import dev.latvian.mods.kubejs.item.ItemStackJS; import dev.latvian.mods.kubejs.registry.RegistryInfo; import dev.latvian.mods.kubejs.typings.Info; import dev.latvian.mods.kubejs.util.JsonUtils; import net.minecraft.Util; import net.minecraft.core.component.DataComponents; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.entity.EntityType; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.item.component.Fireworks; import net.minecraft.world.item.component.ResolvableProfile; +import net.neoforged.neoforge.common.ToolAction; import org.jetbrains.annotations.Nullable; import java.nio.charset.StandardCharsets; @@ -28,9 +32,7 @@ @Info("Various item related helper methods") public interface ItemWrapper { - UUID KJS_BASE_ATTACK_DAMAGE_UUID = UUID.fromString("CB3F55D3-645C-4F38-A497-9C13A33DB5CF"); - UUID KJS_BASE_ATTACK_SPEED_UUID = UUID.fromString("FA233E1C-4180-4865-B01B-BCCE9785ACA3"); - UUID[] KJS_ARMOR_MODIFIER_UUID_PER_SLOT = new UUID[]{UUID.fromString("845DB27C-C624-495F-8C9F-6020A9A58B6B"), UUID.fromString("D8499B04-0E66-4726-AB29-64469D734E0D"), UUID.fromString("9F3D476D-C118-4544-8365-64846904B48E"), UUID.fromString("2AD3F246-FEE1-4E67-B886-69FD380BB150")}; + MapCodec> ENTITY_TYPE_FIELD_CODEC = BuiltInRegistries.ENTITY_TYPE.byNameCodec().fieldOf("id"); @Info("Returns an ItemStack of the input") static ItemStack of(ItemStack in) { @@ -130,4 +132,14 @@ static ItemStack playerHeadFromUrl(String url) { static ItemStack playerHeadFromSkinHash(String hash) { return playerHeadFromUrl("https://textures.minecraft.net/texture/" + hash); } + + static ToolAction toolActionOf(Object object) { + if (object instanceof ToolAction ta) { + return ta; + } else if (object != null) { + return ToolAction.get(object.toString()); + } else { + return null; + } + } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/bindings/TextWrapper.java b/src/main/java/dev/latvian/mods/kubejs/bindings/TextWrapper.java index 7670e0db3..1a0b3b2c6 100644 --- a/src/main/java/dev/latvian/mods/kubejs/bindings/TextWrapper.java +++ b/src/main/java/dev/latvian/mods/kubejs/bindings/TextWrapper.java @@ -97,7 +97,7 @@ static MutableComponent of(Context cx, @Nullable Object o) { text.kjs$obfuscated((Boolean) map.getOrDefault("obfuscated", null)); text.kjs$insertion((String) map.getOrDefault("insertion", null)); - text.kjs$font(map.containsKey("font") ? new ResourceLocation(map.get("font").toString()) : null); + text.kjs$font(map.containsKey("font") ? ResourceLocation.parse(map.get("font").toString()) : null); text.kjs$click(map.containsKey("click") ? clickEventOf(cx, map.get("click")) : null); text.kjs$hover(map.containsKey("hover") ? of(cx, map.get("hover")) : null); @@ -338,7 +338,7 @@ static MutableComponent white(MutableComponent text) { return text.kjs$white(); } - private static MutableComponent icon(MutableComponent character) { + static MutableComponent icon(MutableComponent character) { return character.kjs$font(KubeJS.ICONS_FONT); } @@ -377,4 +377,24 @@ static MutableComponent noIcon() { static MutableComponent yesIcon(boolean yes) { return icon(yes ? Component.literal("Y") : Component.literal("N")); } + + static MutableComponent tagIcon() { + return icon(Component.literal("T")); + } + + static MutableComponent blockTagIcon() { + return icon(Component.literal("B")); + } + + static MutableComponent itemTagIcon() { + return icon(Component.literal("J")); + } + + static MutableComponent fluidTagIcon() { + return icon(Component.literal("F")); + } + + static MutableComponent entityTypeTagIcon() { + return icon(Component.literal("E")); + } } \ No newline at end of file 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 824d2c4d8..ce015c8e1 100644 --- a/src/main/java/dev/latvian/mods/kubejs/bindings/UtilsWrapper.java +++ b/src/main/java/dev/latvian/mods/kubejs/bindings/UtilsWrapper.java @@ -80,11 +80,6 @@ static CountingMap newCountingMap() { return new CountingMap(); } - @Info("Returns a ResourceLocation with the specified namepsace and path") - static ResourceLocation id(String namespace, String path) { - return new ResourceLocation(namespace, path); - } - @Info("Typewraps the input string to a ResourceLocation. Format should be namespace:path") static ResourceLocation id(ResourceLocation id) { // TypeWrapper will convert any object into RL 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 1654626e1..bcd31041e 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 @@ -8,7 +8,7 @@ import dev.latvian.mods.kubejs.item.ItemStackJS; import dev.latvian.mods.kubejs.recipe.AfterRecipesLoadedKubeEvent; import dev.latvian.mods.kubejs.recipe.CompostableRecipesKubeEvent; -import dev.latvian.mods.kubejs.recipe.ModifyRecipeResultKubeEvent; +import dev.latvian.mods.kubejs.recipe.ModifyCraftingItemKubeEvent; import dev.latvian.mods.kubejs.recipe.RecipesKubeEvent; import dev.latvian.mods.kubejs.recipe.schema.RecipeMappingRegistry; import dev.latvian.mods.kubejs.recipe.schema.RecipeSchemaRegistry; @@ -39,5 +39,6 @@ public interface ServerEvents { EventHandler RECIPES_AFTER_LOADED = GROUP.server("afterRecipes", () -> AfterRecipesLoadedKubeEvent.class); EventHandler SPECIAL_RECIPES = GROUP.server("specialRecipeSerializers", () -> SpecialRecipeSerializerManager.class); EventHandler COMPOSTABLE_RECIPES = GROUP.server("compostableRecipes", () -> CompostableRecipesKubeEvent.class); - SpecializedEventHandler MODIFY_RECIPE_RESULT = GROUP.server("modifyRecipeResult", Extra.STRING, () -> ModifyRecipeResultKubeEvent.class).required().hasResult(ItemStackJS.TYPE_INFO); + SpecializedEventHandler MODIFY_RECIPE_RESULT = GROUP.server("modifyRecipeResult", Extra.STRING, () -> ModifyCraftingItemKubeEvent.class).required().hasResult(ItemStackJS.TYPE_INFO); + SpecializedEventHandler MODIFY_RECIPE_INGREDIENT = GROUP.server("modifyRecipeIngredient", Extra.STRING, () -> ModifyCraftingItemKubeEvent.class).required().hasResult(ItemStackJS.TYPE_INFO); } 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 c1a4e173b..a2604b93b 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/BlockBuilder.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/BlockBuilder.java @@ -686,25 +686,25 @@ public BlockBuilder instrument(NoteBlockInstrument i) { @Override @Info("Tags both the block and the item with the given tag.") - public BlockBuilder tag(ResourceLocation tag) { + public BlockBuilder tag(ResourceLocation[] tag) { return tagBoth(tag); } @Info("Tags both the block and the item with the given tag.") - public BlockBuilder tagBoth(ResourceLocation tag) { + public BlockBuilder tagBoth(ResourceLocation[] tag) { tagBlock(tag); tagItem(tag); return this; } @Info("Tags the block with the given tag.") - public BlockBuilder tagBlock(ResourceLocation tag) { + public BlockBuilder tagBlock(ResourceLocation[] tag) { super.tag(tag); return this; } @Info("Tags the item with the given tag.") - public BlockBuilder tagItem(ResourceLocation tag) { + public BlockBuilder tagItem(ResourceLocation[] tag) { itemBuilder.tag(tag); return this; } diff --git a/src/main/java/dev/latvian/mods/kubejs/block/custom/ButtonBlockBuilder.java b/src/main/java/dev/latvian/mods/kubejs/block/custom/ButtonBlockBuilder.java index 04fb99b3d..e53cf38ee 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/custom/ButtonBlockBuilder.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/custom/ButtonBlockBuilder.java @@ -12,6 +12,10 @@ @ReturnsSelf public class ButtonBlockBuilder extends ShapedBlockBuilder { + public static final ResourceLocation[] BUTTON_TAGS = { + BlockTags.BUTTONS.location(), + }; + public transient BlockSetType behaviour; public transient int ticksToStayPressed; public transient boolean arrowsCanPress; @@ -19,7 +23,7 @@ public class ButtonBlockBuilder extends ShapedBlockBuilder { public ButtonBlockBuilder(ResourceLocation i) { super(i, "_button"); noCollision(); - tagBoth(BlockTags.BUTTONS.location()); + tagBoth(BUTTON_TAGS); // tagBoth(BlockTags.WOODEN_BUTTONS.location()); behaviour = BlockSetType.OAK; ticksToStayPressed = 30; @@ -31,17 +35,6 @@ public ButtonBlockBuilder behaviour(BlockSetType wt) { return this; } - public ButtonBlockBuilder behaviour(String wt) { - for (var type : BlockSetType.values().toList()) { - if (type.name().equals(wt)) { - behaviour = type; - return this; - } - } - - return this; - } - public ButtonBlockBuilder ticksToStayPressed(int t) { ticksToStayPressed = t; return this; @@ -55,11 +48,7 @@ public ButtonBlockBuilder arrowsCanPress(boolean b) { @Override public Block createObject() { - // TODO: (maybe) Custom BlockSetTypes? - // instead of all of these methods above, we could just have a single method - // that can take either a string and return an already registered BlockSetType - // or create a BlockSetType using a function like (typeBuilder) => {} - return new ButtonBlock(BlockSetType.OAK, ticksToStayPressed, createProperties()); + return new ButtonBlock(behaviour, ticksToStayPressed, createProperties()); } @Override diff --git a/src/main/java/dev/latvian/mods/kubejs/block/custom/CarpetBlockBuilder.java b/src/main/java/dev/latvian/mods/kubejs/block/custom/CarpetBlockBuilder.java index 0a3196e19..3cdf3a205 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/custom/CarpetBlockBuilder.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/custom/CarpetBlockBuilder.java @@ -10,9 +10,13 @@ @ReturnsSelf public class CarpetBlockBuilder extends ShapedBlockBuilder { + public static final ResourceLocation[] CARPET_TAGS = { + BlockTags.WOOL_CARPETS.location(), + }; + public CarpetBlockBuilder(ResourceLocation i) { super(i, "_carpet"); - tagBoth(BlockTags.WOOL_CARPETS.location()); + tagBoth(CARPET_TAGS); } @Override diff --git a/src/main/java/dev/latvian/mods/kubejs/block/custom/CropBlockBuilder.java b/src/main/java/dev/latvian/mods/kubejs/block/custom/CropBlockBuilder.java index 3cbf5afb4..e5fbf5424 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/custom/CropBlockBuilder.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/custom/CropBlockBuilder.java @@ -25,6 +25,7 @@ import net.minecraft.world.level.material.MapColor; import net.minecraft.world.level.storage.loot.LootTable; import net.minecraft.world.phys.shapes.VoxelShape; +import net.neoforged.neoforge.common.Tags; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; @@ -36,6 +37,14 @@ @ReturnsSelf public class CropBlockBuilder extends BlockBuilder { + public static final ResourceLocation[] CROP_BLOCK_TAGS = { + BlockTags.CROPS.location(), + }; + + public static final ResourceLocation[] CROP_ITEM_TAGS = { + Tags.Items.SEEDS.location(), + }; + @FunctionalInterface public interface SurviveCallback { boolean survive(BlockState state, LevelReader reader, BlockPos pos); @@ -96,8 +105,8 @@ public CropBlockBuilder(ResourceLocation i) { texture(String.valueOf(a), id.getNamespace() + ":block/" + id.getPath() + a); } - tagBlock(BlockTags.CROPS.location()); - tagItem(new ResourceLocation("c:seeds")); + tagBlock(CROP_BLOCK_TAGS); + tagItem(CROP_ITEM_TAGS); } @Info("Add a crop output with a 100% chance.") diff --git a/src/main/java/dev/latvian/mods/kubejs/block/custom/FenceBlockBuilder.java b/src/main/java/dev/latvian/mods/kubejs/block/custom/FenceBlockBuilder.java index 773bf0eec..391cd89ff 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/custom/FenceBlockBuilder.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/custom/FenceBlockBuilder.java @@ -7,13 +7,17 @@ import net.minecraft.tags.BlockTags; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.FenceBlock; +import net.neoforged.neoforge.common.Tags; public class FenceBlockBuilder extends MultipartShapedBlockBuilder { + public static final ResourceLocation[] FENCE_TAGS = { + BlockTags.FENCES.location(), + Tags.Blocks.FENCES.location(), + }; + public FenceBlockBuilder(ResourceLocation i) { super(i, "_fence"); - - tagBoth(BlockTags.FENCES.location()); - tagBoth(new ResourceLocation("c:fences")); + tagBoth(FENCE_TAGS); } @Override diff --git a/src/main/java/dev/latvian/mods/kubejs/block/custom/FenceGateBlockBuilder.java b/src/main/java/dev/latvian/mods/kubejs/block/custom/FenceGateBlockBuilder.java index 4e32944fe..4fcfd750a 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/custom/FenceGateBlockBuilder.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/custom/FenceGateBlockBuilder.java @@ -9,15 +9,20 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.FenceGateBlock; import net.minecraft.world.level.block.state.properties.WoodType; +import net.neoforged.neoforge.common.Tags; @ReturnsSelf public class FenceGateBlockBuilder extends ShapedBlockBuilder { + public static final ResourceLocation[] FENCE_GATE_TAGS = { + BlockTags.FENCE_GATES.location(), + Tags.Blocks.FENCE_GATES.location() + }; + public transient WoodType behaviour; public FenceGateBlockBuilder(ResourceLocation i) { super(i, "_fence_gate"); - tagBoth(BlockTags.FENCE_GATES.location()); - tagBoth(new ResourceLocation("c:fence_gates")); + tagBoth(FENCE_GATE_TAGS); behaviour = WoodType.OAK; } diff --git a/src/main/java/dev/latvian/mods/kubejs/block/custom/PressurePlateBlockBuilder.java b/src/main/java/dev/latvian/mods/kubejs/block/custom/PressurePlateBlockBuilder.java index 6a1386e8d..bd12b1282 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/custom/PressurePlateBlockBuilder.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/custom/PressurePlateBlockBuilder.java @@ -12,12 +12,16 @@ @ReturnsSelf public class PressurePlateBlockBuilder extends ShapedBlockBuilder { + public static final ResourceLocation[] PRESSURE_PLATE_TAGS = { + BlockTags.PRESSURE_PLATES.location(), + }; + public transient BlockSetType behaviour; public PressurePlateBlockBuilder(ResourceLocation i) { super(i, "_pressure_plate"); noCollision(); - tagBoth(BlockTags.PRESSURE_PLATES.location()); + tagBoth(PRESSURE_PLATE_TAGS); // tagBoth(BlockTags.WOODEN_PRESSURE_PLATES.location()); behaviour = BlockSetType.OAK; } diff --git a/src/main/java/dev/latvian/mods/kubejs/block/custom/SlabBlockBuilder.java b/src/main/java/dev/latvian/mods/kubejs/block/custom/SlabBlockBuilder.java index 65a76d0c8..259bb4540 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/custom/SlabBlockBuilder.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/custom/SlabBlockBuilder.java @@ -9,9 +9,13 @@ import net.minecraft.world.level.block.SlabBlock; public class SlabBlockBuilder extends ShapedBlockBuilder { + public static final ResourceLocation[] SLAB_TAGS = { + BlockTags.SLABS.location(), + }; + public SlabBlockBuilder(ResourceLocation i) { super(i, "_slab"); - tagBoth(BlockTags.SLABS.location()); + tagBoth(SLAB_TAGS); } @Override diff --git a/src/main/java/dev/latvian/mods/kubejs/block/custom/StairBlockBuilder.java b/src/main/java/dev/latvian/mods/kubejs/block/custom/StairBlockBuilder.java index 4b251d6b6..47ddd8005 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/custom/StairBlockBuilder.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/custom/StairBlockBuilder.java @@ -9,9 +9,13 @@ import net.minecraft.world.level.block.StairBlock; public class StairBlockBuilder extends ShapedBlockBuilder { + public static final ResourceLocation[] STAIR_TAGS = { + BlockTags.STAIRS.location(), + }; + public StairBlockBuilder(ResourceLocation i) { super(i, "_stairs"); - tagBoth(BlockTags.STAIRS.location()); + tagBoth(STAIR_TAGS); } @Override diff --git a/src/main/java/dev/latvian/mods/kubejs/block/custom/WallBlockBuilder.java b/src/main/java/dev/latvian/mods/kubejs/block/custom/WallBlockBuilder.java index 54e73f0b6..2648f2b99 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/custom/WallBlockBuilder.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/custom/WallBlockBuilder.java @@ -9,9 +9,13 @@ import net.minecraft.world.level.block.WallBlock; public class WallBlockBuilder extends MultipartShapedBlockBuilder { + public static final ResourceLocation[] WALL_TAGS = { + BlockTags.WALLS.location(), + }; + public WallBlockBuilder(ResourceLocation i) { super(i, "_wall"); - tagBoth(BlockTags.WALLS.location()); + tagBoth(WALL_TAGS); } @Override 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 eeb1096a9..5fe217b33 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 @@ -42,8 +42,6 @@ import java.util.regex.Pattern; public sealed interface BlockStatePredicate extends Predicate, ReplacementMatch { - ResourceLocation AIR_ID = new ResourceLocation("minecraft:air"); - @Override boolean test(BlockState state); @@ -62,7 +60,7 @@ static BlockStatePredicate fromString(String s) { } else if (s.equals("-")) { return Simple.NONE; } else if (s.startsWith("#")) { - return new TagMatch(Tags.block(new ResourceLocation(s.substring(1)))); + return new TagMatch(Tags.block(ResourceLocation.parse(s.substring(1)))); } else if (s.indexOf('[') != -1) { var state = BlockWrapper.parseBlockState(s); @@ -70,7 +68,7 @@ static BlockStatePredicate fromString(String s) { return new StateMatch(state); } } else { - var block = RegistryInfo.BLOCK.getValue(new ResourceLocation(s)); + var block = RegistryInfo.BLOCK.getValue(ResourceLocation.parse(s)); if (block != Blocks.AIR) { return new BlockMatch(block); 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 36543a979..c1ecfa0be 100644 --- a/src/main/java/dev/latvian/mods/kubejs/client/BuiltinKubeJSClientPlugin.java +++ b/src/main/java/dev/latvian/mods/kubejs/client/BuiltinKubeJSClientPlugin.java @@ -7,16 +7,13 @@ import dev.latvian.mods.kubejs.event.EventGroupRegistry; import dev.latvian.mods.kubejs.script.BindingRegistry; import dev.latvian.mods.kubejs.script.PlatformWrapper; +import dev.latvian.mods.kubejs.script.TypeWrapperRegistry; import dev.latvian.mods.kubejs.util.ScheduledEvents; +import dev.latvian.mods.unit.Unit; import net.minecraft.client.Minecraft; import net.neoforged.fml.ModList; public class BuiltinKubeJSClientPlugin implements KubeJSPlugin { - @Override - public void clientInit() { - Painter.INSTANCE.registerBuiltinObjects(); - } - @Override public void registerEvents(EventGroupRegistry registry) { registry.register(ClientEvents.GROUP); @@ -25,7 +22,7 @@ public void registerEvents(EventGroupRegistry registry) { @Override public void registerBindings(BindingRegistry bindings) { bindings.add("Client", Minecraft.getInstance()); - bindings.add("Painter", Painter.INSTANCE); + bindings.add("Painter", Painter.getGlobal()); if (bindings.type().isClient()) { var se = Minecraft.getInstance().kjs$getScheduledEvents(); @@ -37,6 +34,11 @@ public void registerBindings(BindingRegistry bindings) { } } + @Override + public void registerTypeWrappers(TypeWrapperRegistry registry) { + registry.register(Unit.class, (ctx, from) -> Painter.getGlobal().unitOf(ctx, from)); + } + @Override public void generateLang(LangKubeEvent event) { event.add(KubeJS.MOD_ID, "key.kubejs.gui", "KubeJS (GUI)"); diff --git a/src/main/java/dev/latvian/mods/kubejs/client/GenerateClientAssetsKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/client/GenerateClientAssetsKubeEvent.java index d56e6fa40..03d8ddc38 100644 --- a/src/main/java/dev/latvian/mods/kubejs/client/GenerateClientAssetsKubeEvent.java +++ b/src/main/java/dev/latvian/mods/kubejs/client/GenerateClientAssetsKubeEvent.java @@ -28,17 +28,17 @@ public void add(ResourceLocation location, JsonElement json) { public void addModel(String type, ResourceLocation id, Consumer consumer) { var gen = Util.make(new ModelGenerator(), consumer); - add(new ResourceLocation(id.getNamespace(), "models/%s/%s".formatted(type, id.getPath())), gen.toJson()); + add(ResourceLocation.fromNamespaceAndPath(id.getNamespace(), "models/%s/%s".formatted(type, id.getPath())), gen.toJson()); } public void addBlockState(ResourceLocation id, Consumer consumer) { var gen = Util.make(new VariantBlockStateGenerator(), consumer); - add(new ResourceLocation(id.getNamespace(), "blockstates/" + id.getPath()), gen.toJson()); + add(ResourceLocation.fromNamespaceAndPath(id.getNamespace(), "blockstates/" + id.getPath()), gen.toJson()); } public void addMultipartBlockState(ResourceLocation id, Consumer consumer) { var gen = Util.make(new MultipartBlockStateGenerator(), consumer); - add(new ResourceLocation(id.getNamespace(), "blockstates/" + id.getPath()), gen.toJson()); + add(ResourceLocation.fromNamespaceAndPath(id.getNamespace(), "blockstates/" + id.getPath()), gen.toJson()); } public void stencil(ResourceLocation target, String stencil, JsonObject colors) throws IOException { diff --git a/src/main/java/dev/latvian/mods/kubejs/client/GeneratedClientResourcePack.java b/src/main/java/dev/latvian/mods/kubejs/client/GeneratedClientResourcePack.java index 820cdc6bb..35a8feb64 100644 --- a/src/main/java/dev/latvian/mods/kubejs/client/GeneratedClientResourcePack.java +++ b/src/main/java/dev/latvian/mods/kubejs/client/GeneratedClientResourcePack.java @@ -141,7 +141,7 @@ public void generate(Map map) { for (var e1 : finalMap.entrySet()) { // namespaces for (var e2 : e1.getValue().entrySet()) { // languages - generator.json(new ResourceLocation(e1.getKey() + ":lang/" + e2.getKey()), e2.getValue()); + generator.json(ResourceLocation.parse(e1.getKey() + ":lang/" + e2.getKey()), e2.getValue()); } } } 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 9e70be3e3..8a692e251 100644 --- a/src/main/java/dev/latvian/mods/kubejs/client/KubeJSClient.java +++ b/src/main/java/dev/latvian/mods/kubejs/client/KubeJSClient.java @@ -3,7 +3,6 @@ import dev.latvian.mods.kubejs.KubeJS; import dev.latvian.mods.kubejs.KubeJSCommon; import dev.latvian.mods.kubejs.KubeJSPaths; -import dev.latvian.mods.kubejs.KubeJSPlugin; import dev.latvian.mods.kubejs.bindings.event.NetworkEvents; import dev.latvian.mods.kubejs.client.painter.Painter; import dev.latvian.mods.kubejs.net.NetworkKubeEvent; @@ -11,7 +10,6 @@ import dev.latvian.mods.kubejs.script.ScriptType; import dev.latvian.mods.kubejs.script.data.ExportablePackResources; import dev.latvian.mods.kubejs.script.data.GeneratedData; -import dev.latvian.mods.kubejs.util.KubeJSPlugins; import net.minecraft.Util; import net.minecraft.client.KeyMapping; import net.minecraft.client.Minecraft; @@ -34,30 +32,12 @@ public class KubeJSClient extends KubeJSCommon { public static KeyMapping guiKey; public static KeyMapping inGameKey; - @Override - public void init() { - var mc = Minecraft.getInstance(); - // You'd think that this is impossible, but not when you use runData gradle task - if (mc == null) { - return; - } - - reloadClientScripts(mc); - - mc.getResourcePackRepository().addPackFinder(new KubeJSResourcePackFinder()); - - KubeJSPlugins.forEachPlugin(KubeJSPlugin::clientInit); - } - @Override public void reloadClientInternal() { - var mc = Minecraft.getInstance(); - if (mc != null) { - reloadClientScripts(mc); - } + reloadClientScripts(); } - public static void reloadClientScripts(Minecraft mc) { + public static void reloadClientScripts() { KubeJSClientEventHandler.staticItemTooltips = null; KubeJS.getClientScriptManager().reload(); } @@ -92,7 +72,7 @@ public Player getClientPlayer() { @Override public void paint(CompoundTag tag) { - Painter.INSTANCE.paint(tag); + Painter.getGlobal().paint(tag); } private void reload(PreparableReloadListener listener) { @@ -122,11 +102,8 @@ public void reloadTextures() { @Override public void reloadLang() { - var mc = Minecraft.getInstance(); - if (mc != null) { - reloadClientScripts(mc); - reload(mc.getLanguageManager()); - } + reloadClientScripts(); + reload(Minecraft.getInstance().getLanguageManager()); } @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 02a3aa3be..d33560f6a 100644 --- a/src/main/java/dev/latvian/mods/kubejs/client/KubeJSClientEventHandler.java +++ b/src/main/java/dev/latvian/mods/kubejs/client/KubeJSClientEventHandler.java @@ -1,6 +1,5 @@ package dev.latvian.mods.kubejs.client; -import dev.architectury.hooks.fluid.FluidBucketHooks; import dev.latvian.mods.kubejs.CommonProperties; import dev.latvian.mods.kubejs.KubeJS; import dev.latvian.mods.kubejs.bindings.event.ClientEvents; @@ -9,14 +8,12 @@ import dev.latvian.mods.kubejs.item.ItemTooltipKubeEvent; import dev.latvian.mods.kubejs.script.ScriptType; import dev.latvian.mods.kubejs.util.ConsoleJS; -import dev.latvian.mods.kubejs.util.Tags; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.components.ImageButton; import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.TitleScreen; import net.minecraft.client.gui.screens.recipebook.RecipeUpdateListener; import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.TagKey; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.BucketItem; import net.minecraft.world.item.Item; @@ -35,17 +32,15 @@ import net.neoforged.neoforge.event.entity.player.ItemTooltipEvent; import org.jetbrains.annotations.Nullable; -import java.util.HashMap; +import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import java.util.function.Consumer; @EventBusSubscriber(modid = KubeJS.MOD_ID, value = Dist.CLIENT) public class KubeJSClientEventHandler { - private static final ResourceLocation RECIPE_BUTTON_TEXTURE = new ResourceLocation("textures/gui/recipe_button.png"); + private static final ResourceLocation RECIPE_BUTTON_TEXTURE = ResourceLocation.parse("textures/gui/recipe_button.png"); public static Map> staticItemTooltips = null; - private static final Map tempTagNames = new LinkedHashMap<>(); @SubscribeEvent public static void debugInfo(CustomizeGuiOverlayEvent.DebugText event) { @@ -65,7 +60,6 @@ public static void debugInfo(CustomizeGuiOverlayEvent.DebugText event) { public static void onItemTooltip(ItemTooltipEvent event) { var stack = event.getItemStack(); var lines = event.getToolTip(); - var tooltipContext = event.getContext(); var flag = event.getFlags(); if (stack.isEmpty()) { @@ -75,36 +69,36 @@ public static void onItemTooltip(ItemTooltipEvent event) { var advanced = flag.isAdvanced(); if (advanced && ClientProperties.get().showTagNames && Screen.hasShiftDown()) { - var addToTempTags = (Consumer>) tag -> tempTagNames.computeIfAbsent(tag.location(), TagInstance::new).registries.add(tag.registry()); - var cx = ScriptType.CLIENT.manager.get().contextFactory.enter(); - - Tags.byItemStack(cx, stack).forEach(addToTempTags); + var tempTagNames = new LinkedHashMap(); + TagInstance.Type.ITEM.append(tempTagNames, stack.getItem().builtInRegistryHolder().tags()); if (stack.getItem() instanceof BlockItem item) { - Tags.byBlock(cx, item.getBlock()).forEach(addToTempTags); + TagInstance.Type.BLOCK.append(tempTagNames, item.getBlock().builtInRegistryHolder().tags()); } if (stack.getItem() instanceof BucketItem bucket) { - Fluid fluid = FluidBucketHooks.getFluid(bucket); + Fluid fluid = bucket.content; if (fluid != Fluids.EMPTY) { - Tags.byFluid(cx, fluid).forEach(addToTempTags); + TagInstance.Type.FLUID.append(tempTagNames, fluid.builtInRegistryHolder().tags()); } } if (stack.getItem() instanceof SpawnEggItem item) { - Tags.byEntityType(cx, item.getType(stack)).forEach(addToTempTags); + var entityType = item.getType(stack); + + if (entityType != null) { + TagInstance.Type.ENTITY.append(tempTagNames, entityType.builtInRegistryHolder().tags()); + } } for (var instance : tempTagNames.values()) { lines.add(instance.toText()); } - - tempTagNames.clear(); } if (staticItemTooltips == null) { - staticItemTooltips = new HashMap<>(); + staticItemTooltips = new IdentityHashMap<>(); ItemEvents.TOOLTIP.post(ScriptType.CLIENT, new ItemTooltipKubeEvent(staticItemTooltips)); } @@ -133,17 +127,17 @@ public static void loggingIn(ClientPlayerNetworkEvent.LoggingIn event) { @SubscribeEvent public static void loggingOut(ClientPlayerNetworkEvent.LoggingOut event) { ClientEvents.LOGGED_OUT.post(ScriptType.CLIENT, new ClientKubeEvent(event.getPlayer())); - Painter.INSTANCE.clear(); + Painter.getGlobal().clear(); } @SubscribeEvent public static void onRenderGuiPost(RenderGuiEvent.Post event) { - Painter.INSTANCE.inGameScreenDraw(event.getGuiGraphics(), event.getPartialTick()); + Painter.getGlobal().inGameScreenDraw(event.getGuiGraphics(), event.getPartialTick()); } @SubscribeEvent public static void onRenderPost(ScreenEvent.Render.Post event) { - Painter.INSTANCE.guiScreenDraw(event.getScreen(), event.getGuiGraphics(), event.getMouseX(), event.getMouseY(), event.getPartialTick()); + Painter.getGlobal().guiScreenDraw(event.getScreen(), event.getGuiGraphics(), event.getMouseX(), event.getMouseY(), event.getPartialTick()); } @Nullable diff --git a/src/main/java/dev/latvian/mods/kubejs/client/NotificationToast.java b/src/main/java/dev/latvian/mods/kubejs/client/NotificationToast.java index 5f3d01a38..dc3be0f4e 100644 --- a/src/main/java/dev/latvian/mods/kubejs/client/NotificationToast.java +++ b/src/main/java/dev/latvian/mods/kubejs/client/NotificationToast.java @@ -77,13 +77,12 @@ public int height() { private void drawRectangle(Matrix4f m, int x0, int y0, int x1, int y1, int r, int g, int b) { RenderSystem.setShader(GameRenderer::getPositionColorShader); - var buf = Tesselator.getInstance().getBuilder(); - buf.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); - buf.vertex(m, x0, y1, 0F).color(r, g, b, 255).endVertex(); - buf.vertex(m, x1, y1, 0F).color(r, g, b, 255).endVertex(); - buf.vertex(m, x1, y0, 0F).color(r, g, b, 255).endVertex(); - buf.vertex(m, x0, y0, 0F).color(r, g, b, 255).endVertex(); - BufferUploader.drawWithShader(buf.end()); + var buf = Tesselator.getInstance().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); + buf.addVertex(m, x0, y1, 0F).setColor(r, g, b, 255); + buf.addVertex(m, x1, y1, 0F).setColor(r, g, b, 255); + buf.addVertex(m, x1, y0, 0F).setColor(r, g, b, 255); + buf.addVertex(m, x0, y0, 0F).setColor(r, g, b, 255); + BufferUploader.drawWithShader(buf.buildOrThrow()); } @Override diff --git a/src/main/java/dev/latvian/mods/kubejs/client/TagInstance.java b/src/main/java/dev/latvian/mods/kubejs/client/TagInstance.java index dec7a9ac2..4ffc732cb 100644 --- a/src/main/java/dev/latvian/mods/kubejs/client/TagInstance.java +++ b/src/main/java/dev/latvian/mods/kubejs/client/TagInstance.java @@ -1,34 +1,52 @@ package dev.latvian.mods.kubejs.client; -import net.minecraft.ChatFormatting; -import net.minecraft.core.Registry; +import dev.latvian.mods.kubejs.bindings.TextWrapper; import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; +import net.minecraft.tags.TagKey; import java.util.LinkedHashSet; -import java.util.stream.Collectors; +import java.util.Map; +import java.util.Set; +import java.util.stream.Stream; public class TagInstance { + public enum Type { + BLOCK('B'), + ITEM('J'), + FLUID('F'), + ENTITY('E'); + + public final char character; + + Type(char c) { + this.character = c; + } + + public void append(Map map, Stream> tags) { + tags.forEach(tag -> map.computeIfAbsent(tag.location(), TagInstance::new).registries.add(this)); + } + } + public final ResourceLocation tag; - public final LinkedHashSet>> registries = new LinkedHashSet<>(); + public final Set registries; public TagInstance(ResourceLocation tag) { this.tag = tag; + this.registries = new LinkedHashSet<>(2); } public Component toText() { - var string = " #" + tag + registries.stream() - .map(ResourceKey::location) - .map(id -> { - if (id.getNamespace().equals("minecraft")) { - return id.getPath(); - } else { - return id.toString(); - } - }) - .collect(Collectors.joining(" + ", " [", "]")); - - return Component.literal(string).withStyle(ChatFormatting.DARK_GRAY); + var sb = new StringBuilder(registries.size() + 1); + sb.append('.'); + + for (var type : registries) { + sb.append(type.character); + } + + return Component.empty() + .append(TextWrapper.icon(Component.literal("T."))) + .append(TextWrapper.darkGray(Component.literal("#" + tag))) + .append(TextWrapper.icon(Component.literal(sb.toString()))); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/client/painter/PaintKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/client/painter/PaintKubeEvent.java index 0989faa9b..97f4e8a1d 100644 --- a/src/main/java/dev/latvian/mods/kubejs/client/painter/PaintKubeEvent.java +++ b/src/main/java/dev/latvian/mods/kubejs/client/painter/PaintKubeEvent.java @@ -1,11 +1,8 @@ package dev.latvian.mods.kubejs.client.painter; import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.BufferBuilder; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.Tesselator; -import com.mojang.blaze3d.vertex.VertexFormat; import dev.latvian.mods.kubejs.client.ClientKubeEvent; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; @@ -26,7 +23,6 @@ public class PaintKubeEvent extends ClientKubeEvent { public final GuiGraphics graphics; public final PoseStack matrices; public final Tesselator tesselator; - public final BufferBuilder buffer; public final float delta; public final Screen screen; @@ -37,7 +33,6 @@ public PaintKubeEvent(Minecraft m, GuiGraphics g, float d, @Nullable Screen s) { graphics = g; matrices = g.pose(); tesselator = Tesselator.getInstance(); - buffer = tesselator.getBuilder(); delta = d; screen = s; } @@ -86,30 +81,6 @@ public void setShaderTexture(ResourceLocation tex) { RenderSystem.setShaderTexture(0, tex); } - public void begin(VertexFormat.Mode type, VertexFormat format) { - buffer.begin(type, format); - } - - public void beginQuads(VertexFormat format) { - begin(VertexFormat.Mode.QUADS, format); - } - - public void beginQuads(boolean texture) { - beginQuads(texture ? DefaultVertexFormat.POSITION_COLOR_TEX : DefaultVertexFormat.POSITION_COLOR); - } - - public void vertex(Matrix4f m, float x, float y, float z, int col) { - buffer.vertex(m, x, y, z).color((col >> 16) & 0xFF, (col >> 8) & 0xFF, col & 0xFF, (col >> 24) & 0xFF).endVertex(); - } - - public void vertex(Matrix4f m, float x, float y, float z, int col, float u, float v) { - buffer.vertex(m, x, y, z).color((col >> 16) & 0xFF, (col >> 8) & 0xFF, col & 0xFF, (col >> 24) & 0xFF).uv(u, v).endVertex(); - } - - public void end() { - tesselator.end(); - } - public void setShaderInstance(Supplier shader) { RenderSystem.setShader(shader); } @@ -118,8 +89,8 @@ public void setPositionColorShader() { RenderSystem.setShader(GameRenderer::getPositionColorShader); } - public void setPositionColorTextureShader() { - RenderSystem.setShader(GameRenderer::getPositionColorTexShader); + public void setPositionTextureColorShader() { + RenderSystem.setShader(GameRenderer::getPositionTexColorShader); } public void blend(boolean enabled) { diff --git a/src/main/java/dev/latvian/mods/kubejs/client/painter/Painter.java b/src/main/java/dev/latvian/mods/kubejs/client/painter/Painter.java index 658236e75..aa5d17b5a 100644 --- a/src/main/java/dev/latvian/mods/kubejs/client/painter/Painter.java +++ b/src/main/java/dev/latvian/mods/kubejs/client/painter/Painter.java @@ -1,6 +1,7 @@ package dev.latvian.mods.kubejs.client.painter; import com.mojang.blaze3d.systems.RenderSystem; +import dev.latvian.mods.kubejs.KubeJSPlugin; import dev.latvian.mods.kubejs.bindings.event.ClientEvents; import dev.latvian.mods.kubejs.client.ClientKubeEvent; import dev.latvian.mods.kubejs.client.painter.screen.AtlasTextureObject; @@ -14,6 +15,7 @@ import dev.latvian.mods.kubejs.client.painter.screen.TextObject; import dev.latvian.mods.kubejs.script.ScriptType; import dev.latvian.mods.kubejs.util.ConsoleJS; +import dev.latvian.mods.kubejs.util.KubeJSPlugins; import dev.latvian.mods.rhino.Context; import dev.latvian.mods.rhino.util.HideFromJS; import dev.latvian.mods.unit.FixedNumberUnit; @@ -22,6 +24,7 @@ import dev.latvian.mods.unit.UnitContext; import dev.latvian.mods.unit.UnitVariables; import dev.latvian.mods.unit.VariableSet; +import net.minecraft.client.DeltaTracker; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.screens.Screen; @@ -33,7 +36,15 @@ import java.util.Map; public class Painter implements UnitVariables { - public static final Painter INSTANCE = new Painter("global"); + public static Painter global; + + public static synchronized Painter getGlobal() { + if (global == null) { + global = new Painter("global"); + } + + return global; + } public final String id; private final Object lock; @@ -72,6 +83,8 @@ public Painter(String id) { variables.set("$screenH", screenHeightUnit); variables.set("$mouseX", mouseXUnit); variables.set("$mouseY", mouseYUnit); + + KubeJSPlugins.forEachPlugin(this, KubeJSPlugin::painterRegistry); } public Unit unitOf(Context cx, Object o) { @@ -176,7 +189,7 @@ public VariableSet getVariables() { return variables; } - public void inGameScreenDraw(GuiGraphics graphics, float delta) { + public void inGameScreenDraw(GuiGraphics graphics, DeltaTracker delta) { var mc = Minecraft.getInstance(); if (mc.player == null || mc.getDebugOverlay().showDebugScreen() || mc.screen != null) { @@ -189,8 +202,8 @@ public void inGameScreenDraw(GuiGraphics graphics, float delta) { RenderSystem.enableDepthTest(); - var event = new PaintScreenKubeEvent(mc, graphics, this, delta); - deltaUnit.set(delta); + var event = new PaintScreenKubeEvent(mc, graphics, this, delta.getGameTimeDeltaTicks()); + deltaUnit.set(delta.getGameTimeDeltaTicks()); screenWidthUnit.set(event.width); screenHeightUnit.set(event.height); mouseXUnit.set(event.width / 2D); diff --git a/src/main/java/dev/latvian/mods/kubejs/client/painter/PainterObjectProperties.java b/src/main/java/dev/latvian/mods/kubejs/client/painter/PainterObjectProperties.java index cfad74084..5799bf141 100644 --- a/src/main/java/dev/latvian/mods/kubejs/client/painter/PainterObjectProperties.java +++ b/src/main/java/dev/latvian/mods/kubejs/client/painter/PainterObjectProperties.java @@ -40,7 +40,7 @@ public String getString(String key, String def) { @Nullable public ResourceLocation getResourceLocation(String key, @Nullable ResourceLocation def) { var s = getString(key, "").trim(); - return s.isEmpty() ? def : new ResourceLocation(s); + return s.isEmpty() ? def : ResourceLocation.parse(s); } public Unit getUnit(String key, Unit def) { diff --git a/src/main/java/dev/latvian/mods/kubejs/client/painter/screen/AtlasTextureObject.java b/src/main/java/dev/latvian/mods/kubejs/client/painter/screen/AtlasTextureObject.java index 1916a5701..8da76bd60 100644 --- a/src/main/java/dev/latvian/mods/kubejs/client/painter/screen/AtlasTextureObject.java +++ b/src/main/java/dev/latvian/mods/kubejs/client/painter/screen/AtlasTextureObject.java @@ -56,11 +56,9 @@ public void draw(PaintScreenKubeEvent event) { var u1 = sprite.getU1(); var v1 = sprite.getV1(); event.resetShaderColor(); - event.setPositionColorTextureShader(); + event.setPositionTextureColorShader(); event.setShaderTexture(atlas); event.blend(true); - event.beginQuads(true); event.rectangle(ax, ay, az, aw, ah, color.getInt(event), u0, v0, u1, v1); - event.end(); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/client/painter/screen/GradientObject.java b/src/main/java/dev/latvian/mods/kubejs/client/painter/screen/GradientObject.java index 5008612e0..5351adc5a 100644 --- a/src/main/java/dev/latvian/mods/kubejs/client/painter/screen/GradientObject.java +++ b/src/main/java/dev/latvian/mods/kubejs/client/painter/screen/GradientObject.java @@ -1,5 +1,8 @@ package dev.latvian.mods.kubejs.client.painter.screen; +import com.mojang.blaze3d.vertex.BufferUploader; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.VertexFormat; import dev.latvian.mods.kubejs.client.painter.Painter; import dev.latvian.mods.kubejs.client.painter.PainterObjectProperties; import dev.latvian.mods.unit.FixedColorUnit; @@ -79,28 +82,27 @@ public void draw(PaintScreenKubeEvent event) { if (texture == null) { event.setPositionColorShader(); event.blend(true); - event.beginQuads(false); - event.vertex(m, ax + aw, ay, az, colTR); - event.vertex(m, ax, ay, az, colTL); - event.vertex(m, ax, ay + ah, az, colBL); - event.vertex(m, ax + aw, ay + ah, az, colBR); - event.end(); + var buf = event.tesselator.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); + buf.addVertex(m, ax + aw, ay, az).setColor(colTR); + buf.addVertex(m, ax, ay, az).setColor(colTL); + buf.addVertex(m, ax, ay + ah, az).setColor(colBL); + buf.addVertex(m, ax + aw, ay + ah, az).setColor(colBR); + BufferUploader.drawWithShader(buf.buildOrThrow()); } else { float u0f = u0.getFloat(event); float v0f = v0.getFloat(event); float u1f = u1.getFloat(event); float v1f = v1.getFloat(event); - event.setPositionColorTextureShader(); + event.setPositionTextureColorShader(); event.setShaderTexture(texture); event.blend(true); - event.beginQuads(true); - event.vertex(m, ax + aw, ay, az, colTR, u1f, v0f); - event.vertex(m, ax, ay, az, colTL, u0f, v0f); - event.vertex(m, ax, ay + ah, az, colBL, u0f, v1f); - event.vertex(m, ax + aw, ay + ah, az, colBR, u1f, v1f); - event.end(); + var buf = event.tesselator.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX_COLOR); + buf.addVertex(m, ax + aw, ay, az).setUv(u1f, v0f).setColor(colTR); + buf.addVertex(m, ax, ay, az).setUv(u0f, v0f).setColor(colTL); + buf.addVertex(m, ax, ay + ah, az).setUv(u0f, v1f).setColor(colBL); + buf.addVertex(m, ax + aw, ay + ah, az).setUv(u1f, v1f).setColor(colBR); + BufferUploader.drawWithShader(buf.buildOrThrow()); } - } } diff --git a/src/main/java/dev/latvian/mods/kubejs/client/painter/screen/ItemObject.java b/src/main/java/dev/latvian/mods/kubejs/client/painter/screen/ItemObject.java index 792ae683a..ef57c8228 100644 --- a/src/main/java/dev/latvian/mods/kubejs/client/painter/screen/ItemObject.java +++ b/src/main/java/dev/latvian/mods/kubejs/client/painter/screen/ItemObject.java @@ -3,6 +3,7 @@ import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.platform.Lighting; import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.BufferUploader; import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.Tesselator; @@ -69,11 +70,11 @@ public void draw(PaintScreenKubeEvent event) { event.scale(aw / 16F, ah / 16F, 1F); event.blend(true); - drawItem(event.matrices, itemStack, 0, overlay.getBoolean(event), customText.isEmpty() ? null : customText); + drawItem(event.matrices, event.delta, itemStack, 0, overlay.getBoolean(event), customText.isEmpty() ? null : customText); event.pop(); } - public static void drawItem(PoseStack poseStack, ItemStack stack, int hash, boolean renderOverlay, @Nullable String text) { + public static void drawItem(PoseStack poseStack, float delta, ItemStack stack, int hash, boolean renderOverlay, @Nullable String text) { if (stack.isEmpty()) { return; } @@ -136,7 +137,7 @@ public static void drawItem(PoseStack poseStack, ItemStack stack, int hash, bool RenderSystem.enableDepthTest(); } - var cooldown = mc.player == null ? 0F : mc.player.getCooldowns().getCooldownPercent(stack.getItem(), mc.getFrameTime()); + var cooldown = mc.player == null ? 0F : mc.player.getCooldowns().getCooldownPercent(stack.getItem(), delta); if (cooldown > 0F) { RenderSystem.disableDepthTest(); @@ -155,12 +156,11 @@ private static void draw(PoseStack matrixStack, Tesselator t, int x, int y, int RenderSystem.setShader(GameRenderer::getPositionColorShader); var m = matrixStack.last().pose(); - var renderer = t.getBuilder(); - renderer.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); - renderer.vertex(m, x, y, 0).color(red, green, blue, alpha).endVertex(); - renderer.vertex(m, x, y + height, 0).color(red, green, blue, alpha).endVertex(); - renderer.vertex(m, x + width, y + height, 0).color(red, green, blue, alpha).endVertex(); - renderer.vertex(m, x + width, y, 0).color(red, green, blue, alpha).endVertex(); - t.end(); + var buf = t.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); + buf.addVertex(m, x, y, 0).setColor(red, green, blue, alpha); + buf.addVertex(m, x, y + height, 0).setColor(red, green, blue, alpha); + buf.addVertex(m, x + width, y + height, 0).setColor(red, green, blue, alpha); + buf.addVertex(m, x + width, y, 0).setColor(red, green, blue, alpha); + BufferUploader.drawWithShader(buf.buildOrThrow()); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/client/painter/screen/LineObject.java b/src/main/java/dev/latvian/mods/kubejs/client/painter/screen/LineObject.java index 3cb7e6ef0..80d9169fd 100644 --- a/src/main/java/dev/latvian/mods/kubejs/client/painter/screen/LineObject.java +++ b/src/main/java/dev/latvian/mods/kubejs/client/painter/screen/LineObject.java @@ -58,9 +58,7 @@ public void draw(PaintScreenKubeEvent event) { event.rotateDeg(aangle); event.setPositionColorShader(); event.blend(true); - event.beginQuads(false); event.rectangle(offset.getFloat(event), -as / 2F, az, alength, as, color.getInt(event)); - event.end(); event.pop(); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/client/painter/screen/PaintScreenKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/client/painter/screen/PaintScreenKubeEvent.java index 5c13a16c8..53fc81125 100644 --- a/src/main/java/dev/latvian/mods/kubejs/client/painter/screen/PaintScreenKubeEvent.java +++ b/src/main/java/dev/latvian/mods/kubejs/client/painter/screen/PaintScreenKubeEvent.java @@ -1,5 +1,8 @@ package dev.latvian.mods.kubejs.client.painter.screen; +import com.mojang.blaze3d.vertex.BufferUploader; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.VertexFormat; import com.mojang.math.Axis; import dev.latvian.mods.kubejs.client.painter.PaintKubeEvent; import dev.latvian.mods.kubejs.client.painter.Painter; @@ -82,18 +85,22 @@ public void rotateRad(float angle) { public void rectangle(float x, float y, float z, float w, float h, int color) { var m = getMatrix(); - vertex(m, x + w, y, z, color); - vertex(m, x, y, z, color); - vertex(m, x, y + h, z, color); - vertex(m, x + w, y + h, z, color); + var buf = tesselator.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); + buf.addVertex(m, x + w, y, z).setColor(color); + buf.addVertex(m, x, y, z).setColor(color); + buf.addVertex(m, x, y + h, z).setColor(color); + buf.addVertex(m, x + w, y + h, z).setColor(color); + BufferUploader.drawWithShader(buf.buildOrThrow()); } public void rectangle(float x, float y, float z, float w, float h, int color, float u0, float v0, float u1, float v1) { var m = getMatrix(); - vertex(m, x + w, y, z, color, u1, v0); - vertex(m, x, y, z, color, u0, v0); - vertex(m, x, y + h, z, color, u0, v1); - vertex(m, x + w, y + h, z, color, u1, v1); + var buf = tesselator.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX_COLOR); + buf.addVertex(m, x + w, y, z).setUv(u1, v0).setColor(color); + buf.addVertex(m, x, y, z).setUv(u0, v0).setColor(color); + buf.addVertex(m, x, y + h, z).setUv(u0, v1).setColor(color); + buf.addVertex(m, x + w, y + h, z).setUv(u1, v1).setColor(color); + BufferUploader.drawWithShader(buf.buildOrThrow()); } public void text(Component text, int x, int y, int color, boolean shadow) { diff --git a/src/main/java/dev/latvian/mods/kubejs/client/painter/screen/RectangleObject.java b/src/main/java/dev/latvian/mods/kubejs/client/painter/screen/RectangleObject.java index bf3ec7d96..23ced58e9 100644 --- a/src/main/java/dev/latvian/mods/kubejs/client/painter/screen/RectangleObject.java +++ b/src/main/java/dev/latvian/mods/kubejs/client/painter/screen/RectangleObject.java @@ -43,21 +43,17 @@ public void draw(PaintScreenKubeEvent event) { if (texture == null) { event.setPositionColorShader(); event.blend(true); - event.beginQuads(false); event.rectangle(ax, ay, az, aw, ah, color.getInt(event)); - event.end(); } else { float u0f = u0.getFloat(event); float v0f = v0.getFloat(event); float u1f = u1.getFloat(event); float v1f = v1.getFloat(event); - event.setPositionColorTextureShader(); + event.setPositionTextureColorShader(); event.setShaderTexture(texture); event.blend(true); - event.beginQuads(true); event.rectangle(ax, ay, az, aw, ah, color.getInt(event), u0f, v0f, u1f, v1f); - event.end(); } } } diff --git a/src/main/java/dev/latvian/mods/kubejs/command/DumpCommands.java b/src/main/java/dev/latvian/mods/kubejs/command/DumpCommands.java new file mode 100644 index 000000000..31a00c127 --- /dev/null +++ b/src/main/java/dev/latvian/mods/kubejs/command/DumpCommands.java @@ -0,0 +1,265 @@ +package dev.latvian.mods.kubejs.command; + +import com.google.common.base.Strings; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import dev.latvian.mods.kubejs.KubeJS; +import dev.latvian.mods.kubejs.KubeJSPaths; +import dev.latvian.mods.kubejs.event.EventGroups; +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.UtilsJS; +import dev.latvian.mods.rhino.JavaMembers; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.core.Registry; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.HoverEvent; +import net.minecraft.network.chat.Style; +import net.minecraft.resources.ResourceKey; +import org.apache.commons.io.FileUtils; + +import java.io.IOException; +import java.lang.reflect.Modifier; +import java.nio.file.Files; + +public class DumpCommands { + private static final char UNICODE_TICK = '✔'; + private static final char UNICODE_CROSS = '✘'; + + public static int events(CommandSourceStack source) { + var groups = EventGroups.ALL.get().map(); + + var output = KubeJSPaths.LOCAL.resolve("event_groups"); + + // create a folder for each event group, + // and a markdown file for each event handler in that group + // the markdown file should contain: + // - the event handler name (i.e. ServerEvents.recipes) + // - the valid script types for that event + // - a link to the event class on GitHub + // (base link is https://github.com/KubeJS-Mods/KubeJS/tree/1902/common/src/main/java/{package}/{class_name}.java, + // but we need to replace the package dots with slashes) + // - a table of all (public, non-transient) fields and (public) methods in the event and their parameters + // - a space for an example script + for (var entry : groups.entrySet()) { + var groupName = entry.getKey(); + var group = entry.getValue(); + + var groupFolder = output.resolve(groupName); + try { + Files.createDirectories(groupFolder); + FileUtils.cleanDirectory(groupFolder.toFile()); + } catch (IOException e) { + ConsoleJS.SERVER.error("Failed to create folder for event group " + groupName, e); + source.sendFailure(Component.literal("Failed to create folder for event group " + groupName)); + return 0; + } + + for (var handlerEntry : group.getHandlers().entrySet()) { + var handlerName = handlerEntry.getKey(); + var handler = handlerEntry.getValue(); + + var handlerFile = groupFolder.resolve(handlerName + ".md"); + + var fullName = "%s.%s".formatted(groupName, handlerName); + + var eventType = handler.eventType.get(); + + var builder = new StringBuilder(); + + builder.append("# ").append(fullName).append("\n\n"); + + builder.append("## Basic info\n\n"); + + builder.append("- Valid script types: ").append(handler.scriptTypePredicate.getValidTypes()).append("\n\n"); + + builder.append("- Has result? ").append(handler.getResult() != null ? UNICODE_TICK : UNICODE_CROSS).append("\n\n"); + + builder.append("- Event class: "); + + if (eventType.getPackageName().startsWith("dev.latvian.mods.kubejs")) { + builder.append('[').append(UtilsJS.toMappedTypeString(eventType)).append(']') + .append('(').append("https://github.com/KubeJS-Mods/KubeJS/tree/") + .append(KubeJS.MC_VERSION_NUMBER) + .append("/common/src/main/java/") + .append(eventType.getPackageName().replace('.', '/')) + .append('/').append(eventType.getSimpleName()).append(".java") + .append(')'); + } else { + builder.append(UtilsJS.toMappedTypeString(eventType)).append(" (third-party)"); + } + + builder.append("\n\n"); + + var classInfo = eventType.getAnnotation(Info.class); + if (classInfo != null) { + builder.append("```\n") + .append(classInfo.value()) + .append("```"); + builder.append("\n\n"); + } + + var scriptManager = source.getServer().getServerResources().managers().kjs$getServerScriptManager(); + var cx = (KubeJSContext) scriptManager.contextFactory.enter(); + + var members = JavaMembers.lookupClass(cx, cx.topLevelScope, eventType, null, false); + + var hasDocumentedMembers = false; + var documentedMembers = new StringBuilder("### Documented members:\n\n"); + + builder.append("### Available fields:\n\n"); + builder.append("| Name | Type | Static? |\n"); + builder.append("| ---- | ---- | ------- |\n"); + for (var field : members.getAccessibleFields(cx, false)) { + if (field.field.getDeclaringClass() == Object.class) { + continue; + } + + var typeName = UtilsJS.toMappedTypeString(field.field.getGenericType()); + builder.append("| ").append(field.name).append(" | ").append(typeName).append(" | "); + builder.append(Modifier.isStatic(field.field.getModifiers()) ? UNICODE_TICK : UNICODE_CROSS).append(" |\n"); + + var info = field.field.getAnnotation(Info.class); + if (info != null) { + hasDocumentedMembers = true; + documentedMembers.append("- `").append(typeName).append(' ').append(field.name).append("`\n"); + documentedMembers.append("```\n"); + var desc = info.value(); + documentedMembers.append(desc); + if (!desc.endsWith("\n")) { + documentedMembers.append("\n"); + } + documentedMembers.append("```\n\n"); + } + } + + builder.append("\n").append("Note: Even if no fields are listed above, some methods are still available as fields through *beans*.\n\n"); + + builder.append("### Available methods:\n\n"); + builder.append("| Name | Parameters | Return type | Static? |\n"); + builder.append("| ---- | ---------- | ----------- | ------- |\n"); + for (var method : members.getAccessibleMethods(cx, false)) { + if (method.hidden || method.method.getDeclaringClass() == Object.class) { + continue; + } + builder.append("| ").append(method.name).append(" | "); + var params = method.method.getGenericParameterTypes(); + + var paramTypes = new String[params.length]; + for (var i = 0; i < params.length; i++) { + paramTypes[i] = UtilsJS.toMappedTypeString(params[i]); + } + builder.append(String.join(", ", paramTypes)).append(" | "); + + var returnType = UtilsJS.toMappedTypeString(method.method.getGenericReturnType()); + builder.append(" | ").append(returnType).append(" | "); + builder.append(Modifier.isStatic(method.method.getModifiers()) ? UNICODE_TICK : UNICODE_CROSS).append(" |\n"); + + var info = method.method.getAnnotation(Info.class); + if (info != null) { + hasDocumentedMembers = true; + documentedMembers.append("- ").append('`'); + if (Modifier.isStatic(method.method.getModifiers())) { + documentedMembers.append("static "); + } + documentedMembers.append(returnType).append(' ').append(method.name).append('('); + + var namedParams = info.params(); + var paramNames = new String[params.length]; + var signature = new String[params.length]; + for (var i = 0; i < params.length; i++) { + var name = "var" + i; + if (namedParams.length > i) { + var name1 = namedParams[i].name(); + if (!Strings.isNullOrEmpty(name1)) { + name = name1; + } + } + paramNames[i] = name; + signature[i] = paramTypes[i] + ' ' + name; + } + + documentedMembers.append(String.join(", ", signature)).append(')').append('`').append("\n"); + + if (params.length > 0) { + documentedMembers.append("\n Parameters:\n"); + for (var i = 0; i < params.length; i++) { + documentedMembers.append(" - ") + .append(paramNames[i]) + .append(": ") + .append(paramTypes[i]) + .append(namedParams.length > i ? "- " + namedParams[i].value() : "") + .append("\n"); + } + documentedMembers.append("\n"); + } + + documentedMembers.append("```\n"); + var desc = info.value(); + documentedMembers.append(desc); + if (!desc.endsWith("\n")) { + documentedMembers.append("\n"); + } + documentedMembers.append("```\n\n"); + } + } + + builder.append("\n\n"); + + if (hasDocumentedMembers) { + builder.append(documentedMembers).append("\n\n"); + } + + builder.append("### Example script:\n\n"); + builder.append("```js\n"); + builder.append(fullName).append('('); + if (handler.extra != null) { + builder.append(handler.extraRequired ? "extra_id, " : "/* extra_id (optional), */ "); + } + builder.append("(event) => {\n"); + builder.append("\t// This space (un)intentionally left blank\n"); + builder.append("});\n"); + builder.append("```\n\n"); + + try { + Files.writeString(handlerFile, builder.toString()); + } catch (IOException e) { + ConsoleJS.SERVER.error("Failed to write file for event handler " + fullName, e); + source.sendFailure(Component.literal("Failed to write file for event handler " + fullName)); + return 0; + } + } + } + + source.sendSystemMessage(Component.literal("Successfully dumped event groups to " + output)); + return 1; + } + + public static int registry(CommandSourceStack source, ResourceKey> registry) throws CommandSyntaxException { + var ids = source.registryAccess().registry(registry) + .orElseThrow(() -> KubeJSCommands.NO_REGISTRY.create(registry.location())) + .holders(); + + source.sendSystemMessage(Component.empty()); + source.sendSystemMessage(Component.literal("List of all entries for registry " + registry.location() + ":")); + source.sendSystemMessage(Component.empty()); + + var size = ids.map(holder -> { + var id = holder.key().location(); + return Component.literal("- %s".formatted(id)).withStyle(Style.EMPTY + .withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.literal("%s [%s]".formatted(holder.value(), holder.value().getClass().getName())))) + ); + }).mapToLong(msg -> { + source.sendSystemMessage(msg); + return 1; + }).sum(); + + source.sendSystemMessage(Component.empty()); + source.sendSystemMessage(Component.literal("Total: %d entries".formatted(size))); + source.sendSystemMessage(Component.empty()); + + + return 1; + } + +} diff --git a/src/main/java/dev/latvian/mods/kubejs/command/InformationCommands.java b/src/main/java/dev/latvian/mods/kubejs/command/InformationCommands.java new file mode 100644 index 000000000..6bd83eaf9 --- /dev/null +++ b/src/main/java/dev/latvian/mods/kubejs/command/InformationCommands.java @@ -0,0 +1,109 @@ +package dev.latvian.mods.kubejs.command; + +import dev.latvian.mods.kubejs.helpers.IngredientHelper; +import net.minecraft.ChatFormatting; +import net.minecraft.core.HolderSet; +import net.minecraft.core.registries.Registries; +import net.minecraft.nbt.NbtOps; +import net.minecraft.network.chat.ClickEvent; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.HoverEvent; +import net.minecraft.network.chat.Style; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.ItemStack; +import net.neoforged.neoforge.fluids.FluidUtil; + +import java.util.List; + +public class InformationCommands { + private static Component copy(String s, ChatFormatting col, String info) { + return copy(Component.literal(s).withStyle(col), info); + } + + private static Component copy(Component c, String info) { + return Component.literal("- ") + .withStyle(ChatFormatting.GRAY) + .withStyle(Style.EMPTY.withClickEvent(new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, c.getString()))) + .withStyle(Style.EMPTY.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.literal(info + " (Click to copy)")))) + .append(c); + } + + public static int hand(ServerPlayer player, InteractionHand hand) { + player.sendSystemMessage(Component.literal("Item in hand:")); + var stack = player.getItemInHand(hand); + var holder = stack.getItemHolder(); + var itemRegistry = player.server.registryAccess().registry(Registries.ITEM).orElseThrow(); + var blockRegistry = player.server.registryAccess().registry(Registries.BLOCK).orElseThrow(); + var fluidRegistry = player.server.registryAccess().registry(Registries.FLUID).orElseThrow(); + + // item info + // id + player.sendSystemMessage(copy(stack.kjs$toItemString0(player.server.registryAccess().createSerializationContext(NbtOps.INSTANCE)), ChatFormatting.GREEN, "Item ID")); + // item tags + var itemTags = holder.tags().toList(); + for (var tag : itemTags) { + var id = "'#%s'".formatted(tag.location()); + var size = itemRegistry.getTag(tag).map(HolderSet::size).orElse(0); + player.sendSystemMessage(copy(id, ChatFormatting.YELLOW, "Item Tag [" + size + " items]")); + } + // mod + player.sendSystemMessage(copy("'@" + stack.kjs$getMod() + "'", ChatFormatting.AQUA, "Mod [" + IngredientHelper.get().mod(stack.kjs$getMod()).kjs$getStacks().size() + " items]")); + // TODO: creative tabs (neo has made them client only in 1.20.1, this is fixed in 1.20.4) + /*var cat = stack.getItem().getItemCategory(); + if (cat != null) { + player.sendSystemMessage(copy("'%" + cat.getRecipeFolderName() + "'", ChatFormatting.LIGHT_PURPLE, "Item Group [" + IngredientPlatformHelper.get().creativeTab(cat).kjs$getStacks().size() + " items]")); + }*/ + + // block info + if (stack.getItem() instanceof BlockItem blockItem) { + player.sendSystemMessage(Component.literal("Held block:")); + var block = blockItem.getBlock(); + var blockHolder = block.builtInRegistryHolder(); + // id + player.sendSystemMessage(copy("'" + block.kjs$getId() + "'", ChatFormatting.GREEN, "Block ID")); + // block tags + var blockTags = blockHolder.tags().toList(); + for (var tag : blockTags) { + var id = "'#%s'".formatted(tag.location()); + var size = blockRegistry.getTag(tag).map(HolderSet::size).orElse(0); + player.sendSystemMessage(copy(id, ChatFormatting.YELLOW, "Block Tag [" + size + " items]")); + } + } + + // fluid info + var containedFluid = FluidUtil.getFluidContained(stack); + if (containedFluid.isPresent()) { + player.sendSystemMessage(Component.literal("Held fluid:")); + var fluid = containedFluid.orElseThrow(); + var fluidHolder = fluid.getFluid().builtInRegistryHolder(); + // id + player.sendSystemMessage(copy(fluidHolder.key().location().toString(), ChatFormatting.GREEN, "Fluid ID")); + // fluid tags + var fluidTags = fluidHolder.tags().toList(); + for (var tag : fluidTags) { + var id = "'#%s'".formatted(tag.location()); + var size = fluidRegistry.getTag(tag).map(HolderSet::size).orElse(0); + player.sendSystemMessage(copy(id, ChatFormatting.YELLOW, "Fluid Tag [" + size + " items]")); + } + } + + return 1; + } + + public static int inventory(ServerPlayer player) { + return dump(player.getInventory().items, player, "Inventory"); + } + + public static int hotbar(ServerPlayer player) { + return dump(player.getInventory().items.subList(0, 9), player, "Hotbar"); + } + + public static int dump(List stacks, ServerPlayer player, String name) { + var ops = player.server.registryAccess().createSerializationContext(NbtOps.INSTANCE); + var dump = stacks.stream().filter(is -> !is.isEmpty()).map(is -> is.kjs$toItemString0(ops)).toList(); + player.sendSystemMessage(copy(dump.toString(), ChatFormatting.WHITE, name + " Item List")); + return 1; + } +} 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 aa362d8bc..69e2512c5 100644 --- a/src/main/java/dev/latvian/mods/kubejs/command/KubeJSCommands.java +++ b/src/main/java/dev/latvian/mods/kubejs/command/KubeJSCommands.java @@ -1,23 +1,17 @@ package dev.latvian.mods.kubejs.command; import com.google.common.base.Predicate; -import com.google.common.base.Strings; import com.mojang.brigadier.Command; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.arguments.StringArgumentType; -import com.mojang.brigadier.builder.ArgumentBuilder; import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.DynamicCommandExceptionType; -import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import dev.latvian.mods.kubejs.CommonProperties; import dev.latvian.mods.kubejs.KubeJS; import dev.latvian.mods.kubejs.KubeJSPaths; import dev.latvian.mods.kubejs.bindings.event.ServerEvents; -import dev.latvian.mods.kubejs.core.WithPersistentData; -import dev.latvian.mods.kubejs.event.EventGroups; import dev.latvian.mods.kubejs.event.EventResult; -import dev.latvian.mods.kubejs.helpers.IngredientHelper; import dev.latvian.mods.kubejs.net.DisplayClientErrorsPayload; import dev.latvian.mods.kubejs.net.DisplayServerErrorsPayload; import dev.latvian.mods.kubejs.net.PaintPayload; @@ -27,10 +21,6 @@ import dev.latvian.mods.kubejs.script.data.ExportablePackResources; import dev.latvian.mods.kubejs.server.CustomCommandKubeEvent; import dev.latvian.mods.kubejs.server.DataExport; -import dev.latvian.mods.kubejs.typings.Info; -import dev.latvian.mods.kubejs.util.ConsoleJS; -import dev.latvian.mods.kubejs.util.UtilsJS; -import dev.latvian.mods.rhino.JavaMembers; import net.minecraft.ChatFormatting; import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.Commands; @@ -38,16 +28,10 @@ import net.minecraft.commands.arguments.CompoundTagArgument; import net.minecraft.commands.arguments.DimensionArgument; import net.minecraft.commands.arguments.EntityArgument; -import net.minecraft.commands.arguments.ObjectiveArgument; import net.minecraft.commands.arguments.ResourceLocationArgument; -import net.minecraft.commands.arguments.ScoreHolderArgument; import net.minecraft.core.BlockPos; -import net.minecraft.core.HolderSet; import net.minecraft.core.Registry; -import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.NbtOps; -import net.minecraft.nbt.NbtUtils; import net.minecraft.network.chat.ClickEvent; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.HoverEvent; @@ -59,35 +43,23 @@ import net.minecraft.server.level.ServerPlayer; import net.minecraft.tags.TagKey; import net.minecraft.world.InteractionHand; -import net.minecraft.world.item.BlockItem; -import net.minecraft.world.item.ItemStack; import net.neoforged.fml.loading.FMLLoader; -import net.neoforged.neoforge.fluids.FluidUtil; import net.neoforged.neoforge.network.PacketDistributor; -import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; -import java.lang.reflect.Modifier; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; -import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Stream; public class KubeJSCommands { - - private static final char UNICODE_TICK = '✔'; - private static final char UNICODE_CROSS = '✘'; - - public static final DynamicCommandExceptionType NO_REGISTRY = new DynamicCommandExceptionType((id) -> - Component.literal("No builtin or static registry found for " + id) - ); + public static final DynamicCommandExceptionType NO_REGISTRY = new DynamicCommandExceptionType(id -> Component.literal("No builtin or static registry found for " + id)); public static void register(CommandDispatcher dispatcher) { Predicate spOrOP = (source) -> source.getServer().isSingleplayer() || source.hasPermission(2); @@ -95,23 +67,17 @@ public static void register(CommandDispatcher dispatcher) { .then(Commands.literal("help") .executes(context -> help(context.getSource())) ) - .then(Commands.literal("custom_command") - .then(Commands.argument("id", StringArgumentType.word()) - .suggests((ctx, builder) -> SharedSuggestionProvider.suggest(ServerEvents.CUSTOM_COMMAND.findUniqueExtraIds(ScriptType.SERVER).stream().map(String::valueOf), builder)) - .executes(context -> customCommand(context.getSource(), StringArgumentType.getString(context, "id"))) - ) - ) .then(Commands.literal("hand") - .executes(context -> hand(context.getSource().getPlayerOrException(), InteractionHand.MAIN_HAND)) + .executes(context -> InformationCommands.hand(context.getSource().getPlayerOrException(), InteractionHand.MAIN_HAND)) ) .then(Commands.literal("offhand") - .executes(context -> hand(context.getSource().getPlayerOrException(), InteractionHand.OFF_HAND)) + .executes(context -> InformationCommands.hand(context.getSource().getPlayerOrException(), InteractionHand.OFF_HAND)) ) .then(Commands.literal("inventory") - .executes(context -> inventory(context.getSource().getPlayerOrException())) + .executes(context -> InformationCommands.inventory(context.getSource().getPlayerOrException())) ) .then(Commands.literal("hotbar") - .executes(context -> hotbar(context.getSource().getPlayerOrException())) + .executes(context -> InformationCommands.hotbar(context.getSource().getPlayerOrException())) ) .then(Commands.literal("errors") .then(Commands.literal("startup") @@ -132,15 +98,15 @@ public static void register(CommandDispatcher dispatcher) { .requires(spOrOP) .executes(context -> reloadConfig(context.getSource())) ) - .then(Commands.literal("startup_scripts") + .then(Commands.literal("startup-scripts") .requires(spOrOP) .executes(context -> reloadStartup(context.getSource())) ) - .then(Commands.literal("server_scripts") + .then(Commands.literal("server-scripts") .requires(spOrOP) .executes(context -> reloadServer(context.getSource())) ) - .then(Commands.literal("client_scripts") + .then(Commands.literal("client-scripts") .requires(source -> true) .executes(context -> reloadClient(context.getSource())) ) @@ -156,10 +122,10 @@ public static void register(CommandDispatcher dispatcher) { .then(Commands.literal("export") .requires(spOrOP) .executes(context -> export(context.getSource())) - .then(Commands.literal("pack_zips") + .then(Commands.literal("pack-zips") .executes(context -> exportPacks(context.getSource(), true)) ) - .then(Commands.literal("pack_folders") + .then(Commands.literal("pack-folders") .executes(context -> exportPacks(context.getSource(), false)) ) ) @@ -174,7 +140,7 @@ public static void register(CommandDispatcher dispatcher) { .executes(context -> checkRecipeConflicts(context.getSource().getPlayerOrException())) ) */ - .then(Commands.literal("list_tag") + .then(Commands.literal("list-tag") .then(Commands.argument("registry", ResourceLocationArgument.id()) .suggests((ctx, builder) -> SharedSuggestionProvider.suggest( ctx.getSource().registryAccess() @@ -194,14 +160,20 @@ public static void register(CommandDispatcher dispatcher) { ) ) ) - .then(Commands.literal("dump_registry") - .then(Commands.argument("registry", ResourceLocationArgument.id()) - .suggests((ctx, builder) -> SharedSuggestionProvider.suggest( - ctx.getSource().registryAccess() - .registries() - .map(entry -> entry.key().location().toString()), builder) + .then(Commands.literal("dump") + .then(Commands.literal("registry") + .then(Commands.argument("registry", ResourceLocationArgument.id()) + .suggests((ctx, builder) -> SharedSuggestionProvider.suggest( + ctx.getSource().registryAccess() + .registries() + .map(entry -> entry.key().location().toString()), builder) + ) + .executes(ctx -> DumpCommands.registry(ctx.getSource(), registry(ctx, "registry"))) ) - .executes(ctx -> dumpRegistry(ctx.getSource(), registry(ctx, "registry"))) + ) + .then(Commands.literal("events") + .requires(spOrOP) + .executes(context -> DumpCommands.events(context.getSource())) ) ) .then(Commands.literal("stages") @@ -209,25 +181,25 @@ public static void register(CommandDispatcher dispatcher) { .then(Commands.literal("add") .then(Commands.argument("player", EntityArgument.players()) .then(Commands.argument("stage", StringArgumentType.string()) - .executes(context -> addStage(context.getSource(), EntityArgument.getPlayers(context, "player"), StringArgumentType.getString(context, "stage"))) + .executes(context -> StageCommands.addStage(context.getSource(), EntityArgument.getPlayers(context, "player"), StringArgumentType.getString(context, "stage"))) ) ) ) .then(Commands.literal("remove") .then(Commands.argument("player", EntityArgument.players()) .then(Commands.argument("stage", StringArgumentType.string()) - .executes(context -> removeStage(context.getSource(), EntityArgument.getPlayers(context, "player"), StringArgumentType.getString(context, "stage"))) + .executes(context -> StageCommands.removeStage(context.getSource(), EntityArgument.getPlayers(context, "player"), StringArgumentType.getString(context, "stage"))) ) ) ) .then(Commands.literal("clear") .then(Commands.argument("player", EntityArgument.players()) - .executes(context -> clearStages(context.getSource(), EntityArgument.getPlayers(context, "player"))) + .executes(context -> StageCommands.clearStages(context.getSource(), EntityArgument.getPlayers(context, "player"))) ) ) .then(Commands.literal("list") .then(Commands.argument("player", EntityArgument.players()) - .executes(context -> listStages(context.getSource(), EntityArgument.getPlayers(context, "player"))) + .executes(context -> StageCommands.listStages(context.getSource(), EntityArgument.getPlayers(context, "player"))) ) ) ) @@ -239,7 +211,7 @@ public static void register(CommandDispatcher dispatcher) { ) ) ) - .then(Commands.literal("generate_typings") + .then(Commands.literal("generate-typings") .requires(spOrOP) .executes(context -> generateTypings(context.getSource())) ) @@ -250,21 +222,15 @@ public static void register(CommandDispatcher dispatcher) { .executes(context -> packmode(context.getSource(), StringArgumentType.getString(context, "name"))) ) ) - .then(Commands.literal("dump_internals") - .then(Commands.literal("events") - .requires(spOrOP) - .executes(context -> dumpEvents(context.getSource())) - ) - ) - .then(Commands.literal("persistent_data") + .then(Commands.literal("persistent-data") .requires(spOrOP) - .then(addPersistentDataCommands(Commands.literal("server"), ctx -> Set.of(ctx.getSource().getServer()))) + .then(PersistentDataCommands.addPersistentDataCommands(Commands.literal("server"), ctx -> Set.of(ctx.getSource().getServer()))) .then(Commands.literal("dimension") - .then(addPersistentDataCommands(Commands.literal("*"), ctx -> (Collection) ctx.getSource().getServer().getAllLevels())) - .then(addPersistentDataCommands(Commands.argument("dimension", DimensionArgument.dimension()), ctx -> Set.of(DimensionArgument.getDimension(ctx, "dimension")))) + .then(PersistentDataCommands.addPersistentDataCommands(Commands.literal("*"), ctx -> (Collection) ctx.getSource().getServer().getAllLevels())) + .then(PersistentDataCommands.addPersistentDataCommands(Commands.argument("dimension", DimensionArgument.dimension()), ctx -> Set.of(DimensionArgument.getDimension(ctx, "dimension")))) ) .then(Commands.literal("entity") - .then(addPersistentDataCommands(Commands.argument("entity", EntityArgument.entities()), ctx -> EntityArgument.getEntities(ctx, "entity")))) + .then(PersistentDataCommands.addPersistentDataCommands(Commands.argument("entity", EntityArgument.entities()), ctx -> EntityArgument.getEntities(ctx, "entity")))) ); if (!FMLLoader.isProduction()) { @@ -278,215 +244,13 @@ public static void register(CommandDispatcher dispatcher) { var cmd1 = dispatcher.register(cmd); dispatcher.register(Commands.literal("kjs").redirect(cmd1)); - } - - private static int dumpEvents(CommandSourceStack source) { - var groups = EventGroups.ALL.get().map(); - - var output = KubeJSPaths.LOCAL.resolve("event_groups"); - - // create a folder for each event group, - // and a markdown file for each event handler in that group - // the markdown file should contain: - // - the event handler name (i.e. ServerEvents.recipes) - // - the valid script types for that event - // - a link to the event class on GitHub - // (base link is https://github.com/KubeJS-Mods/KubeJS/tree/1902/common/src/main/java/{package}/{class_name}.java, - // but we need to replace the package dots with slashes) - // - a table of all (public, non-transient) fields and (public) methods in the event and their parameters - // - a space for an example script - for (var entry : groups.entrySet()) { - var groupName = entry.getKey(); - var group = entry.getValue(); - - var groupFolder = output.resolve(groupName); - try { - Files.createDirectories(groupFolder); - FileUtils.cleanDirectory(groupFolder.toFile()); - } catch (IOException e) { - ConsoleJS.SERVER.error("Failed to create folder for event group " + groupName, e); - source.sendFailure(Component.literal("Failed to create folder for event group " + groupName)); - return 0; - } - - for (var handlerEntry : group.getHandlers().entrySet()) { - var handlerName = handlerEntry.getKey(); - var handler = handlerEntry.getValue(); - - var handlerFile = groupFolder.resolve(handlerName + ".md"); - - var fullName = "%s.%s".formatted(groupName, handlerName); - - var eventType = handler.eventType.get(); - - var builder = new StringBuilder(); - - builder.append("# ").append(fullName).append("\n\n"); - - builder.append("## Basic info\n\n"); - - builder.append("- Valid script types: ").append(handler.scriptTypePredicate.getValidTypes()).append("\n\n"); - - builder.append("- Has result? ").append(handler.getResult() != null ? UNICODE_TICK : UNICODE_CROSS).append("\n\n"); - - builder.append("- Event class: "); - - if (eventType.getPackageName().startsWith("dev.latvian.mods.kubejs")) { - builder.append('[').append(UtilsJS.toMappedTypeString(eventType)).append(']') - .append('(').append("https://github.com/KubeJS-Mods/KubeJS/tree/") - .append(KubeJS.MC_VERSION_NUMBER) - .append("/common/src/main/java/") - .append(eventType.getPackageName().replace('.', '/')) - .append('/').append(eventType.getSimpleName()).append(".java") - .append(')'); - } else { - builder.append(UtilsJS.toMappedTypeString(eventType)).append(" (third-party)"); - } - - builder.append("\n\n"); - - var classInfo = eventType.getAnnotation(Info.class); - if (classInfo != null) { - builder.append("```\n") - .append(classInfo.value()) - .append("```"); - builder.append("\n\n"); - } - - var scriptManager = source.getServer().getServerResources().managers().kjs$getServerScriptManager(); - var cx = (KubeJSContext) scriptManager.contextFactory.enter(); - - var members = JavaMembers.lookupClass(cx, cx.topLevelScope, eventType, null, false); - - var hasDocumentedMembers = false; - var documentedMembers = new StringBuilder("### Documented members:\n\n"); - - builder.append("### Available fields:\n\n"); - builder.append("| Name | Type | Static? |\n"); - builder.append("| ---- | ---- | ------- |\n"); - for (var field : members.getAccessibleFields(cx, false)) { - if (field.field.getDeclaringClass() == Object.class) { - continue; - } - var typeName = UtilsJS.toMappedTypeString(field.field.getGenericType()); - builder.append("| ").append(field.name).append(" | ").append(typeName).append(" | "); - builder.append(Modifier.isStatic(field.field.getModifiers()) ? UNICODE_TICK : UNICODE_CROSS).append(" |\n"); - - var info = field.field.getAnnotation(Info.class); - if (info != null) { - hasDocumentedMembers = true; - documentedMembers.append("- `").append(typeName).append(' ').append(field.name).append("`\n"); - documentedMembers.append("```\n"); - var desc = info.value(); - documentedMembers.append(desc); - if (!desc.endsWith("\n")) { - documentedMembers.append("\n"); - } - documentedMembers.append("```\n\n"); - } - } - - builder.append("\n").append("Note: Even if no fields are listed above, some methods are still available as fields through *beans*.\n\n"); - - builder.append("### Available methods:\n\n"); - builder.append("| Name | Parameters | Return type | Static? |\n"); - builder.append("| ---- | ---------- | ----------- | ------- |\n"); - for (var method : members.getAccessibleMethods(cx, false)) { - if (method.hidden || method.method.getDeclaringClass() == Object.class) { - continue; - } - builder.append("| ").append(method.name).append(" | "); - var params = method.method.getGenericParameterTypes(); - - var paramTypes = new String[params.length]; - for (var i = 0; i < params.length; i++) { - paramTypes[i] = UtilsJS.toMappedTypeString(params[i]); - } - builder.append(String.join(", ", paramTypes)).append(" | "); - - var returnType = UtilsJS.toMappedTypeString(method.method.getGenericReturnType()); - builder.append(" | ").append(returnType).append(" | "); - builder.append(Modifier.isStatic(method.method.getModifiers()) ? UNICODE_TICK : UNICODE_CROSS).append(" |\n"); - - var info = method.method.getAnnotation(Info.class); - if (info != null) { - hasDocumentedMembers = true; - documentedMembers.append("- ").append('`'); - if (Modifier.isStatic(method.method.getModifiers())) { - documentedMembers.append("static "); - } - documentedMembers.append(returnType).append(' ').append(method.name).append('('); - - var namedParams = info.params(); - var paramNames = new String[params.length]; - var signature = new String[params.length]; - for (var i = 0; i < params.length; i++) { - var name = "var" + i; - if (namedParams.length > i) { - var name1 = namedParams[i].name(); - if (!Strings.isNullOrEmpty(name1)) { - name = name1; - } - } - paramNames[i] = name; - signature[i] = paramTypes[i] + ' ' + name; - } - - documentedMembers.append(String.join(", ", signature)).append(')').append('`').append("\n"); - - if (params.length > 0) { - documentedMembers.append("\n Parameters:\n"); - for (var i = 0; i < params.length; i++) { - documentedMembers.append(" - ") - .append(paramNames[i]) - .append(": ") - .append(paramTypes[i]) - .append(namedParams.length > i ? "- " + namedParams[i].value() : "") - .append("\n"); - } - documentedMembers.append("\n"); - } - - documentedMembers.append("```\n"); - var desc = info.value(); - documentedMembers.append(desc); - if (!desc.endsWith("\n")) { - documentedMembers.append("\n"); - } - documentedMembers.append("```\n\n"); - } - } - - builder.append("\n\n"); - - if (hasDocumentedMembers) { - builder.append(documentedMembers).append("\n\n"); - } - - builder.append("### Example script:\n\n"); - builder.append("```js\n"); - builder.append(fullName).append('('); - if (handler.extra != null) { - builder.append(handler.extraRequired ? "extra_id, " : "/* extra_id (optional), */ "); - } - builder.append("(event) => {\n"); - builder.append("\t// This space (un)intentionally left blank\n"); - builder.append("});\n"); - builder.append("```\n\n"); - - try { - Files.writeString(handlerFile, builder.toString()); - } catch (IOException e) { - ConsoleJS.SERVER.error("Failed to write file for event handler " + fullName, e); - source.sendFailure(Component.literal("Failed to write file for event handler " + fullName)); - return 0; - } - } + for (var id : ServerEvents.CUSTOM_COMMAND.findUniqueExtraIds(ScriptType.SERVER)) { + dispatcher.register(Commands.literal(id) + .requires(spOrOP) + .executes(context -> customCommand(context.getSource(), id)) + ); } - - source.sendSystemMessage(Component.literal("Successfully dumped event groups to " + output)); - return 1; } private static ResourceKey> registry(CommandContext ctx, String arg) { @@ -499,18 +263,6 @@ private static Stream> allTags(CommandSourceStack source, Resource .getTagNames(); } - private static Component copy(String s, ChatFormatting col, String info) { - return copy(Component.literal(s).withStyle(col), info); - } - - private static Component copy(Component c, String info) { - return Component.literal("- ") - .withStyle(ChatFormatting.GRAY) - .withStyle(Style.EMPTY.withClickEvent(new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, c.getString()))) - .withStyle(Style.EMPTY.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.literal(info + " (Click to copy)")))) - .append(c); - } - private static void link(CommandSourceStack source, ChatFormatting color, String name, String url) { source.sendSystemMessage(Component.literal("• ").append(Component.literal(name).withStyle(color).withStyle(style -> style.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, url))))); } @@ -537,80 +289,6 @@ private static int customCommand(CommandSourceStack source, String id) { return 0; } - private static int hand(ServerPlayer player, InteractionHand hand) { - player.sendSystemMessage(Component.literal("Item in hand:")); - var stack = player.getItemInHand(hand); - var holder = stack.getItemHolder(); - - // item info - // id - player.sendSystemMessage(copy(stack.kjs$toItemString0(player.server.registryAccess().createSerializationContext(NbtOps.INSTANCE)), ChatFormatting.GREEN, "Item ID")); - // item tags - var itemTags = holder.tags().toList(); - for (var tag : itemTags) { - var id = "'#%s'".formatted(tag.location()); - var size = BuiltInRegistries.ITEM.getTag(tag).map(HolderSet::size).orElse(0); - player.sendSystemMessage(copy(id, ChatFormatting.YELLOW, "Item Tag [" + size + " items]")); - } - // mod - player.sendSystemMessage(copy("'@" + stack.kjs$getMod() + "'", ChatFormatting.AQUA, "Mod [" + IngredientHelper.get().mod(stack.kjs$getMod()).kjs$getStacks().size() + " items]")); - // TODO: creative tabs (neo has made them client only in 1.20.1, this is fixed in 1.20.4) - /*var cat = stack.getItem().getItemCategory(); - if (cat != null) { - player.sendSystemMessage(copy("'%" + cat.getRecipeFolderName() + "'", ChatFormatting.LIGHT_PURPLE, "Item Group [" + IngredientPlatformHelper.get().creativeTab(cat).kjs$getStacks().size() + " items]")); - }*/ - - // block info - if (stack.getItem() instanceof BlockItem blockItem) { - player.sendSystemMessage(Component.literal("Held block:")); - var block = blockItem.getBlock(); - var blockHolder = block.builtInRegistryHolder(); - // id - player.sendSystemMessage(copy(block.kjs$getId(), ChatFormatting.GREEN, "Block ID")); - // block tags - var blockTags = blockHolder.tags().toList(); - for (var tag : blockTags) { - var id = "'#%s'".formatted(tag.location()); - var size = BuiltInRegistries.BLOCK.getTag(tag).map(HolderSet::size).orElse(0); - player.sendSystemMessage(copy(id, ChatFormatting.YELLOW, "Block Tag [" + size + " items]")); - } - } - - // fluid info - var containedFluid = FluidUtil.getFluidContained(stack); - if (containedFluid.isPresent()) { - player.sendSystemMessage(Component.literal("Held fluid:")); - var fluid = containedFluid.orElseThrow(); - var fluidHolder = fluid.getFluid().builtInRegistryHolder(); - // id - player.sendSystemMessage(copy(fluidHolder.key().location().toString(), ChatFormatting.GREEN, "Fluid ID")); - // fluid tags - var fluidTags = fluidHolder.tags().toList(); - for (var tag : fluidTags) { - var id = "'#%s'".formatted(tag.location()); - var size = BuiltInRegistries.FLUID.getTag(tag).map(HolderSet::size).orElse(0); - player.sendSystemMessage(copy(id, ChatFormatting.YELLOW, "Fluid Tag [" + size + " items]")); - } - } - - return 1; - } - - private static int inventory(ServerPlayer player) { - return dump(player.getInventory().items, player, "Inventory"); - } - - private static int hotbar(ServerPlayer player) { - return dump(player.getInventory().items.subList(0, 9), player, "Hotbar"); - } - - private static int dump(List stacks, ServerPlayer player, String name) { - var ops = player.server.registryAccess().createSerializationContext(NbtOps.INSTANCE); - var dump = stacks.stream().filter(is -> !is.isEmpty()).map(is -> is.kjs$toItemString0(ops)).toList(); - player.sendSystemMessage(copy(dump.toString(), ChatFormatting.WHITE, name + " Item List")); - return 1; - } - private static int errors(CommandSourceStack source, ScriptType type) throws CommandSyntaxException { if (type == ScriptType.CLIENT) { var player = source.getPlayerOrException(); @@ -634,6 +312,7 @@ private static int errors(CommandSourceStack source, ScriptType type) throws Com player.sendSystemMessage(Component.literal("You need KubeJS on client side!").withStyle(ChatFormatting.RED), true); PacketDistributor.sendToPlayer(player, new DisplayServerErrorsPayload(type.ordinal(), errors, warnings)); + // FIXME /* var lines = ConsoleJS.SERVER.errors.toArray(ConsoleLine.EMPTY_ARRAY); @@ -779,21 +458,6 @@ private static int exportPacks(CommandSourceStack source, boolean exportZip) { return success; } - private static int outputRecipes(ServerPlayer player) { - player.sendSystemMessage(Component.literal("WIP!")); - return Command.SINGLE_SUCCESS; - } - - private static int inputRecipes(ServerPlayer player) { - player.sendSystemMessage(Component.literal("WIP!")); - return Command.SINGLE_SUCCESS; - } - - private static int checkRecipeConflicts(ServerPlayer player) { - player.sendSystemMessage(Component.literal("WIP!")); - return Command.SINGLE_SUCCESS; - } - private static int listTagsFor(CommandSourceStack source, ResourceKey> registry) throws CommandSyntaxException { var tags = allTags(source, registry); @@ -845,72 +509,6 @@ private static int tagObjects(CommandSourceStack source, TagKey key) thro return Command.SINGLE_SUCCESS; } - private static int dumpRegistry(CommandSourceStack source, ResourceKey> registry) throws CommandSyntaxException { - var ids = source.registryAccess().registry(registry) - .orElseThrow(() -> NO_REGISTRY.create(registry.location())) - .holders(); - - source.sendSystemMessage(Component.empty()); - source.sendSystemMessage(Component.literal("List of all entries for registry " + registry.location() + ":")); - source.sendSystemMessage(Component.empty()); - - var size = ids.map(holder -> { - var id = holder.key().location(); - return Component.literal("- %s".formatted(id)).withStyle(Style.EMPTY - .withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.literal("%s [%s]".formatted(holder.value(), holder.value().getClass().getName())))) - ); - }).mapToLong(msg -> { - source.sendSystemMessage(msg); - return 1; - }).sum(); - - source.sendSystemMessage(Component.empty()); - source.sendSystemMessage(Component.literal("Total: %d entries".formatted(size))); - source.sendSystemMessage(Component.empty()); - - - return 1; - } - - private static int addStage(CommandSourceStack source, Collection players, String stage) { - for (var p : players) { - if (p.kjs$getStages().add(stage)) { - source.sendSuccess(() -> Component.literal("Added '" + stage + "' stage for " + p.getScoreboardName()), true); - } - } - - return 1; - } - - private static int removeStage(CommandSourceStack source, Collection players, String stage) { - for (var p : players) { - if (p.kjs$getStages().remove(stage)) { - source.sendSuccess(() -> Component.literal("Removed '" + stage + "' stage for " + p.getScoreboardName()), true); - } - } - - return 1; - } - - private static int clearStages(CommandSourceStack source, Collection players) { - for (var p : players) { - if (p.kjs$getStages().clear()) { - source.sendSuccess(() -> Component.literal("Cleared stages for " + p.getScoreboardName()), true); - } - } - - return 1; - } - - private static int listStages(CommandSourceStack source, Collection players) { - for (var p : players) { - source.sendSystemMessage(Component.literal(p.getScoreboardName() + " stages:")); - p.kjs$getStages().getAll().stream().sorted().forEach(s -> source.sendSystemMessage(Component.literal("- " + s))); - } - - return 1; - } - private static int painter(CommandSourceStack source, Collection players, CompoundTag object) { var payload = new ClientboundCustomPayloadPacket(new PaintPayload(object)); @@ -942,160 +540,6 @@ private static int packmode(CommandSourceStack source, String packmode) { return 1; } - @FunctionalInterface - private interface PersistentDataFactory { - SimpleCommandExceptionType EMPTY_LIST = new SimpleCommandExceptionType(Component.literal("Expected at least one target")); - - Collection apply(CommandContext ctx) throws CommandSyntaxException; - - default Collection getAll(CommandContext ctx) throws CommandSyntaxException { - var list = apply(ctx); - - if (list.isEmpty()) { - throw EMPTY_LIST.create(); - } - - return list; - } - - default WithPersistentData getOne(CommandContext ctx) throws CommandSyntaxException { - var list = apply(ctx); - - if (list.isEmpty()) { - throw EMPTY_LIST.create(); - } - - return list.iterator().next(); - } - } - - private static ArgumentBuilder addPersistentDataCommands(ArgumentBuilder cmd, PersistentDataFactory factory) { - cmd.then(Commands.literal("get") - .then(Commands.literal("*") - .executes(ctx -> { - var objects = factory.getAll(ctx); - - for (var o : objects) { - var dataStr = NbtUtils.toPrettyComponent(o.kjs$getPersistentData()); - ctx.getSource().sendSuccess(() -> Component.literal("").append(Component.literal("").withStyle(ChatFormatting.YELLOW).append(o.kjs$getDisplayName())).append(": ").append(dataStr), false); - } - - return objects.size(); - }) - ) - .then(Commands.argument("key", StringArgumentType.string()) - .executes(ctx -> { - var objects = factory.getAll(ctx); - var key = StringArgumentType.getString(ctx, "key"); - - for (var o : objects) { - var data = key.equals("*") ? o.kjs$getPersistentData() : o.kjs$getPersistentData().get(key); - var dataStr = data == null ? Component.literal("null").withStyle(ChatFormatting.RED) : NbtUtils.toPrettyComponent(data); - ctx.getSource().sendSuccess(() -> Component.literal("").append(Component.literal("").withStyle(ChatFormatting.YELLOW).append(o.kjs$getDisplayName())).append(": ").append(dataStr), false); - } - - return objects.size(); - }) - ) - ); - - cmd.then(Commands.literal("merge") - .then(Commands.argument("nbt", CompoundTagArgument.compoundTag()) - .executes(ctx -> { - var objects = factory.getAll(ctx); - var tag = CompoundTagArgument.getCompoundTag(ctx, "nbt"); - - for (var o : objects) { - o.kjs$getPersistentData().merge(tag); - ctx.getSource().sendSuccess(() -> Component.literal("").append(Component.literal("").withStyle(ChatFormatting.YELLOW).append(o.kjs$getDisplayName())).append(" updated"), false); - } - - return objects.size(); - }) - ) - ); - - cmd.then(Commands.literal("remove") - .then(Commands.literal("*") - .executes(ctx -> { - var objects = factory.getAll(ctx); - - for (var o : objects) { - o.kjs$getPersistentData().getAllKeys().removeIf(UtilsJS.ALWAYS_TRUE); - } - - return objects.size(); - }) - ) - .then(Commands.argument("key", StringArgumentType.string()) - .executes(ctx -> { - var objects = factory.getAll(ctx); - var key = StringArgumentType.getString(ctx, "key"); - - for (var o : objects) { - o.kjs$getPersistentData().remove(key); - } - - return objects.size(); - }) - ) - ); - - cmd.then(Commands.literal("scoreboard") - .then(Commands.literal("import") - .then(Commands.argument("key", StringArgumentType.string()) - .then(Commands.argument("target", ScoreHolderArgument.scoreHolder()) - .suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS) - .then(Commands.argument("objective", ObjectiveArgument.objective()) - .executes(ctx -> { - var scoreboard = ctx.getSource().getServer().getScoreboard(); - var objects = factory.getAll(ctx); - var key = StringArgumentType.getString(ctx, "key"); - var target = ScoreHolderArgument.getName(ctx, "target"); - var objective = ObjectiveArgument.getObjective(ctx, "objective"); - - var info = scoreboard.getPlayerScoreInfo(target, objective); - - int score = info != null ? info.value() : 0; - - for (var o : objects) { - o.kjs$getPersistentData().putInt(key, score); - } - - return objects.size(); - }) - ) - ) - ) - ).then(Commands.literal("export") - .then(Commands.argument("key", StringArgumentType.string()) - .then(Commands.argument("targets", ScoreHolderArgument.scoreHolders()) - .suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS) - .then(Commands.argument("objective", ObjectiveArgument.objective()) - .executes(ctx -> { - var scoreboard = ctx.getSource().getServer().getScoreboard(); - var object = factory.getOne(ctx); - var key = StringArgumentType.getString(ctx, "key"); - var targets = ScoreHolderArgument.getNames(ctx, "targets"); - var objective = ObjectiveArgument.getObjective(ctx, "objective"); - - int score = object.kjs$getPersistentData().getInt(key); - - for (var target : targets) { - scoreboard.getOrCreatePlayerScore(target, objective).set(score); - } - - return 1; - }) - ) - ) - ) - ) - ); - - return cmd; - } - private static int eval(CommandSourceStack source, String code) { var cx = (KubeJSContext) source.getServer().getServerResources().managers().kjs$getServerScriptManager().contextFactory.enter(); cx.evaluateString(cx.topLevelScope, code, "eval", 1, null); diff --git a/src/main/java/dev/latvian/mods/kubejs/command/PersistentDataCommands.java b/src/main/java/dev/latvian/mods/kubejs/command/PersistentDataCommands.java new file mode 100644 index 000000000..4040955a0 --- /dev/null +++ b/src/main/java/dev/latvian/mods/kubejs/command/PersistentDataCommands.java @@ -0,0 +1,175 @@ +package dev.latvian.mods.kubejs.command; + +import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.builder.ArgumentBuilder; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; +import dev.latvian.mods.kubejs.core.WithPersistentData; +import dev.latvian.mods.kubejs.util.UtilsJS; +import net.minecraft.ChatFormatting; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; +import net.minecraft.commands.arguments.CompoundTagArgument; +import net.minecraft.commands.arguments.ObjectiveArgument; +import net.minecraft.commands.arguments.ScoreHolderArgument; +import net.minecraft.nbt.NbtUtils; +import net.minecraft.network.chat.Component; + +import java.util.Collection; + +public class PersistentDataCommands { + @FunctionalInterface + public interface PersistentDataFactory { + SimpleCommandExceptionType EMPTY_LIST = new SimpleCommandExceptionType(Component.literal("Expected at least one target")); + + Collection apply(CommandContext ctx) throws CommandSyntaxException; + + default Collection getAll(CommandContext ctx) throws CommandSyntaxException { + var list = apply(ctx); + + if (list.isEmpty()) { + throw EMPTY_LIST.create(); + } + + return list; + } + + default WithPersistentData getOne(CommandContext ctx) throws CommandSyntaxException { + var list = apply(ctx); + + if (list.isEmpty()) { + throw EMPTY_LIST.create(); + } + + return list.iterator().next(); + } + } + + public static ArgumentBuilder addPersistentDataCommands(ArgumentBuilder cmd, PersistentDataFactory factory) { + cmd.then(Commands.literal("get") + .then(Commands.literal("*") + .executes(ctx -> { + var objects = factory.getAll(ctx); + + for (var o : objects) { + var dataStr = NbtUtils.toPrettyComponent(o.kjs$getPersistentData()); + ctx.getSource().sendSuccess(() -> Component.literal("").append(Component.literal("").withStyle(ChatFormatting.YELLOW).append(o.kjs$getDisplayName())).append(": ").append(dataStr), false); + } + + return objects.size(); + }) + ) + .then(Commands.argument("key", StringArgumentType.string()) + .executes(ctx -> { + var objects = factory.getAll(ctx); + var key = StringArgumentType.getString(ctx, "key"); + + for (var o : objects) { + var data = key.equals("*") ? o.kjs$getPersistentData() : o.kjs$getPersistentData().get(key); + var dataStr = data == null ? Component.literal("null").withStyle(ChatFormatting.RED) : NbtUtils.toPrettyComponent(data); + ctx.getSource().sendSuccess(() -> Component.literal("").append(Component.literal("").withStyle(ChatFormatting.YELLOW).append(o.kjs$getDisplayName())).append(": ").append(dataStr), false); + } + + return objects.size(); + }) + ) + ); + + cmd.then(Commands.literal("merge") + .then(Commands.argument("nbt", CompoundTagArgument.compoundTag()) + .executes(ctx -> { + var objects = factory.getAll(ctx); + var tag = CompoundTagArgument.getCompoundTag(ctx, "nbt"); + + for (var o : objects) { + o.kjs$getPersistentData().merge(tag); + ctx.getSource().sendSuccess(() -> Component.literal("").append(Component.literal("").withStyle(ChatFormatting.YELLOW).append(o.kjs$getDisplayName())).append(" updated"), false); + } + + return objects.size(); + }) + ) + ); + + cmd.then(Commands.literal("remove") + .then(Commands.literal("*") + .executes(ctx -> { + var objects = factory.getAll(ctx); + + for (var o : objects) { + o.kjs$getPersistentData().getAllKeys().removeIf(UtilsJS.ALWAYS_TRUE); + } + + return objects.size(); + }) + ) + .then(Commands.argument("key", StringArgumentType.string()) + .executes(ctx -> { + var objects = factory.getAll(ctx); + var key = StringArgumentType.getString(ctx, "key"); + + for (var o : objects) { + o.kjs$getPersistentData().remove(key); + } + + return objects.size(); + }) + ) + ); + + cmd.then(Commands.literal("scoreboard") + .then(Commands.literal("import") + .then(Commands.argument("key", StringArgumentType.string()) + .then(Commands.argument("target", ScoreHolderArgument.scoreHolder()) + .suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS) + .then(Commands.argument("objective", ObjectiveArgument.objective()) + .executes(ctx -> { + var scoreboard = ctx.getSource().getServer().getScoreboard(); + var objects = factory.getAll(ctx); + var key = StringArgumentType.getString(ctx, "key"); + var target = ScoreHolderArgument.getName(ctx, "target"); + var objective = ObjectiveArgument.getObjective(ctx, "objective"); + + var info = scoreboard.getPlayerScoreInfo(target, objective); + + int score = info != null ? info.value() : 0; + + for (var o : objects) { + o.kjs$getPersistentData().putInt(key, score); + } + + return objects.size(); + }) + ) + ) + ) + ).then(Commands.literal("export") + .then(Commands.argument("key", StringArgumentType.string()) + .then(Commands.argument("targets", ScoreHolderArgument.scoreHolders()) + .suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS) + .then(Commands.argument("objective", ObjectiveArgument.objective()) + .executes(ctx -> { + var scoreboard = ctx.getSource().getServer().getScoreboard(); + var object = factory.getOne(ctx); + var key = StringArgumentType.getString(ctx, "key"); + var targets = ScoreHolderArgument.getNames(ctx, "targets"); + var objective = ObjectiveArgument.getObjective(ctx, "objective"); + + int score = object.kjs$getPersistentData().getInt(key); + + for (var target : targets) { + scoreboard.getOrCreatePlayerScore(target, objective).set(score); + } + + return 1; + }) + ) + ) + ) + ) + ); + + return cmd; + } +} diff --git a/src/main/java/dev/latvian/mods/kubejs/command/StageCommands.java b/src/main/java/dev/latvian/mods/kubejs/command/StageCommands.java new file mode 100644 index 000000000..ba6788e1d --- /dev/null +++ b/src/main/java/dev/latvian/mods/kubejs/command/StageCommands.java @@ -0,0 +1,48 @@ +package dev.latvian.mods.kubejs.command; + +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerPlayer; + +import java.util.Collection; + +public class StageCommands { + public static int addStage(CommandSourceStack source, Collection players, String stage) { + for (var p : players) { + if (p.kjs$getStages().add(stage)) { + source.sendSuccess(() -> Component.literal("Added '" + stage + "' stage for " + p.getScoreboardName()), true); + } + } + + return 1; + } + + public static int removeStage(CommandSourceStack source, Collection players, String stage) { + for (var p : players) { + if (p.kjs$getStages().remove(stage)) { + source.sendSuccess(() -> Component.literal("Removed '" + stage + "' stage for " + p.getScoreboardName()), true); + } + } + + return 1; + } + + public static int clearStages(CommandSourceStack source, Collection players) { + for (var p : players) { + if (p.kjs$getStages().clear()) { + source.sendSuccess(() -> Component.literal("Cleared stages for " + p.getScoreboardName()), true); + } + } + + return 1; + } + + public static int listStages(CommandSourceStack source, Collection players) { + for (var p : players) { + source.sendSystemMessage(Component.literal(p.getScoreboardName() + " stages:")); + p.kjs$getStages().getAll().stream().sorted().forEach(s -> source.sendSystemMessage(Component.literal("- " + s))); + } + + return 1; + } +} diff --git a/src/main/java/dev/latvian/mods/kubejs/core/CraftingContainerKJS.java b/src/main/java/dev/latvian/mods/kubejs/core/CraftingContainerKJS.java deleted file mode 100644 index 7a0010926..000000000 --- a/src/main/java/dev/latvian/mods/kubejs/core/CraftingContainerKJS.java +++ /dev/null @@ -1,13 +0,0 @@ -package dev.latvian.mods.kubejs.core; - -import dev.latvian.mods.rhino.util.RemapPrefixForJS; -import net.minecraft.world.inventory.AbstractContainerMenu; -import org.jetbrains.annotations.Nullable; - -@RemapPrefixForJS("kjs$") -public interface CraftingContainerKJS { - @Nullable - default AbstractContainerMenu kjs$getMenu() { - throw new NoMixinException(); - } -} diff --git a/src/main/java/dev/latvian/mods/kubejs/core/EnchantmentKJS.java b/src/main/java/dev/latvian/mods/kubejs/core/EnchantmentKJS.java deleted file mode 100644 index 696608a88..000000000 --- a/src/main/java/dev/latvian/mods/kubejs/core/EnchantmentKJS.java +++ /dev/null @@ -1,13 +0,0 @@ -package dev.latvian.mods.kubejs.core; - -import dev.latvian.mods.kubejs.registry.RegistryInfo; -import dev.latvian.mods.rhino.util.RemapPrefixForJS; -import net.minecraft.world.item.enchantment.Enchantment; - -@RemapPrefixForJS("kjs$") -public interface EnchantmentKJS extends RegistryObjectKJS { - @Override - default RegistryInfo kjs$getKubeRegistry() { - return RegistryInfo.ENCHANTMENT; - } -} 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 50f7b0dad..9f4a1b649 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/ItemStackKJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/ItemStackKJS.java @@ -207,13 +207,13 @@ default boolean specialEquals(Context cx, Object o, boolean shallow) { return EnchantmentHelper.getEnchantmentsForCrafting(kjs$self()); } - default boolean kjs$hasEnchantment(Enchantment enchantment, int level) { + default boolean kjs$hasEnchantment(Holder enchantment, int level) { var e = kjs$getEnchantments(); return e != null && e.getLevel(enchantment) >= level; } @ReturnsSelf - default ItemStack kjs$enchant(Enchantment enchantment, int level) { + default ItemStack kjs$enchant(Holder enchantment, int level) { var is = kjs$self(); is.enchant(enchantment, level); return is; @@ -225,7 +225,7 @@ default boolean specialEquals(Context cx, Object o, boolean shallow) { EnchantmentHelper.updateEnchantments(is, mutable -> { for (var entry : enchantments.entrySet()) { - mutable.upgrade(entry.getKey().value(), entry.getValue()); + mutable.upgrade(entry.getKey(), entry.getValue()); } }); 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 e76ea6e9e..e4ed512b7 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/LivingEntityKJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/LivingEntityKJS.java @@ -1,11 +1,14 @@ package dev.latvian.mods.kubejs.core; +import dev.latvian.mods.kubejs.KubeJS; import dev.latvian.mods.kubejs.bindings.event.ItemEvents; import dev.latvian.mods.kubejs.entity.EntityPotionEffectsJS; import dev.latvian.mods.kubejs.entity.RayTraceResultJS; import dev.latvian.mods.kubejs.item.FoodEatenKubeEvent; import dev.latvian.mods.rhino.util.RemapPrefixForJS; import net.minecraft.core.Holder; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EquipmentSlot; @@ -15,25 +18,24 @@ import net.minecraft.world.entity.ai.attributes.AttributeModifier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.ai.behavior.BehaviorUtils; +import net.minecraft.world.food.FoodProperties; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import org.jetbrains.annotations.Nullable; -import java.util.UUID; import java.util.function.Consumer; import java.util.function.Predicate; @RemapPrefixForJS("kjs$") public interface LivingEntityKJS extends EntityKJS { - UUID KJS_PLAYER_CUSTOM_SPEED = UUID.fromString("6715D9C6-1DA0-4B78-971A-5C32F5709F66"); - String KJS_PLAYER_CUSTOM_SPEED_NAME = "kubejs.player.speed.modifier"; + ResourceLocation KJS_PLAYER_CUSTOM_SPEED = KubeJS.id("player.speed.modifier"); @Override default LivingEntity kjs$self() { return (LivingEntity) this; } - default void kjs$foodEaten(ItemStack is) { + default void kjs$foodEaten(ItemStack is, FoodProperties food) { if (this instanceof LivingEntity entity) { var event = new FoodEatenKubeEvent(entity, is); var i = is.getItem(); @@ -144,7 +146,7 @@ public interface LivingEntityKJS extends EntityKJS { var stack = kjs$self().getItemBySlot(slot); if (!stack.isEmpty()) { - stack.hurtAndBreak(amount, kjs$self().getRandom(), kjs$self(), () -> onBroken.accept(stack)); + stack.hurtAndBreak(amount, (ServerLevel) kjs$self().level(), kjs$self(), item -> onBroken.accept(stack)); if (stack.isEmpty()) { kjs$self().setItemSlot(slot, ItemStack.EMPTY); @@ -254,26 +256,24 @@ public interface LivingEntityKJS extends EntityKJS { } } - default void kjs$modifyAttribute(Holder attribute, String identifier, double d, AttributeModifier.Operation operation) { + default void kjs$modifyAttribute(Holder attribute, ResourceLocation identifier, double d, AttributeModifier.Operation operation) { AttributeInstance instance = kjs$self().getAttribute(attribute); if (instance != null) { - UUID uuid = new UUID(identifier.hashCode(), identifier.hashCode()); - instance.removeModifier(uuid); - instance.addTransientModifier(new AttributeModifier(uuid, identifier, d, operation)); + instance.removeModifier(identifier); + instance.addTransientModifier(new AttributeModifier(identifier, d, operation)); } } - default void kjs$removeAttribute(Holder attribute, String identifier) { + default void kjs$removeAttribute(Holder attribute, ResourceLocation identifier) { AttributeInstance instance = kjs$self().getAttribute(attribute); if (instance != null) { - instance.removeModifier(new UUID(identifier.hashCode(), identifier.hashCode())); + instance.removeModifier(identifier); } } private AttributeModifier kjs$createSpeedModifier(double speed, AttributeModifier.Operation operation) { return new AttributeModifier( KJS_PLAYER_CUSTOM_SPEED, - KJS_PLAYER_CUSTOM_SPEED_NAME, speed, operation); } diff --git a/src/main/java/dev/latvian/mods/kubejs/core/RecipeInputKJS.java b/src/main/java/dev/latvian/mods/kubejs/core/RecipeInputKJS.java new file mode 100644 index 000000000..62b623f2e --- /dev/null +++ b/src/main/java/dev/latvian/mods/kubejs/core/RecipeInputKJS.java @@ -0,0 +1,51 @@ +package dev.latvian.mods.kubejs.core; + +import dev.latvian.mods.kubejs.util.SlotFilter; +import dev.latvian.mods.rhino.util.RemapPrefixForJS; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.RecipeInput; + +import java.util.ArrayList; +import java.util.List; + +@RemapPrefixForJS("kjs$") +public interface RecipeInputKJS { + default RecipeInput kjs$self() { + return (RecipeInput) this; + } + + default List kjs$findAll(SlotFilter filter) { + var list = new ArrayList(); + int size = kjs$self().size(); + + for (int i = 0; i < size; i++) { + var stack = kjs$self().getItem(i); + + if (filter.checkFilter(i, stack)) { + list.add(stack.copy()); + } + } + + return list; + } + + default List kjs$findAll() { + return kjs$findAll(SlotFilter.EMPTY); + } + + default ItemStack find(SlotFilter filter, int skip) { + for (var item : kjs$findAll(filter)) { + if (skip == 0) { + return item; + } + + skip--; + } + + return ItemStack.EMPTY; + } + + default ItemStack find(SlotFilter filter) { + return find(filter, 0); + } +} diff --git a/src/main/java/dev/latvian/mods/kubejs/core/mixin/AbstractSelectionListMixin.java b/src/main/java/dev/latvian/mods/kubejs/core/mixin/AbstractSelectionListMixin.java index e5fe65bcc..484f48978 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/mixin/AbstractSelectionListMixin.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/mixin/AbstractSelectionListMixin.java @@ -5,6 +5,7 @@ @Mixin(AbstractSelectionList.class) public abstract class AbstractSelectionListMixin> { + // FIXME /*@ModifyConstant(method = "render", constant = @Constant(intValue = 32), slice = @Slice( from = @At(value = "INVOKE", ordinal = 0, target = "Lcom/mojang/blaze3d/vertex/BufferBuilder;begin(Lcom/mojang/blaze3d/vertex/VertexFormat$Mode;Lcom/mojang/blaze3d/vertex/VertexFormat;)V"), to = @At(value = "INVOKE", ordinal = 0, target = "Lcom/mojang/blaze3d/vertex/Tesselator;end()V") diff --git a/src/main/java/dev/latvian/mods/kubejs/core/mixin/ClickEventMixin.java b/src/main/java/dev/latvian/mods/kubejs/core/mixin/ClickEventMixin.java index c188a5141..438cd0097 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/mixin/ClickEventMixin.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/mixin/ClickEventMixin.java @@ -9,9 +9,6 @@ @Mixin(ClickEvent.class) public abstract class ClickEventMixin implements WithCodec { - @Shadow - public abstract ClickEvent.Action getAction(); - @Shadow public abstract String getValue(); diff --git a/src/main/java/dev/latvian/mods/kubejs/core/mixin/CompoundTagMixin.java b/src/main/java/dev/latvian/mods/kubejs/core/mixin/CompoundTagMixin.java index e457f6239..b304b7f1a 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/mixin/CompoundTagMixin.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/mixin/CompoundTagMixin.java @@ -1,5 +1,6 @@ package dev.latvian.mods.kubejs.core.mixin; +import dev.latvian.mods.kubejs.util.NBTUtils; import dev.latvian.mods.rhino.Context; import dev.latvian.mods.rhino.NativeJavaMap; import dev.latvian.mods.rhino.Scriptable; @@ -10,21 +11,17 @@ import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.Unique; import java.util.Map; @Mixin(CompoundTag.class) public abstract class CompoundTagMixin implements CustomJavaToJsWrapper { - @Unique - private static final TypeInfo TAGS_TYPE_INFO = TypeInfo.RAW_MAP.withParams(TypeInfo.STRING, TypeInfo.of(Tag.class)); - @Shadow @Final public Map tags; @Override public Scriptable convertJavaToJs(Context cx, Scriptable scope, TypeInfo target) { - return new NativeJavaMap(cx, scope, this, tags, TAGS_TYPE_INFO); + return new NativeJavaMap(cx, scope, this, tags, NBTUtils.STRING_TAG_MAP_TYPE); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/core/mixin/CraftingContainerMixin.java b/src/main/java/dev/latvian/mods/kubejs/core/mixin/CraftingContainerMixin.java deleted file mode 100644 index ec4c0cbef..000000000 --- a/src/main/java/dev/latvian/mods/kubejs/core/mixin/CraftingContainerMixin.java +++ /dev/null @@ -1,17 +0,0 @@ -package dev.latvian.mods.kubejs.core.mixin; - -import dev.latvian.mods.kubejs.core.CraftingContainerKJS; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.CraftingContainer; -import net.minecraft.world.inventory.TransientCraftingContainer; -import org.jetbrains.annotations.Nullable; -import org.spongepowered.asm.mixin.Mixin; - -@Mixin(CraftingContainer.class) -public interface CraftingContainerMixin extends CraftingContainerKJS { - @Override - @Nullable - default AbstractContainerMenu kjs$getMenu() { - return this instanceof TransientCraftingContainer container ? container.menu : null; - } -} diff --git a/src/main/java/dev/latvian/mods/kubejs/core/mixin/EnchantmentMixin.java b/src/main/java/dev/latvian/mods/kubejs/core/mixin/EnchantmentMixin.java deleted file mode 100644 index 0da6c2480..000000000 --- a/src/main/java/dev/latvian/mods/kubejs/core/mixin/EnchantmentMixin.java +++ /dev/null @@ -1,46 +0,0 @@ -package dev.latvian.mods.kubejs.core.mixin; - -import dev.latvian.mods.kubejs.core.EnchantmentKJS; -import net.minecraft.core.Holder; -import net.minecraft.resources.ResourceKey; -import net.minecraft.world.item.enchantment.Enchantment; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.Unique; - -@Mixin(Enchantment.class) -public abstract class EnchantmentMixin implements EnchantmentKJS { - @Shadow - @Final - private Holder.Reference builtInRegistryHolder; - - @Unique - private ResourceKey kjs$registryKey; - - @Unique - private String kjs$id; - - @Override - public Holder kjs$asHolder() { - return builtInRegistryHolder; - } - - @Override - public ResourceKey kjs$getRegistryKey() { - if (kjs$registryKey == null) { - kjs$registryKey = EnchantmentKJS.super.kjs$getRegistryKey(); - } - - return kjs$registryKey; - } - - @Override - public String kjs$getId() { - if (kjs$id == null) { - kjs$id = EnchantmentKJS.super.kjs$getId(); - } - - return kjs$id; - } -} 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 90c7fb6d5..b44c65a76 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 @@ -156,9 +156,9 @@ private void getBarColor(ItemStack stack, CallbackInfoReturnable ci) { } @Inject(method = "getUseDuration", at = @At("HEAD"), cancellable = true) - private void getUseDuration(ItemStack itemStack, CallbackInfoReturnable ci) { + private void getUseDuration(ItemStack itemStack, LivingEntity entity, CallbackInfoReturnable cir) { if (kjs$itemBuilder != null && kjs$itemBuilder.useDuration != null) { - ci.setReturnValue(kjs$itemBuilder.useDuration.applyAsInt(itemStack)); + cir.setReturnValue(kjs$itemBuilder.useDuration.applyAsInt(itemStack, entity)); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/core/mixin/ItemStackMixin.java b/src/main/java/dev/latvian/mods/kubejs/core/mixin/ItemStackMixin.java index f0f44ad26..224259774 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/mixin/ItemStackMixin.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/mixin/ItemStackMixin.java @@ -3,6 +3,7 @@ import dev.latvian.mods.kubejs.core.ItemStackKJS; import dev.latvian.mods.rhino.util.HideFromJS; import dev.latvian.mods.rhino.util.RemapPrefixForJS; +import net.minecraft.core.Holder; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.enchantment.Enchantment; import net.minecraft.world.item.enchantment.ItemEnchantments; @@ -14,7 +15,7 @@ public abstract class ItemStackMixin implements ItemStackKJS { @Shadow @HideFromJS - public abstract void enchant(Enchantment enchantment, int level); + public abstract void enchant(Holder enchantment, int level); @Shadow @HideFromJS diff --git a/src/main/java/dev/latvian/mods/kubejs/core/mixin/KeyboardHandlerMixin.java b/src/main/java/dev/latvian/mods/kubejs/core/mixin/KeyboardHandlerMixin.java index 25663a428..e615a5de2 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/mixin/KeyboardHandlerMixin.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/mixin/KeyboardHandlerMixin.java @@ -2,22 +2,15 @@ import dev.latvian.mods.kubejs.client.KubeJSClient; import net.minecraft.client.KeyboardHandler; -import net.minecraft.client.Minecraft; -import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(KeyboardHandler.class) public abstract class KeyboardHandlerMixin { - @Shadow - @Final - private Minecraft minecraft; - @Inject(method = "handleDebugKeys", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;reloadResourcePacks()Ljava/util/concurrent/CompletableFuture;", shift = At.Shift.BEFORE)) private void reloadResources(int i, CallbackInfoReturnable ci) { - KubeJSClient.reloadClientScripts(minecraft); + KubeJSClient.reloadClientScripts(); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/core/mixin/LevelMixin.java b/src/main/java/dev/latvian/mods/kubejs/core/mixin/LevelMixin.java index 99f81bb1d..a00fea7ad 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/mixin/LevelMixin.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/mixin/LevelMixin.java @@ -9,9 +9,11 @@ import net.minecraft.world.level.Level; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; @Mixin(Level.class) public abstract class LevelMixin implements LevelKJS { + @Unique private AttachedData kjs$attachedData; @Override diff --git a/src/main/java/dev/latvian/mods/kubejs/core/mixin/LivingEntityMixin.java b/src/main/java/dev/latvian/mods/kubejs/core/mixin/LivingEntityMixin.java index fa6c75609..fcecef286 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/mixin/LivingEntityMixin.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/mixin/LivingEntityMixin.java @@ -3,6 +3,7 @@ import dev.latvian.mods.kubejs.core.LivingEntityKJS; import dev.latvian.mods.rhino.util.RemapPrefixForJS; import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.food.FoodProperties; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import org.spongepowered.asm.mixin.Mixin; @@ -13,8 +14,8 @@ @Mixin(LivingEntity.class) @RemapPrefixForJS("kjs$") public abstract class LivingEntityMixin implements LivingEntityKJS { - @Inject(method = "eat", at = @At("HEAD")) - private void foodEaten(Level level, ItemStack item, CallbackInfoReturnable ci) { - kjs$foodEaten(item); + @Inject(method = "eat(Lnet/minecraft/world/level/Level;Lnet/minecraft/world/item/ItemStack;Lnet/minecraft/world/food/FoodProperties;)Lnet/minecraft/world/item/ItemStack;", at = @At("HEAD")) + private void foodEaten(Level level, ItemStack item, FoodProperties food, CallbackInfoReturnable cir) { + kjs$foodEaten(item, food); } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/core/mixin/LoadingOverlayMixin.java b/src/main/java/dev/latvian/mods/kubejs/core/mixin/LoadingOverlayMixin.java index a5cd88a70..bf3af4741 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/mixin/LoadingOverlayMixin.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/mixin/LoadingOverlayMixin.java @@ -5,6 +5,7 @@ @Mixin(LoadingOverlay.class) public abstract class LoadingOverlayMixin { + // FIXME /* @SuppressWarnings("UnresolvedMixinReference") @Inject(method = {"lambda$static$0", "m_169327_", "method_35733"}, at = @At("HEAD"), remap = false, cancellable = true) diff --git a/src/main/java/dev/latvian/mods/kubejs/core/mixin/LootDataTypeMixin.java b/src/main/java/dev/latvian/mods/kubejs/core/mixin/LootDataTypeMixin.java index b32daadac..da13e3bb9 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/mixin/LootDataTypeMixin.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/mixin/LootDataTypeMixin.java @@ -4,6 +4,8 @@ import com.mojang.serialization.DynamicOps; import dev.latvian.mods.kubejs.server.DataExport; import dev.latvian.mods.kubejs.util.ConsoleJS; +import net.minecraft.core.Registry; +import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.storage.loot.LootDataType; import org.spongepowered.asm.mixin.Final; @@ -19,13 +21,13 @@ public abstract class LootDataTypeMixin { @Shadow @Final - private String directory; + private ResourceKey> registryKey; @Inject(method = "deserialize", at = @At("RETURN")) private void kjs$exportLootTable(ResourceLocation id, DynamicOps dynamicOps, V object, CallbackInfoReturnable> cir) { if (DataExport.export != null && object instanceof JsonObject json) { try { - var fileName = "%s/%s/%s.json".formatted(directory, id.getNamespace(), id.getPath()); + var fileName = "%s/%s/%s/%s.json".formatted(registryKey.location().getNamespace(), registryKey.location().getPath(), id.getNamespace(), id.getPath()); DataExport.export.addJson(fileName, json); } catch (Exception ex) { ConsoleJS.SERVER.error("Failed to export loot table %s as JSON!".formatted(id), ex); diff --git a/src/main/java/dev/latvian/mods/kubejs/core/mixin/OptionsMixin.java b/src/main/java/dev/latvian/mods/kubejs/core/mixin/OptionsMixin.java index 0ebb2ee32..7490223e3 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/mixin/OptionsMixin.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/mixin/OptionsMixin.java @@ -17,7 +17,7 @@ public class OptionsMixin { @Final private File optionsFile; - @Inject(method = "load", at = @At("HEAD")) + @Inject(method = "load(Z)V", at = @At("HEAD")) private void loadKJS(CallbackInfo ci) { KubeJSClient.copyDefaultOptionsFile(optionsFile); } 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 2b07b9ea9..64d2e3295 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 @@ -5,6 +5,7 @@ @Mixin(PlayerList.class) public abstract class PlayerListMixin { + // FIXME /* @Shadow @Final diff --git a/src/main/java/dev/latvian/mods/kubejs/core/mixin/RecipeInputMixin.java b/src/main/java/dev/latvian/mods/kubejs/core/mixin/RecipeInputMixin.java new file mode 100644 index 000000000..3cc65a897 --- /dev/null +++ b/src/main/java/dev/latvian/mods/kubejs/core/mixin/RecipeInputMixin.java @@ -0,0 +1,9 @@ +package dev.latvian.mods.kubejs.core.mixin; + +import dev.latvian.mods.kubejs.core.RecipeInputKJS; +import net.minecraft.world.item.crafting.RecipeInput; +import org.spongepowered.asm.mixin.Mixin; + +@Mixin(RecipeInput.class) +public interface RecipeInputMixin extends RecipeInputKJS { +} diff --git a/src/main/java/dev/latvian/mods/kubejs/core/mixin/ResourceKeyMixin.java b/src/main/java/dev/latvian/mods/kubejs/core/mixin/ResourceKeyMixin.java index 953328c74..f3d728d72 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/mixin/ResourceKeyMixin.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/mixin/ResourceKeyMixin.java @@ -10,9 +10,6 @@ import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; -/** - * @author LatvianModder - */ @RemapPrefixForJS("kjs$") @Mixin(value = ResourceKey.class, priority = 1001) public abstract class ResourceKeyMixin implements SpecialEquality { diff --git a/src/main/java/dev/latvian/mods/kubejs/core/mixin/ScreenMixin.java b/src/main/java/dev/latvian/mods/kubejs/core/mixin/ScreenMixin.java index b4c7db778..b5a0aabf5 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/mixin/ScreenMixin.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/mixin/ScreenMixin.java @@ -5,6 +5,7 @@ @Mixin(Screen.class) public abstract class ScreenMixin { + // FIXME /* @ModifyConstant(method = "renderDirtBackground", constant = @Constant(intValue = 64), slice = @Slice( from = @At(value = "INVOKE", ordinal = 0, target = "Lcom/mojang/blaze3d/vertex/BufferBuilder;begin(Lcom/mojang/blaze3d/vertex/VertexFormat$Mode;Lcom/mojang/blaze3d/vertex/VertexFormat;)V"), diff --git a/src/main/java/dev/latvian/mods/kubejs/core/mixin/ServerLevelMixin.java b/src/main/java/dev/latvian/mods/kubejs/core/mixin/ServerLevelMixin.java index 549a24b5d..f130a9f61 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/mixin/ServerLevelMixin.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/mixin/ServerLevelMixin.java @@ -10,6 +10,7 @@ import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; import java.util.List; @@ -20,6 +21,7 @@ public abstract class ServerLevelMixin implements ServerLevelKJS { @HideFromJS List players; + @Unique private CompoundTag kjs$persistentData; @Override @@ -39,5 +41,5 @@ public abstract class ServerLevelMixin implements ServerLevelKJS { @Shadow @HideFromJS - protected abstract LevelEntityGetter getEntities(); + public abstract LevelEntityGetter getEntities(); } diff --git a/src/main/java/dev/latvian/mods/kubejs/core/mixin/WorldLoaderPackConfigMixin.java b/src/main/java/dev/latvian/mods/kubejs/core/mixin/WorldLoaderPackConfigMixin.java index ea9359bf5..6fdeb2d23 100644 --- a/src/main/java/dev/latvian/mods/kubejs/core/mixin/WorldLoaderPackConfigMixin.java +++ b/src/main/java/dev/latvian/mods/kubejs/core/mixin/WorldLoaderPackConfigMixin.java @@ -5,6 +5,7 @@ @Mixin(WorldLoader.PackConfig.class) public abstract class WorldLoaderPackConfigMixin { + // FIXME //@ModifyVariable(method = "createResourceManager", at = @At("STORE")) //private CloseableResourceManager injectKubeJSPacks(CloseableResourceManager original) { // return ServerScriptManager.instance.wrapResourceManager(null, original); diff --git a/src/main/java/dev/latvian/mods/kubejs/entity/LivingEntityDropsKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/entity/LivingEntityDropsKubeEvent.java index c25eedac2..4a81f71d6 100644 --- a/src/main/java/dev/latvian/mods/kubejs/entity/LivingEntityDropsKubeEvent.java +++ b/src/main/java/dev/latvian/mods/kubejs/entity/LivingEntityDropsKubeEvent.java @@ -27,10 +27,6 @@ public DamageSource getSource() { return event.getSource(); } - public int getLootingLevel() { - return event.getLootingLevel(); - } - public boolean isRecentlyHit() { return event.isRecentlyHit(); } 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 5f0546cb2..b8eecdebf 100644 --- a/src/main/java/dev/latvian/mods/kubejs/event/Extra.java +++ b/src/main/java/dev/latvian/mods/kubejs/event/Extra.java @@ -63,7 +63,7 @@ private static ResourceKey toKey(ResourceKey registry, Object object) { return ResourceKey.create(registry, rl); } else { var s = object.toString(); - return s.isBlank() ? null : ResourceKey.create(registry, new ResourceLocation(s)); + return s.isBlank() ? null : ResourceKey.create(registry, ResourceLocation.parse(s)); } } @@ -77,7 +77,7 @@ private static ResourceKey> toRegistryKey(Object object) { } var s = object.toString(); - return s.isBlank() ? null : ResourceKey.createRegistryKey(new ResourceLocation(s)); + return s.isBlank() ? null : ResourceKey.createRegistryKey(ResourceLocation.parse(s)); } public final Class type; 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 298467602..4a19aeb50 100644 --- a/src/main/java/dev/latvian/mods/kubejs/fluid/FluidBuilder.java +++ b/src/main/java/dev/latvian/mods/kubejs/fluid/FluidBuilder.java @@ -105,7 +105,7 @@ public void createAdditionalObjects(AdditionalObjectRegistry registry) { } @Override - public BuilderBase tag(ResourceLocation tag) { + public BuilderBase tag(ResourceLocation[] tag) { flowingFluid.tag(tag); return super.tag(tag); } diff --git a/src/main/java/dev/latvian/mods/kubejs/generator/AssetJsonGenerator.java b/src/main/java/dev/latvian/mods/kubejs/generator/AssetJsonGenerator.java index e86124aa4..9263e5326 100644 --- a/src/main/java/dev/latvian/mods/kubejs/generator/AssetJsonGenerator.java +++ b/src/main/java/dev/latvian/mods/kubejs/generator/AssetJsonGenerator.java @@ -29,17 +29,17 @@ public AssetJsonGenerator(Map m) { public void blockState(ResourceLocation id, Consumer consumer) { var gen = Util.make(new VariantBlockStateGenerator(), consumer); - json(new ResourceLocation(id.getNamespace(), "blockstates/" + id.getPath()), gen.toJson()); + json(ResourceLocation.fromNamespaceAndPath(id.getNamespace(), "blockstates/" + id.getPath()), gen.toJson()); } public void multipartState(ResourceLocation id, Consumer consumer) { var gen = Util.make(new MultipartBlockStateGenerator(), consumer); - json(new ResourceLocation(id.getNamespace(), "blockstates/" + id.getPath()), gen.toJson()); + json(ResourceLocation.fromNamespaceAndPath(id.getNamespace(), "blockstates/" + id.getPath()), gen.toJson()); } public void blockModel(ResourceLocation id, Consumer consumer) { var gen = Util.make(new ModelGenerator(), consumer); - json(new ResourceLocation(id.getNamespace(), "models/block/" + id.getPath()), gen.toJson()); + json(ResourceLocation.fromNamespaceAndPath(id.getNamespace(), "models/block/" + id.getPath()), gen.toJson()); } public void itemModel(ResourceLocation id, Consumer consumer) { @@ -48,7 +48,7 @@ public void itemModel(ResourceLocation id, Consumer consumer) { } public static ResourceLocation asItemModelLocation(ResourceLocation id) { - return new ResourceLocation(id.getNamespace(), "models/item/" + id.getPath()); + return ResourceLocation.fromNamespaceAndPath(id.getNamespace(), "models/item/" + id.getPath()); } public void stencil(ResourceLocation target, String stencil, JsonObject colors) throws IOException { @@ -75,10 +75,10 @@ public void stencil(ResourceLocation target, String stencil, JsonObject colors) } var st1 = st; - add(new ResourceLocation(target.getNamespace(), "textures/" + target.getPath() + ".png"), () -> st1.create(colors)); + add(ResourceLocation.fromNamespaceAndPath(target.getNamespace(), "textures/" + target.getPath() + ".png"), () -> st1.create(colors)); if (st.mcmeta != null) { - add(new ResourceLocation(target.getNamespace(), "textures/" + target.getPath() + ".png.mcmeta"), () -> st1.mcmeta); + add(ResourceLocation.fromNamespaceAndPath(target.getNamespace(), "textures/" + target.getPath() + ".png.mcmeta"), () -> st1.mcmeta); } } } diff --git a/src/main/java/dev/latvian/mods/kubejs/generator/ResourceGenerator.java b/src/main/java/dev/latvian/mods/kubejs/generator/ResourceGenerator.java index 085dca0d5..459697366 100644 --- a/src/main/java/dev/latvian/mods/kubejs/generator/ResourceGenerator.java +++ b/src/main/java/dev/latvian/mods/kubejs/generator/ResourceGenerator.java @@ -29,7 +29,7 @@ public void addCached(ResourceLocation id, Supplier data) { } public void json(ResourceLocation id, JsonElement json) { - add(new ResourceLocation(id.getNamespace(), id.getPath() + ".json"), () -> json.toString().getBytes(StandardCharsets.UTF_8)); + add(ResourceLocation.fromNamespaceAndPath(id.getNamespace(), id.getPath() + ".json"), () -> json.toString().getBytes(StandardCharsets.UTF_8)); if (console.getDebugEnabled() || console == ConsoleJS.SERVER && DevProperties.get().dataPackOutput) { console.info("Generated " + id + ": " + json); diff --git a/src/main/java/dev/latvian/mods/kubejs/gui/KubeJSScreen.java b/src/main/java/dev/latvian/mods/kubejs/gui/KubeJSScreen.java index 7f27652c9..13213a7be 100644 --- a/src/main/java/dev/latvian/mods/kubejs/gui/KubeJSScreen.java +++ b/src/main/java/dev/latvian/mods/kubejs/gui/KubeJSScreen.java @@ -8,7 +8,7 @@ import net.minecraft.world.entity.player.Inventory; public class KubeJSScreen extends AbstractContainerScreen implements MenuAccess { - private static final ResourceLocation CONTAINER_BACKGROUND = new ResourceLocation("textures/gui/container/generic_54.png"); + private static final ResourceLocation CONTAINER_BACKGROUND = ResourceLocation.parse("textures/gui/container/generic_54.png"); public final int containerRows; public KubeJSScreen(KubeJSMenu menu, Inventory inventory, Component component) { diff --git a/src/main/java/dev/latvian/mods/kubejs/integration/jei/JEIPlugin.java b/src/main/java/dev/latvian/mods/kubejs/integration/jei/JEIPlugin.java index 9f645a120..d78ea7055 100644 --- a/src/main/java/dev/latvian/mods/kubejs/integration/jei/JEIPlugin.java +++ b/src/main/java/dev/latvian/mods/kubejs/integration/jei/JEIPlugin.java @@ -8,7 +8,7 @@ @JeiPlugin public class JEIPlugin implements IModPlugin { - public static final ResourceLocation ID = new ResourceLocation(KubeJS.MOD_ID, "jei"); + public static final ResourceLocation ID = KubeJS.id("jei"); public IJeiRuntime runtime; @Override diff --git a/src/main/java/dev/latvian/mods/kubejs/item/FoodBuilder.java b/src/main/java/dev/latvian/mods/kubejs/item/FoodBuilder.java index 96c8cad90..254e6ccaa 100644 --- a/src/main/java/dev/latvian/mods/kubejs/item/FoodBuilder.java +++ b/src/main/java/dev/latvian/mods/kubejs/item/FoodBuilder.java @@ -9,9 +9,11 @@ import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.food.FoodConstants; import net.minecraft.world.food.FoodProperties; +import net.minecraft.world.item.ItemStack; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.stream.Collectors; @@ -21,6 +23,7 @@ public class FoodBuilder { private float saturation; private boolean alwaysEdible; private float eatSeconds; + private Optional usingConvertsTo; private final List effects; public Consumer eaten; @@ -29,6 +32,7 @@ public FoodBuilder() { this.saturation = 0; this.alwaysEdible = false; this.eatSeconds = 0.6F; + this.usingConvertsTo = Optional.empty(); this.effects = new ArrayList<>(); } @@ -75,6 +79,11 @@ public FoodBuilder fastToEat() { return eatSeconds(0.8F); } + public FoodBuilder usingConvertsTo(ItemStack stack) { + usingConvertsTo = Optional.of(stack); + return this; + } + @Info(value = """ Adds an effect to the food. Note that the effect duration is in ticks (20 ticks = 1 second). """, @@ -111,7 +120,7 @@ public FoodBuilder eaten(Consumer e) { } public FoodProperties build() { - return new FoodProperties(nutrition, FoodConstants.saturationByModifier(nutrition, saturation), alwaysEdible, eatSeconds, effects); + return new FoodProperties(nutrition, FoodConstants.saturationByModifier(nutrition, saturation), alwaysEdible, eatSeconds, usingConvertsTo, effects); } private static class EffectSupplier implements Supplier { 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 ff4404662..e0fd4e518 100644 --- a/src/main/java/dev/latvian/mods/kubejs/item/ItemBuilder.java +++ b/src/main/java/dev/latvian/mods/kubejs/item/ItemBuilder.java @@ -12,6 +12,7 @@ import dev.latvian.mods.kubejs.util.ConsoleJS; import dev.latvian.mods.kubejs.util.ID; import dev.latvian.mods.rhino.util.ReturnsSelf; +import net.minecraft.core.Holder; import net.minecraft.core.component.DataComponentType; import net.minecraft.core.component.DataComponents; import net.minecraft.network.chat.Component; @@ -19,9 +20,12 @@ import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.EitherHolder; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; +import net.minecraft.world.item.JukeboxPlayable; +import net.minecraft.world.item.JukeboxSong; import net.minecraft.world.item.Rarity; import net.minecraft.world.item.Tier; import net.minecraft.world.item.Tiers; @@ -39,6 +43,7 @@ import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; +import java.util.function.ToIntBiFunction; import java.util.function.ToIntFunction; @SuppressWarnings({"unused", "UnusedReturnValue"}) @@ -67,6 +72,9 @@ public static Tier toolTierOf(Object o) { return ItemBuilder.TOOL_TIERS.getOrDefault(ID.kjsString(asString), Tiers.IRON); } + public record HurtEnemyContext(ItemStack getItem, LivingEntity getTarget, LivingEntity getAttacker) { + } + public transient Map components; public transient int maxStackSize; public transient int maxDamage; @@ -85,11 +93,12 @@ public static Tier toolTierOf(Object o) { public transient NameCallback nameGetter; public transient UseAnim anim; - public transient ToIntFunction useDuration; + public transient ToIntBiFunction useDuration; public transient UseCallback use; public transient FinishUsingCallback finishUsing; public transient ReleaseUsingCallback releaseUsing; public transient Predicate hurtEnemy; + public transient JukeboxPlayable jukeboxPlayable; public String texture; public String parentModel; @@ -329,56 +338,6 @@ public ItemBuilder fireResistant() { return fireResistant(true); } - public Item.Properties createItemProperties() { - var properties = new KubeJSItemProperties(this); - - if (components != null && !components.isEmpty()) { - for (var entry : components.entrySet()) { - var type = DataComponentWrapper.wrapType(entry.getKey()); - - if (type != null) { - properties.component((DataComponentType) type, entry.getValue()); - } else { - ConsoleJS.STARTUP.error("Component '" + entry.getKey() + "' not found for item " + id); - } - } - } - - if (maxDamage > 0) { - properties.durability(maxDamage); - } else if (maxStackSize != -1) { - properties.stacksTo(maxStackSize); - } - - if (rarity != null) { - properties.rarity(rarity); - } - - var item = containerItem == null ? Items.AIR : ItemWrapper.getItem(containerItem); - - if (item != Items.AIR) { - properties.craftRemainder(item); - } - - if (foodBuilder != null) { - properties.food(foodBuilder.build()); - } - - if (fireResistant) { - properties.fireResistant(); - } - - if (tool != null) { - properties.component(DataComponents.TOOL, tool); - } - - if (itemAttributeModifiers != null) { - properties.attributes(itemAttributeModifiers); - } - - return properties; - } - @Info("Determines the animation of the item when used, e.g. eating food.") public ItemBuilder useAnimation(UseAnim animation) { this.anim = animation; @@ -391,7 +350,7 @@ public ItemBuilder useAnimation(UseAnim animation) { For example, when eating food, this is the time it takes to eat the food. This can change the eating speed, or be used for other things (like making a custom bow). """) - public ItemBuilder useDuration(ToIntFunction useDuration) { + public ItemBuilder useDuration(ToIntBiFunction useDuration) { this.useDuration = useDuration; return this; } @@ -440,6 +399,15 @@ public ItemBuilder hurtEnemy(Predicate context) { return this; } + public ItemBuilder jukeboxPlayable(Holder song, boolean showInTooltip) { + this.jukeboxPlayable = new JukeboxPlayable(new EitherHolder<>(song), showInTooltip); + return this; + } + + public ItemBuilder jukeboxPlayable(Holder song) { + return jukeboxPlayable(song, true); + } + @FunctionalInterface public interface UseCallback { boolean use(Level level, Player player, InteractionHand interactionHand); @@ -460,6 +428,57 @@ public interface NameCallback { Component apply(ItemStack itemStack); } - public record HurtEnemyContext(ItemStack getItem, LivingEntity getTarget, LivingEntity getAttacker) { + public Item.Properties createItemProperties() { + var properties = new KubeJSItemProperties(this); + + if (components != null && !components.isEmpty()) { + for (var entry : components.entrySet()) { + var type = DataComponentWrapper.wrapType(entry.getKey()); + + if (type != null) { + properties.component((DataComponentType) type, entry.getValue()); + } else { + ConsoleJS.STARTUP.error("Component '" + entry.getKey() + "' not found for item " + id); + } + } + } + + if (maxDamage > 0) { + properties.durability(maxDamage); + } else if (maxStackSize != -1) { + properties.stacksTo(maxStackSize); + } + + if (rarity != null) { + properties.rarity(rarity); + } + + var item = containerItem == null ? Items.AIR : ItemWrapper.getItem(containerItem); + + if (item != Items.AIR) { + properties.craftRemainder(item); + } + + if (foodBuilder != null) { + properties.food(foodBuilder.build()); + } + + if (fireResistant) { + properties.fireResistant(); + } + + if (tool != null) { + properties.component(DataComponents.TOOL, tool); + } + + if (itemAttributeModifiers != null) { + properties.attributes(itemAttributeModifiers); + } + + if (jukeboxPlayable != null) { + properties.component(DataComponents.JUKEBOX_PLAYABLE, jukeboxPlayable); + } + + return properties; } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/item/ItemEnchantmentsWrapper.java b/src/main/java/dev/latvian/mods/kubejs/item/ItemEnchantmentsWrapper.java index fab5421fb..b38dc31c7 100644 --- a/src/main/java/dev/latvian/mods/kubejs/item/ItemEnchantmentsWrapper.java +++ b/src/main/java/dev/latvian/mods/kubejs/item/ItemEnchantmentsWrapper.java @@ -3,19 +3,20 @@ import dev.latvian.mods.rhino.Context; import dev.latvian.mods.rhino.NativeJavaMap; import dev.latvian.mods.rhino.type.TypeInfo; +import net.minecraft.core.Holder; import net.minecraft.world.item.enchantment.Enchantment; import net.minecraft.world.item.enchantment.ItemEnchantments; import java.util.Map; public class ItemEnchantmentsWrapper { - public static final TypeInfo MAP_TYPE = TypeInfo.RAW_MAP.withParams(TypeInfo.of(Enchantment.class), TypeInfo.INT); + public static final TypeInfo MAP_TYPE = TypeInfo.RAW_MAP.withParams(TypeInfo.of(Holder.class).withParams(TypeInfo.of(Enchantment.class)), TypeInfo.INT); public static ItemEnchantments from(Context cx, Object from) { if (from instanceof ItemEnchantments e) { return e; } else if (from instanceof Map || from instanceof NativeJavaMap) { - var map = (Map) cx.jsToJava(from, MAP_TYPE); + var map = (Map, Integer>) cx.jsToJava(from, MAP_TYPE); var mutable = new ItemEnchantments.Mutable(ItemEnchantments.EMPTY); for (var entry : map.entrySet()) { 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 2b6301160..b93386cc0 100644 --- a/src/main/java/dev/latvian/mods/kubejs/item/ItemStackJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/item/ItemStackJS.java @@ -72,7 +72,7 @@ public interface ItemStackJS { } for (var itemId : CACHED_ITEM_TYPE_LIST.get()) { - var itemRl = new ResourceLocation(itemId); + var itemRl = ResourceLocation.parse(itemId); map.computeIfAbsent(itemRl, id -> Set.of(RegistryInfo.ITEM.getValue(id).getDefaultInstance())); } diff --git a/src/main/java/dev/latvian/mods/kubejs/item/JukeboxSongBuilder.java b/src/main/java/dev/latvian/mods/kubejs/item/JukeboxSongBuilder.java new file mode 100644 index 000000000..705478ded --- /dev/null +++ b/src/main/java/dev/latvian/mods/kubejs/item/JukeboxSongBuilder.java @@ -0,0 +1,54 @@ +package dev.latvian.mods.kubejs.item; + +import dev.latvian.mods.kubejs.registry.BuilderBase; +import dev.latvian.mods.kubejs.registry.RegistryInfo; +import dev.latvian.mods.rhino.util.ReturnsSelf; +import net.minecraft.Util; +import net.minecraft.core.Holder; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundEvents; +import net.minecraft.world.item.JukeboxSong; + +@ReturnsSelf +public class JukeboxSongBuilder extends BuilderBase { + public transient Holder sound; + public transient float lengthInSeconds; + public transient Component description; + public transient int comparatorOutput; + + public JukeboxSongBuilder(ResourceLocation id) { + super(id); + this.sound = SoundEvents.MUSIC_DISC_11; + this.lengthInSeconds = 71F; + this.description = Component.translatable(Util.makeDescriptionId("jukebox_song", id)); + this.comparatorOutput = 0; + } + + @Override + public final RegistryInfo getRegistryType() { + return RegistryInfo.JUKEBOX_SONG; + } + + @Override + public JukeboxSong createObject() { + return new JukeboxSong(sound, description, lengthInSeconds, comparatorOutput); + } + + public JukeboxSongBuilder song(Holder sound, float length) { + this.sound = sound; + this.lengthInSeconds = length; + return this; + } + + public JukeboxSongBuilder description(Component description) { + this.description = description; + return this; + } + + public JukeboxSongBuilder comparatorOutput(int comparatorOutput) { + this.comparatorOutput = comparatorOutput; + return this; + } +} diff --git a/src/main/java/dev/latvian/mods/kubejs/item/custom/RecordItemJS.java b/src/main/java/dev/latvian/mods/kubejs/item/custom/RecordItemJS.java deleted file mode 100644 index 72a13d692..000000000 --- a/src/main/java/dev/latvian/mods/kubejs/item/custom/RecordItemJS.java +++ /dev/null @@ -1,86 +0,0 @@ -package dev.latvian.mods.kubejs.item.custom; - -import dev.latvian.mods.kubejs.item.ItemBuilder; -import dev.latvian.mods.kubejs.registry.RegistryInfo; -import dev.latvian.mods.kubejs.typings.Info; -import dev.latvian.mods.kubejs.typings.Param; -import dev.latvian.mods.rhino.util.ReturnsSelf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.sounds.SoundEvent; -import net.minecraft.sounds.SoundEvents; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.Rarity; -import net.minecraft.world.item.RecordItem; - -public class RecordItemJS extends RecordItem { - @ReturnsSelf - public static class Builder extends ItemBuilder { - public transient ResourceLocation song; - public transient SoundEvent songSoundEvent; - public transient int length; - public transient int analogOutput; - - public Builder(ResourceLocation i) { - super(i); - song = new ResourceLocation("minecraft:music_disc.11"); - length = 71; - analogOutput = 1; - maxStackSize(1); - rarity(Rarity.RARE); - } - - @Info(value = """ - Sets the song that will play when this record is played. - """, - params = { - @Param(name = "s", value = "The location of sound event."), - @Param(name = "seconds", value = "The length of the song in seconds.") - }) - public Builder song(ResourceLocation s, int seconds) { - song = s; - length = seconds; - songSoundEvent = null; - return this; - } - - @Info("Sets the redstone output of the jukebox when this record is played.") - public Builder analogOutput(int o) { - analogOutput = o; - return this; - } - - @Override - public Item createObject() { - return new RecordItemJS(this, analogOutput, SoundEvents.ITEM_PICKUP, createItemProperties()); - } - - public SoundEvent getSoundEvent() { - if (songSoundEvent == null) { - songSoundEvent = RegistryInfo.SOUND_EVENT.getValue(song); - - if (songSoundEvent == null || songSoundEvent == SoundEvents.ITEM_PICKUP) { - songSoundEvent = SoundEvents.MUSIC_DISC_11; - } - } - - return songSoundEvent; - } - } - - private final Builder builder; - - public RecordItemJS(Builder b, int analogOutput, SoundEvent song, Item.Properties properties) { - super(analogOutput, song, properties, b.length); - builder = b; - } - - @Override - public SoundEvent getSound() { - return builder.getSoundEvent(); - } - - @Override - public int getLengthInTicks() { - return builder.length * 20; - } -} \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/item/custom/ShearsItemBuilder.java b/src/main/java/dev/latvian/mods/kubejs/item/custom/ShearsItemBuilder.java index 2968b809a..780940626 100644 --- a/src/main/java/dev/latvian/mods/kubejs/item/custom/ShearsItemBuilder.java +++ b/src/main/java/dev/latvian/mods/kubejs/item/custom/ShearsItemBuilder.java @@ -11,15 +11,18 @@ import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.DispenserBlock; import net.minecraft.world.level.block.state.BlockState; +import net.neoforged.neoforge.common.Tags; @ReturnsSelf public class ShearsItemBuilder extends ItemBuilder { + public static final ResourceLocation[] SHEAR_TAGS = { + Tags.Items.TOOLS_SHEARS.location(), + }; + public static boolean isCustomShears(ItemStack stack) { return stack.getItem() instanceof ShearsItemKJS; } - public static final ResourceLocation TAG = new ResourceLocation("c:shears"); - public transient float speedBaseline; public ShearsItemBuilder(ResourceLocation i) { @@ -27,7 +30,7 @@ public ShearsItemBuilder(ResourceLocation i) { speedBaseline(5f); parentModel("minecraft:item/handheld"); unstackable(); - tag(TAG); + tag(SHEAR_TAGS); tool = ShearsItem.createToolProperties(); } diff --git a/src/main/java/dev/latvian/mods/kubejs/item/ingredient/IngredientJS.java b/src/main/java/dev/latvian/mods/kubejs/item/ingredient/IngredientJS.java index cb3eeefaf..74822b312 100644 --- a/src/main/java/dev/latvian/mods/kubejs/item/ingredient/IngredientJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/item/ingredient/IngredientJS.java @@ -108,7 +108,7 @@ static Ingredient ofString(String s) { } else if (s.startsWith("@")) { return IngredientHelper.get().mod(s.substring(1)); } else if (s.startsWith("%")) { - var group = UtilsJS.findCreativeTab(new ResourceLocation(s.substring(1))); + var group = UtilsJS.findCreativeTab(ResourceLocation.parse(s.substring(1))); if (group == null) { if (KubeRecipe.itemErrors) { @@ -141,7 +141,7 @@ static Ingredient ofString(String s) { s = s.substring(0, i); } - var item = RegistryInfo.ITEM.getValue(new ResourceLocation(s)); + var item = RegistryInfo.ITEM.getValue(ResourceLocation.parse(s)); if (item == null || item == Items.AIR) { return Ingredient.EMPTY; 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 c684e2ab1..aecd9bca7 100644 --- a/src/main/java/dev/latvian/mods/kubejs/level/BlockContainerJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/level/BlockContainerJS.java @@ -40,8 +40,6 @@ import java.util.stream.Collectors; public class BlockContainerJS implements SpecialEquality { - private static final ResourceLocation AIR_ID = new ResourceLocation("minecraft:air"); - public final Level minecraftLevel; private final BlockPos pos; diff --git a/src/main/java/dev/latvian/mods/kubejs/misc/BasicEnchantment.java b/src/main/java/dev/latvian/mods/kubejs/misc/BasicEnchantment.java index b4be90550..1ff29030e 100644 --- a/src/main/java/dev/latvian/mods/kubejs/misc/BasicEnchantment.java +++ b/src/main/java/dev/latvian/mods/kubejs/misc/BasicEnchantment.java @@ -1,5 +1,5 @@ package dev.latvian.mods.kubejs.misc; - +/* import dev.latvian.mods.kubejs.registry.RegistryInfo; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.Entity; @@ -91,3 +91,4 @@ public boolean isDiscoverable() { return enchantmentBuilder.discoverable; } } +*/ \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/misc/BasicMobEffect.java b/src/main/java/dev/latvian/mods/kubejs/misc/BasicMobEffect.java index 380fffd11..a6ed906a9 100644 --- a/src/main/java/dev/latvian/mods/kubejs/misc/BasicMobEffect.java +++ b/src/main/java/dev/latvian/mods/kubejs/misc/BasicMobEffect.java @@ -54,9 +54,9 @@ public void removeAttributeModifiers(AttributeMap attributeMap) { } @Override - public MobEffect addAttributeModifier(Holder attribute, String string, double d, AttributeModifier.Operation operation) { + public MobEffect addAttributeModifier(Holder attribute, ResourceLocation id, double d, AttributeModifier.Operation operation) { applyAttributeModifications(); - return super.addAttributeModifier(attribute, string, d, operation); + return super.addAttributeModifier(attribute, id, d, operation); } @Override diff --git a/src/main/java/dev/latvian/mods/kubejs/misc/EnchantmentBuilder.java b/src/main/java/dev/latvian/mods/kubejs/misc/EnchantmentBuilder.java index d63f04a13..963c34a4a 100644 --- a/src/main/java/dev/latvian/mods/kubejs/misc/EnchantmentBuilder.java +++ b/src/main/java/dev/latvian/mods/kubejs/misc/EnchantmentBuilder.java @@ -1,5 +1,5 @@ package dev.latvian.mods.kubejs.misc; - +/* import dev.latvian.mods.kubejs.KubeJS; import dev.latvian.mods.kubejs.registry.BuilderBase; import dev.latvian.mods.kubejs.registry.RegistryInfo; @@ -235,3 +235,4 @@ public EnchantmentBuilder undiscoverable() { return this; } } +*/ \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/misc/MobEffectBuilder.java b/src/main/java/dev/latvian/mods/kubejs/misc/MobEffectBuilder.java index 539c03c45..e0265bdff 100644 --- a/src/main/java/dev/latvian/mods/kubejs/misc/MobEffectBuilder.java +++ b/src/main/java/dev/latvian/mods/kubejs/misc/MobEffectBuilder.java @@ -10,10 +10,8 @@ import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.attributes.AttributeModifier; -import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; -import java.util.UUID; /** * @author Prunoideae @@ -45,9 +43,8 @@ public final RegistryInfo getRegistryType() { return RegistryInfo.MOB_EFFECT; } - public MobEffectBuilder modifyAttribute(ResourceLocation attribute, String id, double d, AttributeModifier.Operation operation) { - var uuid = UUID.nameUUIDFromBytes(id.getBytes(StandardCharsets.UTF_8)); - attributeModifiers.put(attribute, new MobEffect.AttributeTemplate(uuid, d, operation)); + public MobEffectBuilder modifyAttribute(ResourceLocation attribute, ResourceLocation id, double d, AttributeModifier.Operation operation) { + attributeModifiers.put(attribute, new MobEffect.AttributeTemplate(id, d, operation)); return this; } diff --git a/src/main/java/dev/latvian/mods/kubejs/misc/PaintingVariantBuilder.java b/src/main/java/dev/latvian/mods/kubejs/misc/PaintingVariantBuilder.java index 88f45b16d..9429b3e80 100644 --- a/src/main/java/dev/latvian/mods/kubejs/misc/PaintingVariantBuilder.java +++ b/src/main/java/dev/latvian/mods/kubejs/misc/PaintingVariantBuilder.java @@ -6,10 +6,11 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.decoration.PaintingVariant; +import java.util.Objects; + @ReturnsSelf public class PaintingVariantBuilder extends BuilderBase { - public transient int width; - public transient int height; + public transient PaintingVariant paintingVariant; public PaintingVariantBuilder(ResourceLocation i) { super(i); @@ -22,16 +23,11 @@ public final RegistryInfo getRegistryType() { @Override public PaintingVariant createObject() { - return new PaintingVariant(width, height); - } - - public PaintingVariantBuilder width(int width) { - this.width = width; - return this; + return Objects.requireNonNull(paintingVariant); } - public PaintingVariantBuilder height(int height) { - this.height = height; + public PaintingVariantBuilder painting(int width, int height, ResourceLocation texture) { + this.paintingVariant = new PaintingVariant(width, height, texture); return this; } } 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 cc155f18c..531ce8e16 100644 --- a/src/main/java/dev/latvian/mods/kubejs/neoforge/KubeJSNeoForgeClient.java +++ b/src/main/java/dev/latvian/mods/kubejs/neoforge/KubeJSNeoForgeClient.java @@ -10,6 +10,7 @@ import dev.latvian.mods.kubejs.client.ClientInitKubeEvent; import dev.latvian.mods.kubejs.client.ItemTintFunctionWrapper; import dev.latvian.mods.kubejs.client.KubeJSClient; +import dev.latvian.mods.kubejs.client.KubeJSResourcePackFinder; import dev.latvian.mods.kubejs.fluid.FluidBucketItemBuilder; import dev.latvian.mods.kubejs.fluid.FluidBuilder; import dev.latvian.mods.kubejs.gui.KubeJSMenus; @@ -22,6 +23,7 @@ import net.minecraft.client.renderer.ItemBlockRenderTypes; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.texture.TextureAtlas; +import net.minecraft.server.packs.PackType; import net.neoforged.api.distmarker.Dist; import net.neoforged.bus.api.EventPriority; import net.neoforged.bus.api.SubscribeEvent; @@ -32,15 +34,24 @@ import net.neoforged.neoforge.client.event.RegisterMenuScreensEvent; import net.neoforged.neoforge.client.settings.KeyConflictContext; import net.neoforged.neoforge.client.settings.KeyModifier; +import net.neoforged.neoforge.event.AddPackFindersEvent; import org.lwjgl.glfw.GLFW; @EventBusSubscriber(modid = KubeJS.MOD_ID, value = Dist.CLIENT, bus = EventBusSubscriber.Bus.MOD) public class KubeJSNeoForgeClient { @SubscribeEvent(priority = EventPriority.LOW) public static void setupClient(FMLClientSetupEvent event) { + KubeJS.PROXY = new KubeJSClient(); event.enqueueWork(KubeJSNeoForgeClient::setupClient0); } + @SubscribeEvent + public static void addClientPacks(AddPackFindersEvent event) { + if (event.getPackType() == PackType.CLIENT_RESOURCES) { + event.addRepositorySource(new KubeJSResourcePackFinder()); + } + } + private static void setupClient0() { ClientEvents.INIT.post(ScriptType.STARTUP, new ClientInitKubeEvent()); ItemEvents.MODEL_PROPERTIES.post(ScriptType.STARTUP, new ItemModelPropertiesKubeEvent()); diff --git a/src/main/java/dev/latvian/mods/kubejs/player/EntityArrayList.java b/src/main/java/dev/latvian/mods/kubejs/player/EntityArrayList.java index a5b223204..2d97b7b94 100644 --- a/src/main/java/dev/latvian/mods/kubejs/player/EntityArrayList.java +++ b/src/main/java/dev/latvian/mods/kubejs/player/EntityArrayList.java @@ -14,6 +14,7 @@ import java.util.ArrayList; import java.util.Collection; +import java.util.List; import java.util.function.Predicate; @RemapPrefixForJS("kjs$") @@ -94,16 +95,18 @@ public void playSound(SoundEvent id) { playSound(id, 1F, 1F); } - public EntityArrayList filter(Predicate filter) { - if (isEmpty()) { + public EntityArrayList filter(List> filterList) { + if (isEmpty() || filterList.isEmpty()) { return this; } var list = new EntityArrayList(level, size()); for (var entity : this) { - if (filter.test(entity)) { - list.add(entity); + for (var filter : filterList) { + if (filter.test(entity)) { + list.add(entity); + } } } @@ -111,7 +114,7 @@ public EntityArrayList filter(Predicate filter) { } public EntityArrayList filterSelector(EntitySelector selector) { - return filter(selector.predicate); + return filter(selector.contextFreePredicates); } @Override diff --git a/src/main/java/dev/latvian/mods/kubejs/player/PlayerStatsJS.java b/src/main/java/dev/latvian/mods/kubejs/player/PlayerStatsJS.java index 5c08d347d..cbe604986 100644 --- a/src/main/java/dev/latvian/mods/kubejs/player/PlayerStatsJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/player/PlayerStatsJS.java @@ -25,7 +25,7 @@ public static Stat statOf(Object o) { } else if (o instanceof ResourceLocation rl) { return Stats.CUSTOM.get(rl); } else if (o instanceof CharSequence cs) { - return Stats.CUSTOM.get(new ResourceLocation(cs.toString())); + return Stats.CUSTOM.get(ResourceLocation.parse(cs.toString())); } return null; } diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/ContainerModifyRecipeCraftingGrid.java b/src/main/java/dev/latvian/mods/kubejs/recipe/ContainerModifyRecipeCraftingGrid.java deleted file mode 100644 index df0ddda02..000000000 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/ContainerModifyRecipeCraftingGrid.java +++ /dev/null @@ -1,50 +0,0 @@ -package dev.latvian.mods.kubejs.recipe; - -import dev.latvian.mods.kubejs.core.CraftingContainerKJS; -import dev.latvian.mods.kubejs.util.SlotFilter; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.CraftingContainer; -import net.minecraft.world.item.ItemStack; -import org.jetbrains.annotations.Nullable; - -import java.util.ArrayList; -import java.util.List; - -public class ContainerModifyRecipeCraftingGrid implements ModifyRecipeCraftingGrid { - private final CraftingContainer container; - - public ContainerModifyRecipeCraftingGrid(CraftingContainer c) { - container = c; - } - - @Override - public List findAll(SlotFilter filter) { - List list = new ArrayList<>(); - - for (int i = 0; i < container.getContainerSize(); i++) { - ItemStack stack = container.getItem(i); - - if (filter.checkFilter(i, stack)) { - list.add(stack.copy()); - } - } - - return list; - } - - @Override - public int getWidth() { - return container.getWidth(); - } - - @Override - public int getHeight() { - return container.getHeight(); - } - - @Override - @Nullable - public AbstractContainerMenu getMenu() { - return ((CraftingContainerKJS) container).kjs$getMenu(); - } -} diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/ModifyCraftingItemKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/recipe/ModifyCraftingItemKubeEvent.java new file mode 100644 index 000000000..85b552372 --- /dev/null +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/ModifyCraftingItemKubeEvent.java @@ -0,0 +1,41 @@ +package dev.latvian.mods.kubejs.recipe; + +import dev.latvian.mods.kubejs.event.KubeEvent; +import dev.latvian.mods.kubejs.item.ItemStackJS; +import dev.latvian.mods.rhino.Context; +import dev.latvian.mods.rhino.type.TypeInfo; +import dev.latvian.mods.rhino.util.HideFromJS; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.CraftingInput; +import net.minecraft.world.item.crafting.RecipeInput; + +public class ModifyCraftingItemKubeEvent implements KubeEvent { + public final RecipeInput grid; + public final int width; + public final int height; + public ItemStack item; + public final int index; + + public ModifyCraftingItemKubeEvent(RecipeInput grid, int width, int height, ItemStack item, int index) { + this.grid = grid; + this.width = width; + this.height = height; + this.item = item; + this.index = index; + } + + public ModifyCraftingItemKubeEvent(CraftingInput grid, ItemStack item, int index) { + this(grid, grid.width(), grid.height(), item, index); + } + + @Override + public ItemStack defaultExitValue(Context cx) { + return item; + } + + @Override + @HideFromJS + public TypeInfo getExitValueType() { + return ItemStackJS.TYPE_INFO; + } +} \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/ModifyRecipeCraftingGrid.java b/src/main/java/dev/latvian/mods/kubejs/recipe/ModifyRecipeCraftingGrid.java deleted file mode 100644 index 5a9c35c9a..000000000 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/ModifyRecipeCraftingGrid.java +++ /dev/null @@ -1,45 +0,0 @@ -package dev.latvian.mods.kubejs.recipe; - -import dev.latvian.mods.kubejs.util.SlotFilter; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.item.ItemStack; -import org.jetbrains.annotations.Nullable; - -import java.util.List; - -public interface ModifyRecipeCraftingGrid { - List findAll(SlotFilter filter); - - default List findAll() { - return findAll(SlotFilter.EMPTY); - } - - default ItemStack find(SlotFilter filter, int skip) { - for (var item : findAll(filter)) { - if (skip == 0) { - return item; - } - - skip--; - } - - return ItemStack.EMPTY; - } - - default ItemStack find(SlotFilter filter) { - return find(filter, 0); - } - - default int getWidth() { - return 0; - } - - default int getHeight() { - return 0; - } - - @Nullable - default AbstractContainerMenu getMenu() { - return null; - } -} diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/ModifyRecipeResultKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/recipe/ModifyRecipeResultKubeEvent.java deleted file mode 100644 index 25a57512b..000000000 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/ModifyRecipeResultKubeEvent.java +++ /dev/null @@ -1,33 +0,0 @@ -package dev.latvian.mods.kubejs.recipe; - -import dev.latvian.mods.kubejs.event.KubeEvent; -import dev.latvian.mods.kubejs.item.ItemStackJS; -import dev.latvian.mods.rhino.Context; -import dev.latvian.mods.rhino.type.TypeInfo; -import dev.latvian.mods.rhino.util.HideFromJS; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.ItemStack; -import org.jetbrains.annotations.Nullable; - -public class ModifyRecipeResultKubeEvent implements KubeEvent { - public final Player player; - public final ModifyRecipeCraftingGrid grid; - public ItemStack result; - - public ModifyRecipeResultKubeEvent(@Nullable Player player, ModifyRecipeCraftingGrid grid, ItemStack result) { - this.player = player; - this.grid = grid; - this.result = result; - } - - @Override - public ItemStack defaultExitValue(Context cx) { - return result; - } - - @Override - @HideFromJS - public TypeInfo getExitValueType() { - return ItemStackJS.TYPE_INFO; - } -} \ No newline at end of file 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 e25eec48f..b9a0245a2 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/RecipesKubeEvent.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/RecipesKubeEvent.java @@ -33,6 +33,7 @@ import dev.latvian.mods.rhino.Context; import dev.latvian.mods.rhino.WrappedException; import dev.latvian.mods.rhino.util.HideFromJS; +import net.minecraft.ReportType; import net.minecraft.ReportedException; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.Bootstrap; @@ -139,7 +140,7 @@ private String recipeToString(Recipe recipe) { if (ex instanceof ReportedException crashed) { // crash the same way Minecraft would - Bootstrap.realStdoutPrintln(crashed.getReport().getFriendlyReport()); + Bootstrap.realStdoutPrintln(crashed.getReport().getFriendlyReport(ReportType.CRASH)); System.exit(-1); } @@ -249,7 +250,7 @@ public RecipesKubeEvent(RecipeSchemaStorage recipeSchemaStorage, StaticRegistrie recipeFunctions.put("smithing", smithing); recipeFunctions.put("smithingTrim", smithingTrim); - stageSerializer = RegistryInfo.RECIPE_SERIALIZER.getValue(new ResourceLocation("recipestages:stage")); + stageSerializer = RegistryInfo.RECIPE_SERIALIZER.getValue(ResourceLocation.parse("recipestages:stage")); } @HideFromJS @@ -655,10 +656,10 @@ public void printExamples(String type) { public synchronized ResourceLocation takeId(KubeRecipe recipe, String prefix, String ids) { int i = 2; - var id = new ResourceLocation(prefix + ids); + var id = ResourceLocation.parse(prefix + ids); while (takenIds.containsKey(id)) { - id = new ResourceLocation(prefix + ids + '_' + i); + id = ResourceLocation.parse(prefix + ids + '_' + i); i++; } diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/component/StringComponent.java b/src/main/java/dev/latvian/mods/kubejs/recipe/component/StringComponent.java index e16cab266..f6fe96957 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/component/StringComponent.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/component/StringComponent.java @@ -27,13 +27,7 @@ public record StringComponent(String name, Codec stringCodec) implements return DataResult.success(s); })); - public static final RecipeComponent ID = new StringComponent("id", Codec.STRING.validate(s -> { - if (!ResourceLocation.isValidResourceLocation(s)) { - return DataResult.error(() -> "invalid ID"); - } - - return DataResult.success(s); - })); + public static final RecipeComponent ID = new StringComponent("id", Codec.STRING.validate(s -> ResourceLocation.read(s).map(ResourceLocation::toString))); @Override public Codec codec() { 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 52d15cedc..118fca41f 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 @@ -60,7 +60,7 @@ public TagKey wrap(Context cx, KubeRecipe recipe, Object from) { s = s.substring(1); } - return TagKey.create(registry, new ResourceLocation(s)); + return TagKey.create(registry, ResourceLocation.parse(s)); } @Override diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/ingredientaction/ConsumeAction.java b/src/main/java/dev/latvian/mods/kubejs/recipe/ingredientaction/ConsumeAction.java index c1f8f6fa6..3b1f8feab 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/ingredientaction/ConsumeAction.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/ingredientaction/ConsumeAction.java @@ -1,8 +1,8 @@ package dev.latvian.mods.kubejs.recipe.ingredientaction; import com.mojang.serialization.MapCodec; -import net.minecraft.world.inventory.CraftingContainer; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.CraftingInput; public class ConsumeAction implements IngredientAction { public static final IngredientActionType TYPE = new IngredientActionType("consume", MapCodec.unit(new ConsumeAction())); @@ -13,7 +13,7 @@ public IngredientActionType getType() { } @Override - public ItemStack transform(ItemStack old, int index, CraftingContainer container) { + public ItemStack transform(ItemStack old, int index, CraftingInput input) { return ItemStack.EMPTY; } } diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/ingredientaction/CustomIngredientAction.java b/src/main/java/dev/latvian/mods/kubejs/recipe/ingredientaction/CustomIngredientAction.java index f786d4ff3..add2229f0 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/ingredientaction/CustomIngredientAction.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/ingredientaction/CustomIngredientAction.java @@ -2,15 +2,13 @@ import com.mojang.serialization.Codec; import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.world.inventory.CraftingContainer; +import dev.latvian.mods.kubejs.bindings.event.ServerEvents; +import dev.latvian.mods.kubejs.recipe.ModifyCraftingItemKubeEvent; +import dev.latvian.mods.kubejs.script.ScriptType; import net.minecraft.world.item.ItemStack; - -import java.util.HashMap; -import java.util.Map; +import net.minecraft.world.item.crafting.CraftingInput; public record CustomIngredientAction(String id) implements IngredientAction { - public static final Map MAP = new HashMap<>(); - public static final IngredientActionType TYPE = new IngredientActionType("custom", RecordCodecBuilder.mapCodec(instance -> instance.group( Codec.STRING.fieldOf("id").forGetter(CustomIngredientAction::id) ).apply(instance, CustomIngredientAction::new))); @@ -21,8 +19,7 @@ public IngredientActionType getType() { } @Override - public ItemStack transform(ItemStack old, int index, CraftingContainer container) { - var callback = MAP.get(id); - return callback == null ? ItemStack.EMPTY : callback.transform(old, index, container).copy(); + public ItemStack transform(ItemStack old, int index, CraftingInput input) { + return ((ItemStack) ServerEvents.MODIFY_RECIPE_INGREDIENT.post(ScriptType.SERVER, id, new ModifyCraftingItemKubeEvent(input, old, index)).value()).copy(); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/ingredientaction/CustomIngredientActionCallback.java b/src/main/java/dev/latvian/mods/kubejs/recipe/ingredientaction/CustomIngredientActionCallback.java deleted file mode 100644 index 188028ab3..000000000 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/ingredientaction/CustomIngredientActionCallback.java +++ /dev/null @@ -1,9 +0,0 @@ -package dev.latvian.mods.kubejs.recipe.ingredientaction; - -import dev.latvian.mods.kubejs.core.InventoryKJS; -import net.minecraft.world.item.ItemStack; - -@FunctionalInterface -public interface CustomIngredientActionCallback { - ItemStack transform(ItemStack old, int index, InventoryKJS craftingTable); -} diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/ingredientaction/DamageAction.java b/src/main/java/dev/latvian/mods/kubejs/recipe/ingredientaction/DamageAction.java index cc3633dc9..bb6e2322d 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/ingredientaction/DamageAction.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/ingredientaction/DamageAction.java @@ -2,8 +2,8 @@ import com.mojang.serialization.Codec; import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.world.inventory.CraftingContainer; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.CraftingInput; public record DamageAction(int damage) implements IngredientAction { public static final IngredientActionType TYPE = new IngredientActionType("damage", RecordCodecBuilder.mapCodec(instance -> instance.group( @@ -16,7 +16,7 @@ public IngredientActionType getType() { } @Override - public ItemStack transform(ItemStack old, int index, CraftingContainer container) { + public ItemStack transform(ItemStack old, int index, CraftingInput input) { old.setDamageValue(old.getDamageValue() + damage); return old.getDamageValue() >= old.getMaxDamage() ? ItemStack.EMPTY : old; } diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/ingredientaction/IngredientAction.java b/src/main/java/dev/latvian/mods/kubejs/recipe/ingredientaction/IngredientAction.java index fc2285b5a..b01bbc12f 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/ingredientaction/IngredientAction.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/ingredientaction/IngredientAction.java @@ -4,8 +4,8 @@ import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.codec.ByteBufCodecs; import net.minecraft.network.codec.StreamCodec; -import net.minecraft.world.inventory.CraftingContainer; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.CraftingInput; import java.util.List; @@ -13,8 +13,8 @@ public interface IngredientAction { Codec CODEC = IngredientActionType.CODEC.dispatch("type", IngredientAction::getType, IngredientActionType::codec); StreamCodec STREAM_CODEC = ByteBufCodecs.fromCodecWithRegistries(CODEC); - static ItemStack getRemaining(CraftingContainer container, int index, List ingredientActions) { - var stack = container.getItem(index); + static ItemStack getRemaining(CraftingInput input, int index, List ingredientActions) { + var stack = input.getItem(index); if (stack == null || stack.isEmpty()) { return ItemStack.EMPTY; @@ -22,7 +22,7 @@ static ItemStack getRemaining(CraftingContainer container, int index, ListmapCodec(instance -> instance.group( @@ -15,7 +15,7 @@ public IngredientActionType getType() { } @Override - public ItemStack transform(ItemStack old, int index, CraftingContainer container) { + public ItemStack transform(ItemStack old, int index, CraftingInput input) { return item.copy(); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/schema/JsonRecipeSchemaLoader.java b/src/main/java/dev/latvian/mods/kubejs/recipe/schema/JsonRecipeSchemaLoader.java index bba6cfa3e..b926df5b2 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/schema/JsonRecipeSchemaLoader.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/schema/JsonRecipeSchemaLoader.java @@ -211,7 +211,7 @@ public static void load(RecipeSchemaStorage storage, RecipeSchemaRegistry event, for (var entry : resourceManager.listResources("kubejs/recipe_schemas", path -> path.getPath().endsWith(".json")).entrySet()) { try (var reader = entry.getValue().openAsReader()) { var json = JsonUtils.GSON.fromJson(reader, JsonObject.class); - var holder = new RecipeSchemaBuilder(new ResourceLocation(entry.getKey().getNamespace(), entry.getKey().getPath().substring("kubejs/recipe_schemas/".length(), entry.getKey().getPath().length() - ".json".length())), json); + var holder = new RecipeSchemaBuilder(ResourceLocation.fromNamespaceAndPath(entry.getKey().getNamespace(), entry.getKey().getPath().substring("kubejs/recipe_schemas/".length(), entry.getKey().getPath().length() - ".json".length())), json); map.put(holder.id, holder); if (holder.json.has("mappings")) { @@ -225,10 +225,10 @@ public static void load(RecipeSchemaStorage storage, RecipeSchemaRegistry event, } for (var holder : map.values()) { - holder.parent = holder.json.has("parent") ? map.get(new ResourceLocation(holder.json.get("parent").getAsString())) : null; + holder.parent = holder.json.has("parent") ? map.get(ResourceLocation.parse(holder.json.get("parent").getAsString())) : null; if (holder.json.has("factory")) { - var fname = new ResourceLocation(holder.json.get("factory").getAsString()); + var fname = ResourceLocation.parse(holder.json.get("factory").getAsString()); holder.recipeFactory = storage.recipeTypes.get(fname); if (holder.recipeFactory == null) { diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/schema/RecipeMappingRegistry.java b/src/main/java/dev/latvian/mods/kubejs/recipe/schema/RecipeMappingRegistry.java index aa8f97f13..4138f8c80 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/schema/RecipeMappingRegistry.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/schema/RecipeMappingRegistry.java @@ -17,6 +17,6 @@ public void register(String name, ResourceLocation type) { @HideFromJS public void register(String name, String type) { - register(name, new ResourceLocation(type)); + register(name, ResourceLocation.parse(type)); } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/schema/RecipeNamespace.java b/src/main/java/dev/latvian/mods/kubejs/recipe/schema/RecipeNamespace.java index 556294b3b..a03162004 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/schema/RecipeNamespace.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/schema/RecipeNamespace.java @@ -15,7 +15,7 @@ public RecipeNamespace(RecipeSchemaStorage storage, String name) { } public RecipeNamespace register(String id, RecipeSchema type) { - put(id, new RecipeSchemaType(this, new ResourceLocation(name, id), type)); + put(id, new RecipeSchemaType(this, ResourceLocation.fromNamespaceAndPath(name, id), type)); return this; } diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/schema/RecipeSchemaStorage.java b/src/main/java/dev/latvian/mods/kubejs/recipe/schema/RecipeSchemaStorage.java index efb08dc09..deeaa86c0 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/schema/RecipeSchemaStorage.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/schema/RecipeSchemaStorage.java @@ -63,7 +63,7 @@ public void fireEvents(ResourceManager resourceManager) { var json = JsonUtils.GSON.fromJson(reader, JsonObject.class); for (var entry1 : json.entrySet()) { - var id = new ResourceLocation(entry.getKey().getNamespace(), entry1.getKey()); + var id = ResourceLocation.fromNamespaceAndPath(entry.getKey().getNamespace(), entry1.getKey()); if (entry1.getValue() instanceof JsonArray arr) { for (var n : arr) { diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/schema/minecraft/ShapedKubeRecipe.java b/src/main/java/dev/latvian/mods/kubejs/recipe/schema/minecraft/ShapedKubeRecipe.java index b347d6076..fc939e892 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/schema/minecraft/ShapedKubeRecipe.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/schema/minecraft/ShapedKubeRecipe.java @@ -72,7 +72,6 @@ public RecipeTypeFunction getSerializationTypeFunction() { && !json.has(KubeJSCraftingRecipe.MODIFY_RESULT_KEY) && !json.has(KubeJSCraftingRecipe.STAGE_KEY) && !json.has(KubeJSCraftingRecipe.MIRROR_KEY) - && !json.has(KubeJSCraftingRecipe.SHRINK_KEY) ) { return type.event.vanillaShaped; } diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/special/KubeJSCraftingRecipe.java b/src/main/java/dev/latvian/mods/kubejs/recipe/special/KubeJSCraftingRecipe.java index a95e3131c..631a3a1bd 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/special/KubeJSCraftingRecipe.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/special/KubeJSCraftingRecipe.java @@ -1,9 +1,7 @@ package dev.latvian.mods.kubejs.recipe.special; import dev.latvian.mods.kubejs.bindings.event.ServerEvents; -import dev.latvian.mods.kubejs.core.CraftingContainerKJS; -import dev.latvian.mods.kubejs.recipe.ContainerModifyRecipeCraftingGrid; -import dev.latvian.mods.kubejs.recipe.ModifyRecipeResultKubeEvent; +import dev.latvian.mods.kubejs.recipe.ModifyCraftingItemKubeEvent; import dev.latvian.mods.kubejs.recipe.ingredientaction.IngredientAction; import dev.latvian.mods.kubejs.recipe.ingredientaction.IngredientActionHolder; import dev.latvian.mods.kubejs.script.ScriptType; @@ -11,10 +9,10 @@ import net.minecraft.core.NonNullList; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.CraftingContainer; import net.minecraft.world.inventory.CraftingMenu; import net.minecraft.world.inventory.InventoryMenu; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.CraftingInput; import net.minecraft.world.item.crafting.CraftingRecipe; import net.neoforged.neoforge.server.ServerLifecycleHooks; import org.jetbrains.annotations.Nullable; @@ -23,7 +21,6 @@ public interface KubeJSCraftingRecipe extends CraftingRecipe { String STAGE_KEY = "kubejs:stage"; - String SHRINK_KEY = "kubejs:shrink"; String MIRROR_KEY = "kubejs:mirror"; String INGREDIENT_ACTIONS_KEY = "kubejs:ingredient_actions"; String MODIFY_RESULT_KEY = "kubejs:modify_result"; @@ -34,23 +31,25 @@ public interface KubeJSCraftingRecipe extends CraftingRecipe { String kjs$getStage(); - default NonNullList kjs$getRemainingItems(CraftingContainer container) { - var list = NonNullList.withSize(container.getContainerSize(), ItemStack.EMPTY); + default NonNullList kjs$getRemainingItems(CraftingInput input) { + var list = NonNullList.withSize(input.size(), ItemStack.EMPTY); for (var i = 0; i < list.size(); i++) { - list.set(i, IngredientAction.getRemaining(container, i, kjs$getIngredientActions())); + list.set(i, IngredientAction.getRemaining(input, i, kjs$getIngredientActions())); } return list; } - default ItemStack kjs$assemble(CraftingContainer container, HolderLookup.Provider registryAccess) { - var player = getPlayer(((CraftingContainerKJS) container).kjs$getMenu()); - + default ItemStack kjs$assemble(CraftingInput input, HolderLookup.Provider registryAccess) { if (!kjs$getStage().isEmpty()) { + /* FIXME + var player = getPlayer(((CraftingContainerKJS) container).kjs$getMenu()); + if (player == null || !player.kjs$getStages().has(kjs$getStage())) { return ItemStack.EMPTY; } + */ } var modifyResult = kjs$getModifyResult(); @@ -59,7 +58,7 @@ public interface KubeJSCraftingRecipe extends CraftingRecipe { result = (result == null || result.isEmpty()) ? ItemStack.EMPTY : result.copy(); if (!modifyResult.isEmpty()) { - var event = new ModifyRecipeResultKubeEvent(player, new ContainerModifyRecipeCraftingGrid(container), result); + var event = new ModifyCraftingItemKubeEvent(input, result, 0); return (ItemStack) ServerEvents.MODIFY_RECIPE_RESULT.post(ScriptType.SERVER, modifyResult, event).value(); } 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 10ac33af6..c5ea6a7cb 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 @@ -2,10 +2,7 @@ import com.mojang.serialization.Codec; import com.mojang.serialization.DataResult; -import com.mojang.serialization.DynamicOps; import com.mojang.serialization.MapCodec; -import com.mojang.serialization.MapLike; -import com.mojang.serialization.RecordBuilder; import com.mojang.serialization.codecs.RecordCodecBuilder; import dev.latvian.mods.kubejs.recipe.KubeJSRecipeSerializers; import dev.latvian.mods.kubejs.recipe.ingredientaction.IngredientActionHolder; @@ -15,9 +12,9 @@ import net.minecraft.core.NonNullList; import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.codec.StreamCodec; -import net.minecraft.world.inventory.CraftingContainer; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.CraftingBookCategory; +import net.minecraft.world.item.crafting.CraftingInput; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.RecipeSerializer; import net.minecraft.world.item.crafting.ShapedRecipe; @@ -26,43 +23,8 @@ import java.util.List; import java.util.Optional; -import java.util.stream.Stream; public class ShapedKubeJSRecipe extends ShapedRecipe implements KubeJSCraftingRecipe { - public static final MapCodec PATTERN_NO_SHRINK_CODEC = ShapedRecipePattern.Data.MAP_CODEC - .flatXmap(ShapedKubeJSRecipe::unpackNoShrink, - pattern -> pattern.data().map(DataResult::success) - .orElseGet(() -> DataResult.error(() -> "Cannot encode unpacked recipe"))); - - public static final MapCodec PATTERN_CODEC = new MapCodec<>() { - @Override - public Stream keys(DynamicOps ops) { - return Stream.concat(ShapedRecipePattern.MAP_CODEC.keys(ops), Stream.of(ops.createString(SHRINK_KEY))); - } - - @Override - public DataResult decode(DynamicOps ops, MapLike input) { - var shrink = input.get(SHRINK_KEY); - - if (shrink == null) { - return ShapedRecipePattern.MAP_CODEC.decode(ops, input); - } - - return ops.getBooleanValue(shrink).flatMap(shrinkVal -> { - if (shrinkVal) { - return ShapedRecipePattern.MAP_CODEC.decode(ops, input); - } else { - return PATTERN_NO_SHRINK_CODEC.decode(ops, input); - } - }); - } - - @Override - public RecordBuilder encode(ShapedRecipePattern input, DynamicOps ops, RecordBuilder prefix) { - return PATTERN_NO_SHRINK_CODEC.encode(input, ops, prefix).add(SHRINK_KEY, ops.createBoolean(false)); - } - }; - private final boolean mirror; private final List ingredientActions; private final String modifyResult; @@ -101,30 +63,19 @@ public RecipeSerializer getSerializer() { } @Override - public NonNullList getRemainingItems(CraftingContainer container) { - return kjs$getRemainingItems(container); + public NonNullList getRemainingItems(CraftingInput input) { + return kjs$getRemainingItems(input); } @Override - public ItemStack assemble(CraftingContainer container, HolderLookup.Provider registryAccess) { - return kjs$assemble(container, registryAccess); + public ItemStack assemble(CraftingInput input, HolderLookup.Provider registryAccess) { + return kjs$assemble(input, registryAccess); } @Override - public boolean matches(CraftingContainer craftingContainer, Level level) { - for (var i = 0; i <= craftingContainer.getWidth() - pattern.width(); ++i) { - for (var j = 0; j <= craftingContainer.getHeight() - pattern.height(); ++j) { - if (mirror && pattern.matches(craftingContainer, i, j, true)) { - return true; - } - - if (pattern.matches(craftingContainer, i, j, false)) { - return true; - } - } - } - - return false; + public boolean matches(CraftingInput input, Level level) { + // FIXME: mirror + return pattern.matches(input); } public static class SerializerKJS implements RecipeSerializer { @@ -136,7 +87,7 @@ public static class SerializerKJS implements RecipeSerializer recipe.pattern), + ShapedRecipePattern.MAP_CODEC.forGetter(recipe -> recipe.pattern), ItemStack.STRICT_CODEC.fieldOf("result").forGetter(r -> r.result), Codec.BOOL.optionalFieldOf("show_notification", true).forGetter(ShapedRecipe::showNotification), // KubeJS additions 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 3e7d29dcf..11950b885 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 @@ -10,8 +10,8 @@ import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.codec.ByteBufCodecs; import net.minecraft.network.codec.StreamCodec; -import net.minecraft.world.inventory.CraftingContainer; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.CraftingInput; import net.minecraft.world.item.crafting.RecipeSerializer; import net.minecraft.world.item.crafting.ShapelessRecipe; @@ -50,13 +50,13 @@ public RecipeSerializer getSerializer() { } @Override - public NonNullList getRemainingItems(CraftingContainer container) { - return kjs$getRemainingItems(container); + public NonNullList getRemainingItems(CraftingInput input) { + return kjs$getRemainingItems(input); } @Override - public ItemStack assemble(CraftingContainer container, HolderLookup.Provider registryAccess) { - return kjs$assemble(container, registryAccess); + public ItemStack assemble(CraftingInput input, HolderLookup.Provider registryAccess) { + return kjs$assemble(input, registryAccess); } public static class SerializerKJS implements RecipeSerializer { diff --git a/src/main/java/dev/latvian/mods/kubejs/registry/BuilderBase.java b/src/main/java/dev/latvian/mods/kubejs/registry/BuilderBase.java index 518021575..c9dc4e192 100644 --- a/src/main/java/dev/latvian/mods/kubejs/registry/BuilderBase.java +++ b/src/main/java/dev/latvian/mods/kubejs/registry/BuilderBase.java @@ -10,6 +10,7 @@ import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; +import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.function.Supplier; @@ -98,8 +99,8 @@ public BuilderBase formattedDisplayName(Component name) { @Info(""" Adds a tag to this object, e.g. `minecraft:stone`. """) - public BuilderBase tag(ResourceLocation tag) { - defaultTags.add(tag); + public BuilderBase tag(ResourceLocation[] tag) { + defaultTags.addAll(Arrays.asList(tag)); getRegistryType().hasDefaultTags = true; return this; } @@ -109,7 +110,7 @@ public ResourceLocation newID(String pre, String post) { return id; } - return new ResourceLocation(id.getNamespace() + ':' + pre + id.getPath() + post); + return ResourceLocation.fromNamespaceAndPath(id.getNamespace(), pre + id.getPath() + post); } public void generateDataJsons(DataJsonGenerator generator) { 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 7552b4d0f..8c1342e38 100644 --- a/src/main/java/dev/latvian/mods/kubejs/registry/RegistryInfo.java +++ b/src/main/java/dev/latvian/mods/kubejs/registry/RegistryInfo.java @@ -24,9 +24,9 @@ import net.minecraft.world.item.ArmorMaterial; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.Item; +import net.minecraft.world.item.JukeboxSong; import net.minecraft.world.item.alchemy.Potion; import net.minecraft.world.item.crafting.RecipeSerializer; -import net.minecraft.world.item.enchantment.Enchantment; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.material.Fluid; @@ -71,7 +71,6 @@ public static RegistryInfo wrap(Object from) { public static final RegistryInfo FLUID = of(Registries.FLUID); public static final RegistryInfo MOB_EFFECT = of(Registries.MOB_EFFECT).languageKeyPrefix("effect"); public static final RegistryInfo BLOCK = of(Registries.BLOCK); - public static final RegistryInfo ENCHANTMENT = of(Registries.ENCHANTMENT); public static final RegistryInfo> ENTITY_TYPE = of(Registries.ENTITY_TYPE); public static final RegistryInfo ITEM = of(Registries.ITEM); public static final RegistryInfo POTION = of(Registries.POTION); @@ -88,6 +87,7 @@ public static RegistryInfo wrap(Object from) { public static final RegistryInfo POINT_OF_INTEREST_TYPE = of(Registries.POINT_OF_INTEREST_TYPE); public static final RegistryInfo> COMMAND_ARGUMENT_TYPE = of(Registries.COMMAND_ARGUMENT_TYPE); public static final RegistryInfo CREATIVE_MODE_TAB = of(Registries.CREATIVE_MODE_TAB); + public static final RegistryInfo JUKEBOX_SONG = of(Registries.JUKEBOX_SONG); public final ResourceKey> key; BuilderType defaultType; 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 09e8af4d3..b309e401d 100644 --- a/src/main/java/dev/latvian/mods/kubejs/script/KubeJSContext.java +++ b/src/main/java/dev/latvian/mods/kubejs/script/KubeJSContext.java @@ -3,7 +3,6 @@ import com.google.gson.JsonElement; import com.mojang.datafixers.util.Either; import dev.latvian.mods.kubejs.KubeJS; -import dev.latvian.mods.kubejs.registry.RegistryInfo; import dev.latvian.mods.kubejs.registry.RegistryType; import dev.latvian.mods.kubejs.util.ConsoleJS; import dev.latvian.mods.kubejs.util.ID; @@ -16,6 +15,7 @@ import dev.latvian.mods.rhino.util.ClassVisibilityContext; import net.minecraft.core.Holder; import net.minecraft.core.HolderSet; +import net.minecraft.core.Registry; import net.minecraft.core.RegistryAccess; import net.minecraft.nbt.Tag; import net.minecraft.resources.RegistryOps; @@ -25,6 +25,7 @@ import java.util.HashMap; import java.util.Map; +import java.util.Optional; public class KubeJSContext extends Context { public final KubeJSContextFactory kjsFactory; @@ -84,110 +85,113 @@ public RegistryOps getJavaOps() { return getRegistries().java(); } - /* - static Holder holderOf(Context cx, Object from, TypeInfo target) { - if (from == null) { - return null; - } else if (from instanceof Holder h) { - return h; - } else if (from instanceof RegistryObjectKJS w) { - return w.kjs$asHolder(); - } + @Override + public int internalConversionWeightLast(Object fromObj, TypeInfo target) { + var c = target.asClass(); - var reg = RegistryInfo.ofClass(target.param(0).asClass()); + if (c == Optional.class || c == ResourceKey.class || c == Holder.class || c == HolderSet.class || c == TagKey.class) { + return CONVERSION_TRIVIAL; + } else if (c != Object.class) { + var reg = RegistryType.allOfClass(target.asClass()); - if (reg != null) { - return reg.getHolder(ID.mc(from)); + if (!reg.isEmpty()) { + return CONVERSION_TRIVIAL; + } } - return new Holder.Direct<>(from); + return super.internalConversionWeightLast(fromObj, target); } - static ResourceKey resourceKeyOf(Context cx, Object from, TypeInfo target) { - if (from == null) { - return null; - } else if (from instanceof ResourceKey k) { - return k; - } else if (from instanceof RegistryObjectKJS w) { - return w.kjs$getRegistryKey(); - } - - var cl = target.param(0).asClass(); - - if (cl == ResourceKey.class) { - return ResourceKey.createRegistryKey(ID.mc(from)); - } - - var reg = RegistryInfo.ofClass(cl); + private RegistryType lookupRegistryType(TypeInfo type, Object from) { + var registryType = RegistryType.lookup(type); - if (reg != null) { - return ResourceKey.create(reg.key, ID.mc(from)); + if (registryType == null) { + throw reportRuntimeError("Can't interpret '" + from + "': no registries for type '" + type + "' found", this); } - throw new IllegalArgumentException("Can't parse " + from + " as ResourceKey!"); + return registryType; } - */ - @Override - public int internalConversionWeight(Object fromObj, TypeInfo target) { - var s = super.internalConversionWeight(fromObj, target); + private Registry lookupRegistry(TypeInfo type, Object from) { + var registryType = lookupRegistryType(type, from); - if (s == CONVERSION_NONE && target.shouldConvert()) { - var reg = RegistryType.allOfClass(target.asClass()); + var registry = getRegistries().access().registry(registryType.key()).orElse(null); - if (!reg.isEmpty()) { - return CONVERSION_TRIVIAL; - } + if (registry == null) { + throw reportRuntimeError("Can't interpret '" + from + "' as '" + registryType.key().location() + "': registry not found", this); } - return s; + return registry; } @Override protected Object internalJsToJavaLast(Object from, TypeInfo target) { - if (target.asClass() == ResourceKey.class) { - var reg = RegistryType.lookup(target.param(0)); + var c = target.asClass(); + + if (c == Optional.class) { + if (from instanceof Optional o) { + return o; + } - if (reg == null) { - throw reportRuntimeError("Can't find matching '" + target + "' registry type", this); + return Optional.ofNullable(jsToJava(from, target.param(0))); + } else if (c == ResourceKey.class) { + if (from instanceof ResourceKey k) { + return k; } - throw reportRuntimeError("Can't interpret '" + from + "' as ResourceKey: not supported yet", this); - } else if (target.asClass() == Holder.class) { - var reg = RegistryType.lookup(target.param(0)); + var registry = lookupRegistry(target.param(0), from); + var id = ID.mc(from); - if (reg == null) { - throw reportRuntimeError("Can't find matching '" + target + "' registry type", this); + return ResourceKey.create(registry.key(), id); + } else if (c == Holder.class) { + if (from instanceof Holder h) { + return h; } - throw reportRuntimeError("Can't interpret '" + from + "' as Holder: not supported yet", this); - } else if (target.asClass() == HolderSet.class) { - var reg = RegistryType.lookup(target.param(0)); + var registry = lookupRegistry(target.param(0), from); + var id = ID.mc(from); - if (reg == null) { - throw reportRuntimeError("Can't find matching '" + target + "' registry type", this); + var holder = registry.getHolder(id); + + if (holder.isEmpty()) { + throw reportRuntimeError("Can't interpret '" + from + "' as Holder: entry not found", this); + } + + return holder.get(); + } else if (c == HolderSet.class) { + if (from instanceof HolderSet h) { + return h; } - throw reportRuntimeError("Can't interpret '" + from + "' as TagKey: not supported yet", this); - } else if (target.asClass() == TagKey.class) { - var reg = RegistryType.lookup(target.param(0)); + var registry = lookupRegistry(target.param(0), from); - if (reg == null) { - throw reportRuntimeError("Can't find matching '" + target + "' registry type", this); + throw reportRuntimeError("Can't interpret '" + from + "' as HolderSet: not supported yet", this); + } else if (c == TagKey.class) { + if (from instanceof TagKey k) { + return k; } - throw reportRuntimeError("Can't interpret '" + from + "' as TagKey: not supported yet", this); + var registryType = lookupRegistryType(target.param(0), from); + var id = ID.mc(from); + return TagKey.create(registryType.key(), id); + } else if (from instanceof Holder holder && c.isInstance(holder.value())) { + return holder.value(); } else { var reg = RegistryType.lookup(target); if (reg != null) { - var regInfo = RegistryInfo.of(reg.key()); - var value = regInfo.getValue(ID.mc(from)); + var registry = getRegistries().access().registry(reg.key()).orElse(null); + + if (registry == null) { + throw reportRuntimeError("Can't interpret '" + from + "' as '" + reg.key().location() + "': registry not found", this); + } + + var value = registry.get(ID.mc(from)); if (value != null) { return value; } else { - throw reportRuntimeError("Can't interpret '" + from + "' as '" + regInfo + "' registry object", this); + throw reportRuntimeError("Can't interpret '" + from + "' as '" + reg.key().location() + "': entry not found", this); } } } 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 345dc8529..2023ea726 100644 --- a/src/main/java/dev/latvian/mods/kubejs/script/ScriptFileInfo.java +++ b/src/main/java/dev/latvian/mods/kubejs/script/ScriptFileInfo.java @@ -32,7 +32,7 @@ public class ScriptFileInfo { public ScriptFileInfo(ScriptPackInfo p, String f) { pack = p; file = f; - id = new ResourceLocation(pack.namespace, FILE_FIXER.matcher(pack.pathStart + file).replaceAll("_").toLowerCase()); + id = ResourceLocation.fromNamespaceAndPath(pack.namespace, FILE_FIXER.matcher(pack.pathStart + file).replaceAll("_").toLowerCase()); location = ID.string(pack.namespace + ":" + pack.pathStart + file); properties = new HashMap<>(); priority = 0; diff --git a/src/main/java/dev/latvian/mods/kubejs/script/data/DataPackKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/script/data/DataPackKubeEvent.java index 9ad310e5a..018c51ba5 100644 --- a/src/main/java/dev/latvian/mods/kubejs/script/data/DataPackKubeEvent.java +++ b/src/main/java/dev/latvian/mods/kubejs/script/data/DataPackKubeEvent.java @@ -19,7 +19,7 @@ public void add(ResourceLocation id, String content) { public void addJson(ResourceLocation id, JsonElement json) { if (json != null) { // append .json to the filename if it doesn't have it already - id = id.getPath().endsWith(".json") ? id : new ResourceLocation(id.getNamespace(), id.getPath() + ".json"); + id = id.getPath().endsWith(".json") ? id : ResourceLocation.fromNamespaceAndPath(id.getNamespace(), id.getPath() + ".json"); add(id, JsonIO.toString(json)); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/script/data/GeneratedResourcePack.java b/src/main/java/dev/latvian/mods/kubejs/script/data/GeneratedResourcePack.java index a9cf2b382..bef29a37a 100644 --- a/src/main/java/dev/latvian/mods/kubejs/script/data/GeneratedResourcePack.java +++ b/src/main/java/dev/latvian/mods/kubejs/script/data/GeneratedResourcePack.java @@ -113,7 +113,7 @@ public Map getGenerated() { continue; } - var data = new GeneratedData(new ResourceLocation(ns, pathStr), () -> { + var data = new GeneratedData(ResourceLocation.fromNamespaceAndPath(ns, pathStr), () -> { try { return Files.readAllBytes(path); } catch (Exception ex) { 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 544212ef7..a9e27be47 100644 --- a/src/main/java/dev/latvian/mods/kubejs/server/ServerScriptManager.java +++ b/src/main/java/dev/latvian/mods/kubejs/server/ServerScriptManager.java @@ -7,7 +7,6 @@ import dev.latvian.mods.kubejs.core.RecipeManagerKJS; import dev.latvian.mods.kubejs.recipe.CompostableRecipesKubeEvent; import dev.latvian.mods.kubejs.recipe.RecipesKubeEvent; -import dev.latvian.mods.kubejs.recipe.ingredientaction.CustomIngredientAction; import dev.latvian.mods.kubejs.recipe.schema.RecipeSchemaStorage; import dev.latvian.mods.kubejs.recipe.special.SpecialRecipeSerializerManager; import dev.latvian.mods.kubejs.script.ScriptManager; @@ -127,7 +126,6 @@ public void reload() { ConsoleJS.SERVER.setCapturingErrors(true); super.reload(); ConsoleJS.SERVER.info("Scripts loaded"); - CustomIngredientAction.MAP.clear(); SpecialRecipeSerializerManager.INSTANCE.reset(); ServerEvents.SPECIAL_RECIPES.post(ScriptType.SERVER, SpecialRecipeSerializerManager.INSTANCE); PreTagKubeEvent.handle(preTagEvents); diff --git a/src/main/java/dev/latvian/mods/kubejs/server/tag/TagEventFilter.java b/src/main/java/dev/latvian/mods/kubejs/server/tag/TagEventFilter.java index 409514aeb..42ace4d9e 100644 --- a/src/main/java/dev/latvian/mods/kubejs/server/tag/TagEventFilter.java +++ b/src/main/java/dev/latvian/mods/kubejs/server/tag/TagEventFilter.java @@ -37,9 +37,9 @@ static TagEventFilter of(TagKubeEvent event, Object o) { if (!s.isEmpty()) { return switch (s.charAt(0)) { - case '#' -> new Tag(event.get(new ResourceLocation(s.substring(1)))); + case '#' -> new Tag(event.get(ResourceLocation.parse(s.substring(1)))); case '@' -> new Namespace(s.substring(1)); - default -> new ID(new ResourceLocation(s)); + default -> new ID(ResourceLocation.parse(s)); }; } diff --git a/src/main/java/dev/latvian/mods/kubejs/util/ID.java b/src/main/java/dev/latvian/mods/kubejs/util/ID.java index da2b79081..f5d505bee 100644 --- a/src/main/java/dev/latvian/mods/kubejs/util/ID.java +++ b/src/main/java/dev/latvian/mods/kubejs/util/ID.java @@ -10,7 +10,7 @@ import org.jetbrains.annotations.Nullable; public interface ID { - ResourceLocation UNKNOWN = new ResourceLocation("unknown", "unknown"); + ResourceLocation UNKNOWN = ResourceLocation.fromNamespaceAndPath("unknown", "unknown"); static String string(@Nullable String id) { if (id == null || id.isEmpty()) { @@ -74,7 +74,7 @@ static ResourceLocation of(@Nullable Object o, boolean preferKJS) { } try { - return new ResourceLocation(s); + return ResourceLocation.parse(s); } catch (ResourceLocationException ex) { throw new IllegalArgumentException("Could not create ID from '%s'!".formatted(s)); } diff --git a/src/main/java/dev/latvian/mods/kubejs/util/IconKJS.java b/src/main/java/dev/latvian/mods/kubejs/util/IconKJS.java index faa7687b3..97efa9f57 100644 --- a/src/main/java/dev/latvian/mods/kubejs/util/IconKJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/util/IconKJS.java @@ -72,13 +72,12 @@ public void draw(Minecraft mc, GuiGraphics graphics, int x, int y, int size) { int p0 = -size / 2; int p1 = p0 + size; - var buf = Tesselator.getInstance().getBuilder(); - buf.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX_COLOR); - buf.vertex(m, x + p0, y + p1, 0F).uv(0F, 1F).color(255, 255, 255, 255).endVertex(); - buf.vertex(m, x + p1, y + p1, 0F).uv(1F, 1F).color(255, 255, 255, 255).endVertex(); - buf.vertex(m, x + p1, y + p0, 0F).uv(1F, 0F).color(255, 255, 255, 255).endVertex(); - buf.vertex(m, x + p0, y + p0, 0F).uv(0F, 0F).color(255, 255, 255, 255).endVertex(); - BufferUploader.drawWithShader(buf.end()); + var buf = Tesselator.getInstance().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX_COLOR); + buf.addVertex(m, x + p0, y + p1, 0F).setUv(0F, 1F).setColor(255, 255, 255, 255); + buf.addVertex(m, x + p1, y + p1, 0F).setUv(1F, 1F).setColor(255, 255, 255, 255); + buf.addVertex(m, x + p1, y + p0, 0F).setUv(1F, 0F).setColor(255, 255, 255, 255); + buf.addVertex(m, x + p0, y + p0, 0F).setUv(0F, 0F).setColor(255, 255, 255, 255); + BufferUploader.drawWithShader(buf.buildOrThrow()); } } @@ -117,13 +116,12 @@ public void draw(Minecraft mc, GuiGraphics graphics, int x, int y, int size) { float u1 = sprite.getU1(); float v1 = sprite.getV1(); - var buf = Tesselator.getInstance().getBuilder(); - buf.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX_COLOR); - buf.vertex(m, x + p0, y + p1, 0F).uv(u0, v1).color(255, 255, 255, 255).endVertex(); - buf.vertex(m, x + p1, y + p1, 0F).uv(u1, v1).color(255, 255, 255, 255).endVertex(); - buf.vertex(m, x + p1, y + p0, 0F).uv(u1, v0).color(255, 255, 255, 255).endVertex(); - buf.vertex(m, x + p0, y + p0, 0F).uv(u0, v0).color(255, 255, 255, 255).endVertex(); - BufferUploader.drawWithShader(buf.end()); + var buf = Tesselator.getInstance().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX_COLOR); + buf.addVertex(m, x + p0, y + p1, 0F).setUv(u0, v1).setColor(255, 255, 255, 255); + buf.addVertex(m, x + p1, y + p1, 0F).setUv(u1, v1).setColor(255, 255, 255, 255); + buf.addVertex(m, x + p1, y + p0, 0F).setUv(u1, v0).setColor(255, 255, 255, 255); + buf.addVertex(m, x + p0, y + p0, 0F).setUv(u0, v0).setColor(255, 255, 255, 255); + BufferUploader.drawWithShader(buf.buildOrThrow()); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/util/NBTUtils.java b/src/main/java/dev/latvian/mods/kubejs/util/NBTUtils.java index 6f30c93bd..0bfaee18a 100644 --- a/src/main/java/dev/latvian/mods/kubejs/util/NBTUtils.java +++ b/src/main/java/dev/latvian/mods/kubejs/util/NBTUtils.java @@ -8,6 +8,7 @@ import com.google.gson.JsonPrimitive; import dev.latvian.mods.rhino.Context; import dev.latvian.mods.rhino.Undefined; +import dev.latvian.mods.rhino.type.TypeInfo; import io.netty.buffer.ByteBufInputStream; import io.netty.handler.codec.EncoderException; import net.minecraft.nbt.ByteArrayTag; @@ -45,6 +46,8 @@ import java.util.Map; public interface NBTUtils { + TypeInfo STRING_TAG_MAP_TYPE = TypeInfo.RAW_MAP.withParams(TypeInfo.STRING, TypeInfo.of(Tag.class)); + @Nullable static Object fromTag(@Nullable Tag t) { if (t == null || t instanceof EndTag) { 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 bc5e49e2c..94a965e69 100644 --- a/src/main/java/dev/latvian/mods/kubejs/util/UtilsJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/util/UtilsJS.java @@ -37,6 +37,7 @@ import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; @@ -48,7 +49,7 @@ public class UtilsJS { public static final Random RANDOM = new Random(); - public static final ResourceLocation AIR_LOCATION = new ResourceLocation("minecraft:air"); + public static final ResourceLocation AIR_LOCATION = ResourceLocation.parse("minecraft:air"); public static final Pattern SNAKE_CASE_SPLIT = Pattern.compile("[:_/]"); public static final Set ALWAYS_LOWER_CASE = new HashSet<>(Arrays.asList("a", "an", "the", "of", "on", "in", "and", "or", "but", "for")); public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; @@ -56,7 +57,7 @@ public class UtilsJS { public static final Predicate ALWAYS_TRUE = o -> true; 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); + private static final EntitySelector ALL_ENTITIES_SELECTOR = new EntitySelector(EntitySelector.INFINITE, true, false, List.of(), MinMaxBounds.Doubles.ANY, Function.identity(), null, EntitySelectorParser.ORDER_RANDOM, false, null, null, null, true); @FunctionalInterface public interface TryIO { diff --git a/src/main/resources/architectury.common.json b/src/main/resources/architectury.common.json index 724730c31..38ebffa70 100644 --- a/src/main/resources/architectury.common.json +++ b/src/main/resources/architectury.common.json @@ -57,9 +57,6 @@ "net/minecraft/class_1263": [ "dev/latvian/mods/kubejs/core/ContainerKJS" ], - "net/minecraft/class_1715": [ - "dev/latvian/mods/kubejs/core/CraftingContainerKJS" - ], "net/minecraft/class_8786": [ "dev/latvian/mods/kubejs/core/RecipeHolderKJS" ], @@ -80,9 +77,6 @@ ], "net/minecraft/class_1299": [ "dev/latvian/mods/kubejs/core/EntityTypeKJS" - ], - "net/minecraft/class_1887": [ - "dev/latvian/mods/kubejs/core/EnchantmentKJS" ] } } \ No newline at end of file diff --git a/src/main/resources/assets/kubejs/font/icons.json b/src/main/resources/assets/kubejs/font/icons.json index fa7d248d2..804fe4ff8 100644 --- a/src/main/resources/assets/kubejs/font/icons.json +++ b/src/main/resources/assets/kubejs/font/icons.json @@ -2,39 +2,69 @@ "providers": [ { "type": "bitmap", - "file": "kubejs:font/icons/k.png", + "file": "kubejs:font/icons/small_space.png", "ascent": 7, - "chars": ["K"] + "chars": ["."] }, { "type": "bitmap", - "file": "kubejs:font/icons/small_space.png", + "file": "kubejs:font/icons/kube.png", "ascent": 7, - "chars": ["."] + "chars": ["K"] }, { "type": "bitmap", - "file": "kubejs:font/icons/i.png", + "file": "kubejs:font/icons/info.png", "ascent": 7, "chars": ["I"] }, { "type": "bitmap", - "file": "kubejs:font/icons/w.png", + "file": "kubejs:font/icons/warn.png", "ascent": 7, "chars": ["W"] }, { "type": "bitmap", - "file": "kubejs:font/icons/y.png", + "file": "kubejs:font/icons/yes.png", "ascent": 7, "chars": ["Y"] }, { "type": "bitmap", - "file": "kubejs:font/icons/n.png", + "file": "kubejs:font/icons/no.png", "ascent": 7, "chars": ["N"] + }, + { + "type": "bitmap", + "file": "kubejs:font/icons/tag.png", + "ascent": 7, + "chars": ["T"] + }, + { + "type": "bitmap", + "file": "kubejs:font/icons/item_tag.png", + "ascent": 7, + "chars": ["J"] + }, + { + "type": "bitmap", + "file": "kubejs:font/icons/block_tag.png", + "ascent": 7, + "chars": ["B"] + }, + { + "type": "bitmap", + "file": "kubejs:font/icons/fluid_tag.png", + "ascent": 7, + "chars": ["F"] + }, + { + "type": "bitmap", + "file": "kubejs:font/icons/entity_type_tag.png", + "ascent": 7, + "chars": ["E"] } ] } \ No newline at end of file diff --git a/src/main/resources/assets/kubejs/textures/font/icons/block_tag.png b/src/main/resources/assets/kubejs/textures/font/icons/block_tag.png new file mode 100644 index 0000000000000000000000000000000000000000..e18ea7c5a59f351f283313093a5f18f5dd5bdf62 GIT binary patch literal 249 zcmeAS@N?(olHy`uVBq!ia0vp^93afW3?x5a^xFxf7>k44ofy`glX(f`u%tWsIx;Y9 z?C1WI$O`1^2Ka=y+Qpg1^#{6T*;q#!J0zOBW!qMUTJ3C&N%pqS$;p|P;}vPE>2Gal zrKJqi@%;b$A3%z~B*-uLKMG*Da%aXupcH3;M`SSr1K)lSX0%`pRsjlHdAc};NQBEC zixg^b;9w3kkeZ_U-Tqxb*?$}3`})%@3#{cN9at2r_a}s%o+UZ8TT`uAEI4-ah5026 YmfM&#r|7-%1De9%>FVdQ&MBb@0EA{y<^TWy literal 0 HcmV?d00001 diff --git a/src/main/resources/assets/kubejs/textures/font/icons/entity_type_tag.png b/src/main/resources/assets/kubejs/textures/font/icons/entity_type_tag.png new file mode 100644 index 0000000000000000000000000000000000000000..502c32247b3a81819123f1e632a032d821cded31 GIT binary patch literal 216 zcmeAS@N?(olHy`uVBq!ia0vp^93afW3?x5a^xFxf7>k44ofy`glX(f`u%tWsIx;Y9 z?C1WI$O`032l#}zzFWHF@$S)Wu z1qKYk{uM$X!2*v+pc=mYAk1jN8ms~oH1u?F43P+zJ#kQwL4k+qAa~co|6Qhs(w{fX xYG1|ZST*I)txey!{vB<8Y@D(G5#LX5J@F!jx6PR|Oo5siJYD@<);T3K0RTYzO1c05 literal 0 HcmV?d00001 diff --git a/src/main/resources/assets/kubejs/textures/font/icons/fluid_tag.png b/src/main/resources/assets/kubejs/textures/font/icons/fluid_tag.png new file mode 100644 index 0000000000000000000000000000000000000000..14d5fe5fe41618164e2f25608846154e996e6b2e GIT binary patch literal 220 zcmeAS@N?(olHy`uVBq!ia0vp^93afW3?x5a^xFxf7>k44ofy`glX(f`u%tWsIx;Y9 z?C1WI$O`1k1^9%xnwpxr?W*Sr{iQhzYlh5NuQ7N%?WIQ8aOK3e(GwDNj;9SZ$i)sAD>Z(RpG!PC{xWt~$(69D8CJ3s&c literal 0 HcmV?d00001 diff --git a/src/main/resources/assets/kubejs/textures/font/icons/k.png b/src/main/resources/assets/kubejs/textures/font/icons/kube.png similarity index 100% rename from src/main/resources/assets/kubejs/textures/font/icons/k.png rename to src/main/resources/assets/kubejs/textures/font/icons/kube.png diff --git a/src/main/resources/assets/kubejs/textures/font/icons/n.png b/src/main/resources/assets/kubejs/textures/font/icons/no.png similarity index 100% rename from src/main/resources/assets/kubejs/textures/font/icons/n.png rename to src/main/resources/assets/kubejs/textures/font/icons/no.png diff --git a/src/main/resources/assets/kubejs/textures/font/icons/tag.png b/src/main/resources/assets/kubejs/textures/font/icons/tag.png new file mode 100644 index 0000000000000000000000000000000000000000..7c2dbd19ad23621f0c0a915d8465b470b88af8cd GIT binary patch literal 223 zcmeAS@N?(olHy`uVBq!ia0vp^93afW3?x5a^xFxf7>k44ofy`glX(f`u%tWsIx;Y9 z?C1WI$O_~u2Ka=yK6wAWclP{qYjTfVyB5_l^V#v9s{Dktd-lY*h*uRR0aaZLea{A@ zxJ!ckg8#z-gO@+!C!jEAfk$L90|VcF5N5Ps4ORgP8hE-mhDd~~c02MhC~zERa4q~_ zzd`!VCAG6Wb9OolaYs*jK27CwYY~s8^RldO-OP4Q` (Ljava/util/UUID;DLnet/minecraft/world/entity/ai/attributes/AttributeModifier$Operation;)V +accessible method net/minecraft/world/effect/MobEffect$AttributeTemplate (Lnet/minecraft/resources/ResourceLocation;DLnet/minecraft/world/entity/ai/attributes/AttributeModifier$Operation;)V accessible field net/minecraft/world/item/ArmorItem defaultModifiers Ljava/util/function/Supplier; mutable field net/minecraft/world/item/ArmorItem defaultModifiers Ljava/util/function/Supplier; @@ -68,7 +68,7 @@ accessible method net/minecraft/world/item/crafting/ShapedRecipePattern matches accessible field net/minecraft/server/level/ServerPlayerGameMode isDestroyingBlock Z accessible method net/minecraft/server/commands/TeleportCommand performTeleport (Lnet/minecraft/commands/CommandSourceStack;Lnet/minecraft/world/entity/Entity;Lnet/minecraft/server/level/ServerLevel;DDDLjava/util/Set;FFLnet/minecraft/server/commands/TeleportCommand$LookAt;)V -accessible field net/minecraft/commands/arguments/selector/EntitySelector predicate Ljava/util/function/Predicate; +accessible field net/minecraft/commands/arguments/selector/EntitySelector contextFreePredicates Ljava/util/List; accessible field net/minecraft/world/level/storage/loot/LootContext$EntityTarget name Ljava/lang/String; accessible field net/minecraft/world/level/storage/loot/LootDataType codec Lcom/mojang/serialization/Codec; accessible method net/minecraft/world/level/storage/loot/functions/SetComponentsFunction (Ljava/util/List;Lnet/minecraft/core/component/DataComponentPatch;)V diff --git a/src/main/resources/kubejs.mixins.json b/src/main/resources/kubejs.mixins.json index 4727d4e14..bf40fca35 100644 --- a/src/main/resources/kubejs.mixins.json +++ b/src/main/resources/kubejs.mixins.json @@ -14,14 +14,12 @@ "CommandSourceStackMixin", "CompoundTagMixin", "ContainerMixin", - "CraftingContainerMixin", "CreativeModeTabMixin", "CropBlockMixin", "DamageSourceMixin", "DifferenceIngredientMixin", "DirectionMixin", "DyeColorMixin", - "EnchantmentMixin", "EntityMixin", "EntityTypeMixin", "FireworkRocketEntityMixin", @@ -45,6 +43,7 @@ "PlayerListMixin", "PlayerMixin", "RecipeHolderMixin", + "RecipeInputMixin", "RecipeManagerMixin", "ReloadableServerResourcesMixin", "ResourceKeyMixin",