From ba204e2bc02b9307afa0e592a1d0c9cece0c5967 Mon Sep 17 00:00:00 2001 From: Osip Fatkullin Date: Mon, 16 Nov 2026 10:39:31 +0100 Subject: [PATCH 01/11] feat: Add BlockProvider.hasBlock Mimic asks the provider whether a block exists instead of looking for the ID in allBlocks. By default, it still looks there, but a provider may override it with a faster check, or if it can't list its blocks. Co-Authored-By: Claude Fable 5.2 --- mimic-bukkit-api/api/mimic-bukkit-api.api | 1 + .../src/main/kotlin/blocks/BlockProvider.kt | 8 ++++++- .../kotlin/blocks/WrappedBlockProvider.kt | 1 + .../craftengine/CraftEngineBlockProvider.kt | 11 +++------ .../src/main/kotlin/impl/mimic/MimicBlocks.kt | 2 +- .../test/kotlin/impl/mimic/MimicBlocksTest.kt | 24 +++++++++++++++++++ 6 files changed, 37 insertions(+), 10 deletions(-) diff --git a/mimic-bukkit-api/api/mimic-bukkit-api.api b/mimic-bukkit-api/api/mimic-bukkit-api.api index f6de0b67..f0efab70 100644 --- a/mimic-bukkit-api/api/mimic-bukkit-api.api +++ b/mimic-bukkit-api/api/mimic-bukkit-api.api @@ -49,6 +49,7 @@ public abstract interface class ru/endlesscode/mimic/blocks/BlockProvider : ru/e public abstract fun getAllBlocks ()Ljava/util/Collection; public abstract fun getBlockId (Lorg/bukkit/block/Block;)Ljava/lang/String; public abstract fun getBlockIdFromItem (Lorg/bukkit/inventory/ItemStack;)Ljava/lang/String; + public fun hasBlock (Ljava/lang/String;)Z public abstract fun setBlock (Lorg/bukkit/block/Block;Ljava/lang/String;Ljava/lang/String;)Z } diff --git a/mimic-bukkit-api/src/main/kotlin/blocks/BlockProvider.kt b/mimic-bukkit-api/src/main/kotlin/blocks/BlockProvider.kt index ac2c51ad..12a26518 100644 --- a/mimic-bukkit-api/src/main/kotlin/blocks/BlockProvider.kt +++ b/mimic-bukkit-api/src/main/kotlin/blocks/BlockProvider.kt @@ -55,10 +55,16 @@ public interface BlockProvider : MimicService { /** * IDs of all blocks this provider knows. * The list may change while the plugin loads or reloads its data, so it is read on every request. - * Return a [Set] if you can, Mimic uses it to check that a block exists. */ public val allBlocks: Collection + /** + * Returns `true` if the block with [blockId] exists. By default, looks for the ID in [allBlocks]. + * Override it if your plugin can check a block faster, or can't list all its blocks. + * It should return `true` at least for every ID from [allBlocks]. + */ + public fun hasBlock(@KeyPattern.Value blockId: String): Boolean = blockId in allBlocks + /** Returns ID of the [block], or `null` if it isn't a block of this provider. */ public fun getBlockId(block: Block): String? diff --git a/mimic-bukkit/src/main/kotlin/blocks/WrappedBlockProvider.kt b/mimic-bukkit/src/main/kotlin/blocks/WrappedBlockProvider.kt index 83817fc7..16b6ec7c 100644 --- a/mimic-bukkit/src/main/kotlin/blocks/WrappedBlockProvider.kt +++ b/mimic-bukkit/src/main/kotlin/blocks/WrappedBlockProvider.kt @@ -16,6 +16,7 @@ internal class WrappedBlockProvider( override val allBlocks: Collection get() = delegate.allBlocks + override fun hasBlock(blockId: String): Boolean = delegate.hasBlock(blockId) override fun getBlockId(block: Block): String? = delegate.getBlockId(block) override fun getBlockIdFromItem(item: ItemStack): String? = delegate.getBlockIdFromItem(item) override fun createBlockItem(blockId: String, amount: Int): ItemStack? = delegate.createBlockItem(blockId, amount) diff --git a/mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineBlockProvider.kt b/mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineBlockProvider.kt index 110cbfce..8033af34 100644 --- a/mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineBlockProvider.kt +++ b/mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineBlockProvider.kt @@ -31,15 +31,10 @@ internal class CraftEngineBlockProvider private constructor( override val id: String = ID override val isEnabled: Boolean get() = craftEngine.isEnabled - /** A view of the loaded blocks, so checking that a block exists doesn't convert all IDs. */ - override val allBlocks: Set = object : AbstractSet() { - override val size: Int get() = craftEngine.loadedBlockIds.size + override val allBlocks: Collection + get() = craftEngine.loadedBlockIds.map(Key::toMimicId) - override fun iterator(): Iterator = - craftEngine.loadedBlockIds.asSequence().map(Key::toMimicId).iterator() - - override fun contains(element: String): Boolean = craftEngineKey(element) in craftEngine.loadedBlockIds - } + override fun hasBlock(blockId: String): Boolean = findBlock(blockId) != null override fun getBlockId(block: Block): String? { val state = getCustomBlockState(block) ?: return null diff --git a/mimic-bukkit/src/main/kotlin/impl/mimic/MimicBlocks.kt b/mimic-bukkit/src/main/kotlin/impl/mimic/MimicBlocks.kt index 6d4b6399..4d1cbeee 100644 --- a/mimic-bukkit/src/main/kotlin/impl/mimic/MimicBlocks.kt +++ b/mimic-bukkit/src/main/kotlin/impl/mimic/MimicBlocks.kt @@ -60,7 +60,7 @@ internal class MimicBlocks(blockProviders: ServiceRegistry) : Blo private fun findProvider(blockId: Key): BlockProviderEntry? = providers.find(blockId, BLOCK) { path -> hasBlock(path) } - private fun BlockProviderEntry.hasBlock(path: String): Boolean = call(default = false) { path in allBlocks } + private fun BlockProviderEntry.hasBlock(path: String): Boolean = call(default = false) { hasBlock(path) } // IDs are checked inside call, so a provider returning nulls from Java is skipped private fun BlockProviderEntry.getAllBlocks(): List = diff --git a/mimic-bukkit/src/test/kotlin/impl/mimic/MimicBlocksTest.kt b/mimic-bukkit/src/test/kotlin/impl/mimic/MimicBlocksTest.kt index 49d38f25..4ea593b7 100644 --- a/mimic-bukkit/src/test/kotlin/impl/mimic/MimicBlocksTest.kt +++ b/mimic-bukkit/src/test/kotlin/impl/mimic/MimicBlocksTest.kt @@ -85,6 +85,17 @@ internal class MimicBlocksTest : BukkitTestBase() { blocks.hasBlock(Key.key(blockId)) shouldBe shouldExist } + @Test + fun `when provider can't list its blocks - should ask it whether a block exists`() { + blockProviders.register(UnlistedBlockProvider(), plugin, Normal) + + assertSoftly { + blocks.hasBlock(Key.key("unlisted:ruby_block")).shouldBeTrue() + blocks.hasBlock(Key.key("unlisted:stone")).shouldBeFalse() + blocks.getAllBlocks().filter { it.namespace() == "unlisted" }.shouldBeEmpty() + } + } + @ParameterizedTest @CsvSource( "STONE, minecraft:stone", @@ -415,6 +426,19 @@ private class CustomBlockProvider : BlockProvider { } } +/** Provider imitating a plugin which can't list its blocks. */ +private class UnlistedBlockProvider : BlockProvider { + override val id = "unlisted" + override val allBlocks = emptyList() + + override fun hasBlock(blockId: String): Boolean = blockId == "ruby_block" + override fun getBlockId(block: Block): String? = null + override fun getBlockIdFromItem(item: ItemStack): String? = null + override fun createBlockItem(blockId: String, amount: Int): ItemStack? = null + override fun setBlock(block: Block, blockId: String, state: String?): Boolean = false + override fun breakBlock(block: Block, tool: ItemStack?, dropsConsumer: DropsConsumer): Boolean = false +} + /** Provider returning invalid IDs. */ private class InvalidIdBlockProvider : BlockProvider { override val id = "invalid" From 8856bcc8c3be8ea57f5e73e0cdc696e943b0836f Mon Sep 17 00:00:00 2001 From: Osip Fatkullin Date: Mon, 16 Nov 2026 11:34:21 +0100 Subject: [PATCH 02/11] feat: Treat blank block state as the default state Mimic passes a blank state to block providers as null, so providers don't have to handle it. Co-Authored-By: Claude Fable 5.2 --- .../src/main/kotlin/blocks/BlockProvider.kt | 2 +- mimic-bukkit-api/src/main/kotlin/blocks/Blocks.kt | 2 +- mimic-bukkit/src/main/kotlin/impl/mimic/MimicBlocks.kt | 3 ++- .../src/test/kotlin/impl/mimic/MimicBlocksTest.kt | 10 ++++++++++ 4 files changed, 14 insertions(+), 3 deletions(-) diff --git a/mimic-bukkit-api/src/main/kotlin/blocks/BlockProvider.kt b/mimic-bukkit-api/src/main/kotlin/blocks/BlockProvider.kt index 12a26518..1fe3b102 100644 --- a/mimic-bukkit-api/src/main/kotlin/blocks/BlockProvider.kt +++ b/mimic-bukkit-api/src/main/kotlin/blocks/BlockProvider.kt @@ -87,7 +87,7 @@ public interface BlockProvider : MimicService { * Apply block physics as usual, so neighboring blocks are updated. * * @param state State of the block in the format of its provider, usually block state properties - * like `[facing=north]`, or `null` for the default state. + * like `[facing=north]`, or `null` for the default state. It is never blank. * If the state is invalid, log a warning and don't set the block. * @return `false` if the ID is unknown, the state is invalid, or the block can't be set. */ diff --git a/mimic-bukkit-api/src/main/kotlin/blocks/Blocks.kt b/mimic-bukkit-api/src/main/kotlin/blocks/Blocks.kt index 7f18c030..c711365b 100644 --- a/mimic-bukkit-api/src/main/kotlin/blocks/Blocks.kt +++ b/mimic-bukkit-api/src/main/kotlin/blocks/Blocks.kt @@ -102,7 +102,7 @@ public interface Blocks { * Block physics is applied as usual, so neighboring blocks are updated. * * @param state State of the block in the format of its provider, usually block state properties - * like `[facing=north]`, or `null` for the default state. + * like `[facing=north]`. A blank state is the same as `null`: the default state. * If the state is invalid, the block is not set and a warning is logged. * @return `false` if the [block] is not empty, the ID is unknown, the state is invalid, or the block can't be set. */ diff --git a/mimic-bukkit/src/main/kotlin/impl/mimic/MimicBlocks.kt b/mimic-bukkit/src/main/kotlin/impl/mimic/MimicBlocks.kt index 4d1cbeee..a8a1dd07 100644 --- a/mimic-bukkit/src/main/kotlin/impl/mimic/MimicBlocks.kt +++ b/mimic-bukkit/src/main/kotlin/impl/mimic/MimicBlocks.kt @@ -49,7 +49,8 @@ internal class MimicBlocks(blockProviders: ServiceRegistry) : Blo override fun setBlock(block: Block, blockId: Key, state: String?): Boolean { if (!block.isEmpty) return false val provider = findProvider(blockId) ?: return false - return provider.call(default = false) { setBlock(block, blockId.value(), state) } + val nonBlankState = state?.takeIf { it.isNotBlank() } + return provider.call(default = false) { setBlock(block, blockId.value(), nonBlankState) } } override fun breakBlock(block: Block, tool: ItemStack?, dropsConsumer: DropsConsumer): Boolean { diff --git a/mimic-bukkit/src/test/kotlin/impl/mimic/MimicBlocksTest.kt b/mimic-bukkit/src/test/kotlin/impl/mimic/MimicBlocksTest.kt index 4ea593b7..b8bd83a3 100644 --- a/mimic-bukkit/src/test/kotlin/impl/mimic/MimicBlocksTest.kt +++ b/mimic-bukkit/src/test/kotlin/impl/mimic/MimicBlocksTest.kt @@ -190,6 +190,16 @@ internal class MimicBlocksTest : BukkitTestBase() { } } + @ParameterizedTest + @ValueSource(strings = ["", " "]) + fun `when set block with blank state - should pass null to the provider`(state: String) { + // The fake provider keeps the last state, so set it first to see that it is replaced + blocks.setBlock(mockBlock(Material.AIR), Key.key("minecraft:stone"), "[facing=north]") + + blocks.setBlock(mockBlock(Material.AIR), Key.key("minecraft:stone"), state).shouldBeTrue() + minecraft.lastState.shouldBeNull() + } + @Test fun `when set custom block - should set block`() { val block = mockBlock(Material.AIR) From 9e4df10fc597ec8df68194cdb2c8884deeeb0ef6 Mon Sep 17 00:00:00 2001 From: Osip Fatkullin Date: Mon, 16 Nov 2026 10:21:27 +0100 Subject: [PATCH 03/11] refactor: Extract item building helpers from items registries Co-Authored-By: Claude Fable 5.2 --- .../kotlin/impl/mmoitems/MmoItemsRegistry.kt | 14 +++-------- .../kotlin/impl/mmoitems/MmoItemsWrapper.kt | 25 ++++++++++++++++--- .../kotlin/impl/vanilla/ItemMetaPayload.kt | 19 ++++++++++++++ .../impl/vanilla/MinecraftItemsRegistry.kt | 19 -------------- 4 files changed, 43 insertions(+), 34 deletions(-) diff --git a/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsRegistry.kt b/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsRegistry.kt index 9071ef9b..7253701c 100644 --- a/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsRegistry.kt +++ b/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsRegistry.kt @@ -18,29 +18,21 @@ public class MmoItemsRegistry private constructor(private val mmoItems: MmoItems get() = templates.map { it.id.lowercase() } private val templates: Collection - get() = mmoItems.templatesManager.collectTemplates() + get() = mmoItems.templates override fun isItemExists(itemId: String): Boolean = itemId in knownIds override fun getItemId(item: ItemStack): String? { - val nbtItem = mmoItems.getNbtItem(item) - return nbtItem.getString("MMOITEMS_ITEM_ID")?.lowercase() + return mmoItems.getId(item)?.lowercase() } override fun getItem(itemId: String, payload: Any?, amount: Int): ItemStack? { val template = templates.find { it.id.equals(itemId, ignoreCase = true) } ?: return null - return template.buildItemStack() + return mmoItems.buildItem(template, player = null) ?.also { it.amount = amount.coerceIn(1, it.maxStackSize) } } - private fun MMOItemTemplate.buildItemStack(): ItemStack? { - return newBuilder(0, null) - .build() - .newBuilder() - .build() - } - public companion object { public const val ID: String = "mmoitems" } diff --git a/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsWrapper.kt b/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsWrapper.kt index ed364431..f96bced9 100644 --- a/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsWrapper.kt +++ b/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsWrapper.kt @@ -3,15 +3,32 @@ package ru.endlesscode.mimic.impl.mmoitems -import io.lumine.mythic.lib.api.item.NBTItem import net.Indyuce.mmoitems.MMOItems -import net.Indyuce.mmoitems.manager.TemplateManager +import net.Indyuce.mmoitems.api.item.template.MMOItemTemplate +import org.bukkit.entity.Player import org.bukkit.inventory.ItemStack internal class MmoItemsWrapper { val isEnabled: Boolean get() = MMOItems.plugin.isEnabled - val templatesManager: TemplateManager get() = MMOItems.plugin.templates + val templates: Collection get() = MMOItems.plugin.templates.collectTemplates() - fun getNbtItem(item: ItemStack): NBTItem = NBTItem.get(item) + /** Returns name of the item type like `SWORD`. */ + fun getTypeName(template: MMOItemTemplate): String = template.type.id + + /** Returns name of the item type like `SWORD`, or `null` if the [item] isn't an MMOItems item. */ + fun getTypeName(item: ItemStack): String? = MMOItems.getTypeName(item) + + /** Returns ID of the [item] within its type, or `null` if the [item] isn't an MMOItems item. */ + fun getId(item: ItemStack): String? = MMOItems.getID(item)?.takeIf { it.isNotEmpty() } + + /** + * Builds an item from the [template]. + * If the [player] is given, the item is built for them as MMOItems does, for example, scaled to their level. + * Otherwise, the item has no tier and no level. + */ + fun buildItem(template: MMOItemTemplate, player: Player?): ItemStack? { + val builder = if (player != null) template.newBuilder(player) else template.newBuilder(0, null) + return builder.build().newBuilder().build() + } } diff --git a/mimic-bukkit/src/main/kotlin/impl/vanilla/ItemMetaPayload.kt b/mimic-bukkit/src/main/kotlin/impl/vanilla/ItemMetaPayload.kt index 69861b28..b30e3472 100644 --- a/mimic-bukkit/src/main/kotlin/impl/vanilla/ItemMetaPayload.kt +++ b/mimic-bukkit/src/main/kotlin/impl/vanilla/ItemMetaPayload.kt @@ -13,6 +13,8 @@ import kotlinx.serialization.hocon.decodeFromConfig import net.kyori.adventure.text.Component import org.bukkit.enchantments.Enchantment import org.bukkit.inventory.ItemFlag +import org.bukkit.inventory.meta.Damageable +import org.bukkit.inventory.meta.ItemMeta import ru.endlesscode.mimic.internal.* /** @@ -85,3 +87,20 @@ public data class ItemMetaPayload( } } } + +internal fun ItemMeta.applyPayload(payload: ItemMetaPayload): ItemMeta { + // Apply text options + displayName(payload.name) + lore(payload.lore) + + // Apply damage and custom model data + isUnbreakable = payload.isUnbreakable + (this as? Damageable)?.damage = payload.damage + if (payload.customModelData != null) setCustomModelData(payload.customModelData) + + // Apply enchants and item flags + payload.enchantments.forEach { (enchant, level) -> addEnchant(enchant, level, true) } + addItemFlags(*payload.flags.toTypedArray()) + + return this +} diff --git a/mimic-bukkit/src/main/kotlin/impl/vanilla/MinecraftItemsRegistry.kt b/mimic-bukkit/src/main/kotlin/impl/vanilla/MinecraftItemsRegistry.kt index 7ec3ee65..53155cba 100644 --- a/mimic-bukkit/src/main/kotlin/impl/vanilla/MinecraftItemsRegistry.kt +++ b/mimic-bukkit/src/main/kotlin/impl/vanilla/MinecraftItemsRegistry.kt @@ -6,8 +6,6 @@ package ru.endlesscode.mimic.impl.vanilla import org.bukkit.Bukkit import org.bukkit.Material import org.bukkit.inventory.ItemStack -import org.bukkit.inventory.meta.Damageable -import org.bukkit.inventory.meta.ItemMeta import ru.endlesscode.mimic.internal.Log import ru.endlesscode.mimic.items.BukkitItemsRegistry @@ -67,23 +65,6 @@ public class MinecraftItemsRegistry : BukkitItemsRegistry { ?.takeIf { it.isItem } } - private fun ItemMeta.applyPayload(payload: ItemMetaPayload): ItemMeta { - // Apply text options - displayName(payload.name) - lore(payload.lore) - - // Apply damage and custom model data - isUnbreakable = payload.isUnbreakable - (this as? Damageable)?.damage = payload.damage - if (payload.customModelData != null) setCustomModelData(payload.customModelData) - - // Apply enchants and item flags - payload.enchantments.forEach { (enchant, level) -> addEnchant(enchant, level, true) } - addItemFlags(*payload.flags.toTypedArray()) - - return this - } - public companion object { public const val ID: String = "minecraft" } From 2a4e3e472b4aa3cab657c59fe5cbf99865cd4b78 Mon Sep 17 00:00:00 2001 From: Osip Fatkullin Date: Mon, 16 Nov 2026 10:35:29 +0100 Subject: [PATCH 04/11] feat: Introduce Items API ItemProvider is implemented by plugins to expose their items, Items is the consumer API combining items of all providers. Item IDs are Keys with the provider ID as a required namespace. Co-Authored-By: Claude Fable 5.2 --- mimic-api/src/main/kotlin/MimicApiLevel.kt | 1 + mimic-bukkit-api/api/mimic-bukkit-api.api | 19 ++++ .../src/main/kotlin/items/ItemProvider.kt | 89 +++++++++++++++++ .../src/main/kotlin/items/Items.kt | 99 +++++++++++++++++++ 4 files changed, 208 insertions(+) create mode 100644 mimic-bukkit-api/src/main/kotlin/items/ItemProvider.kt create mode 100644 mimic-bukkit-api/src/main/kotlin/items/Items.kt diff --git a/mimic-api/src/main/kotlin/MimicApiLevel.kt b/mimic-api/src/main/kotlin/MimicApiLevel.kt index fd7d81f0..bbf92d63 100644 --- a/mimic-api/src/main/kotlin/MimicApiLevel.kt +++ b/mimic-api/src/main/kotlin/MimicApiLevel.kt @@ -53,6 +53,7 @@ public object MimicApiLevel { /** * # Version 0.11 * - Blocks API, experimental BlockRegistry API is removed + * - Items API, ItemsRegistry API is deprecated */ public const val VERSION_0_11: Int = 7 diff --git a/mimic-bukkit-api/api/mimic-bukkit-api.api b/mimic-bukkit-api/api/mimic-bukkit-api.api index f0efab70..0148889a 100644 --- a/mimic-bukkit-api/api/mimic-bukkit-api.api +++ b/mimic-bukkit-api/api/mimic-bukkit-api.api @@ -152,6 +152,25 @@ public abstract interface class ru/endlesscode/mimic/inventory/BukkitPlayerInven public abstract interface class ru/endlesscode/mimic/items/BukkitItemsRegistry : ru/endlesscode/mimic/items/ItemsRegistry { } +public abstract interface class ru/endlesscode/mimic/items/ItemProvider : ru/endlesscode/mimic/MimicService { + public abstract fun createItem (Ljava/lang/String;ILorg/bukkit/entity/Player;Ljava/lang/String;)Lorg/bukkit/inventory/ItemStack; + public abstract fun getAllItems ()Ljava/util/Collection; + public abstract fun getItemId (Lorg/bukkit/inventory/ItemStack;)Ljava/lang/String; + public fun hasItem (Ljava/lang/String;)Z +} + +public abstract interface class ru/endlesscode/mimic/items/Items { + public fun createItem (Lnet/kyori/adventure/key/Key;)Lorg/bukkit/inventory/ItemStack; + public fun createItem (Lnet/kyori/adventure/key/Key;I)Lorg/bukkit/inventory/ItemStack; + public fun createItem (Lnet/kyori/adventure/key/Key;ILorg/bukkit/entity/Player;)Lorg/bukkit/inventory/ItemStack; + public abstract fun createItem (Lnet/kyori/adventure/key/Key;ILorg/bukkit/entity/Player;Ljava/lang/String;)Lorg/bukkit/inventory/ItemStack; + public static synthetic fun createItem$default (Lru/endlesscode/mimic/items/Items;Lnet/kyori/adventure/key/Key;ILorg/bukkit/entity/Player;Ljava/lang/String;ILjava/lang/Object;)Lorg/bukkit/inventory/ItemStack; + public abstract fun getAllItems ()Ljava/util/List; + public abstract fun getItemId (Lorg/bukkit/inventory/ItemStack;)Lnet/kyori/adventure/key/Key; + public abstract fun hasItem (Lnet/kyori/adventure/key/Key;)Z + public abstract fun isItem (Lorg/bukkit/inventory/ItemStack;Lnet/kyori/adventure/key/Key;)Z +} + public abstract class ru/endlesscode/mimic/level/BukkitLevelSystem : ru/endlesscode/mimic/level/LevelSystem { public fun (Lorg/bukkit/entity/Player;)V public final fun getPlayer ()Lorg/bukkit/entity/Player; diff --git a/mimic-bukkit-api/src/main/kotlin/items/ItemProvider.kt b/mimic-bukkit-api/src/main/kotlin/items/ItemProvider.kt new file mode 100644 index 00000000..8e718136 --- /dev/null +++ b/mimic-bukkit-api/src/main/kotlin/items/ItemProvider.kt @@ -0,0 +1,89 @@ +// Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors +// SPDX-License-Identifier: MIT + +package ru.endlesscode.mimic.items + +import net.kyori.adventure.key.KeyPattern +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack +import ru.endlesscode.mimic.MimicService + +/** + * Implement it to make your plugin's items available via [Items]. + * Register it in `onLoad` via [Mimic.registerItemProvider][ru.endlesscode.mimic.Mimic.registerItemProvider]. + * To create or identify items, use [Items] instead. + * + * ### IDs + * + * Mimic adds your provider [id] as the namespace, so receive and return IDs without it: + * `ruby_sword` becomes `myplugin:ruby_sword`. Don't change [id] later, it breaks consumers' configs. + * + * If your plugin has its own namespaced IDs, convert them to paths: + * - Drop your plugin's own namespace: `myplugin:ruby_sword` -> `ruby_sword`. + * - Keep other namespaces as the first path part: `default:palm_log` -> `default/palm_log`. + * + * Other rules: + * - Allowed characters: `a-z`, `0-9`, `.`, `_`, `-` and `/`. Items with other characters are ignored. + * - To convert other IDs, lowercase them and replace other characters with `_`. + * Keep a map back to the original IDs. + * - If two IDs become the same (`Ruby_Sword` and `ruby_sword`), log a warning and keep one of them. + * + * ### Ownership + * + * An item belongs to the provider with the highest priority that returns an ID for it. + * So return an ID only for your items, and `null` for the rest, including the vanilla items your items are built on. + * Vanilla items belong to Mimic's own `minecraft` provider, which is always asked last. + * + * ### Rules + * + * - Never throw. Return `null` instead. + * - Item IDs may be unknown until your plugin loads its data. Return `null` for them until then. + * - [allItems], [hasItem] and [getItemId] may be called from any thread, [createItem] is called on the main thread. + * - Document the format of the payload your provider takes, or that it takes none. + * + * Mimic does the rest: selects the provider by the item ID namespace, finds the owner of an item, + * compares items by ID, limits the amount of the created stack, and catches errors thrown by the provider. + * + * @since 0.11.0 + */ +public interface ItemProvider : MimicService { + + /** + * IDs of all items this provider knows. + * The list may change while the plugin loads or reloads its data, so it is read on every request. + */ + public val allItems: Collection + + /** + * Returns `true` if the item with [itemId] exists. By default, looks for the ID in [allItems]. + * Override it if your plugin can check an item faster, or can't list all its items. + * It should return `true` at least for every ID from [allItems]. + */ + public fun hasItem(@KeyPattern.Value itemId: String): Boolean = itemId in allItems + + /** + * Returns ID of the [item], or `null` if it isn't an item of this provider. + * Amount, stats, durability and lore of the stack don't affect the ID. + */ + public fun getItemId(item: ItemStack): String? + + /** + * Creates a new stack of the item with [itemId]. + * The caller owns the returned stack, so never return a shared one. + * + * @param amount Amount of items, at least `1`. If it is greater than the maximum stack size, + * Mimic lowers the amount of the returned stack. + * @param player The player the item is created for, or `null` if there is no such player. + * Use it if the item depends on the player, like items scaled to the player's level. + * @param payload Additional configuration of the item in the format of this provider, or `null`. It is never blank. + * If the provider takes no payload, ignore it. If the payload can't be parsed, return `null`: + * Mimic logs a warning with the item ID and the payload. + * @return the stack, or `null` if the ID is unknown or the payload is invalid. + */ + public fun createItem( + @KeyPattern.Value itemId: String, + amount: Int, + player: Player?, + payload: String?, + ): ItemStack? +} diff --git a/mimic-bukkit-api/src/main/kotlin/items/Items.kt b/mimic-bukkit-api/src/main/kotlin/items/Items.kt new file mode 100644 index 00000000..66bb7345 --- /dev/null +++ b/mimic-bukkit-api/src/main/kotlin/items/Items.kt @@ -0,0 +1,99 @@ +// Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors +// SPDX-License-Identifier: MIT + +package ru.endlesscode.mimic.items + +import net.kyori.adventure.key.Key +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack + +/** + * Vanilla items and custom items from all plugins supported by Mimic. + * Get it via [Mimic.items][ru.endlesscode.mimic.Mimic.items]. + * To make your own plugin's items available here, implement [ItemProvider] instead. + * + * ### Quick start + * + * ```java + * Key excalibur = Key.key("mmoitems:sword/excalibur"); + * + * // Check the ID read from a config + * if (!items.hasItem(excalibur)) { ... } + * + * // Create an item for the player + * ItemStack sword = items.createItem(excalibur, 1, player); + * + * // Identify an item + * if (items.isItem(player.getInventory().getItemInMainHand(), excalibur)) { ... } + * ``` + * + * ### IDs + * + * Items are identified by [Key], which consists of a namespace and a path: + * - The namespace is the ID of the plugin providing the item: `minecraft`, `mmoitems`, `craftengine`. + * - The path is the item within that plugin: `diamond`, `sword/excalibur`, `default/palm_log`. + * + * The namespace is required, there is no search over all plugins. + * Note that `Key.key("excalibur")` turns into `minecraft:excalibur`, + * so validate item IDs read from configs with [hasItem] or against [getAllItems]. + * + * ### Ownership + * + * An item belongs to the plugin with the highest priority that recognizes it, and vanilla items belong to `minecraft`. + * So a custom item is never recognized as the vanilla item it is built on: + * a ruby built on a diamond is not `minecraft:diamond`. + * To check the vanilla item regardless of plugins, use [ItemStack.getType]. + * + * ### Rules + * + * - [createItem] must be called on the main thread, other methods may be called from any thread. + * - Item IDs may be unknown until their plugins finish loading, and may change when a plugin reloads. + * Don't validate configs in `onLoad`, and don't keep created stacks across reloads. + * - `null` or `false` means "not possible": the item doesn't exist, no plugin recognizes it, or the payload is invalid. + * + * @since 0.11.0 + */ +public interface Items { + + /** + * Returns IDs of all items of all providers. Use it for config validation and tab completion. + * IDs are sorted by provider priority, then in the order the provider returns them. + */ + public fun getAllItems(): List + + /** Returns `true` if the item with [itemId] exists. */ + public fun hasItem(itemId: Key): Boolean + + /** Returns ID of the [item] in the provider owning it, or `null` if no provider recognizes the item. */ + public fun getItemId(item: ItemStack): Key? + + /** + * Returns `true` if the [item] has [itemId]. Same as `getItemId(item) == itemId`: + * amount, stats, durability and lore of the stack are ignored. + */ + public fun isItem(item: ItemStack, itemId: Key): Boolean + + /** Creates a new stack with a single item with [itemId]. */ + public fun createItem(itemId: Key): ItemStack? = createItem(itemId, amount = 1) + + /** Creates a new stack of the item with [itemId] and the given [amount]. */ + public fun createItem(itemId: Key, amount: Int): ItemStack? = createItem(itemId, amount, player = null) + + /** Creates a new stack of the item with [itemId] and the given [amount] for the [player]. */ + public fun createItem(itemId: Key, amount: Int, player: Player?): ItemStack? = + createItem(itemId, amount, player, payload = null) + + /** + * Creates a new stack of the item with [itemId]. The caller owns the returned stack. + * + * @param amount Amount of items. It is kept within `1` and the maximum stack size of the item. + * @param player The player the item is created for, or `null` if there is no such player. + * Some items depend on the player, like items scaled to the player's level. + * @param payload Additional configuration of the item in the format of its provider. + * A blank payload is the same as `null`. + * For example, `minecraft` takes item components like `[damage=10]`. + * Providers taking no payload ignore it. If the payload is invalid, the item is not created and a warning is logged. + * @return the stack, or `null` if the ID is unknown or the payload is invalid. + */ + public fun createItem(itemId: Key, amount: Int = 1, player: Player? = null, payload: String? = null): ItemStack? +} From 30a2e10ac25d0727a62895a7ace3e2b517e46651 Mon Sep 17 00:00:00 2001 From: Osip Fatkullin Date: Mon, 16 Nov 2026 10:35:52 +0100 Subject: [PATCH 05/11] feat: Implement Items API MimicItems combines items of all item providers, using provider IDs as namespaces. An item belongs to the provider with the highest priority recognizing it. Mimic.registerItemProvider and Mimic.items give access to it. Co-Authored-By: Claude Fable 5.2 --- mimic-bukkit-api/api/mimic-bukkit-api.api | 3 + mimic-bukkit-api/src/main/kotlin/Mimic.kt | 51 +++ mimic-bukkit/src/main/kotlin/MimicImpl.kt | 22 ++ .../src/main/kotlin/impl/mimic/MimicItems.kt | 79 ++++ .../main/kotlin/items/WrappedItemProvider.kt | 25 ++ .../test/kotlin/impl/mimic/MimicItemsTest.kt | 370 ++++++++++++++++++ 6 files changed, 550 insertions(+) create mode 100644 mimic-bukkit/src/main/kotlin/impl/mimic/MimicItems.kt create mode 100644 mimic-bukkit/src/main/kotlin/items/WrappedItemProvider.kt create mode 100644 mimic-bukkit/src/test/kotlin/impl/mimic/MimicItemsTest.kt diff --git a/mimic-bukkit-api/api/mimic-bukkit-api.api b/mimic-bukkit-api/api/mimic-bukkit-api.api index 0148889a..3c08c020 100644 --- a/mimic-bukkit-api/api/mimic-bukkit-api.api +++ b/mimic-bukkit-api/api/mimic-bukkit-api.api @@ -9,6 +9,7 @@ public abstract interface class ru/endlesscode/mimic/Mimic { public abstract fun getClassSystemProvider ()Lru/endlesscode/mimic/classes/BukkitClassSystem$Provider; public abstract fun getClasses ()Lru/endlesscode/mimic/classes/Classes; public static fun getInstance ()Lru/endlesscode/mimic/Mimic; + public abstract fun getItems ()Lru/endlesscode/mimic/items/Items; public abstract fun getItemsRegistry ()Lru/endlesscode/mimic/items/BukkitItemsRegistry; public fun getLevelSystem (Lorg/bukkit/entity/Player;)Lru/endlesscode/mimic/level/BukkitLevelSystem; public abstract fun getLevelSystemProvider ()Lru/endlesscode/mimic/level/BukkitLevelSystem$Provider; @@ -22,6 +23,8 @@ public abstract interface class ru/endlesscode/mimic/Mimic { public abstract fun registerClassProvider (Lru/endlesscode/mimic/classes/ClassProvider;ILorg/bukkit/plugin/Plugin;Lorg/bukkit/plugin/ServicePriority;)Lru/endlesscode/mimic/classes/ClassProvider; public fun registerClassSystem (Lru/endlesscode/mimic/classes/BukkitClassSystem$Provider;ILorg/bukkit/plugin/Plugin;)Lru/endlesscode/mimic/classes/BukkitClassSystem$Provider; public abstract fun registerClassSystem (Lru/endlesscode/mimic/classes/BukkitClassSystem$Provider;ILorg/bukkit/plugin/Plugin;Lorg/bukkit/plugin/ServicePriority;)Lru/endlesscode/mimic/classes/BukkitClassSystem$Provider; + public fun registerItemProvider (Lru/endlesscode/mimic/items/ItemProvider;ILorg/bukkit/plugin/Plugin;)Lru/endlesscode/mimic/items/ItemProvider; + public abstract fun registerItemProvider (Lru/endlesscode/mimic/items/ItemProvider;ILorg/bukkit/plugin/Plugin;Lorg/bukkit/plugin/ServicePriority;)Lru/endlesscode/mimic/items/ItemProvider; public fun registerItemsRegistry (Lru/endlesscode/mimic/items/BukkitItemsRegistry;ILorg/bukkit/plugin/Plugin;)Lru/endlesscode/mimic/items/BukkitItemsRegistry; public abstract fun registerItemsRegistry (Lru/endlesscode/mimic/items/BukkitItemsRegistry;ILorg/bukkit/plugin/Plugin;Lorg/bukkit/plugin/ServicePriority;)Lru/endlesscode/mimic/items/BukkitItemsRegistry; public fun registerLevelProvider (Lru/endlesscode/mimic/level/LevelProvider;ILorg/bukkit/plugin/Plugin;)Lru/endlesscode/mimic/level/LevelProvider; diff --git a/mimic-bukkit-api/src/main/kotlin/Mimic.kt b/mimic-bukkit-api/src/main/kotlin/Mimic.kt index abacdf71..2227a231 100644 --- a/mimic-bukkit-api/src/main/kotlin/Mimic.kt +++ b/mimic-bukkit-api/src/main/kotlin/Mimic.kt @@ -18,6 +18,8 @@ import ru.endlesscode.mimic.classes.ClassProvider import ru.endlesscode.mimic.classes.Classes import ru.endlesscode.mimic.inventory.BukkitPlayerInventory import ru.endlesscode.mimic.items.BukkitItemsRegistry +import ru.endlesscode.mimic.items.ItemProvider +import ru.endlesscode.mimic.items.Items import ru.endlesscode.mimic.level.BukkitLevelSystem import ru.endlesscode.mimic.level.LevelProvider import ru.endlesscode.mimic.level.Levels @@ -201,6 +203,55 @@ public interface Mimic { public fun getAllItemsRegistries(): Map // endregion + // region Items + /** + * Registers the given [provider] of items with normal priority. + * + * @param provider The [ItemProvider] implementation. + * @param apiLevel Minimal required API level for this item provider implementation: + * - if the required API level is higher than installed Mimic, provider will not be registered, + * - if the required API level is lower - will be enabled compatibility mode. + * Specify `MimicApiLevel.CURRENT` to use API level of Mimic dependency used at compile time. + * @param plugin The plugin implementing this item provider. + * @return registered provider or `null` if it was not registered. + * @since 0.11.0 + */ + public fun registerItemProvider( + provider: ItemProvider, + apiLevel: Int, + plugin: Plugin, + ): ItemProvider? = registerItemProvider(provider, apiLevel, plugin, ServicePriority.Normal) + + /** + * Registers the given [provider] of items. + * + * @param provider The [ItemProvider] implementation. + * @param apiLevel Minimal required API level for this item provider implementation: + * - if the required API level is higher than installed Mimic, provider will not be registered, + * - if the required API level is lower - will be enabled compatibility mode. + * Specify `MimicApiLevel.CURRENT` to use API level of Mimic dependency used at compile time. + * @param plugin The plugin implementing this item provider. + * @param priority Default priority. An item recognized by several providers belongs to the provider + * with the highest priority. + * @return registered provider or `null` if it was not registered. + * @since 0.11.0 + */ + public fun registerItemProvider( + provider: ItemProvider, + apiLevel: Int, + plugin: Plugin, + priority: ServicePriority, + ): ItemProvider? + + /** + * Vanilla and custom items from all plugins: create them by ID, identify stacks, list and validate IDs. + * See [Items] for details and examples. + * To make your plugin's items available here, use [registerItemProvider]. + * @since 0.11.0 + */ + public val items: Items + // endregion + // region Level System /** * Registers the given [provider] for [BukkitLevelSystem] with normal priority. diff --git a/mimic-bukkit/src/main/kotlin/MimicImpl.kt b/mimic-bukkit/src/main/kotlin/MimicImpl.kt index 008a9521..6a987c49 100644 --- a/mimic-bukkit/src/main/kotlin/MimicImpl.kt +++ b/mimic-bukkit/src/main/kotlin/MimicImpl.kt @@ -17,6 +17,7 @@ import ru.endlesscode.mimic.classes.* import ru.endlesscode.mimic.config.MimicConfig import ru.endlesscode.mimic.impl.mimic.MimicBlocks import ru.endlesscode.mimic.impl.mimic.MimicClasses +import ru.endlesscode.mimic.impl.mimic.MimicItems import ru.endlesscode.mimic.impl.mimic.MimicItemsRegistry import ru.endlesscode.mimic.impl.mimic.MimicLevels import ru.endlesscode.mimic.impl.mimic.MimicResources @@ -26,6 +27,8 @@ import ru.endlesscode.mimic.internal.Log import ru.endlesscode.mimic.internal.authorsMention import ru.endlesscode.mimic.inventory.WrappedPlayerInventoryProvider import ru.endlesscode.mimic.items.BukkitItemsRegistry +import ru.endlesscode.mimic.items.ItemProvider +import ru.endlesscode.mimic.items.WrappedItemProvider import ru.endlesscode.mimic.items.WrappedItemsRegistry import ru.endlesscode.mimic.level.* import ru.endlesscode.mimic.resources.ResourceProvider @@ -67,6 +70,11 @@ internal class MimicImpl( defaultId = MinecraftItemsRegistry.ID, disabledIds = { config.disabledItemsRegistries }, ) + val itemProviders = registry( + "ItemProvider", + defaultId = MinecraftItemsRegistry.ID, + disabledIds = { config.disabledItemsRegistries }, + ) private val levelSystems = registry( "LevelSystem", defaultId = MinecraftLevelSystem.ID, @@ -87,6 +95,7 @@ internal class MimicImpl( classProviders, playerInventories, itemsRegistries, + itemProviders, levelSystems, levelProviders, resourceProviders, @@ -159,6 +168,19 @@ internal class MimicImpl( override fun getAllItemsRegistries(): Map = itemsRegistries.loadAll() // endregion + // region Items + override fun registerItemProvider( + provider: ItemProvider, + apiLevel: Int, + plugin: Plugin, + priority: ServicePriority, + ): ItemProvider? = itemProviders.tryRegister(apiLevel, plugin, priority) { + WrappedItemProvider(provider, plugin) + } + + override val items = MimicItems(itemProviders) + // endregion + // region Level System override fun registerLevelSystem( provider: BukkitLevelSystem.Provider, diff --git a/mimic-bukkit/src/main/kotlin/impl/mimic/MimicItems.kt b/mimic-bukkit/src/main/kotlin/impl/mimic/MimicItems.kt new file mode 100644 index 00000000..075ccfea --- /dev/null +++ b/mimic-bukkit/src/main/kotlin/impl/mimic/MimicItems.kt @@ -0,0 +1,79 @@ +// Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors +// SPDX-License-Identifier: MIT + +package ru.endlesscode.mimic.impl.mimic + +import net.kyori.adventure.key.Key +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack +import ru.endlesscode.mimic.Mimic +import ru.endlesscode.mimic.ServiceEntry +import ru.endlesscode.mimic.ServiceRegistry +import ru.endlesscode.mimic.call +import ru.endlesscode.mimic.items.ItemProvider +import ru.endlesscode.mimic.items.Items + +internal typealias ItemProviderEntry = ServiceEntry + +/** + * Items combining items of all item providers, using provider IDs as namespaces: + * `sword/excalibur` -> `mmoitems:sword/excalibur`. + * + * An item belongs to the provider with the highest priority recognizing it, + * so a custom item built on a vanilla item is not recognized as the vanilla item. + */ +internal class MimicItems(itemProviders: ServiceRegistry) : Items { + + val providers = NamespacedProviders(itemProviders, hasVanillaValues = true) + + override fun getAllItems(): List = providers.enabled.flatMap { it.getAllItems() } + + override fun hasItem(itemId: Key): Boolean = findProvider(itemId)?.hasItem(itemId.value()) == true + + override fun getItemId(item: ItemStack): Key? = owner(item)?.second + + override fun isItem(item: ItemStack, itemId: Key): Boolean = getItemId(item) == itemId + + override fun createItem(itemId: Key, amount: Int, player: Player?, payload: String?): ItemStack? = + findProvider(itemId)?.createItem(itemId.value(), amount, player, payload) + + /** Returns the provider owning the [item] paired with the ID of the item, or `null` if no provider recognizes it. */ + fun owner(item: ItemStack): Pair? = providers.owner(ITEM) { getItemId(item) } + + private fun findProvider(itemId: Key): ItemProviderEntry? = + providers.find(itemId, ITEM) { path -> hasItem(path) } + + // IDs are checked inside call, so a provider returning nulls from Java is skipped + private fun ItemProviderEntry.getAllItems(): List = + call(default = emptyList()) { validValues(allItems, ITEM) { it }.map { key(it) } } + + private companion object { + const val ITEM = "item" + } +} + +/** Returns `true` if this provider has the item with the given [path]. */ +internal fun ItemProviderEntry.hasItem(path: String): Boolean = call(default = false) { hasItem(path) } + +/** + * Creates the item with the given [path] via this provider, keeping the amount within `1` and the maximum stack size. + * A blank [payload] is passed to the provider as `null`. + * Warns once if the provider can't create an existing item with the given [payload]. + */ +internal fun ItemProviderEntry.createItem(path: String, amount: Int, player: Player?, payload: String?): ItemStack? { + val minAmount = amount.coerceAtLeast(1) + val nonBlankPayload = payload?.takeIf { it.isNotBlank() } + return call(default = null) { + val item = createItem(path, minAmount, player, nonBlankPayload) + if (item == null && nonBlankPayload != null && hasItem(path)) { + val itemId = key(path).asString() + warnings.warn("invalid-payload:$itemId:$nonBlankPayload") { + "Item '$itemId' isn't created, because $apiName '${service.id}' can't use payload '$nonBlankPayload'." + } + } + item?.also { it.amount = it.amount.coerceIn(1, it.maxStackSize) } + } +} + +/** IDs of all registered item providers, including bridged items registries, the values of `disabled-item-providers` config option. */ +internal fun Mimic.getItemProviderIds(): Set = (items as MimicItems).providers.allIds diff --git a/mimic-bukkit/src/main/kotlin/items/WrappedItemProvider.kt b/mimic-bukkit/src/main/kotlin/items/WrappedItemProvider.kt new file mode 100644 index 00000000..eb7c3f0b --- /dev/null +++ b/mimic-bukkit/src/main/kotlin/items/WrappedItemProvider.kt @@ -0,0 +1,25 @@ +// Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors +// SPDX-License-Identifier: MIT + +package ru.endlesscode.mimic.items + +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack +import org.bukkit.plugin.Plugin +import ru.endlesscode.mimic.WrappedMimicService + +internal class WrappedItemProvider( + private val delegate: ItemProvider, + plugin: Plugin, +) : WrappedMimicService(delegate, plugin.name), ItemProvider { + + override val allItems: Collection + get() = delegate.allItems + + override fun hasItem(itemId: String): Boolean = delegate.hasItem(itemId) + + override fun getItemId(item: ItemStack): String? = delegate.getItemId(item) + + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack? = + delegate.createItem(itemId, amount, player, payload) +} diff --git a/mimic-bukkit/src/test/kotlin/impl/mimic/MimicItemsTest.kt b/mimic-bukkit/src/test/kotlin/impl/mimic/MimicItemsTest.kt new file mode 100644 index 00000000..14e1071e --- /dev/null +++ b/mimic-bukkit/src/test/kotlin/impl/mimic/MimicItemsTest.kt @@ -0,0 +1,370 @@ +// Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors +// SPDX-License-Identifier: MIT + +package ru.endlesscode.mimic.impl.mimic + +import io.kotest.assertions.assertSoftly +import io.kotest.matchers.booleans.shouldBeFalse +import io.kotest.matchers.booleans.shouldBeTrue +import io.kotest.matchers.collections.shouldBeEmpty +import io.kotest.matchers.collections.shouldContainExactly +import io.kotest.matchers.nulls.shouldBeNull +import io.kotest.matchers.shouldBe +import io.kotest.matchers.string.shouldContain +import io.kotest.matchers.types.shouldBeSameInstanceAs +import io.kotest.matchers.types.shouldNotBeSameInstanceAs +import net.kyori.adventure.key.Key +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack +import org.bukkit.plugin.ServicePriority.* +import org.junit.jupiter.api.assertNotNull +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.CsvSource +import org.junit.jupiter.params.provider.ValueSource +import ru.endlesscode.mimic.BukkitTestBase +import ru.endlesscode.mimic.ServiceRegistry +import ru.endlesscode.mimic.internal.Log +import ru.endlesscode.mimic.items.ItemProvider +import ru.endlesscode.mimic.items.Items +import kotlin.test.Test + +internal class MimicItemsTest : BukkitTestBase() { + + private val minecraft = TestItemProvider() + private val custom = CustomItemProvider() + + private var disabledProviders = emptySet() + private val itemProviders = ServiceRegistry( + apiName = "ItemProvider", + mimicPlugin = plugin, + defaultId = "minecraft", + disabledIds = { disabledProviders }, + ) + + // SUT + private val items: Items = MimicItems(itemProviders) + + init { + itemProviders.register(minecraft, plugin, Lowest) + itemProviders.register(custom, plugin, Normal) + } + + @Test + fun `when get all items - should return namespaced items of all providers`() { + items.getAllItems().map { it.asString() } shouldContainExactly listOf( + "custom:ruby", + "custom:default/ruby_sword", + "minecraft:stone", + "minecraft:diamond", + "minecraft:ender_pearl", + ) + } + + @Test + fun `when get all items - should skip invalid and duplicated paths`() { + itemProviders.register(InvalidIdItemProvider(), plugin, High) + + val invalidItems = items.getAllItems().filter { it.namespace() == "invalid" } + invalidItems.map { it.asString() } shouldContainExactly listOf("invalid:emerald") + } + + @ParameterizedTest + @CsvSource( + "minecraft:stone, true", + "ns:stone, false", + "mimic:stone, false", + "minecraft:unknown, false", + "custom:default/ruby_sword, true", + "custom:stone, false", + "minecraft:default/ruby_sword, false", + "minecraft:ruby, false", + ) + fun `when check has item`(itemId: String, shouldExist: Boolean) { + items.hasItem(Key.key(itemId)) shouldBe shouldExist + } + + @Test + fun `when provider can't list its items - should ask it whether an item exists`() { + itemProviders.register(UnlistedItemProvider(), plugin, Normal) + + assertSoftly { + items.hasItem(Key.key("unlisted:ruby")).shouldBeTrue() + items.hasItem(Key.key("unlisted:stone")).shouldBeFalse() + items.getAllItems().filter { it.namespace() == "unlisted" }.shouldBeEmpty() + } + } + + @ParameterizedTest + @CsvSource( + "STONE, minecraft:stone", + "DIAMOND, custom:ruby", + ) + fun `when get item id - should return id of the provider with the highest priority`( + material: Material, + expectedId: String, + ) { + items.getItemId(ItemStack(material)) shouldBe Key.key(expectedId) + } + + @Test + fun `when get id of unknown item - should return null`() { + items.getItemId(ItemStack(Material.AIR)).shouldBeNull() + } + + // https://github.com/EndlessCodeGroup/Mimic/issues/86 + @ParameterizedTest + @CsvSource( + "STONE, minecraft:stone, true", + "STONE, minecraft:diamond, false", + "DIAMOND, custom:ruby, true", + "DIAMOND, minecraft:diamond, false", + "DIAMOND, custom:diamond, false", + ) + fun `when check is item - should compare with id of the owner`( + material: Material, + itemId: String, + shouldBeSame: Boolean, + ) { + items.isItem(ItemStack(material, 5), Key.key(itemId)) shouldBe shouldBeSame + } + + @ParameterizedTest + @CsvSource( + "minecraft:stone, STONE", + "custom:ruby, DIAMOND", + ) + fun `when create item - should return item from the provider`(itemId: String, expected: Material) { + itemProviders.register(FailingItemProvider(), plugin, High) + + val item = items.createItem(Key.key(itemId), amount = 5) + assertNotNull(item, "Item should not be null") + // Not assertSoftly(item), it prints ItemStack requiring ItemFactory which isn't mocked + assertSoftly { + item.type shouldBe expected + item.amount shouldBe 5 + } + } + + @ParameterizedTest + @CsvSource( + "minecraft:stone, 0, 1", + "minecraft:stone, -5, 1", + "minecraft:stone, 64, 64", + "minecraft:stone, 100, 64", + "minecraft:ender_pearl, 64, 16", + ) + fun `when create item - should keep amount within stack size`(itemId: String, amount: Int, expectedAmount: Int) { + val item = items.createItem(Key.key(itemId), amount) + + assertNotNull(item, "Item should not be null") + item.amount shouldBe expectedAmount + } + + @ParameterizedTest + @ValueSource(strings = ["minecraft:unknown", "custom:stone", "ns:stone", "mimic:stone", "failing:stone"]) + fun `when create unknown item - should return null`(itemId: String) { + itemProviders.register(FailingItemProvider(), plugin, High) + + items.createItem(Key.key(itemId), amount = 1).shouldBeNull() + } + + @Test + fun `when create item - should pass player and payload only to the provider of the item`() { + items.createItem(Key.key("minecraft:stone"), amount = 1, player, payload = "[damage=10]") + + assertSoftly { + minecraft.lastPlayer shouldBeSameInstanceAs player + minecraft.lastPayload shouldBe "[damage=10]" + custom.createdItems shouldBe 0 + } + } + + @Test + fun `when use short forms - should use defaults`() { + assertSoftly { + items.createItem(Key.key("minecraft:stone"))?.amount shouldBe 1 + items.createItem(Key.key("minecraft:stone"), 5)?.amount shouldBe 5 + minecraft.lastPlayer.shouldBeNull() + minecraft.lastPayload.shouldBeNull() + + items.createItem(Key.key("minecraft:stone"), 5, player)?.amount shouldBe 5 + minecraft.lastPlayer shouldBeSameInstanceAs player + minecraft.lastPayload.shouldBeNull() + + items.createItem(Key.key("minecraft:stone"), payload = "[damage=10]")?.amount shouldBe 1 + minecraft.lastPlayer.shouldBeNull() + minecraft.lastPayload shouldBe "[damage=10]" + } + } + + @Test + fun `when provider can't parse payload - should return null and warn with id and payload once`() { + val warnings = mutableListOf() + Log.init({ _, message, _ -> warnings += message.orEmpty() }) + + repeat(2) { + items.createItem(Key.key("minecraft:stone"), amount = 1, player = null, payload = "[invalid").shouldBeNull() + // Unknown item is not a payload problem + items.createItem(Key.key("minecraft:unknown"), amount = 1, player = null, payload = "[invalid").shouldBeNull() + } + + warnings.single() shouldContain "'minecraft:stone'" + warnings.single() shouldContain "'[invalid'" + } + + @ParameterizedTest + @ValueSource(strings = ["", " "]) + fun `when payload is blank - should pass null to the provider`(payload: String) { + val item = items.createItem(Key.key("minecraft:stone"), amount = 1, player = null, payload) + + assertSoftly { + item?.type shouldBe Material.STONE + minecraft.lastPayload.shouldBeNull() + } + } + + @Test + fun `when provider takes no payload - should ignore it`() { + val item = items.createItem(Key.key("custom:ruby"), amount = 1, player = null, payload = "[invalid") + + item?.type shouldBe Material.DIAMOND + } + + @Test + fun `when create item twice - should return different stacks`() { + val first = items.createItem(Key.key("minecraft:stone")) + val second = items.createItem(Key.key("minecraft:stone")) + + first shouldNotBeSameInstanceAs second + } + + @Test + fun `when provider is disabled in config - should ignore it`() { + disabledProviders = setOf(custom.id) + + assertSoftly { + items.hasItem(Key.key("custom:ruby")).shouldBeFalse() + items.createItem(Key.key("custom:ruby")).shouldBeNull() + items.getItemId(ItemStack(Material.DIAMOND)) shouldBe Key.key("minecraft:diamond") + } + } + + @Test + fun `when provider fails to identify item - should not fall back to the default provider`() { + itemProviders.register(FailingItemProvider(), plugin, High) + val item = ItemStack(Material.STONE) + + assertSoftly { + items.getItemId(item).shouldBeNull() + items.isItem(item, Key.key("minecraft:stone")).shouldBeFalse() + } + } + + @Test + fun `when provider fails to identify item - should fall back to other custom providers`() { + itemProviders.register(FailingItemProvider(), plugin, High) + + items.getItemId(ItemStack(Material.DIAMOND)) shouldBe Key.key("custom:ruby") + } + + @Test + fun `when provider fails - should return defaults`() { + itemProviders.register(FailingItemProvider(), plugin, High) + + assertSoftly { + items.getAllItems().filter { it.namespace() == "failing" }.shouldBeEmpty() + items.hasItem(Key.key("failing:stone")).shouldBeFalse() + items.createItem(Key.key("failing:stone")).shouldBeNull() + } + } + + @Test + fun `when provider returns invalid id - should ignore it`() { + itemProviders.register(InvalidIdItemProvider(), plugin, High) + + assertSoftly { + // Should not fall back to the default provider + items.getItemId(ItemStack(Material.STONE)).shouldBeNull() + items.getItemId(ItemStack(Material.DIAMOND)) shouldBe Key.key("custom:ruby") + } + } + + @Test + fun `when minecraft item is unknown - should warn once only if other provider has it`() { + val warnings = mutableListOf() + Log.init({ _, message, _ -> warnings += message.orEmpty() }) + + repeat(2) { + items.hasItem(Key.key("minecraft:ruby")).shouldBeFalse() + items.hasItem(Key.key("minecraft:unknown")).shouldBeFalse() + } + + warnings.single() shouldContain "'minecraft:ruby' doesn't exist" + warnings.single() shouldContain "Did you mean 'custom:ruby'?" + } +} + +/** Provider imitating vanilla items. Takes payload starting with `[`. */ +private class TestItemProvider : ItemProvider { + override val id = "minecraft" + + // Material.isItem requires a server, so the known items are listed explicitly + override val allItems = listOf(Material.STONE, Material.DIAMOND, Material.ENDER_PEARL).map { it.name.lowercase() } + + var lastPlayer: Player? = null + var lastPayload: String? = null + + override fun getItemId(item: ItemStack): String? = item.type.name.lowercase().takeIf { it in allItems } + + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack? { + lastPlayer = player + lastPayload = payload + if (itemId !in allItems || payload == "[invalid") return null + return ItemStack(Material.valueOf(itemId.uppercase()), amount) + } +} + +/** Provider imitating a plugin with custom items built on diamond. Takes no payload. */ +private class CustomItemProvider : ItemProvider { + override val id = "custom" + override val allItems = listOf("ruby", "default/ruby_sword") + + var createdItems = 0 + + override fun getItemId(item: ItemStack): String? = "ruby".takeIf { item.type == Material.DIAMOND } + + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack? { + createdItems++ + return if (itemId == "ruby") ItemStack(Material.DIAMOND, amount) else null + } +} + +/** Provider imitating a plugin which can't list its items. */ +private class UnlistedItemProvider : ItemProvider { + override val id = "unlisted" + override val allItems = emptyList() + + override fun hasItem(itemId: String): Boolean = itemId == "ruby" + override fun getItemId(item: ItemStack): String? = null + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack? = null +} + +/** Provider returning invalid IDs. */ +private class InvalidIdItemProvider : ItemProvider { + override val id = "invalid" + override val allItems = listOf("Ruby Sword", "emerald", "ns:item", "", "emerald") + + override fun getItemId(item: ItemStack): String = allItems.first() + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack? = null +} + +/** Provider failing on every call. */ +private class FailingItemProvider : ItemProvider { + override val id = "failing" + override val allItems: List get() = error("Failure") + + override fun getItemId(item: ItemStack): String = error("Failure") + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack = + error("Failure") +} From 16e44755fd116eaf20e2ebe82f19306bb1810c76 Mon Sep 17 00:00:00 2001 From: Osip Fatkullin Date: Mon, 16 Nov 2026 10:36:09 +0100 Subject: [PATCH 06/11] feat: Add built-in item providers Providers for vanilla items, MMOItems, CraftEngine and CustomItems. MMOItems IDs include the item type: mmoitems:sword/excalibur (#87). MMOItems and CraftEngine build an item for the given player. Empty stacks have no ID, and air is not an item. Co-Authored-By: Claude Fable 5.2 --- mimic-bukkit/build.gradle.kts | 1 + mimic-bukkit/src/main/kotlin/MimicImpl.kt | 2 +- mimic-bukkit/src/main/kotlin/MimicPlugin.kt | 16 +++ .../craftengine/CraftEngineItemProvider.kt | 38 ++++++ .../impl/craftengine/CraftEngineWrapper.kt | 13 +- .../customitems/CustomItemsItemProvider.kt | 33 +++++ .../impl/mmoitems/MmoItemsItemProvider.kt | 46 +++++++ .../impl/vanilla/MinecraftItemProvider.kt | 65 +++++++++ .../impl/mmoitems/MmoItemsItemProviderTest.kt | 78 +++++++++++ .../impl/vanilla/MinecraftItemProviderTest.kt | 129 ++++++++++++++++++ 10 files changed, 417 insertions(+), 4 deletions(-) create mode 100644 mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineItemProvider.kt create mode 100644 mimic-bukkit/src/main/kotlin/impl/customitems/CustomItemsItemProvider.kt create mode 100644 mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsItemProvider.kt create mode 100644 mimic-bukkit/src/main/kotlin/impl/vanilla/MinecraftItemProvider.kt create mode 100644 mimic-bukkit/src/test/kotlin/impl/mmoitems/MmoItemsItemProviderTest.kt create mode 100644 mimic-bukkit/src/test/kotlin/impl/vanilla/MinecraftItemProviderTest.kt diff --git a/mimic-bukkit/build.gradle.kts b/mimic-bukkit/build.gradle.kts index 65a3aab3..dd7a5388 100644 --- a/mimic-bukkit/build.gradle.kts +++ b/mimic-bukkit/build.gradle.kts @@ -105,6 +105,7 @@ dependencies { testImplementation(libs.rpgplugins.valhallammo) { isTransitive = false } testImplementation(libs.rpgplugins.heroes) { isTransitive = false } testImplementation(libs.rpgplugins.mmocore) { isTransitive = false } + testImplementation(libs.rpgplugins.mmoitems) { isTransitive = false } testImplementation(libs.rpgplugins.mythiclib) { isTransitive = false } testImplementation(libs.rpgplugins.fabled) { isTransitive = false } testImplementation(libs.rpgplugins.codex) { isTransitive = false } diff --git a/mimic-bukkit/src/main/kotlin/MimicImpl.kt b/mimic-bukkit/src/main/kotlin/MimicImpl.kt index 6a987c49..a9fe6db7 100644 --- a/mimic-bukkit/src/main/kotlin/MimicImpl.kt +++ b/mimic-bukkit/src/main/kotlin/MimicImpl.kt @@ -72,7 +72,7 @@ internal class MimicImpl( ) val itemProviders = registry( "ItemProvider", - defaultId = MinecraftItemsRegistry.ID, + defaultId = MinecraftItemProvider.ID, disabledIds = { config.disabledItemsRegistries }, ) private val levelSystems = registry( diff --git a/mimic-bukkit/src/main/kotlin/MimicPlugin.kt b/mimic-bukkit/src/main/kotlin/MimicPlugin.kt index 05ab9d36..5ee6c262 100644 --- a/mimic-bukkit/src/main/kotlin/MimicPlugin.kt +++ b/mimic-bukkit/src/main/kotlin/MimicPlugin.kt @@ -19,7 +19,9 @@ import ru.endlesscode.mimic.config.MimicConfig import ru.endlesscode.mimic.impl.auraskills.AuraSkillsLevelProvider import ru.endlesscode.mimic.impl.auraskills.AuraSkillsResourceProvider import ru.endlesscode.mimic.impl.craftengine.CraftEngineBlockProvider +import ru.endlesscode.mimic.impl.craftengine.CraftEngineItemProvider import ru.endlesscode.mimic.impl.craftengine.CraftEngineItemsRegistry +import ru.endlesscode.mimic.impl.customitems.CustomItemsItemProvider import ru.endlesscode.mimic.impl.customitems.CustomItemsRegistry import ru.endlesscode.mimic.impl.fabled.FabledClassProvider import ru.endlesscode.mimic.impl.fabled.FabledLevelProvider @@ -37,12 +39,14 @@ import ru.endlesscode.mimic.impl.mmocore.MmoCoreClassSystem import ru.endlesscode.mimic.impl.mmocore.MmoCoreLevelProvider import ru.endlesscode.mimic.impl.mmocore.MmoCoreLevelSystem import ru.endlesscode.mimic.impl.mmocore.MmoCoreResourceProvider +import ru.endlesscode.mimic.impl.mmoitems.MmoItemsItemProvider import ru.endlesscode.mimic.impl.mmoitems.MmoItemsRegistry import ru.endlesscode.mimic.impl.valhallammo.ValhallaMmoLevelProvider import ru.endlesscode.mimic.impl.vanilla.* import ru.endlesscode.mimic.internal.Log import ru.endlesscode.mimic.inventory.BukkitPlayerInventory import ru.endlesscode.mimic.items.BukkitItemsRegistry +import ru.endlesscode.mimic.items.ItemProvider import ru.endlesscode.mimic.level.BukkitLevelSystem import ru.endlesscode.mimic.level.LevelProvider import ru.endlesscode.mimic.resources.ResourceProvider @@ -86,6 +90,7 @@ public class MimicPlugin : JavaPlugin() { hookClasses(PermissionsClassSystem::Provider, priority = Lowest) hookResources(::MinecraftResourceProvider, priority = Lowest) hookInventory(MinecraftPlayerInventory::Provider, priority = Lowest) + hookItems(::MinecraftItemProvider, priority = Lowest) hookItems(::MinecraftItemsRegistry, priority = Lowest) hookBlocks(::MinecraftBlockProvider, priority = Lowest) @@ -106,14 +111,17 @@ public class MimicPlugin : JavaPlugin() { } pluginHooks("CustomItems", "com.jojodmo.customitems.api.CustomItemsAPI") { + hookItems(::CustomItemsItemProvider) hookItems(::CustomItemsRegistry) } pluginHooks("MMOItems", "net.Indyuce.mmoitems.MMOItems") { + hookItems(::MmoItemsItemProvider) hookItems(::MmoItemsRegistry) } pluginHooks("CraftEngine", "net.momirealms.craftengine.bukkit.api.CraftEngineBlocks") { + hookItems(::CraftEngineItemProvider) hookItems(::CraftEngineItemsRegistry) hookBlocks(::CraftEngineBlockProvider) } @@ -197,6 +205,14 @@ public class MimicPlugin : JavaPlugin() { mimic.registerPlayerInventoryProvider(constructor.invoke(), MimicApiLevel.CURRENT, this, priority) } + private fun hookItems( + constructor: () -> ItemProvider, + priority: ServicePriority = Normal, + ) { + mimic.registerItemProvider(constructor.invoke(), MimicApiLevel.CURRENT, this, priority) + } + + @JvmName("hookItems_deprecated") private fun hookItems( constructor: () -> BukkitItemsRegistry, priority: ServicePriority = Normal, diff --git a/mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineItemProvider.kt b/mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineItemProvider.kt new file mode 100644 index 00000000..cd754433 --- /dev/null +++ b/mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineItemProvider.kt @@ -0,0 +1,38 @@ +// Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors +// SPDX-License-Identifier: MIT + +package ru.endlesscode.mimic.impl.craftengine + +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack +import ru.endlesscode.mimic.items.ItemProvider + +/** + * Item provider for CraftEngine custom items. + * CraftEngine namespace becomes the first path segment of item ID: `default:palm_log` -> `default/palm_log`. + * Vanilla items modified by CraftEngine are left to the `minecraft` provider. + * Takes no payload. An item created for a player is built by CraftEngine for this player. + */ +internal class CraftEngineItemProvider( + private val craftEngine: CraftEngineWrapper = CraftEngineWrapper(), +) : ItemProvider { + + override val id: String = ID + override val isEnabled: Boolean get() = craftEngine.isEnabled + + override val allItems: Collection + get() = craftEngine.loadedCustomItems.map { it.id().toMimicId() } + + override fun hasItem(itemId: String): Boolean = craftEngineKey(itemId)?.let(craftEngine::getCustomItem) != null + + override fun getItemId(item: ItemStack): String? = craftEngine.getCustomItem(item)?.id()?.toMimicId() + + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack? { + val key = craftEngineKey(itemId) ?: return null + return craftEngine.createCustomItem(key, amount, player) + } + + companion object { + const val ID: String = "craftengine" + } +} diff --git a/mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineWrapper.kt b/mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineWrapper.kt index 3380380e..20333fb7 100644 --- a/mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineWrapper.kt +++ b/mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineWrapper.kt @@ -16,6 +16,7 @@ import net.momirealms.craftengine.core.util.Key import org.bukkit.Bukkit import org.bukkit.Location import org.bukkit.block.Block +import org.bukkit.entity.Player import org.bukkit.inventory.ItemStack /** @@ -35,9 +36,15 @@ internal class CraftEngineWrapper { fun getCustomItem(item: ItemStack): BukkitItemDefinition? = CraftEngineItems.byItemStack(item)?.takeUnless { it.isVanillaItem } - /** Creates custom item with the given [amount], limited to the item's maximum stack size. */ - fun createCustomItem(id: Key, amount: Int): ItemStack? = - getCustomItem(id)?.buildBukkitItem()?.also { it.amount = amount.coerceIn(1, it.maxStackSize) } + /** + * Creates custom item with the given [amount], limited to the item's maximum stack size. + * The item is built for the [player] if it is given. + */ + fun createCustomItem(id: Key, amount: Int, player: Player? = null): ItemStack? { + val definition = getCustomItem(id) ?: return null + val item = if (player != null) definition.buildBukkitItem(player) else definition.buildBukkitItem() + return item?.also { it.amount = amount.coerceIn(1, it.maxStackSize) } + } fun getBlock(id: Key): BlockDefinition? = CraftEngineBlocks.byId(id) fun getBlockState(block: Block): ImmutableBlockState? = CraftEngineBlocks.getCustomBlockState(block) diff --git a/mimic-bukkit/src/main/kotlin/impl/customitems/CustomItemsItemProvider.kt b/mimic-bukkit/src/main/kotlin/impl/customitems/CustomItemsItemProvider.kt new file mode 100644 index 00000000..ad61d7cc --- /dev/null +++ b/mimic-bukkit/src/main/kotlin/impl/customitems/CustomItemsItemProvider.kt @@ -0,0 +1,33 @@ +// Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors +// SPDX-License-Identifier: MIT + +package ru.endlesscode.mimic.impl.customitems + +import com.jojodmo.customitems.api.CustomItemsAPI +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack +import ru.endlesscode.mimic.items.ItemProvider + +/** + * Item provider for CustomItems. Takes no payload, items don't depend on a player. + * + * CustomItems can't list its items, so [allItems] is empty, but [hasItem] still checks that an item exists. + */ +internal class CustomItemsItemProvider : ItemProvider { + + override val id: String = ID + override val isEnabled: Boolean get() = CustomItemsAPI.isEnabled() + + override val allItems: Collection = emptyList() + + override fun hasItem(itemId: String): Boolean = CustomItemsAPI.getCustomItem(itemId) != null + + override fun getItemId(item: ItemStack): String? = CustomItemsAPI.getCustomItemID(item)?.lowercase() + + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack? = + CustomItemsAPI.getCustomItem(itemId, amount) + + companion object { + const val ID: String = "customitems" + } +} diff --git a/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsItemProvider.kt b/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsItemProvider.kt new file mode 100644 index 00000000..b485ae07 --- /dev/null +++ b/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsItemProvider.kt @@ -0,0 +1,46 @@ +// Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors +// SPDX-License-Identifier: MIT + +package ru.endlesscode.mimic.impl.mmoitems + +import net.Indyuce.mmoitems.api.item.template.MMOItemTemplate +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack +import ru.endlesscode.mimic.items.ItemProvider + +/** + * Item provider for MMOItems. + * MMOItems IDs are unique only within an item type, so the type is the first path segment of item ID: + * `EXCALIBUR` of the type `SWORD` -> `sword/excalibur`. + * Takes no payload. An item created for a player is built by MMOItems for this player. + */ +internal class MmoItemsItemProvider( + private val mmoItems: MmoItemsWrapper = MmoItemsWrapper(), +) : ItemProvider { + + override val id: String = ID + override val isEnabled: Boolean get() = mmoItems.isEnabled + + override val allItems: Collection + get() = mmoItems.templates.map { it.mimicId } + + override fun getItemId(item: ItemStack): String? { + val type = mmoItems.getTypeName(item) ?: return null + val id = mmoItems.getId(item) ?: return null + return mimicId(type, id) + } + + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack? { + val template = mmoItems.templates.find { it.mimicId == itemId } ?: return null + return mmoItems.buildItem(template, player)?.also { it.amount = amount } + } + + private val MMOItemTemplate.mimicId: String + get() = mimicId(mmoItems.getTypeName(this), id) + + private fun mimicId(type: String, id: String): String = "${type.lowercase()}/${id.lowercase()}" + + companion object { + const val ID: String = "mmoitems" + } +} diff --git a/mimic-bukkit/src/main/kotlin/impl/vanilla/MinecraftItemProvider.kt b/mimic-bukkit/src/main/kotlin/impl/vanilla/MinecraftItemProvider.kt new file mode 100644 index 00000000..306b543b --- /dev/null +++ b/mimic-bukkit/src/main/kotlin/impl/vanilla/MinecraftItemProvider.kt @@ -0,0 +1,65 @@ +// Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors +// SPDX-License-Identifier: MIT + +@file:Suppress("DEPRECATION") // ItemMetaPayload is deprecated but still supported + +package ru.endlesscode.mimic.impl.vanilla + +import org.bukkit.Bukkit +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack +import ru.endlesscode.mimic.internal.OnceWarnings +import ru.endlesscode.mimic.items.ItemProvider + +/** + * Item provider using material name as item ID. It recognizes any item, so it is asked last. + * + * Payload is [item components](https://minecraft.wiki/w/Data_component_format) in the format of the `/give` command, + * for example `[damage=10,unbreakable={}]`. Components syntax depends on the server version. + * + * Deprecated [ItemMetaPayload] in HOCON format is still accepted with a warning. + */ +internal class MinecraftItemProvider : ItemProvider { + + override val id: String = ID + + private val warnings = OnceWarnings() + + override val allItems: Set by lazy { + Material.entries.asSequence() + .filter { it.isObtainableItem } + .mapTo(LinkedHashSet()) { it.name.lowercase() } + } + + override fun getItemId(item: ItemStack): String? = if (item.isEmpty) null else item.type.name.lowercase() + + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack? { + val material = Material.getMaterial(itemId.uppercase())?.takeIf { it.isObtainableItem } ?: return null + if (payload == null) return ItemStack(material, amount) + + if (payload.startsWith("[")) { + return try { + Bukkit.getItemFactory().createItemStack("${material.key.asString()}$payload") + .apply { this.amount = amount } + } catch (_: IllegalArgumentException) { + null + } + } + + val metaPayload = ItemMetaPayload.parse(payload) ?: return null + warnings.warn("hocon-payload:$payload") { + "[$TAG] Payload in HOCON format is deprecated, use item components instead, " + + "for example [damage=10,unbreakable={}]. Deprecated payload of item $itemId: $payload" + } + return ItemStack(material, amount).apply { itemMeta = itemMeta?.applyPayload(metaPayload) } + } + + private val Material.isObtainableItem: Boolean + get() = !isLegacy && !isAir && isItem + + companion object { + const val ID: String = "minecraft" + private const val TAG = "MinecraftItemProvider" + } +} diff --git a/mimic-bukkit/src/test/kotlin/impl/mmoitems/MmoItemsItemProviderTest.kt b/mimic-bukkit/src/test/kotlin/impl/mmoitems/MmoItemsItemProviderTest.kt new file mode 100644 index 00000000..534c06f6 --- /dev/null +++ b/mimic-bukkit/src/test/kotlin/impl/mmoitems/MmoItemsItemProviderTest.kt @@ -0,0 +1,78 @@ +// Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors +// SPDX-License-Identifier: MIT + +package ru.endlesscode.mimic.impl.mmoitems + +import io.kotest.matchers.collections.shouldContainExactly +import io.kotest.matchers.nulls.shouldBeNull +import io.kotest.matchers.shouldBe +import io.mockk.every +import io.mockk.mockk +import io.mockk.verify +import net.Indyuce.mmoitems.api.item.template.MMOItemTemplate +import org.bukkit.Material +import org.bukkit.inventory.ItemStack +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.CsvSource +import org.junit.jupiter.params.provider.ValueSource +import ru.endlesscode.mimic.BukkitTestBase +import kotlin.test.Test + +internal class MmoItemsItemProviderTest : BukkitTestBase() { + + private val typeNames = mutableMapOf() + private val swordExcalibur = mockTemplate("SWORD", "EXCALIBUR") + private val daggerExcalibur = mockTemplate("DAGGER", "EXCALIBUR") + + private val mmoItems: MmoItemsWrapper = mockk { + every { templates } returns listOf(swordExcalibur, daggerExcalibur) + every { getTypeName(any()) } answers { typeNames.getValue(firstArg()) } + every { getTypeName(any()) } returns null + every { getId(any()) } returns null + every { buildItem(swordExcalibur, any()) } answers { ItemStack(Material.DIAMOND_SWORD) } + every { buildItem(daggerExcalibur, any()) } answers { ItemStack(Material.IRON_SWORD) } + } + + // SUT + private val provider = MmoItemsItemProvider(mmoItems) + + @Test + fun `when get all items - should return ids with item types`() { + provider.allItems shouldContainExactly listOf("sword/excalibur", "dagger/excalibur") + } + + @ParameterizedTest + @CsvSource( + "sword/excalibur, DIAMOND_SWORD", + "dagger/excalibur, IRON_SWORD", + ) + fun `when create item - should use the template of the given type`(itemId: String, expected: Material) { + val item = provider.createItem(itemId, amount = 2, player, payload = null) + + item?.type shouldBe expected + item?.amount shouldBe 2 + verify { mmoItems.buildItem(any(), player) } + } + + @ParameterizedTest + @ValueSource(strings = ["excalibur", "sword/unknown", "axe/excalibur", "sword/excalibur/extra"]) + fun `when create item without type or unknown item - should return null`(itemId: String) { + provider.createItem(itemId, amount = 1, player = null, payload = null).shouldBeNull() + } + + @Test + fun `when get item id - should return id with item type`() { + every { mmoItems.getTypeName(any()) } returns "DAGGER" + every { mmoItems.getId(any()) } returns "EXCALIBUR" + + provider.getItemId(ItemStack(Material.IRON_SWORD)) shouldBe "dagger/excalibur" + } + + @Test + fun `when get id of not MMOItems item - should return null`() { + provider.getItemId(ItemStack(Material.IRON_SWORD)).shouldBeNull() + } + + private fun mockTemplate(type: String, id: String): MMOItemTemplate = + mockk { every { this@mockk.id } returns id }.also { typeNames[it] = type } +} diff --git a/mimic-bukkit/src/test/kotlin/impl/vanilla/MinecraftItemProviderTest.kt b/mimic-bukkit/src/test/kotlin/impl/vanilla/MinecraftItemProviderTest.kt new file mode 100644 index 00000000..79515f04 --- /dev/null +++ b/mimic-bukkit/src/test/kotlin/impl/vanilla/MinecraftItemProviderTest.kt @@ -0,0 +1,129 @@ +// Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors +// SPDX-License-Identifier: MIT + +package ru.endlesscode.mimic.impl.vanilla + +import io.kotest.assertions.assertSoftly +import io.kotest.matchers.nulls.shouldBeNull +import io.kotest.matchers.nulls.shouldNotBeNull +import io.kotest.matchers.shouldBe +import io.kotest.matchers.string.shouldContain +import io.kotest.matchers.types.shouldBeSameInstanceAs +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.mockkStatic +import io.mockk.unmockkObject +import io.mockk.unmockkStatic +import io.mockk.verify +import net.kyori.adventure.text.Component.text +import org.bukkit.Bukkit +import org.bukkit.Material +import org.bukkit.inventory.ItemFactory +import org.bukkit.inventory.ItemStack +import org.bukkit.inventory.meta.ItemMeta +import ru.endlesscode.mimic.BukkitTestBase +import ru.endlesscode.mimic.internal.Log +import kotlin.test.AfterTest +import kotlin.test.Test + +internal class MinecraftItemProviderTest : BukkitTestBase() { + + private val itemMeta: ItemMeta = mockk(relaxed = true) { + every { clone() } returns this + } + private val itemFactory: ItemFactory = mockk(relaxed = true) { + every { getItemMeta(any()) } returns itemMeta + every { isApplicable(any(), any()) } returns true + every { asMetaFor(any(), any()) } returns itemMeta + } + + // SUT + private val provider = MinecraftItemProvider() + + init { + mockkStatic(Bukkit::class) + every { Bukkit.getItemFactory() } returns itemFactory + // Material.isItem and Material.isAir require Paper registries which aren't available in tests + mockkObject(Material.STONE, Material.AIR) + every { Material.STONE.isItem } returns true + every { Material.STONE.isAir } returns false + every { Material.AIR.isAir } returns true + } + + @AfterTest + fun tearDown() { + unmockkStatic(Bukkit::class) + unmockkObject(Material.STONE, Material.AIR) + } + + @Test + fun `when create item - should return new stack with amount`() { + val item = provider.createItem("stone", amount = 5, player = null, payload = null).shouldNotBeNull() + + assertSoftly { + item.type shouldBe Material.STONE + item.amount shouldBe 5 + } + } + + @Test + fun `when create unknown item - should return null`() { + assertSoftly { + provider.createItem("unknown", amount = 1, player = null, payload = null).shouldBeNull() + provider.createItem("air", amount = 1, player = null, payload = null).shouldBeNull() + provider.createItem("legacy_stone", amount = 1, player = null, payload = null).shouldBeNull() + } + } + + @Test + fun `when get item id - should return material name`() { + assertSoftly { + provider.getItemId(ItemStack(Material.STONE)) shouldBe "stone" + provider.getItemId(ItemStack(Material.AIR)).shouldBeNull() + } + } + + @Test + fun `when create item with components payload - should create item from components`() { + val createdItem = ItemStack(Material.STONE) + every { itemFactory.createItemStack("minecraft:stone[damage=10]") } returns createdItem + + val item = provider.createItem("stone", amount = 5, player = null, payload = "[damage=10]").shouldNotBeNull() + + assertSoftly { + item shouldBeSameInstanceAs createdItem + item.amount shouldBe 5 + } + verify(exactly = 0) { itemFactory.getItemMeta(any()) } + } + + @Test + fun `when create item with invalid components payload - should return null`() { + every { itemFactory.createItemStack(any()) } throws IllegalArgumentException("Invalid components") + + provider.createItem("stone", amount = 5, player = null, payload = "[unknown=1]").shouldBeNull() + } + + @Test + fun `when create item with deprecated HOCON payload - should apply it and warn once`() { + val warnings = mutableListOf() + Log.init({ _, message, _ -> warnings += message.orEmpty() }) + + provider.createItem("stone", amount = 5, player = null, payload = "name = Name").shouldNotBeNull() + val item = provider.createItem("stone", amount = 5, player = null, payload = "name = Name").shouldNotBeNull() + + assertSoftly { + item.type shouldBe Material.STONE + item.amount shouldBe 5 + warnings.single() shouldContain "HOCON format is deprecated" + } + verify { itemMeta.displayName(text("Name")) } + verify(exactly = 0) { itemFactory.createItemStack(any()) } + } + + @Test + fun `when create item with invalid HOCON payload - should return null`() { + provider.createItem("stone", amount = 5, player = null, payload = "name = {").shouldBeNull() + } +} From e0dec77cea40c9b5f200a72d9cbc4814da574e70 Mon Sep 17 00:00:00 2001 From: Osip Fatkullin Date: Mon, 16 Nov 2026 10:36:33 +0100 Subject: [PATCH 07/11] feat: Move /mimic items to Items API Item IDs require a namespace, items are created for the target player. ID suggestions no longer search the 'mimic' namespace over all namespaces. Co-Authored-By: Claude Fable 5.2 --- .../main/kotlin/command/ItemsSubcommand.kt | 98 +++++++++---------- .../src/main/kotlin/command/MainCommand.kt | 4 +- .../src/main/kotlin/command/brigadier.kt | 34 +------ .../src/test/kotlin/command/IdHintsTest.kt | 2 - 4 files changed, 52 insertions(+), 86 deletions(-) diff --git a/mimic-bukkit/src/main/kotlin/command/ItemsSubcommand.kt b/mimic-bukkit/src/main/kotlin/command/ItemsSubcommand.kt index ec5d9c59..dffc4d82 100644 --- a/mimic-bukkit/src/main/kotlin/command/ItemsSubcommand.kt +++ b/mimic-bukkit/src/main/kotlin/command/ItemsSubcommand.kt @@ -6,19 +6,18 @@ package ru.endlesscode.mimic.command import com.mojang.brigadier.arguments.IntegerArgumentType import com.mojang.brigadier.arguments.StringArgumentType import io.papermc.paper.command.brigadier.argument.ArgumentTypes +import net.kyori.adventure.key.Key import net.kyori.adventure.text.Component import org.bukkit.command.CommandSender import org.bukkit.entity.Player import org.bukkit.inventory.ItemStack -import ru.endlesscode.mimic.impl.mimic.MimicItemsRegistry -import ru.endlesscode.mimic.impl.mimic.registry import ru.endlesscode.mimic.internal.append import ru.endlesscode.mimic.internal.appendLine import ru.endlesscode.mimic.internal.text -import ru.endlesscode.mimic.items.BukkitItemsRegistry +import ru.endlesscode.mimic.items.Items /** - * Commands to deal with items registries + * Commands to deal with items. * ``` * /mimic items (info) * /mimic items give [target] [item] (amount) (payload) @@ -26,41 +25,41 @@ import ru.endlesscode.mimic.items.BukkitItemsRegistry * /mimic items find [item] * ``` */ -internal fun CommandBuilder.itemsSubcommand(itemsRegistry: BukkitItemsRegistry) = literal("items") { - executesAny(infoExecutor(itemsRegistry)) +internal fun CommandBuilder.itemsSubcommand(items: Items) = literal("items") { + executesAny(infoExecutor(items)) - // Show information about items service + // Show information about items literal("info") { - executesAny(infoExecutor(itemsRegistry)) + executesAny(infoExecutor(items)) } // Give item to player literal("give") { argument(TARGET, ArgumentTypes.player()) { - itemArgument(itemsRegistry) { - executesAny(giveExecutor(itemsRegistry)) + itemArgument(items) { + executesAny(giveExecutor(items)) argument(AMOUNT, IntegerArgumentType.integer(1, 64)) { suggestsStrings { listOf("1", "64") } - executesAny(giveExecutor(itemsRegistry)) + executesAny(giveExecutor(items)) argument(PAYLOAD, StringArgumentType.greedyString()) { - executesAny(giveExecutor(itemsRegistry)) + executesAny(giveExecutor(items)) } } } } } - // Compare item in hand corresponds and given item + // Compare item in hand with the given item literal("compare") { - itemArgument(itemsRegistry) { + itemArgument(items) { executesPlayer { sender, context -> - val item = context.getArgument(ITEM) - val isSame = itemsRegistry.isSameItem(sender.requireItemInMainHand(), item) + val itemId = context.getArgument(ITEM) + val isSame = items.isItem(sender.requireItemInMainHand(), itemId) sender.sendMessage(successText { append("Item in hand ") appendVerdict(isSame, "matches", "doesn't match") append(" ") - appendId(item) + appendId(itemId.asString()) append(".") }) } @@ -69,13 +68,13 @@ internal fun CommandBuilder.itemsSubcommand(itemsRegistry: BukkitItemsRegistry) // Check that item with given ID exists literal("find") { - itemArgument(itemsRegistry) { + itemArgument(items) { executesAny { sender, context -> - val item = context.getArgument(ITEM) - val itemExists = itemsRegistry.isItemExists(item) + val itemId = context.getArgument(ITEM) + val itemExists = items.hasItem(itemId) sender.sendMessage(successText { append("Item ") - appendId(item) + appendId(itemId.asString()) append(" ") appendVerdict(itemExists, "exists", "doesn't exist") append(".") @@ -86,51 +85,42 @@ internal fun CommandBuilder.itemsSubcommand(itemsRegistry: BukkitItemsRegistry) } private fun CommandBuilder.itemArgument( - itemRegistry: BukkitItemsRegistry, + items: Items, configure: CommandBuilder.() -> Unit, -) = argument(ITEM, ResourceLocationArgumentType) { - suggestsIds({ context -> itemHints(itemRegistry, context.source.sender) }) { itemRegistry.knownIds } +) = argument(ITEM, KeyArgumentType("item", "minecraft:diamond")) { + suggestsIds({ context -> itemHints(items, context.source.sender) }) { items.itemIds() } configure() } -/** Suggests ID of the item in hand and namespaces of items registries. */ -private fun itemHints(itemRegistry: BukkitItemsRegistry, sender: CommandSender): List { - val itemInHandId = itemInHandId(itemRegistry, sender) - val namespaces = (itemRegistry as? MimicItemsRegistry)?.providers.orEmpty().map { it.registry.id } - val knownIds = itemRegistry.knownIds +private fun Items.itemIds(): List = getAllItems().map { it.asString() } - return listOfNotNull(itemInHandId?.let { SuggestionHint(it, Component.text("Item in hand")) }) + - namespaces.map { SuggestionHint(collapseFolders("$it:", knownIds), Component.text("Items from $it")) } -} +/** Suggests ID of the item in hand and namespaces of items. */ +private fun itemHints(items: Items, sender: CommandSender): List = listOfNotNull( + itemInHandId(items, sender)?.let { SuggestionHint(it.asString(), Component.text("Item in hand")) }, +) + namespaceHints(items.itemIds()) { "Items from $it" } /** Returns ID of the item in [sender]'s hand, or `null` if sender isn't a player or the hand is empty. */ -private fun itemInHandId(itemRegistry: BukkitItemsRegistry, sender: CommandSender): String? = - (sender as? Player)?.inventory?.itemInMainHand - ?.takeUnless { it.type.isAir } - ?.let(itemRegistry::getItemId) +private fun itemInHandId(items: Items, sender: CommandSender): Key? = + (sender as? Player)?.inventory?.itemInMainHand?.let(items::getItemId) private fun Player.requireItemInMainHand(): ItemStack { val item = inventory.itemInMainHand - if (item.type.isAir) throw commandError("You aren't holding an item.") + if (item.isEmpty) throw commandError("You aren't holding an item.") return item } -private fun infoExecutor(itemRegistry: BukkitItemsRegistry): CommandAction = { sender, _ -> - val providers = (itemRegistry as? MimicItemsRegistry)?.providers.orEmpty().map { it.registry } +private fun infoExecutor(items: Items): CommandAction = { sender, _ -> + val allItems = items.getAllItems() val message = text { appendHeader("Mimic Items") - appendStats( - "Item Registry" to itemRegistry.id, - "Known IDs amount" to itemRegistry.knownIds.size.toString(), - ) - - for (provider in providers) { - appendKey(" ${provider.id}: ") - appendValue(provider.knownIds.size.toString()) + appendStats("Items amount" to allItems.size.toString()) + for ((namespace, amount) in allItems.groupingBy { it.namespace() }.eachCount()) { + appendKey(" $namespace: ") + appendValue(amount.toString()) appendLine() } - appendIdStat("Item in hand", itemInHandId(itemRegistry, sender)) + appendIdStat("Item in hand", itemInHandId(items, sender)?.asString()) appendCommands( suggestedCommand("give", "/mimic items give [target] [item] (amount) (payload)", "Give item to player"), suggestedCommand("compare", "/mimic items compare [item]", "Compare item in hand with the given item"), @@ -140,18 +130,22 @@ private fun infoExecutor(itemRegistry: BukkitItemsRegistry): CommandAction = { sender, context -> +private fun giveExecutor(items: Items): CommandAction = { sender, context -> val target = context.getPlayer(TARGET) - val item = context.getArgument(ITEM) + val itemId = context.getArgument(ITEM) val amount = context.getArgumentOrNull(AMOUNT) ?: 1 val payload = context.getArgumentOrNull(PAYLOAD) - val itemStack = itemRegistry.getItem(item, payload, amount) ?: throw commandError("Unknown item '$item'.") + if (!items.hasItem(itemId)) throw commandError("Unknown item '${itemId.asString()}'.") + val itemStack = items.createItem(itemId, amount, target, payload) ?: run { + val payloadHint = if (payload != null) " The payload '$payload' may be invalid, see the console." else "" + throw commandError("Can't create item '${itemId.asString()}'.$payloadHint") + } val givenAmount = itemStack.amount // addItem may change the amount of the passed stack target.giveItem(itemStack) sender.sendMessage(successText { append("Gave $givenAmount ") - appendId(item) + appendId(itemId.asString()) append(" to ${target.name}.") }) if (givenAmount < amount) { diff --git a/mimic-bukkit/src/main/kotlin/command/MainCommand.kt b/mimic-bukkit/src/main/kotlin/command/MainCommand.kt index 72e7f166..cf4f55f4 100644 --- a/mimic-bukkit/src/main/kotlin/command/MainCommand.kt +++ b/mimic-bukkit/src/main/kotlin/command/MainCommand.kt @@ -38,7 +38,7 @@ private fun buildCommand( classesSubcommand(mimic) resourcesSubcommand(mimic) inventorySubcommand(mimic) - itemsSubcommand(mimic.itemsRegistry) + itemsSubcommand(mimic.items) blocksSubcommand(mimic.blocks) }.build() @@ -51,7 +51,7 @@ private fun infoExecutor(pluginFullName: String): CommandAction = executedCommand("classes", "/$COMMAND_NAME classes", "Player classes"), executedCommand("resources", "/$COMMAND_NAME resources", "Player resources: mana, stamina and similar"), executedCommand("inventory", "/$COMMAND_NAME inventory", "Player inventory provider"), - executedCommand("items", "/$COMMAND_NAME items", "Items registries"), + executedCommand("items", "/$COMMAND_NAME items", "Vanilla and custom items"), executedCommand("blocks", "/$COMMAND_NAME blocks", "Vanilla and custom blocks"), ) } diff --git a/mimic-bukkit/src/main/kotlin/command/brigadier.kt b/mimic-bukkit/src/main/kotlin/command/brigadier.kt index 38327167..fe3e1b61 100644 --- a/mimic-bukkit/src/main/kotlin/command/brigadier.kt +++ b/mimic-bukkit/src/main/kotlin/command/brigadier.kt @@ -92,7 +92,6 @@ internal fun RequiredArgumentBuilder.suggestsStrings(prov * Suggests namespaced IDs like `minecraft:stone`, matching the typed input against the path after namespace. * - Empty input: hints from [provideEmptyInputHints]. * - `namespace:path`: [path hints][pathHints] from the namespace, or similar namespaces if the namespace is unknown. - * Namespace `mimic` searches over all namespaces. * - `path` without namespace: [path hints][pathHints] from all namespaces and namespaces starting with `path`. */ internal fun RequiredArgumentBuilder.suggestsIds( @@ -130,7 +129,6 @@ private fun collectIdHints(input: String, ids: Collection): List pathHints(path, parsedIds) in namespaces -> pathHints(path, parsedIds.filter { it.namespace == namespace }) else -> namespaces .filter { namespace in it } @@ -174,10 +172,6 @@ internal fun namespaceHints(ids: List, tooltip: (namespace: String) -> S SuggestionHint(collapseFolders("$namespace:", namespaceIds), Component.text(tooltip(namespace))) } -/** Extends [prefix] with the folders shared by all [ids] starting with it, see [collapseFolders]. */ -internal fun collapseFolders(prefix: String, ids: Collection): String = - collapseFolders(prefix, ids.map(::ParsedId)) - /** * Extends [prefix] with the folders shared by all IDs starting with it, * so `craftengine:` becomes `craftengine:default/` if all IDs are inside `default/`. @@ -209,9 +203,6 @@ private class ParsedId(val id: String) { } } -/** Namespace used by Mimic registries to search IDs over all registries. */ -private const val SEARCH_ALL_NAMESPACE = "mimic" - internal fun CommandContext<*>.hasArgument(name: String): Boolean = nodes.any { it.node.name == name } internal inline fun CommandContext<*>.getArgument(name: String): T = @@ -242,26 +233,6 @@ internal fun CommandContext.getBlockLocation(name: String): internal fun commandError(message: String): CommandSyntaxException = SimpleCommandExceptionType(LiteralMessage(message)).create() -/** - * Resource location like `minecraft:stone`, shown to the client as a key. - * Unlike [ArgumentTypes.key], keeps an ID without namespace as is instead of adding the `minecraft` namespace. - */ -internal object ResourceLocationArgumentType : CustomArgumentType { - - private val expectedId = SimpleCommandExceptionType(LiteralMessage("Expected ID")) - - override fun parse(reader: StringReader): String { - val start = reader.cursor - while (reader.canRead() && reader.peek().isAllowedInResourceLocation()) reader.skip() - if (reader.cursor == start) throw expectedId.createWithContext(reader) - return reader.string.substring(start, reader.cursor) - } - - override fun getNativeType(): ArgumentType = ArgumentTypes.key() - - private fun Char.isAllowedInResourceLocation() = this in 'a'..'z' || this in '0'..'9' || this in "_-.:/" -} - /** * ID with namespace like `minecraft:level`, shown to the client as a key. * Unlike [ArgumentTypes.key], requires the namespace instead of adding `minecraft`. @@ -275,7 +246,8 @@ internal class KeyArgumentType(valueName: String, example: String) : CustomArgum override fun parse(reader: StringReader): Key { val start = reader.cursor - val id = ResourceLocationArgumentType.parse(reader) + while (reader.canRead() && reader.peek().isAllowedInKey()) reader.skip() + val id = reader.string.substring(start, reader.cursor) if (':' !in id || !Key.parseable(id)) { reader.cursor = start throw invalidId.createWithContext(reader, id) @@ -284,4 +256,6 @@ internal class KeyArgumentType(valueName: String, example: String) : CustomArgum } override fun getNativeType(): ArgumentType = ArgumentTypes.key() + + private fun Char.isAllowedInKey() = this in 'a'..'z' || this in '0'..'9' || this in "_-.:/" } diff --git a/mimic-bukkit/src/test/kotlin/command/IdHintsTest.kt b/mimic-bukkit/src/test/kotlin/command/IdHintsTest.kt index 4d7e0960..f8099104 100644 --- a/mimic-bukkit/src/test/kotlin/command/IdHintsTest.kt +++ b/mimic-bukkit/src/test/kotlin/command/IdHintsTest.kt @@ -76,8 +76,6 @@ internal class IdHintsTest { arguments("craftengine:default/t", listOf("craftengine:default/trees/palm_sapling")), arguments("craftengine:default/trees/", listOf("craftengine:default/trees/palm_sapling")), arguments("minecraft:", listOf("minecraft:stone", "minecraft:stone_stairs")), - // Search over all namespaces - arguments("mimic:def", listOf("craftengine:default/palm_log", "craftengine:default/palm_planks", "craftengine:default/trees/palm_sapling", "craftengine:default/")), // Unknown namespace arguments("craft:palm", listOf("craftengine:palm", "minecraft:palm")), ) From 6abf6c544c70e320c7522602d1fb529df68a68a7 Mon Sep 17 00:00:00 2001 From: Osip Fatkullin Date: Mon, 16 Nov 2026 10:37:02 +0100 Subject: [PATCH 08/11] feat: Deprecate ItemsRegistry API ItemsRegistry, BukkitItemsRegistry, the built-in items registries and the items registry methods of Mimic are deprecated in favor of Items API, but keep working. ItemMetaPayload is deprecated in favor of item components. Co-Authored-By: Claude Fable 5.2 --- mimic-api/src/main/kotlin/items/ItemsRegistry.kt | 1 + mimic-bukkit-api/src/main/kotlin/Mimic.kt | 6 +++++- .../src/main/kotlin/items/BukkitItemsRegistry.kt | 3 +++ mimic-bukkit/src/main/kotlin/MimicImpl.kt | 2 +- mimic-bukkit/src/main/kotlin/MimicPlugin.kt | 2 +- mimic-bukkit/src/main/kotlin/command/ConfigCommand.kt | 2 ++ mimic-bukkit/src/main/kotlin/command/ConfigMessage.kt | 2 ++ mimic-bukkit/src/main/kotlin/config/MimicConfig.kt | 2 ++ .../kotlin/impl/craftengine/CraftEngineItemsRegistry.kt | 3 +++ .../src/main/kotlin/impl/customitems/CustomItemsRegistry.kt | 3 +++ .../src/main/kotlin/impl/mimic/ItemsRegistryProvider.kt | 2 ++ .../src/main/kotlin/impl/mimic/MimicItemsRegistry.kt | 3 +++ .../src/main/kotlin/impl/mimic/SafeBukkitItemsRegistry.kt | 2 ++ .../src/main/kotlin/impl/mmoitems/MmoItemsRegistry.kt | 3 +++ .../src/main/kotlin/impl/vanilla/ItemMetaPayload.kt | 2 ++ .../src/main/kotlin/impl/vanilla/MinecraftItemsRegistry.kt | 3 +++ mimic-bukkit/src/main/kotlin/items/WrappedItemsRegistry.kt | 2 ++ mimic-bukkit/src/test/kotlin/MimicImplTest.kt | 2 +- .../src/test/kotlin/impl/mimic/MimicItemsRegistryTest.kt | 2 ++ .../src/test/kotlin/impl/vanilla/ItemMetaPayloadTest.kt | 2 ++ .../test/kotlin/impl/vanilla/MinecraftItemsRegistryTest.kt | 2 ++ 21 files changed, 47 insertions(+), 4 deletions(-) diff --git a/mimic-api/src/main/kotlin/items/ItemsRegistry.kt b/mimic-api/src/main/kotlin/items/ItemsRegistry.kt index a9e80bf1..c6b9c953 100644 --- a/mimic-api/src/main/kotlin/items/ItemsRegistry.kt +++ b/mimic-api/src/main/kotlin/items/ItemsRegistry.kt @@ -19,6 +19,7 @@ import ru.endlesscode.mimic.MimicService * Mapping them to the plugin's own IDs is up to the implementation: `itemsadder:ruby_sword` -> `itemsadder/ruby_sword`. * Invalid IDs are ignored. */ +@Deprecated("Use Items API from mimic-bukkit-api instead, it identifies items by their owner and creates them for a player.") public interface ItemsRegistry : MimicService { /** Returns all known item IDs. */ diff --git a/mimic-bukkit-api/src/main/kotlin/Mimic.kt b/mimic-bukkit-api/src/main/kotlin/Mimic.kt index 2227a231..0dc800cd 100644 --- a/mimic-bukkit-api/src/main/kotlin/Mimic.kt +++ b/mimic-bukkit-api/src/main/kotlin/Mimic.kt @@ -1,7 +1,7 @@ // Copyright (c) 2022 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT -@file:Suppress("DEPRECATION") // LevelSystem and ClassSystem APIs are deprecated but still supported +@file:Suppress("DEPRECATION") // LevelSystem, ClassSystem and ItemsRegistry APIs are deprecated but still supported package ru.endlesscode.mimic @@ -170,6 +170,7 @@ public interface Mimic { * @param plugin The plugin implementing this item registry. * @return registered registry or `null` if it was not registered. */ + @Deprecated("Use registerItemProvider instead.") public fun registerItemsRegistry( registry: BukkitItemsRegistry, apiLevel: Int, @@ -189,6 +190,7 @@ public interface Mimic { * preferred service in config. * @return registered registry or `null` if it was not registered. */ + @Deprecated("Use registerItemProvider instead.") public fun registerItemsRegistry( registry: BukkitItemsRegistry, apiLevel: Int, @@ -197,9 +199,11 @@ public interface Mimic { ): BukkitItemsRegistry? /** Returns [BukkitItemsRegistry] implementation. */ + @Deprecated("Use items instead.") public val itemsRegistry: BukkitItemsRegistry /** Returns map containing all known [BukkitItemsRegistry], where key is an item registry ID. */ + @Deprecated("Use items.getAllItems() instead.") public fun getAllItemsRegistries(): Map // endregion diff --git a/mimic-bukkit-api/src/main/kotlin/items/BukkitItemsRegistry.kt b/mimic-bukkit-api/src/main/kotlin/items/BukkitItemsRegistry.kt index de16f99d..d2c62409 100644 --- a/mimic-bukkit-api/src/main/kotlin/items/BukkitItemsRegistry.kt +++ b/mimic-bukkit-api/src/main/kotlin/items/BukkitItemsRegistry.kt @@ -1,9 +1,12 @@ // Copyright (c) 2018 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT +@file:Suppress("DEPRECATION") // ItemsRegistry API is deprecated but still supported + package ru.endlesscode.mimic.items import org.bukkit.inventory.ItemStack /** [ItemsRegistry] for Bukkit. */ +@Deprecated("Use Items API instead: implement ItemProvider to provide items, use Items to get them.") public interface BukkitItemsRegistry : ItemsRegistry diff --git a/mimic-bukkit/src/main/kotlin/MimicImpl.kt b/mimic-bukkit/src/main/kotlin/MimicImpl.kt index a9fe6db7..3517acfb 100644 --- a/mimic-bukkit/src/main/kotlin/MimicImpl.kt +++ b/mimic-bukkit/src/main/kotlin/MimicImpl.kt @@ -1,7 +1,7 @@ // Copyright (c) 2022 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT -@file:Suppress("DEPRECATION", "OVERRIDE_DEPRECATION") // LevelSystem and ClassSystem APIs are deprecated but still supported +@file:Suppress("DEPRECATION", "OVERRIDE_DEPRECATION") // LevelSystem, ClassSystem and ItemsRegistry APIs are deprecated but still supported package ru.endlesscode.mimic diff --git a/mimic-bukkit/src/main/kotlin/MimicPlugin.kt b/mimic-bukkit/src/main/kotlin/MimicPlugin.kt index 5ee6c262..7f50b192 100644 --- a/mimic-bukkit/src/main/kotlin/MimicPlugin.kt +++ b/mimic-bukkit/src/main/kotlin/MimicPlugin.kt @@ -1,7 +1,7 @@ // Copyright (c) 2018 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT -@file:Suppress("DEPRECATION") // LevelSystem and ClassSystem APIs are deprecated but still supported +@file:Suppress("DEPRECATION") // LevelSystem, ClassSystem and ItemsRegistry APIs are deprecated but still supported package ru.endlesscode.mimic diff --git a/mimic-bukkit/src/main/kotlin/command/ConfigCommand.kt b/mimic-bukkit/src/main/kotlin/command/ConfigCommand.kt index 13c73fe1..e12e8613 100644 --- a/mimic-bukkit/src/main/kotlin/command/ConfigCommand.kt +++ b/mimic-bukkit/src/main/kotlin/command/ConfigCommand.kt @@ -1,6 +1,8 @@ // Copyright (c) 2023 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT +@file:Suppress("DEPRECATION") // ItemsRegistry API is deprecated but still supported + package ru.endlesscode.mimic.command import com.mojang.brigadier.arguments.StringArgumentType diff --git a/mimic-bukkit/src/main/kotlin/command/ConfigMessage.kt b/mimic-bukkit/src/main/kotlin/command/ConfigMessage.kt index 1f4c97e1..438ec41e 100644 --- a/mimic-bukkit/src/main/kotlin/command/ConfigMessage.kt +++ b/mimic-bukkit/src/main/kotlin/command/ConfigMessage.kt @@ -1,6 +1,8 @@ // Copyright (c) 2023 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT +@file:Suppress("DEPRECATION") // ItemsRegistry API is deprecated but still supported + package ru.endlesscode.mimic.command import net.kyori.adventure.text.TextComponent diff --git a/mimic-bukkit/src/main/kotlin/config/MimicConfig.kt b/mimic-bukkit/src/main/kotlin/config/MimicConfig.kt index f5d32740..73322d96 100644 --- a/mimic-bukkit/src/main/kotlin/config/MimicConfig.kt +++ b/mimic-bukkit/src/main/kotlin/config/MimicConfig.kt @@ -1,6 +1,8 @@ // Copyright (c) 2022 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT +@file:Suppress("DEPRECATION") // ItemsRegistry API is deprecated but still supported + package ru.endlesscode.mimic.config import org.bukkit.configuration.Configuration diff --git a/mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineItemsRegistry.kt b/mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineItemsRegistry.kt index 68de5345..58d5b891 100644 --- a/mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineItemsRegistry.kt +++ b/mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineItemsRegistry.kt @@ -1,6 +1,8 @@ // Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT +@file:Suppress("DEPRECATION") // ItemsRegistry API is deprecated but still supported + package ru.endlesscode.mimic.impl.craftengine import net.momirealms.craftengine.bukkit.item.BukkitItemDefinition @@ -12,6 +14,7 @@ import ru.endlesscode.mimic.items.BukkitItemsRegistry * CraftEngine namespace becomes the first path segment of item ID: `default:palm_log` -> `default/palm_log`. * Vanilla items modified by CraftEngine are left to the vanilla registry. */ +@Deprecated("Use Items API instead, CraftEngine items have the same IDs there.") public class CraftEngineItemsRegistry private constructor( private val craftEngine: CraftEngineWrapper, ) : BukkitItemsRegistry { diff --git a/mimic-bukkit/src/main/kotlin/impl/customitems/CustomItemsRegistry.kt b/mimic-bukkit/src/main/kotlin/impl/customitems/CustomItemsRegistry.kt index cae4e343..ac7ca2aa 100644 --- a/mimic-bukkit/src/main/kotlin/impl/customitems/CustomItemsRegistry.kt +++ b/mimic-bukkit/src/main/kotlin/impl/customitems/CustomItemsRegistry.kt @@ -1,12 +1,15 @@ // Copyright (c) 2020 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT +@file:Suppress("DEPRECATION") // ItemsRegistry API is deprecated but still supported + package ru.endlesscode.mimic.impl.customitems import com.jojodmo.customitems.api.CustomItemsAPI import org.bukkit.inventory.ItemStack import ru.endlesscode.mimic.items.BukkitItemsRegistry +@Deprecated("Use Items API instead, CustomItems items have the same IDs there.") public class CustomItemsRegistry : BukkitItemsRegistry { override val id: String = ID diff --git a/mimic-bukkit/src/main/kotlin/impl/mimic/ItemsRegistryProvider.kt b/mimic-bukkit/src/main/kotlin/impl/mimic/ItemsRegistryProvider.kt index a3c1ae3d..6ca7b751 100644 --- a/mimic-bukkit/src/main/kotlin/impl/mimic/ItemsRegistryProvider.kt +++ b/mimic-bukkit/src/main/kotlin/impl/mimic/ItemsRegistryProvider.kt @@ -1,6 +1,8 @@ // Copyright (c) 2018 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT +@file:Suppress("DEPRECATION", "TYPEALIAS_EXPANSION_DEPRECATION") // ItemsRegistry API is deprecated but still supported + package ru.endlesscode.mimic.impl.mimic import ru.endlesscode.mimic.ServiceEntry diff --git a/mimic-bukkit/src/main/kotlin/impl/mimic/MimicItemsRegistry.kt b/mimic-bukkit/src/main/kotlin/impl/mimic/MimicItemsRegistry.kt index 4231d317..e6604b2b 100644 --- a/mimic-bukkit/src/main/kotlin/impl/mimic/MimicItemsRegistry.kt +++ b/mimic-bukkit/src/main/kotlin/impl/mimic/MimicItemsRegistry.kt @@ -1,6 +1,8 @@ // Copyright (c) 2020 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT +@file:Suppress("DEPRECATION", "TYPEALIAS_EXPANSION_DEPRECATION") // ItemsRegistry API is deprecated but still supported + package ru.endlesscode.mimic.impl.mimic import org.bukkit.inventory.ItemStack @@ -15,6 +17,7 @@ import ru.endlesscode.mimic.items.BukkitItemsRegistry * ID without namespace or with the `mimic` namespace is searched over all registries. * Deprecated IDs with uppercase letters or more than one `:` are accepted with a warning. */ +@Deprecated("Use Items API instead.") public class MimicItemsRegistry internal constructor( private val registries: ServiceRegistry, ) : BukkitItemsRegistry { diff --git a/mimic-bukkit/src/main/kotlin/impl/mimic/SafeBukkitItemsRegistry.kt b/mimic-bukkit/src/main/kotlin/impl/mimic/SafeBukkitItemsRegistry.kt index 3fdac80a..9e802e5a 100644 --- a/mimic-bukkit/src/main/kotlin/impl/mimic/SafeBukkitItemsRegistry.kt +++ b/mimic-bukkit/src/main/kotlin/impl/mimic/SafeBukkitItemsRegistry.kt @@ -1,6 +1,8 @@ // Copyright (c) 2021 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT +@file:Suppress("DEPRECATION", "TYPEALIAS_EXPANSION_DEPRECATION") // ItemsRegistry API is deprecated but still supported + package ru.endlesscode.mimic.impl.mimic import org.bukkit.inventory.ItemStack diff --git a/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsRegistry.kt b/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsRegistry.kt index 7253701c..e196c1f1 100644 --- a/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsRegistry.kt +++ b/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsRegistry.kt @@ -1,12 +1,15 @@ // Copyright (c) 2021 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT +@file:Suppress("DEPRECATION") // ItemsRegistry API is deprecated but still supported + package ru.endlesscode.mimic.impl.mmoitems import net.Indyuce.mmoitems.api.item.template.MMOItemTemplate import org.bukkit.inventory.ItemStack import ru.endlesscode.mimic.items.BukkitItemsRegistry +@Deprecated("Use Items API instead, MMOItems IDs include the item type there: `mmoitems:sword/excalibur`.") public class MmoItemsRegistry private constructor(private val mmoItems: MmoItemsWrapper) : BukkitItemsRegistry { internal constructor() : this(MmoItemsWrapper()) diff --git a/mimic-bukkit/src/main/kotlin/impl/vanilla/ItemMetaPayload.kt b/mimic-bukkit/src/main/kotlin/impl/vanilla/ItemMetaPayload.kt index b30e3472..6afc5ace 100644 --- a/mimic-bukkit/src/main/kotlin/impl/vanilla/ItemMetaPayload.kt +++ b/mimic-bukkit/src/main/kotlin/impl/vanilla/ItemMetaPayload.kt @@ -1,6 +1,7 @@ // Copyright (c) 2018 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT +@file:Suppress("DEPRECATION") // ItemMetaPayload is deprecated but still supported @file:UseSerializers(EnchantmentSerializer::class, ItemFlagsSerializer::class, MiniMessageComponentSerializer::class) package ru.endlesscode.mimic.impl.vanilla @@ -30,6 +31,7 @@ import ru.endlesscode.mimic.internal.* * @see org.bukkit.inventory.meta.ItemMeta * @see ItemMetaPayload.parse */ +@Deprecated("Use item components as a payload instead, for example `[damage=10,unbreakable={}]`.") @Serializable public data class ItemMetaPayload( val name: Component? = null, diff --git a/mimic-bukkit/src/main/kotlin/impl/vanilla/MinecraftItemsRegistry.kt b/mimic-bukkit/src/main/kotlin/impl/vanilla/MinecraftItemsRegistry.kt index 53155cba..718a9554 100644 --- a/mimic-bukkit/src/main/kotlin/impl/vanilla/MinecraftItemsRegistry.kt +++ b/mimic-bukkit/src/main/kotlin/impl/vanilla/MinecraftItemsRegistry.kt @@ -1,6 +1,8 @@ // Copyright (c) 2020 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT +@file:Suppress("DEPRECATION") // ItemsRegistry API is deprecated but still supported + package ru.endlesscode.mimic.impl.vanilla import org.bukkit.Bukkit @@ -21,6 +23,7 @@ import ru.endlesscode.mimic.items.BukkitItemsRegistry * Name and lore support MiniMessage formatting. * - [ItemMetaPayload] instance. */ +@Deprecated("Use Items API instead, vanilla items have the `minecraft` namespace there too.") public class MinecraftItemsRegistry : BukkitItemsRegistry { override val id: String = ID diff --git a/mimic-bukkit/src/main/kotlin/items/WrappedItemsRegistry.kt b/mimic-bukkit/src/main/kotlin/items/WrappedItemsRegistry.kt index 3b92b539..9d8e2526 100644 --- a/mimic-bukkit/src/main/kotlin/items/WrappedItemsRegistry.kt +++ b/mimic-bukkit/src/main/kotlin/items/WrappedItemsRegistry.kt @@ -1,6 +1,8 @@ // Copyright (c) 2022 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT +@file:Suppress("DEPRECATION") // ItemsRegistry API is deprecated but still supported + package ru.endlesscode.mimic.items import org.bukkit.inventory.ItemStack diff --git a/mimic-bukkit/src/test/kotlin/MimicImplTest.kt b/mimic-bukkit/src/test/kotlin/MimicImplTest.kt index dd311dff..bf47916d 100644 --- a/mimic-bukkit/src/test/kotlin/MimicImplTest.kt +++ b/mimic-bukkit/src/test/kotlin/MimicImplTest.kt @@ -1,7 +1,7 @@ // Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT -@file:Suppress("DEPRECATION") // LevelSystem and ClassSystem APIs are deprecated but still supported +@file:Suppress("DEPRECATION") // LevelSystem, ClassSystem and ItemsRegistry APIs are deprecated but still supported package ru.endlesscode.mimic diff --git a/mimic-bukkit/src/test/kotlin/impl/mimic/MimicItemsRegistryTest.kt b/mimic-bukkit/src/test/kotlin/impl/mimic/MimicItemsRegistryTest.kt index 85dbf4e8..946324f8 100644 --- a/mimic-bukkit/src/test/kotlin/impl/mimic/MimicItemsRegistryTest.kt +++ b/mimic-bukkit/src/test/kotlin/impl/mimic/MimicItemsRegistryTest.kt @@ -1,6 +1,8 @@ // Copyright (c) 2020 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT +@file:Suppress("DEPRECATION") // ItemsRegistry API is deprecated but still supported + package ru.endlesscode.mimic.impl.mimic import io.kotest.assertions.assertSoftly diff --git a/mimic-bukkit/src/test/kotlin/impl/vanilla/ItemMetaPayloadTest.kt b/mimic-bukkit/src/test/kotlin/impl/vanilla/ItemMetaPayloadTest.kt index e44986ab..8e948d05 100644 --- a/mimic-bukkit/src/test/kotlin/impl/vanilla/ItemMetaPayloadTest.kt +++ b/mimic-bukkit/src/test/kotlin/impl/vanilla/ItemMetaPayloadTest.kt @@ -1,6 +1,8 @@ // Copyright (c) 2021 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT +@file:Suppress("DEPRECATION") // ItemMetaPayload is deprecated but still supported + package ru.endlesscode.mimic.impl.vanilla import io.kotest.matchers.nulls.shouldBeNull diff --git a/mimic-bukkit/src/test/kotlin/impl/vanilla/MinecraftItemsRegistryTest.kt b/mimic-bukkit/src/test/kotlin/impl/vanilla/MinecraftItemsRegistryTest.kt index 4f26be21..8786a27f 100644 --- a/mimic-bukkit/src/test/kotlin/impl/vanilla/MinecraftItemsRegistryTest.kt +++ b/mimic-bukkit/src/test/kotlin/impl/vanilla/MinecraftItemsRegistryTest.kt @@ -1,6 +1,8 @@ // Copyright (c) 2020 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT +@file:Suppress("DEPRECATION") // ItemsRegistry API is deprecated but still supported + package ru.endlesscode.mimic.impl.vanilla import io.kotest.assertions.assertSoftly From f52a41873900078940dd3f357a802b00262899be Mon Sep 17 00:00:00 2001 From: Osip Fatkullin Date: Mon, 16 Nov 2026 10:37:17 +0100 Subject: [PATCH 09/11] feat: Bridge from ItemsRegistry to Items API Every registered ItemsRegistry is available via Items API as an item provider, an ItemProvider with the same ID always replaces the bridge. Mimic.itemsRegistry is a view over Items: it keeps the search without a namespace, IDs with more than one ':' and MMOItems IDs without item type, but compares items by their owner (#86). Items registries' own isSameItem is used again (#85). Co-Authored-By: Claude Fable 5.2 --- mimic-bukkit-api/src/main/kotlin/Mimic.kt | 5 +- mimic-bukkit/src/main/kotlin/MimicImpl.kt | 20 +- mimic-bukkit/src/main/kotlin/MimicMetrics.kt | 2 +- .../impl/mimic/ItemsRegistryProvider.kt | 14 - .../kotlin/impl/mimic/MimicItemsRegistry.kt | 137 ++++++---- .../impl/mimic/SafeBukkitItemsRegistry.kt | 24 -- .../kotlin/items/ItemsRegistryItemProvider.kt | 48 ++++ .../main/kotlin/items/WrappedItemsRegistry.kt | 2 + mimic-bukkit/src/test/kotlin/MimicImplTest.kt | 63 +++++ .../impl/mimic/MimicItemsRegistryTest.kt | 242 +++++++++++++++--- 10 files changed, 421 insertions(+), 136 deletions(-) delete mode 100644 mimic-bukkit/src/main/kotlin/impl/mimic/ItemsRegistryProvider.kt delete mode 100644 mimic-bukkit/src/main/kotlin/impl/mimic/SafeBukkitItemsRegistry.kt create mode 100644 mimic-bukkit/src/main/kotlin/items/ItemsRegistryItemProvider.kt diff --git a/mimic-bukkit-api/src/main/kotlin/Mimic.kt b/mimic-bukkit-api/src/main/kotlin/Mimic.kt index 0dc800cd..32fe0c33 100644 --- a/mimic-bukkit-api/src/main/kotlin/Mimic.kt +++ b/mimic-bukkit-api/src/main/kotlin/Mimic.kt @@ -198,7 +198,10 @@ public interface Mimic { priority: ServicePriority, ): BukkitItemsRegistry? - /** Returns [BukkitItemsRegistry] implementation. */ + /** + * Returns [BukkitItemsRegistry] combining items of all item providers. + * Unlike [items], it searches an ID without a namespace over all providers. + */ @Deprecated("Use items instead.") public val itemsRegistry: BukkitItemsRegistry diff --git a/mimic-bukkit/src/main/kotlin/MimicImpl.kt b/mimic-bukkit/src/main/kotlin/MimicImpl.kt index 3517acfb..8e19e49a 100644 --- a/mimic-bukkit/src/main/kotlin/MimicImpl.kt +++ b/mimic-bukkit/src/main/kotlin/MimicImpl.kt @@ -28,6 +28,7 @@ import ru.endlesscode.mimic.internal.authorsMention import ru.endlesscode.mimic.inventory.WrappedPlayerInventoryProvider import ru.endlesscode.mimic.items.BukkitItemsRegistry import ru.endlesscode.mimic.items.ItemProvider +import ru.endlesscode.mimic.items.ItemsRegistryItemProvider import ru.endlesscode.mimic.items.WrappedItemProvider import ru.endlesscode.mimic.items.WrappedItemsRegistry import ru.endlesscode.mimic.level.* @@ -65,10 +66,9 @@ internal class MimicImpl( "PlayerInventory", defaultId = MinecraftPlayerInventory.ID, ) - val itemsRegistries = registry( + private val itemsRegistries = registry( "ItemsRegistry", defaultId = MinecraftItemsRegistry.ID, - disabledIds = { config.disabledItemsRegistries }, ) val itemProviders = registry( "ItemProvider", @@ -160,11 +160,20 @@ internal class MimicImpl( apiLevel: Int, plugin: Plugin, priority: ServicePriority, - ): BukkitItemsRegistry? = itemsRegistries.tryRegister(apiLevel, plugin, priority) { - WrappedItemsRegistry(registry, plugin) + ): BukkitItemsRegistry? { + val itemsRegistry = itemsRegistries.tryRegister(apiLevel, plugin, priority) { + WrappedItemsRegistry(registry, plugin) + } + if (itemsRegistry != null) { + itemProviders.registerBridge(ItemsRegistryItemProvider(itemsRegistry), plugin, priority) { + "ItemsRegistry '${itemsRegistry.id}' by $plugin uses deprecated ItemsRegistry API, " + + "so its items are available via Items API as '${itemsRegistry.id}:'. " + + "Please ask ${plugin.authorsMention} to migrate to ItemProvider." + } + } + return itemsRegistry } - override val itemsRegistry: BukkitItemsRegistry = MimicItemsRegistry(itemsRegistries) override fun getAllItemsRegistries(): Map = itemsRegistries.loadAll() // endregion @@ -179,6 +188,7 @@ internal class MimicImpl( } override val items = MimicItems(itemProviders) + override val itemsRegistry: BukkitItemsRegistry = MimicItemsRegistry(items) // endregion // region Level System diff --git a/mimic-bukkit/src/main/kotlin/MimicMetrics.kt b/mimic-bukkit/src/main/kotlin/MimicMetrics.kt index bf8a6db5..de087003 100644 --- a/mimic-bukkit/src/main/kotlin/MimicMetrics.kt +++ b/mimic-bukkit/src/main/kotlin/MimicMetrics.kt @@ -25,7 +25,7 @@ internal fun Plugin.initMetrics(mimic: MimicImpl) { metrics.addCustomChart(DrilldownPie("level_providers") { registryChartData(mimic.levelProviders) }) metrics.addCustomChart(DrilldownPie("class_providers") { registryChartData(mimic.classProviders) }) metrics.addCustomChart(DrilldownPie("resource_providers") { registryChartData(mimic.resourceProviders) }) - metrics.addCustomChart(DrilldownPie("items_registries") { registryChartData(mimic.itemsRegistries) }) + metrics.addCustomChart(DrilldownPie("item_providers") { registryChartData(mimic.itemProviders) }) metrics.addCustomChart(DrilldownPie("block_providers") { registryChartData(mimic.blockProviders) }) metrics.addCustomChart(SimplePie("inventory_provider") { mimic.getPlayerInventoryProvider().id }) metrics.addCustomChart(DrilldownPie("dependent_plugins") { dependentPluginsChartData() }) diff --git a/mimic-bukkit/src/main/kotlin/impl/mimic/ItemsRegistryProvider.kt b/mimic-bukkit/src/main/kotlin/impl/mimic/ItemsRegistryProvider.kt deleted file mode 100644 index 6ca7b751..00000000 --- a/mimic-bukkit/src/main/kotlin/impl/mimic/ItemsRegistryProvider.kt +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) 2018 Osip Fatkullin, EndlessCode Group and contributors -// SPDX-License-Identifier: MIT - -@file:Suppress("DEPRECATION", "TYPEALIAS_EXPANSION_DEPRECATION") // ItemsRegistry API is deprecated but still supported - -package ru.endlesscode.mimic.impl.mimic - -import ru.endlesscode.mimic.ServiceEntry -import ru.endlesscode.mimic.items.BukkitItemsRegistry - -internal typealias ItemsRegistryProvider = ServiceEntry - -internal inline val ItemsRegistryProvider.registry: BukkitItemsRegistry - get() = service diff --git a/mimic-bukkit/src/main/kotlin/impl/mimic/MimicItemsRegistry.kt b/mimic-bukkit/src/main/kotlin/impl/mimic/MimicItemsRegistry.kt index e6604b2b..d80388a6 100644 --- a/mimic-bukkit/src/main/kotlin/impl/mimic/MimicItemsRegistry.kt +++ b/mimic-bukkit/src/main/kotlin/impl/mimic/MimicItemsRegistry.kt @@ -1,66 +1,67 @@ // Copyright (c) 2020 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT -@file:Suppress("DEPRECATION", "TYPEALIAS_EXPANSION_DEPRECATION") // ItemsRegistry API is deprecated but still supported +@file:Suppress("DEPRECATION") // ItemsRegistry API is deprecated but still supported package ru.endlesscode.mimic.impl.mimic import org.bukkit.inventory.ItemStack -import ru.endlesscode.mimic.ServiceRegistry +import ru.endlesscode.mimic.call +import ru.endlesscode.mimic.impl.mmoitems.MmoItemsItemProvider import ru.endlesscode.mimic.internal.MimicId -import ru.endlesscode.mimic.internal.authorsMention +import ru.endlesscode.mimic.internal.OnceWarnings import ru.endlesscode.mimic.internal.parseMimicId import ru.endlesscode.mimic.items.BukkitItemsRegistry +import ru.endlesscode.mimic.items.ItemsRegistryItemProvider /** - * Items registry combining all items registries, using their IDs as namespaces: `acacia_boat` -> `minecraft:acacia_boat`. - * ID without namespace or with the `mimic` namespace is searched over all registries. - * Deprecated IDs with uppercase letters or more than one `:` are accepted with a warning. + * Items registry showing items of all item providers via the deprecated ItemsRegistry API, + * using provider IDs as namespaces: `acacia_boat` -> `minecraft:acacia_boat`. + * + * Unlike Items API, it accepts IDs deprecated there: + * - ID without namespace or with the `mimic` namespace is searched over all providers. + * - IDs with uppercase letters or more than one `:` are accepted with a warning. + * - MMOItems ID without item type (`mmoitems:excalibur`) is accepted with a warning if only one type has this item. */ @Deprecated("Use Items API instead.") -public class MimicItemsRegistry internal constructor( - private val registries: ServiceRegistry, -) : BukkitItemsRegistry { +public class MimicItemsRegistry internal constructor(private val items: MimicItems) : BukkitItemsRegistry { override val id: String = ID override val knownIds: Collection - get() = providers.flatMap { provider -> - provider.tryGetKnownIds().mapNotNull { provider.namespaced(it) } - } + get() = items.getAllItems().map { it.asString() } - internal val providers: List - get() = registries.enabledEntries + private val warnings: OnceWarnings + get() = items.providers.registry.warnings override fun isSameItem(item: ItemStack, itemId: String): Boolean { - val id = parse(itemId) ?: return false - return getRegistries(id) - .any { provider -> provider.tryIsSameItem(item, id.path) } - } - - override fun isItemExists(itemId: String): Boolean { - val id = parse(itemId) ?: return false - return getRegistries(id) - .any { provider -> provider.tryIsItemExists(id.path) } - } - - override fun getItemId(item: ItemStack): String? { - val (provider, itemId) = providers.firstNotNullOfOrNull { provider -> - provider.tryGetItemId(item)?.let { provider to it } - } ?: return null - return provider.namespaced(itemId) - } - - override fun getItem(itemId: String, payload: Any?, amount: Int): ItemStack? { - val id = parse(itemId) ?: return null - return getRegistries(id) - .mapNotNull { service -> service.tryGetItem(id.path, payload, amount) } - .firstOrNull() + val (owner, ownerId) = items.owner(item) ?: return false + return candidates(itemId) { it == owner }.any { (provider, path) -> + path == ownerId.value() || provider.isSameItemInRegistry(item, path) + } } - private fun getRegistries(id: MimicId): Sequence { - return providers.asSequence() - .filter { id.matches(it.registry.id) } + override fun isItemExists(itemId: String): Boolean = + candidates(itemId).any { (provider, path) -> provider.hasItem(path) } + + override fun getItemId(item: ItemStack): String? = items.getItemId(item)?.asString() + + override fun getItem(itemId: String, payload: Any?, amount: Int): ItemStack? = + candidates(itemId).firstNotNullOfOrNull { (provider, path) -> provider.getItem(path, payload, amount) } + + /** + * Returns providers that may have the item with the given [itemId], paired with the ID of the item in the provider. + * Only providers matching the [filter] are returned. + */ + private inline fun candidates( + itemId: String, + filter: (ItemProviderEntry) -> Boolean = { true }, + ): List> { + val id = parse(itemId) ?: return emptyList() + val path = id.path.replace(':', '/') + return items.providers.enabled + .filter { id.matches(it.service.id) && filter(it) } + .map { provider -> provider to provider.withMmoItemsType(path) } } /** Parses the given [itemId], or returns `null` if it is invalid. */ @@ -69,32 +70,56 @@ public class MimicItemsRegistry internal constructor( val id = parseMimicId(lowercaseId, allowLegacy = true) ?: return null if (lowercaseId != itemId) { - registries.warnings.warn("uppercase:$itemId") { "Item ID '$itemId' is deprecated, use '$lowercaseId' instead." } + warnings.warn("uppercase:$itemId") { "Item ID '$itemId' is deprecated, use '$lowercaseId' instead." } } if (id.isLegacy) { - registries.warnings.warn("legacy") { "Item ID '$itemId' contains more than one ':', this is deprecated." } + warnings.warn("legacy:$itemId") { + "Item ID '$itemId' contains more than one ':', this is deprecated. Use '/' instead of the next ones." + } } return id } - /** Returns the given [itemId] prefixed with the registry ID, or `null` if the result is invalid. */ - private fun ItemsRegistryProvider.namespaced(itemId: String): String? { - val namespacedId = "${registry.id}:$itemId" - val id = parseMimicId(namespacedId, allowLegacy = true) - when { - id == null -> warnings.warn("invalid:${registry.id}") { - "Items registry '${registry.id}' returned invalid ID '$itemId', such items are ignored. " + - "IDs may contain only a-z, 0-9, '.', '_', '-' and '/'. " + - "Please, report it to ${plugin.authorsMention}." + /** + * MMOItems IDs had no item type before Mimic 0.11: `mmoitems:excalibur` instead of `mmoitems:sword/excalibur`. + * Returns the [path] with the type if this is MMOItems provider and only one type has the item. + */ + private fun ItemProviderEntry.withMmoItemsType(path: String): String { + if (service.id != MmoItemsItemProvider.ID || '/' in path) return path + val paths = call(default = emptyList()) { allItems.filter { it.substringAfter('/') == path } } + if (paths.isEmpty()) return path + + val typedPath = paths.singleOrNull() + warnings.warn("mmoitems-type:$path") { + if (typedPath != null) { + "Item ID '${service.id}:$path' without item type is deprecated, use '${service.id}:$typedPath' instead." + } else { + "Item ID '${service.id}:$path' is ambiguous, specify item type: ${paths.joinToString { "'${service.id}:$it'" }}." } + } + return typedPath ?: path + } + + /** Asks the registry behind this provider to compare items, so its own rules still work, like ignoring a part of the ID. */ + private fun ItemProviderEntry.isSameItemInRegistry(item: ItemStack, path: String): Boolean { + val registry = service as? ItemsRegistryItemProvider ?: return false + return call(default = false) { registry.isSameItem(item, path) } + } - id.isLegacy -> warnings.warn("legacy:${registry.id}") { - "Items registry '${registry.id}' returned ID '$itemId' containing ':', this is deprecated. " + - "Use '/' instead: '${itemId.replace(':', '/')}'. " + - "Please, report it to ${plugin.authorsMention}." + /** Payload may be of any type in ItemsRegistry API, but only registries may take a payload which isn't a string. */ + private fun ItemProviderEntry.getItem(path: String, payload: Any?, amount: Int): ItemStack? { + val registry = service as? ItemsRegistryItemProvider + return when { + payload == null || payload is String -> createItem(path, amount, player = null, payload as String?) + registry != null -> call(default = null) { registry.getItem(path, payload, amount) } + else -> { + warnings.warn("payload-type:${service.id}:${payload.javaClass.name}") { + "$apiName '${service.id}' takes only string payloads, but got ${payload.javaClass.name}. " + + "Items with such payloads aren't created." + } + null } } - return namespacedId.takeIf { id != null } } public companion object { diff --git a/mimic-bukkit/src/main/kotlin/impl/mimic/SafeBukkitItemsRegistry.kt b/mimic-bukkit/src/main/kotlin/impl/mimic/SafeBukkitItemsRegistry.kt deleted file mode 100644 index 9e802e5a..00000000 --- a/mimic-bukkit/src/main/kotlin/impl/mimic/SafeBukkitItemsRegistry.kt +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) 2021 Osip Fatkullin, EndlessCode Group and contributors -// SPDX-License-Identifier: MIT - -@file:Suppress("DEPRECATION", "TYPEALIAS_EXPANSION_DEPRECATION") // ItemsRegistry API is deprecated but still supported - -package ru.endlesscode.mimic.impl.mimic - -import org.bukkit.inventory.ItemStack -import ru.endlesscode.mimic.call - -internal fun ItemsRegistryProvider.tryGetKnownIds(): Collection = - call(default = emptyList()) { knownIds } - -internal fun ItemsRegistryProvider.tryIsSameItem(itemStack: ItemStack, itemId: String): Boolean = - call(default = false) { isSameItem(itemStack, itemId) } - -internal fun ItemsRegistryProvider.tryIsItemExists(itemId: String): Boolean = - call(default = false) { isItemExists(itemId) } - -internal fun ItemsRegistryProvider.tryGetItemId(itemStack: ItemStack): String? = - call(default = null) { getItemId(itemStack) } - -internal fun ItemsRegistryProvider.tryGetItem(itemId: String, payload: Any?, amount: Int): ItemStack? = - call(default = null) { getItem(itemId, payload, amount) } diff --git a/mimic-bukkit/src/main/kotlin/items/ItemsRegistryItemProvider.kt b/mimic-bukkit/src/main/kotlin/items/ItemsRegistryItemProvider.kt new file mode 100644 index 00000000..749169a8 --- /dev/null +++ b/mimic-bukkit/src/main/kotlin/items/ItemsRegistryItemProvider.kt @@ -0,0 +1,48 @@ +// Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors +// SPDX-License-Identifier: MIT + +@file:Suppress("DEPRECATION") // ItemsRegistry API is deprecated but still supported + +package ru.endlesscode.mimic.items + +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack + +/** + * Exposes the given [ItemsRegistry][BukkitItemsRegistry] as an item provider. + * + * Registries may return IDs containing `:`, like `itemsadder:ruby_sword`. Such IDs are exposed with `/` instead. + * A registry may return a shared stack, so created items are cloned. + * The player is ignored, the registry can't create an item for a player. + */ +internal class ItemsRegistryItemProvider(private val registry: BukkitItemsRegistry) : ItemProvider { + + override val id: String get() = registry.id + override val isEnabled: Boolean get() = registry.isEnabled + + override val allItems: Collection + get() = registry.knownIds.map(::toPath) + + // A registry may be unable to list its items, so ask it instead of looking in allItems + override fun hasItem(itemId: String): Boolean = registry.isItemExists(toRegistryId(itemId)) + + override fun getItemId(item: ItemStack): String? = registry.getItemId(item)?.let(::toPath) + + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack? = + getItem(itemId, payload, amount) + + /** Creates item with a payload of any type, as [ItemsRegistry] allows. */ + fun getItem(itemId: String, payload: Any?, amount: Int): ItemStack? = + registry.getItem(toRegistryId(itemId), payload, amount)?.clone() + + /** Compares the [item] with the [itemId] in the way of the registry, for example, ignoring a part of the ID. */ + fun isSameItem(item: ItemStack, itemId: String): Boolean = registry.isSameItem(item, toRegistryId(itemId)) + + private fun toPath(registryId: String): String = registryId.replace(':', '/') + + /** Returns ID of the registry for the [path], restoring `:` replaced by [toPath]. */ + private fun toRegistryId(path: String): String { + if ('/' !in path || registry.isItemExists(path)) return path + return registry.knownIds.find { toPath(it) == path } ?: path + } +} diff --git a/mimic-bukkit/src/main/kotlin/items/WrappedItemsRegistry.kt b/mimic-bukkit/src/main/kotlin/items/WrappedItemsRegistry.kt index 9d8e2526..9cd0030f 100644 --- a/mimic-bukkit/src/main/kotlin/items/WrappedItemsRegistry.kt +++ b/mimic-bukkit/src/main/kotlin/items/WrappedItemsRegistry.kt @@ -18,6 +18,8 @@ internal class WrappedItemsRegistry( override val knownIds: Collection by delegate::knownIds + override fun isSameItem(item: ItemStack, itemId: String) = delegate.isSameItem(item, itemId) + override fun isItemExists(itemId: String) = delegate.isItemExists(itemId) override fun getItemId(item: ItemStack) = delegate.getItemId(item) diff --git a/mimic-bukkit/src/test/kotlin/MimicImplTest.kt b/mimic-bukkit/src/test/kotlin/MimicImplTest.kt index bf47916d..b6eb8286 100644 --- a/mimic-bukkit/src/test/kotlin/MimicImplTest.kt +++ b/mimic-bukkit/src/test/kotlin/MimicImplTest.kt @@ -9,12 +9,15 @@ import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.maps.shouldBeEmpty import io.kotest.matchers.nulls.shouldBeNull +import io.kotest.matchers.booleans.shouldBeTrue import io.kotest.matchers.shouldBe import io.mockk.every import io.mockk.mockk import net.kyori.adventure.text.Component +import org.bukkit.Material import org.bukkit.entity.Player import org.bukkit.event.server.PluginDisableEvent +import org.bukkit.inventory.ItemStack import org.bukkit.plugin.Plugin import org.bukkit.plugin.ServicePriority.* import ru.endlesscode.mimic.classes.BukkitClassSystem @@ -23,6 +26,8 @@ import ru.endlesscode.mimic.config.MimicConfig import ru.endlesscode.mimic.impl.mimic.MimicLevels import ru.endlesscode.mimic.impl.mimic.getPrimaryClassProviderId import ru.endlesscode.mimic.impl.vanilla.MinecraftLevelProvider +import ru.endlesscode.mimic.items.BukkitItemsRegistry +import ru.endlesscode.mimic.items.ItemProvider import ru.endlesscode.mimic.level.* import kotlin.test.Test @@ -38,6 +43,7 @@ internal class MimicImplTest : BukkitTestBase() { private val config: MimicConfig = mockk { every { levelProvider } answers { preferredLevelProvider } every { classProvider } answers { preferredClassProvider } + every { disabledItemsRegistries } returns emptySet() } // SUT @@ -213,6 +219,49 @@ internal class MimicImplTest : BukkitTestBase() { mimic.getClassSystemProvider().id shouldBe "permissions" } + @Test + fun `when items registry is registered - should provide its items via items`() { + mimic.registerItemsRegistry(TestItemsRegistry("legacy"), MimicApiLevel.CURRENT, thirdParty, Normal) + + mimic.items.getAllItems().map { it.asString() } shouldContainExactly listOf("legacy:registry_item") + mimic.itemsRegistry.knownIds shouldContainExactly listOf("legacy:registry_item") + mimic.getAllItemsRegistries().keys shouldContainExactly listOf("legacy") + } + + // https://github.com/EndlessCodeGroup/Mimic/issues/85 + @Test + fun `when items registry is registered - should keep its own way to compare items`() { + val registry = mimic.registerItemsRegistry(TestItemsRegistry("legacy"), MimicApiLevel.CURRENT, thirdParty, Normal) + + registry?.isSameItem(ItemStack(Material.STONE), "any").shouldBeTrue() + } + + @Test + fun `when item provider is registered after items registry by another plugin - should replace it`() { + mimic.registerItemsRegistry(TestItemsRegistry("custom"), MimicApiLevel.CURRENT, thirdParty, High) + mimic.registerItemProvider(TestItemProvider("custom"), MimicApiLevel.CURRENT, otherPlugin, Normal) + + mimic.items.getAllItems().map { it.asString() } shouldContainExactly listOf("custom:provider_item") + } + + @Test + fun `when items registry is registered after item provider with the same ID - should not bridge it`() { + mimic.registerItemProvider(TestItemProvider("custom"), MimicApiLevel.CURRENT, thirdParty, Normal) + mimic.registerItemsRegistry(TestItemsRegistry("custom"), MimicApiLevel.CURRENT, otherPlugin, High) + + mimic.items.getAllItems().map { it.asString() } shouldContainExactly listOf("custom:provider_item") + } + + @Test + fun `when plugin is disabled - should unregister its items registries and item providers`() { + mimic.registerItemsRegistry(TestItemsRegistry("legacy"), MimicApiLevel.CURRENT, thirdParty, Normal) + mimic.registerItemProvider(TestItemProvider("custom"), MimicApiLevel.CURRENT, thirdParty, Normal) + + mimic.onPluginDisable(PluginDisableEvent(thirdParty)) + + mimic.items.getAllItems().shouldBeEmpty() + } + private fun List.keys() = map { it.key().asString() } private fun Levels.trackName(id: String) = getAllTracks().single { it.key().asString() == id }.name() @@ -242,6 +291,20 @@ internal class MimicImplTest : BukkitTestBase() { override fun getPrimarySlot(player: Player): ClassProvider.Slot? = null } + private class TestItemProvider(override val id: String) : ItemProvider { + override val allItems: Collection = listOf("provider_item") + override fun getItemId(item: ItemStack): String? = null + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack? = null + } + + private class TestItemsRegistry(override val id: String) : BukkitItemsRegistry { + override val knownIds: Collection = listOf("registry_item") + override fun isSameItem(item: ItemStack, itemId: String): Boolean = true + override fun isItemExists(itemId: String): Boolean = itemId in knownIds + override fun getItemId(item: ItemStack): String? = null + override fun getItem(itemId: String, payload: Any?, amount: Int): ItemStack? = null + } + private class TestClassSystemProvider(override val id: String) : BukkitClassSystem.Provider { override fun getSystem(player: Player): BukkitClassSystem = mockk { every { primaryClass } returns "Mage" diff --git a/mimic-bukkit/src/test/kotlin/impl/mimic/MimicItemsRegistryTest.kt b/mimic-bukkit/src/test/kotlin/impl/mimic/MimicItemsRegistryTest.kt index 946324f8..e869e40c 100644 --- a/mimic-bukkit/src/test/kotlin/impl/mimic/MimicItemsRegistryTest.kt +++ b/mimic-bukkit/src/test/kotlin/impl/mimic/MimicItemsRegistryTest.kt @@ -6,6 +6,7 @@ package ru.endlesscode.mimic.impl.mimic import io.kotest.assertions.assertSoftly +import io.kotest.matchers.booleans.shouldBeFalse import io.kotest.matchers.booleans.shouldBeTrue import io.kotest.matchers.collections.shouldContain import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder @@ -13,10 +14,13 @@ import io.kotest.matchers.collections.shouldNotContain import io.kotest.matchers.nulls.shouldBeNull import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.shouldBe +import io.kotest.matchers.string.shouldContain +import io.kotest.matchers.types.shouldNotBeSameInstanceAs import io.mockk.every import io.mockk.mockk import io.mockk.verify import org.bukkit.Material +import org.bukkit.entity.Player import org.bukkit.inventory.ItemStack import org.bukkit.plugin.ServicePriority.Lowest import org.bukkit.plugin.ServicePriority.Normal @@ -27,25 +31,57 @@ import ru.endlesscode.mimic.BukkitTestBase import ru.endlesscode.mimic.ServiceRegistry import ru.endlesscode.mimic.internal.Log import ru.endlesscode.mimic.items.BukkitItemsRegistry +import ru.endlesscode.mimic.items.ItemProvider +import ru.endlesscode.mimic.items.ItemsRegistryItemProvider import kotlin.test.Test internal class MimicItemsRegistryTest : BukkitTestBase() { + private val providers = ServiceRegistry("ItemProvider", plugin, defaultId = "test") + // SUT - private val registries = ServiceRegistry("ItemsRegistry", plugin, defaultId = "minecraft") - private val itemsService: BukkitItemsRegistry = MimicItemsRegistry(registries) + private val itemsService: BukkitItemsRegistry = MimicItemsRegistry(MimicItems(providers)) init { - registries.register(TestItemRegistry(), plugin, Lowest) + providers.register(VanillaItemProvider(), plugin, Lowest) } @ParameterizedTest - @ValueSource(strings = ["acacia_boat", "test:acacia_boat"]) + @ValueSource(strings = ["acacia_boat", "test:acacia_boat", "mimic:acacia_boat"]) fun `when check is same item - should return true`(itemId: String) { val item = ItemStack(Material.ACACIA_BOAT) itemsService.isSameItem(item, itemId).shouldBeTrue() } + // https://github.com/EndlessCodeGroup/Mimic/issues/86 + @ParameterizedTest + @CsvSource( + "test:emerald, false", + "emerald, false", + "custom:ruby, true", + "ruby, true", + ) + fun `when check is same item - should not match custom item with its vanilla base`(itemId: String, isSame: Boolean) { + providers.register(RubyItemProvider(), plugin, Normal) + + itemsService.isSameItem(ItemStack(Material.EMERALD), itemId) shouldBe isSame + } + + // https://github.com/EndlessCodeGroup/Mimic/issues/85 + @ParameterizedTest + @CsvSource( + "quantum:gems/ruby, true", + "quantum:ruby, true", + "ruby, true", + "quantum:emerald, false", + "test:ruby, false", + ) + fun `when registry compares items in its own way - should use it`(itemId: String, isSame: Boolean) { + registerRegistry(ModularItemRegistry()) + + itemsService.isSameItem(ItemStack(Material.EMERALD), itemId) shouldBe isSame + } + @ParameterizedTest @ValueSource(strings = ["acacia_boat", "test:acacia_boat", "mimic:acacia_boat", "test:ACACIA_BOAT", "Test:acacia_boat"]) fun `when get item - should return item stack`(itemId: String) { @@ -63,6 +99,33 @@ internal class MimicItemsRegistryTest : BukkitTestBase() { itemsService.getItem(itemId).shouldBeNull() } + @Test + fun `when get item with payload - should pass string payload to provider`() { + val provider = VanillaItemProvider() + providers.register(provider, plugin, Lowest) + + assertSoftly { + itemsService.getItem("test:stone", "[damage=10]", 5)?.amount shouldBe 5 + provider.lastPayload shouldBe "[damage=10]" + // Item providers can't take a payload which isn't a string + itemsService.getItem("test:stone", 42, 5).shouldBeNull() + } + } + + @Test + fun `when get item from registry - should pass payload of any type and copy the stack`() { + val registry = ModularItemRegistry() + registerRegistry(registry) + + val item = itemsService.getItem("quantum:gems/ruby", 42, 5) + + assertSoftly { + registry.lastPayload shouldBe 42 + item?.type shouldBe Material.EMERALD + item shouldNotBeSameInstanceAs registry.sharedStack + } + } + @Test fun `when get id - should return id`() { val item = ItemStack(Material.ACACIA_BOAT) @@ -71,28 +134,38 @@ internal class MimicItemsRegistryTest : BukkitTestBase() { @ParameterizedTest @CsvSource( - "air, true", - "ns:air, false", - "test:air, true", + "stone, true", + "ns:stone, false", + "test:stone, true", "unknown, false", "gold_sword, false", "golden_sword, true", - "mimic:air, true", - "test:AIR, true", - "test:air!, false", + "mimic:stone, true", + "test:STONE, true", + "test:stone!, false", ) fun `when check is item exists`(itemId: String, shouldExist: Boolean) { itemsService.isItemExists(itemId) shouldBe shouldExist } + @Test + fun `when registry can't list an item - should ask it whether the item exists`() { + registerRegistry(ModularItemRegistry()) + + assertSoftly { + itemsService.isItemExists("quantum:ruby").shouldBeTrue() + itemsService.isItemExists("quantum:emerald").shouldBeFalse() + } + } + @ParameterizedTest @ValueSource(strings = ["test:acacia boat", ":acacia_boat", "test:", "test:acacia_boat!"]) - fun `when use invalid id - should not query registries`(itemId: String) { - val registry = mockk(relaxed = true) { + fun `when use invalid id - should not query providers`(itemId: String) { + val provider = mockk(relaxed = true) { every { id } returns "mock" every { isEnabled } returns true } - registries.register(registry, plugin, Normal) + providers.register(provider, plugin, Normal) assertSoftly { itemsService.isItemExists(itemId) shouldBe false @@ -100,71 +173,170 @@ internal class MimicItemsRegistryTest : BukkitTestBase() { itemsService.isSameItem(ItemStack(Material.ACACIA_BOAT), itemId) shouldBe false } verify(exactly = 0) { - registry.isItemExists(any()) - registry.getItem(any(), any(), any()) - registry.isSameItem(any(), any()) + provider.allItems + provider.hasItem(any()) + provider.createItem(any(), any(), any(), any()) + } + } + + @ParameterizedTest + @ValueSource(strings = ["ia:itemsadder:ruby_sword", "ia:itemsadder/ruby_sword", "mimic:itemsadder:ruby_sword"]) + fun `when registry uses ids with colon - should accept both forms`(itemId: String) { + registerRegistry(LegacyItemRegistry()) + + assertSoftly { + itemsService.isItemExists(itemId).shouldBeTrue() + itemsService.getItem(itemId)?.type shouldBe Material.EMERALD + itemsService.isSameItem(ItemStack(Material.EMERALD), itemId).shouldBeTrue() } } @Test - fun `when registry uses legacy ids - should pass them through`() { - registries.register(LegacyItemRegistry(), plugin, Normal) + fun `when registry uses ids with colon - should return them with slash`() { + registerRegistry(LegacyItemRegistry()) assertSoftly { - itemsService.knownIds shouldContain "ia:itemsadder:ruby_sword" - itemsService.getItemId(ItemStack(Material.EMERALD)) shouldBe "ia:itemsadder:ruby_sword" - itemsService.isItemExists("ia:itemsadder:ruby_sword").shouldBeTrue() - itemsService.getItem("ia:itemsadder:ruby_sword")?.type shouldBe Material.EMERALD + itemsService.knownIds shouldContain "ia:itemsadder/ruby_sword" + itemsService.getItemId(ItemStack(Material.EMERALD)) shouldBe "ia:itemsadder/ruby_sword" } } @Test fun `when registry returns invalid id - should ignore it`() { - registries.register(InvalidIdItemRegistry(), plugin, Normal) + registerRegistry(InvalidIdItemRegistry()) assertSoftly { itemsService.knownIds shouldNotContain "invalid:Ruby Sword" itemsService.knownIds shouldContain "invalid:emerald" - // Should not fall back to the registry with lower priority + // Should not fall back to the provider with lower priority itemsService.getItemId(ItemStack(Material.EMERALD)).shouldBeNull() } } + // https://github.com/EndlessCodeGroup/Mimic/issues/87 + @ParameterizedTest + @ValueSource(strings = ["mmoitems:katana", "katana", "mmoitems:KATANA", "mmoitems:sword/katana"]) + fun `when MMOItems id has no type and is unique - should resolve it`(itemId: String) { + providers.register(MmoItemProvider(), plugin, Normal) + + assertSoftly { + itemsService.isItemExists(itemId).shouldBeTrue() + itemsService.getItem(itemId)?.type shouldBe Material.IRON_SWORD + itemsService.isSameItem(ItemStack(Material.IRON_SWORD), itemId).shouldBeTrue() + itemsService.getItemId(ItemStack(Material.IRON_SWORD)) shouldBe "mmoitems:sword/katana" + } + } + + @Test + fun `when MMOItems id has no type and is not unique - should not resolve it`() { + providers.register(MmoItemProvider(), plugin, Normal) + + assertSoftly { + itemsService.isItemExists("mmoitems:excalibur").shouldBeFalse() + itemsService.getItem("mmoitems:excalibur").shouldBeNull() + } + } + + @Test + fun `when MMOItems id has no type - should warn once`() { + val warnings = mutableListOf() + Log.init({ _, message, _ -> warnings += message.orEmpty() }) + providers.register(MmoItemProvider(), plugin, Normal) + + repeat(2) { + itemsService.getItem("mmoitems:katana") + itemsService.getItem("mmoitems:excalibur") + itemsService.getItem("mmoitems:sword/katana") + } + + warnings.size shouldBe 2 + warnings[0] shouldContain "use 'mmoitems:sword/katana' instead" + warnings[1] shouldContain "'mmoitems:sword/excalibur', 'mmoitems:dagger/excalibur'" + } + @Test fun `when ids are deprecated or invalid - should warn once`() { val warnings = mutableListOf() Log.init({ _, message, _ -> warnings += message.orEmpty() }) - registries.register(LegacyItemRegistry(), plugin, Normal) - registries.register(InvalidIdItemRegistry(), plugin, Normal) + registerRegistry(LegacyItemRegistry()) + registerRegistry(InvalidIdItemRegistry()) repeat(2) { itemsService.knownIds itemsService.getItem("ia:itemsadder:ruby_sword") - itemsService.getItem("ia:itemsadder:ruby_axe") itemsService.getItem("test:ACACIA_BOAT") } - // The first quoted value is the registry ID for registry warnings, and the item ID for input warnings + // The first quoted value is the provider ID for provider warnings, and the item ID for input warnings warnings.map { it.substringAfter("'").substringBefore("'") } shouldContainExactlyInAnyOrder listOf( - "ia", "invalid", "ia:itemsadder:ruby_sword", "test:ACACIA_BOAT", ) } + + private fun registerRegistry(registry: BukkitItemsRegistry) { + providers.register(ItemsRegistryItemProvider(registry), plugin, Normal, isBridge = true) + } } -private class TestItemRegistry : BukkitItemsRegistry { +/** Provider imitating vanilla items. */ +private class VanillaItemProvider : ItemProvider { override val id = "test" - override val knownIds = Material.entries.map { it.name.lowercase() } + override val allItems = Material.entries.filterNot { it.isLegacy }.mapTo(HashSet()) { it.name.lowercase() } - override fun isItemExists(itemId: String): Boolean = itemId in knownIds + var lastPayload: String? = null override fun getItemId(item: ItemStack): String = item.type.name.lowercase() - override fun getItem(itemId: String, payload: Any?, amount: Int): ItemStack { - val material = Material.valueOf(itemId.uppercase()) - return ItemStack(material, amount) + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack? { + lastPayload = payload + return if (itemId in allItems) ItemStack(Material.valueOf(itemId.uppercase()), amount) else null + } +} + +/** Provider imitating a plugin with a custom item built on emerald. */ +private class RubyItemProvider : ItemProvider { + override val id = "custom" + override val allItems = listOf("ruby") + + override fun getItemId(item: ItemStack): String? = "ruby".takeIf { item.type == Material.EMERALD } + + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack? = + if (itemId == "ruby") ItemStack(Material.EMERALD, amount) else null +} + +/** Provider imitating MMOItems, where IDs are unique only within an item type. */ +private class MmoItemProvider : ItemProvider { + override val id = "mmoitems" + override val allItems = listOf("sword/excalibur", "dagger/excalibur", "sword/katana") + + override fun getItemId(item: ItemStack): String? = "sword/katana".takeIf { item.type == Material.IRON_SWORD } + + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack? = + if (itemId == "sword/katana") ItemStack(Material.IRON_SWORD, amount) else null +} + +/** + * Registry imitating QuantumRPG: an item may be referred without its module, and the same stack is returned every time. + */ +private class ModularItemRegistry : BukkitItemsRegistry { + override val id = "quantum" + override val knownIds = listOf("gems/ruby") + + val sharedStack = ItemStack(Material.EMERALD) + var lastPayload: Any? = null + + override fun isSameItem(item: ItemStack, itemId: String): Boolean = + item.type == Material.EMERALD && itemId.substringAfter('/') == "ruby" + + override fun isItemExists(itemId: String): Boolean = itemId.substringAfter('/') == "ruby" + + override fun getItemId(item: ItemStack): String? = knownIds.first().takeIf { item.type == Material.EMERALD } + + override fun getItem(itemId: String, payload: Any?, amount: Int): ItemStack? { + lastPayload = payload + return sharedStack.takeIf { isItemExists(itemId) } } } From 98a1a7c84eeea5c139e65635d6271fd86c1497af Mon Sep 17 00:00:00 2001 From: Osip Fatkullin Date: Mon, 16 Nov 2026 10:37:22 +0100 Subject: [PATCH 10/11] feat: Rename disabled-items-registries option to disabled-item-providers The option lists plugins whose items should not be available via Mimic, including bridged items registries. The legacy disabled-items-registries value is moved automatically. Co-Authored-By: Claude Fable 5.2 --- mimic-bukkit/src/main/kotlin/MimicImpl.kt | 2 +- .../src/main/kotlin/command/ConfigCommand.kt | 27 ++++++++------- .../src/main/kotlin/command/ConfigMessage.kt | 13 ++++---- .../src/main/kotlin/config/MimicConfig.kt | 33 +++++++++---------- mimic-bukkit/src/test/kotlin/MimicImplTest.kt | 2 +- .../src/test/kotlin/config/MimicConfigTest.kt | 15 +++++++++ 6 files changed, 52 insertions(+), 40 deletions(-) diff --git a/mimic-bukkit/src/main/kotlin/MimicImpl.kt b/mimic-bukkit/src/main/kotlin/MimicImpl.kt index 8e19e49a..4a003be2 100644 --- a/mimic-bukkit/src/main/kotlin/MimicImpl.kt +++ b/mimic-bukkit/src/main/kotlin/MimicImpl.kt @@ -73,7 +73,7 @@ internal class MimicImpl( val itemProviders = registry( "ItemProvider", defaultId = MinecraftItemProvider.ID, - disabledIds = { config.disabledItemsRegistries }, + disabledIds = { config.disabledItemProviders }, ) private val levelSystems = registry( "LevelSystem", diff --git a/mimic-bukkit/src/main/kotlin/command/ConfigCommand.kt b/mimic-bukkit/src/main/kotlin/command/ConfigCommand.kt index e12e8613..9eaae531 100644 --- a/mimic-bukkit/src/main/kotlin/command/ConfigCommand.kt +++ b/mimic-bukkit/src/main/kotlin/command/ConfigCommand.kt @@ -1,8 +1,6 @@ // Copyright (c) 2023 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT -@file:Suppress("DEPRECATION") // ItemsRegistry API is deprecated but still supported - package ru.endlesscode.mimic.command import com.mojang.brigadier.arguments.StringArgumentType @@ -12,10 +10,11 @@ import ru.endlesscode.mimic.Mimic import ru.endlesscode.mimic.config.MimicConfig import ru.endlesscode.mimic.impl.mimic.getBlockProviderIds import ru.endlesscode.mimic.impl.mimic.getClassProviderIds +import ru.endlesscode.mimic.impl.mimic.getItemProviderIds import ru.endlesscode.mimic.impl.mimic.getLevelProviderIds import ru.endlesscode.mimic.impl.mimic.getResourceProviderIds import ru.endlesscode.mimic.impl.vanilla.MinecraftBlockProvider -import ru.endlesscode.mimic.impl.vanilla.MinecraftItemsRegistry +import ru.endlesscode.mimic.impl.vanilla.MinecraftItemProvider /** * Commands to see and change Mimic config. @@ -72,22 +71,22 @@ internal fun CommandBuilder.configSubcommand( } } - // Enable/Disable an item registry in Mimic - literal("disabled-items-registries") { + // Enable/Disable an item provider in Mimic + literal("disabled-item-providers") { literal(ACTION_ADD) { stringSetArgument( - ITEMS_REGISTRY, - "items registry", - { mimic.getAllItemsRegistries().keys - MinecraftItemsRegistry.ID }, - permanentOptions = setOf(MinecraftItemsRegistry.ID), - ) { sender, itemsRegistry -> - config.disabledItemsRegistries += itemsRegistry + ITEM_PROVIDER, + "item provider", + { mimic.getItemProviderIds() - MinecraftItemProvider.ID }, + permanentOptions = setOf(MinecraftItemProvider.ID), + ) { sender, itemProvider -> + config.disabledItemProviders += itemProvider showConfig(sender) } } literal(ACTION_REMOVE) { - stringSetArgument(ITEMS_REGISTRY, "disabled items registry", { config.disabledItemsRegistries }) { sender, itemsRegistry -> - config.disabledItemsRegistries -= itemsRegistry + stringSetArgument(ITEM_PROVIDER, "disabled item provider", { config.disabledItemProviders }) { sender, itemProvider -> + config.disabledItemProviders -= itemProvider showConfig(sender) } } @@ -144,7 +143,7 @@ private fun CommandBuilder.stringSetArgument( } private const val VALUE = "value" -private const val ITEMS_REGISTRY = "items-registry" +private const val ITEM_PROVIDER = "item-provider" private const val BLOCK_PROVIDER = "block-provider" private const val ACTION_ADD = "add" private const val ACTION_REMOVE = "remove" diff --git a/mimic-bukkit/src/main/kotlin/command/ConfigMessage.kt b/mimic-bukkit/src/main/kotlin/command/ConfigMessage.kt index 438ec41e..55464d76 100644 --- a/mimic-bukkit/src/main/kotlin/command/ConfigMessage.kt +++ b/mimic-bukkit/src/main/kotlin/command/ConfigMessage.kt @@ -1,8 +1,6 @@ // Copyright (c) 2023 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT -@file:Suppress("DEPRECATION") // ItemsRegistry API is deprecated but still supported - package ru.endlesscode.mimic.command import net.kyori.adventure.text.TextComponent @@ -14,13 +12,14 @@ import ru.endlesscode.mimic.config.StringConfigProperty import ru.endlesscode.mimic.config.StringSetConfigProperty import ru.endlesscode.mimic.impl.mimic.getBlockProviderIds import ru.endlesscode.mimic.impl.mimic.getClassProviderIds +import ru.endlesscode.mimic.impl.mimic.getItemProviderIds import ru.endlesscode.mimic.impl.mimic.getLevelProviderIds import ru.endlesscode.mimic.impl.mimic.getPrimaryClassProviderId import ru.endlesscode.mimic.impl.mimic.getPrimaryLevelProviderId import ru.endlesscode.mimic.impl.mimic.getPrimaryResourceProviderId import ru.endlesscode.mimic.impl.mimic.getResourceProviderIds import ru.endlesscode.mimic.impl.vanilla.MinecraftBlockProvider -import ru.endlesscode.mimic.impl.vanilla.MinecraftItemsRegistry +import ru.endlesscode.mimic.impl.vanilla.MinecraftItemProvider import ru.endlesscode.mimic.internal.append import ru.endlesscode.mimic.internal.appendLine import ru.endlesscode.mimic.internal.text @@ -53,10 +52,10 @@ internal fun buildConfigMessage(mimic: Mimic, config: MimicConfig): TextComponen options = mimic.getAllPlayerInventoryProviders().keys, ) appendSetPropertyConfig( - property = MimicConfig.DISABLED_ITEMS_REGISTRIES, - values = config.disabledItemsRegistries, - options = mimic.getAllItemsRegistries().keys, - permanentOptions = setOf(MinecraftItemsRegistry.ID), + property = MimicConfig.DISABLED_ITEM_PROVIDERS, + values = config.disabledItemProviders, + options = mimic.getItemProviderIds(), + permanentOptions = setOf(MinecraftItemProvider.ID), ) appendSetPropertyConfig( property = MimicConfig.DISABLED_BLOCK_PROVIDERS, diff --git a/mimic-bukkit/src/main/kotlin/config/MimicConfig.kt b/mimic-bukkit/src/main/kotlin/config/MimicConfig.kt index 73322d96..f7840b64 100644 --- a/mimic-bukkit/src/main/kotlin/config/MimicConfig.kt +++ b/mimic-bukkit/src/main/kotlin/config/MimicConfig.kt @@ -1,8 +1,6 @@ // Copyright (c) 2022 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT -@file:Suppress("DEPRECATION") // ItemsRegistry API is deprecated but still supported - package ru.endlesscode.mimic.config import org.bukkit.configuration.Configuration @@ -10,7 +8,7 @@ import org.bukkit.configuration.file.FileConfiguration import org.bukkit.configuration.file.YamlConfiguration import org.bukkit.plugin.Plugin import ru.endlesscode.mimic.impl.vanilla.MinecraftBlockProvider -import ru.endlesscode.mimic.impl.vanilla.MinecraftItemsRegistry +import ru.endlesscode.mimic.impl.vanilla.MinecraftItemProvider import ru.endlesscode.mimic.internal.Log import ru.endlesscode.mimic.internal.applyDefaults import ru.endlesscode.mimic.internal.setComments @@ -27,7 +25,7 @@ internal class MimicConfig( var classProvider: String by configuration.property(CLASS_PROVIDER) var resourceProvider: String by configuration.property(RESOURCE_PROVIDER) var inventoryProvider: String by configuration.property(INVENTORY_PROVIDER) - var disabledItemsRegistries: Set by configuration.property(DISABLED_ITEMS_REGISTRIES) + var disabledItemProviders: Set by configuration.property(DISABLED_ITEM_PROVIDERS) var disabledBlockProviders: Set by configuration.property(DISABLED_BLOCK_PROVIDERS) constructor(plugin: Plugin) : this(plugin.toString(), File(plugin.dataFolder, "config.yml")) @@ -54,6 +52,7 @@ internal class MimicConfig( configuration.load(file) migrateOption(LEGACY_LEVEL_SYSTEM_PATH, LEVEL_PROVIDER) migrateOption(LEGACY_CLASS_SYSTEM_PATH, CLASS_PROVIDER) + migrateOption(LEGACY_DISABLED_ITEMS_REGISTRIES_PATH, DISABLED_ITEM_PROVIDERS) migrateOption(LEGACY_DISABLED_BLOCK_REGISTRIES_PATH, DISABLED_BLOCK_PROVIDERS) validateConfigValues() } catch (e: Throwable) { @@ -71,12 +70,11 @@ internal class MimicConfig( } private fun validateConfigValues() { - val configuredDisabledItemsRegistries = disabledItemsRegistries - disabledItemsRegistries = configuredDisabledItemsRegistries - MinecraftItemsRegistry.ID - - val notDisabledRegistries = configuredDisabledItemsRegistries - disabledItemsRegistries - if (notDisabledRegistries.isNotEmpty()) { - Log.w("Config: Items registries $notDisabledRegistries can not be disabled. It will be removed from config.") + val configuredDisabledItemProviders = disabledItemProviders + disabledItemProviders = configuredDisabledItemProviders - MinecraftItemProvider.ID + val notDisabledItemProviders = configuredDisabledItemProviders - disabledItemProviders + if (notDisabledItemProviders.isNotEmpty()) { + Log.w("Config: Item providers $notDisabledItemProviders can not be disabled. It will be removed from config.") } val configuredDisabledBlockProviders = disabledBlockProviders @@ -121,6 +119,7 @@ internal class MimicConfig( private const val LEGACY_LEVEL_SYSTEM_PATH = "level-system" private const val LEGACY_CLASS_SYSTEM_PATH = "class-system" + private const val LEGACY_DISABLED_ITEMS_REGISTRIES_PATH = "disabled-items-registries" private const val LEGACY_DISABLED_BLOCK_REGISTRIES_PATH = "disabled-block-registries" val LEVEL_PROVIDER = StringConfigProperty( @@ -161,13 +160,13 @@ internal class MimicConfig( EMPTY_VALUE_MESSAGE, ), ) - val DISABLED_ITEMS_REGISTRIES = StringSetConfigProperty( - path = "disabled-items-registries", - title = "ItemsRegistry API", + val DISABLED_ITEM_PROVIDERS = StringSetConfigProperty( + path = "disabled-item-providers", + title = "Items API", comments = arrayOf( - "List here disabled items registry implementations.", - "You can't disable 'minecraft' items registry.", - "By default, all implementations are enabled.", + "List here plugins whose items should not be available via Mimic.", + "You can't disable 'minecraft' item provider.", + "By default, all item providers are enabled.", ), ) @@ -186,7 +185,7 @@ internal class MimicConfig( CLASS_PROVIDER, RESOURCE_PROVIDER, INVENTORY_PROVIDER, - DISABLED_ITEMS_REGISTRIES, + DISABLED_ITEM_PROVIDERS, DISABLED_BLOCK_PROVIDERS, ) } diff --git a/mimic-bukkit/src/test/kotlin/MimicImplTest.kt b/mimic-bukkit/src/test/kotlin/MimicImplTest.kt index b6eb8286..c7cf0603 100644 --- a/mimic-bukkit/src/test/kotlin/MimicImplTest.kt +++ b/mimic-bukkit/src/test/kotlin/MimicImplTest.kt @@ -43,7 +43,7 @@ internal class MimicImplTest : BukkitTestBase() { private val config: MimicConfig = mockk { every { levelProvider } answers { preferredLevelProvider } every { classProvider } answers { preferredClassProvider } - every { disabledItemsRegistries } returns emptySet() + every { disabledItemProviders } returns emptySet() } // SUT diff --git a/mimic-bukkit/src/test/kotlin/config/MimicConfigTest.kt b/mimic-bukkit/src/test/kotlin/config/MimicConfigTest.kt index f8fc456f..ddf275cf 100644 --- a/mimic-bukkit/src/test/kotlin/config/MimicConfigTest.kt +++ b/mimic-bukkit/src/test/kotlin/config/MimicConfigTest.kt @@ -36,6 +36,21 @@ internal class MimicConfigTest : BukkitTestBase() { file.readText() shouldNotContain "disabled-block-registries" } + @Test + fun `when load disabled item providers - should remove default providers`() { + file.writeText("disabled-item-providers: [custom, minecraft]\n") + + loadConfig().disabledItemProviders shouldBe setOf("custom") + } + + @Test + fun `when load legacy disabled items registries option - should move it to disabled item providers`() { + file.writeText("disabled-items-registries: [custom, minecraft]\n") + + loadConfig().disabledItemProviders shouldBe setOf("custom") + file.readText() shouldNotContain "disabled-items-registries" + } + @Test fun `when load legacy level system option - should move it to level provider`() { file.writeText("level-system: custom\n") From ea3d1951931f6075b19c948ea07697e242d51fee Mon Sep 17 00:00:00 2001 From: Osip Fatkullin Date: Mon, 16 Nov 2026 10:37:22 +0100 Subject: [PATCH 11/11] docs: Document Items API Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 31 +++++++ README.md | 4 +- mimic-bukkit-api/README.md | 166 ++++++++++++++++++++++++++++++++----- mimic-bukkit/README.md | 34 ++++---- 4 files changed, 200 insertions(+), 35 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e31026fa..8a4e5adc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,34 @@ ## [Unreleased] +### Items API + +New Items API replaces `ItemsRegistry` ([#95](https://github.com/EndlessCodeGroup/Mimic/issues/95)). +See [Items](https://github.com/EndlessCodeGroup/Mimic/blob/develop/mimic-bukkit-api/README.md#items) for details and examples. + +- `Mimic.getItems()` creates and identifies items, `Mimic.registerItemProvider()` makes a plugin's items available. + Requires Mimic API level `MimicApiLevel.VERSION_0_11`. The API is stable. +- Item IDs are `Key`s with a required namespace: `minecraft:diamond`, `craftengine:default/palm_log`. + There is no search over all providers in the new API. +- An item belongs to the provider with the highest priority recognizing it, + so a custom item no longer matches the ID of its vanilla base ([#86](https://github.com/EndlessCodeGroup/Mimic/issues/86)). +- Items can be created for a player, MMOItems and CraftEngine use it. +- A provider may override `ItemProvider.hasItem` to check an item faster, or if it can't list its items. +- The payload is a `String` in the format of the item's provider. An item is not created if its payload is invalid. + A blank payload is the same as no payload. +- `ItemsRegistry` API is deprecated but keeps working, every items registry is available via Items API. + `Mimic.getItemsRegistry()` shows items of all item providers and still accepts IDs without a namespace. +- Items registries' own `isSameItem` is used again ([#85](https://github.com/EndlessCodeGroup/Mimic/issues/85)). +- **Changed:** MMOItems IDs include the item type: `mmoitems:sword/excalibur` instead of `mmoitems:excalibur` ([#87](https://github.com/EndlessCodeGroup/Mimic/issues/87)). + `ItemsRegistry` API still accepts IDs without the type if only one type has the item, but logs a warning. +- **Changed:** `ItemsRegistry.getItem` returns `null` if an item provider can't use the payload. Previously, the payload was ignored. + A payload which isn't a `String`, like an `ItemMetaPayload` instance, is passed only to items registries. +- **Changed:** A built-in item provider is replaced only by an `ItemProvider` with the same ID, not by an `ItemsRegistry`. +- **Deprecated:** The HOCON payload (`ItemMetaPayload`) of `minecraft` items still works, but logs a warning. + Use item components instead, for example `[damage=10,unbreakable={}]`. +- **Changed:** Empty stacks have no ID, and `minecraft:air` is not an item. +- Config option `disabled-items-registries` is renamed to `disabled-item-providers`, the old value is moved automatically. +- `/mimic items` requires item IDs with a namespace and gives items created for the target player. + ### Blocks API New Blocks API replaces the experimental `BlockRegistry` ([#96](https://github.com/EndlessCodeGroup/Mimic/issues/96)). @@ -11,9 +40,11 @@ See [Blocks](https://github.com/EndlessCodeGroup/Mimic/blob/develop/mimic-bukkit The package is the same, it is no longer experimental. - Block IDs are `Key`s with a required namespace: `minecraft:stone`, `craftengine:default/palm_log`. IDs without a namespace and the `mimic:` namespace are no longer searched over all providers. +- A provider may override `BlockProvider.hasBlock` to check a block faster, or if it can't list its blocks. - **Breaking:** `BlockRegistry`, `BukkitBlockRegistry`, `Mimic.getBlockRegistry()`, `Mimic.registerBlockRegistry()` and `Mimic.getAllBlockRegistries()` are removed without replacement bridges. - **Breaking:** A block is not set if its state is invalid. Previously, the default state was used. + A blank state is the same as no state. - Config option `disabled-block-registries` is renamed to `disabled-block-providers`, the old value is moved automatically. - `/mimic blocks` requires block IDs with a namespace, `payload` argument of `/mimic blocks set` is renamed to `state`. diff --git a/README.md b/README.md index 916cdfe5..cf6a43b7 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,8 @@ With Mimic, you don't need to download all RPG plugins and write specific code f - [ClassSystem] *(deprecated, use [Classes])* - API to work with player's classes. - [Resources] - API to work with player's resources: mana, stamina and similar. Read them, take costs, give them back. - [PlayerInventory] *(experimental)* - API to access player's inventories content. -- [ItemsRegistry] - API adding the possibility to create and validate custom items created with plugins. +- [Items] - API to create and identify vanilla items and custom items created with plugins. +- [ItemsRegistry] *(deprecated, use [Items])* - API to create and validate custom items created with plugins. - [Blocks] - API to identify, set and break vanilla blocks and custom blocks created with plugins. ### Implementations @@ -97,5 +98,6 @@ Please make sure to update tests as appropriate. [ClassSystem]: mimic-api/src/main/kotlin/classes/ClassSystem.kt [Resources]: mimic-bukkit-api/src/main/kotlin/resources/Resources.kt [PlayerInventory]: mimic-api/src/main/kotlin/inventory/PlayerInventory.kt +[Items]: mimic-bukkit-api/src/main/kotlin/items/Items.kt [ItemsRegistry]: mimic-api/src/main/kotlin/items/ItemsRegistry.kt [Blocks]: mimic-bukkit-api/src/main/kotlin/blocks/Blocks.kt diff --git a/mimic-bukkit-api/README.md b/mimic-bukkit-api/README.md index 47416e4b..5416a17c 100644 --- a/mimic-bukkit-api/README.md +++ b/mimic-bukkit-api/README.md @@ -12,7 +12,8 @@ Available services: - [ClassProvider] - [BukkitClassSystem.Provider] *(deprecated, use [ClassProvider])* - [BukkitPlayerInventory.Provider] *(experimental)* -- [BukkitItemsRegistry] +- [ItemProvider] +- [BukkitItemsRegistry] *(deprecated, use [ItemProvider])* - [BlockProvider] > Experimental APIs may change in future versions. @@ -59,7 +60,7 @@ Levels levels = mimic.getLevels(); Classes classes = mimic.getClasses(); Resources resources = mimic.getResources(); BukkitPlayerInventory inventory = mimic.getPlayerInventory(player); -BukkitItemsRegistry itemsRegistry = mimic.getItemsRegistry(); +Items items = mimic.getItems(); Blocks blocks = mimic.getBlocks(); ``` @@ -77,10 +78,9 @@ CharacterClass playerClass = classes.getPrimaryClass(player); // See the "Resources" section below for details boolean isPaid = resources.take(player, Key.key("mmocore:mana"), 20.0); -// ItemsRegistry is not related to player so it can be used without provider -ItemStack stick = itemsRegistry.getItem("minecraft:stick"); -boolean isPalmLogInHand = itemsRegistry.isSameItem(player.getInventory().getItemInMainHand(), "craftengine:default/palm_log"); -boolean isPalmLogExists = itemsRegistry.isItemExists("craftengine:default/palm_log"); +// See the "Items" section below for details +ItemStack sword = items.createItem(Key.key("mmoitems:sword/excalibur"), 1, player); +boolean isSwordInHand = items.isItem(player.getInventory().getItemInMainHand(), Key.key("mmoitems:sword/excalibur")); // See the "Blocks" section below for details boolean isPalmLog = blocks.isBlock(block, Key.key("craftengine:default/palm_log")); @@ -93,14 +93,15 @@ Mimic identifies items, blocks, level tracks, classes and resources by [resource where the namespace is the ID of the plugin's implementation: `minecraft:acacia_boat`, `craftengine:default/palm_log`, `auraskills:mining`. The path may contain lowercase letters, digits, `.`, `_`, `-` and `/`. -- **Items:** ID without namespace, or with the `mimic` namespace, is searched over all registries in order of priority. +- **Items:** the namespace is required, see [Item IDs](#item-ids). - **Blocks:** the namespace is required, see [Block IDs](#block-ids). - **Level tracks:** the namespace is required, see [Track IDs](#track-ids). - **Classes and class slots:** the namespace is required, see [Class IDs](#class-ids). - **Resources:** the namespace is required, see [Resource IDs](#resource-ids). -> Item IDs with uppercase letters (`minecraft:DIAMOND_SWORD`) or with more than one `:` (`ia:itemsadder:ruby_sword`) are deprecated. -> They still work but log a warning. +> The deprecated `ItemsRegistry` API still searches an item ID without namespace, or with the `mimic` namespace, over all plugins. +> It also accepts item IDs with uppercase letters (`minecraft:DIAMOND_SWORD`), with more than one `:` (`ia:itemsadder:ruby_sword`) +> and MMOItems IDs without item type (`mmoitems:excalibur`), but logs a warning.
Full example @@ -112,7 +113,7 @@ The path may contain lowercase letters, digits, `.`, `_`, `-` and `/`. import ru.endlesscode.mimic.Mimic; import ru.endlesscode.mimic.MimicApiLevel; import ru.endlesscode.mimic.classes.Classes; - import ru.endlesscode.mimic.items.BukkitItemsRegistry; + import ru.endlesscode.mimic.items.Items; import ru.endlesscode.mimic.level.Levels; import net.kyori.adventure.key.Key; @@ -128,8 +129,8 @@ The path may contain lowercase letters, digits, `.`, `_`, `-` and `/`. return mimic.getClasses(); } - public static BukkitItemsRegistry getItemsRegistry() { - return mimic.getItemsRegistry(); + public static Items getItems() { + return mimic.getItems(); } @Override @@ -166,11 +167,9 @@ The path may contain lowercase letters, digits, `.`, `_`, `-` and `/`. boolean isWarrior = getClasses().hasClass(player, Key.key("fabled:warrior")); - // ItemsRegistry is not related to player so it can be used without provider - BukkitItemsRegistry itemsRegistry = getItemsRegistry(); - ItemStack stick = itemsRegistry.getItem("minecraft:stick"); - boolean isPalmLogInHand = itemsRegistry.isSameItem(player.getInventory().getItemInMainHand(), "craftengine:default/palm_log"); - boolean isPalmLogExists = itemsRegistry.isItemExists("craftengine:default/palm_log"); + Key excalibur = Key.key("mmoitems:sword/excalibur"); + ItemStack sword = getItems().createItem(excalibur, 1, player); + boolean isSwordInHand = getItems().isItem(player.getInventory().getItemInMainHand(), excalibur); } } ``` @@ -420,6 +419,85 @@ To make resources of your plugin available, implement [ResourceProvider]: only r `minecraft:health` is changed directly, as a cost and not as damage: no damage or regain events are fired, armor and absorption hearts are ignored, and taking all health kills the player. +### Items + +[Items] gives access to vanilla items and custom items of all supported plugins: +create an item by its ID, get the ID of a stack, check that a stack is a specific item. + +#### Item IDs + +An item ID is a `Key` like `mmoitems:sword/excalibur`: the namespace is the ID of the plugin providing the item, +the path is the item within that plugin. +The namespace is required, there is no search over all plugins. +`Key.key("excalibur")` turns into `minecraft:excalibur`, so validate IDs read from configs: + +```java +Key itemId = Key.key(config.getString("item")); +if (!items.hasItem(itemId)) { + getLogger().warning("Unknown item " + itemId.asString()); +} +``` + +`items.getAllItems()` lists all IDs, for example, for tab completion. +See ID formats of the supported plugins in [Supported Implementations](../mimic-bukkit/README.md#supported-implementations). + +#### Identifying items + +An item belongs to the plugin with the highest priority that recognizes it, and vanilla items belong to `minecraft`. +So a ruby built on a diamond is never `minecraft:diamond`. +Items are compared by ID only: amount, stats, durability and lore of the stack are ignored. + +```java +Key itemId = items.getItemId(stack); // null if no plugin recognizes the item +boolean isExcalibur = items.isItem(stack, Key.key("mmoitems:sword/excalibur")); +// Any diamond, vanilla or a custom item built on it +boolean isDiamond = stack.getType() == Material.DIAMOND; +``` + +#### Creating items + +```java +// A new stack with a single item, or null if the item doesn't exist +ItemStack stick = items.createItem(Key.key("minecraft:stick")); +ItemStack palmLogs = items.createItem(Key.key("craftengine:default/palm_log"), 16); + +// Create the item for the player: some plugins scale items to the player's level +ItemStack excalibur = items.createItem(Key.key("mmoitems:sword/excalibur"), 1, player); + +// The payload is in the format of the plugin providing the item, with an invalid payload the item is not created +ItemStack sword = items.createItem(Key.key("minecraft:diamond_sword"), 1, player, "[damage=10]"); +``` + +In Kotlin, the parameters have default values: `items.createItem(itemId, player = player)`. + +The amount is kept within `1` and the maximum stack size of the item. +Each call returns a new stack, so it is safe to change it. + +#### Rules + +- Call `createItem` on the main thread. Other methods may be called from any thread. +- Item IDs may be unknown until their plugins finish loading, and may change when a plugin reloads. + Don't keep created stacks across reloads. +- A payload is passed only to the plugin named by the item ID. Plugins taking no payload ignore it. + +#### Migration from ItemsRegistry + +`ItemsRegistry` API is deprecated but keeps working: every registered items registry is available via [Items], +and `Mimic.getItemsRegistry()` shows items of all item providers. + +| ItemsRegistry | Items | +|--------------------------------------|-----------------------------------------------------| +| `getItem(id, payload, amount)` | `createItem(id, amount, player, payload)` | +| `getItemId(item)` | `getItemId(item)` | +| `isSameItem(item, id)` | `isItem(item, id)` | +| `isItemExists(id)` | `hasItem(id)` | +| `getKnownIds()` | `getAllItems()` | + +- IDs are `Key`s with a required namespace. To keep accepting IDs without a namespace in your configs, + look them up in `getAllItems()` yourself. +- MMOItems IDs include the item type: `mmoitems:sword/excalibur` instead of `mmoitems:excalibur`. +- The payload is a `String`. + ### Blocks [Blocks] gives access to vanilla blocks and custom blocks of all supported plugins: @@ -537,10 +615,55 @@ public class MyClassProvider implements ClassProvider { } ``` -Items registries and block providers receive and return IDs without the namespace, Mimic adds it. +Item providers and block providers receive and return IDs without the namespace, Mimic adds it. Mapping the plugin's own IDs to valid Mimic IDs is up to the implementation, for example `default:palm_log` → `default/palm_log`. Invalid IDs returned by an implementation are ignored with a warning. -See [BlockProvider] for the rules about block IDs, ownership of blocks and threading. +See [ItemProvider] and [BlockProvider] for the rules about IDs, ownership of items and blocks, and threading. + +
+ Item provider example + + ```java + import org.bukkit.entity.Player; + import org.bukkit.inventory.ItemStack; + import org.jetbrains.annotations.NotNull; + import org.jetbrains.annotations.Nullable; + import ru.endlesscode.mimic.items.ItemProvider; + + import java.util.Collection; + + public class MyItemProvider implements ItemProvider { + + @NotNull + @Override + public String getId() { + return "myplugin"; + } + + // Read on every request, so it can change on the plugin reload + @NotNull + @Override + public Collection getAllItems() { + return MyItems.getIds(); + } + + // Return null for items of other plugins and for vanilla items + @Nullable + @Override + public String getItemId(@NotNull ItemStack item) { + return MyItems.getId(item); + } + + // Return a new stack on every call, or null if the item is unknown. + // This provider takes no payload, so it is ignored + @Nullable + @Override + public ItemStack createItem(@NotNull String itemId, int amount, @Nullable Player player, @Nullable String payload) { + return MyItems.create(itemId, amount, player); + } + } + ``` +
Block provider example @@ -696,6 +819,7 @@ public void onLoad() { // Register your implementations and specify minimal required Mimic version for it. mimic.registerClassProvider(new MyClassProvider(), MimicApiLevel.CURRENT, this); + mimic.registerItemProvider(new MyItemProvider(), MimicApiLevel.CURRENT, this); mimic.registerBlockProvider(new MyBlockProvider(), MimicApiLevel.CURRENT, this); mimic.registerLevelProvider(new MyLevelProvider(), MimicApiLevel.CURRENT, this); } @@ -704,6 +828,8 @@ public void onLoad() { Each ID belongs to a single implementation. If your plugin registers an implementation with the same ID as a Mimic built-in integration, yours replaces the built-in one. So you can ship the integration with your plugin and keep it up to date. +An implementation of a deprecated API doesn't replace a built-in implementation of the API replacing it: +an `ItemsRegistry` with the ID `mmoitems` doesn't replace the built-in `mmoitems` item provider. If two plugins register the same ID, the one with higher priority is used. IDs of the default implementations (`mimic`, `minecraft`, `permissions`) are reserved. @@ -723,6 +849,8 @@ IDs of the default implementations (`mimic`, `minecraft`, `permissions`) are res [BukkitClassSystem]: src/main/kotlin/classes/BukkitClassSystem.kt [BukkitPlayerInventory.Provider]: src/main/kotlin/inventory/BukkitPlayerInventory.kt [BukkitItemsRegistry]: src/main/kotlin/items/BukkitItemsRegistry.kt +[Items]: https://endlesscodegroup.github.io/Mimic/mimic-bukkit-api/ru.endlesscode.mimic.items/-items/index.html +[ItemProvider]: https://endlesscodegroup.github.io/Mimic/mimic-bukkit-api/ru.endlesscode.mimic.items/-item-provider/index.html [Blocks]: https://endlesscodegroup.github.io/Mimic/mimic-bukkit-api/ru.endlesscode.mimic.blocks/-blocks/index.html [BlockProvider]: https://endlesscodegroup.github.io/Mimic/mimic-bukkit-api/ru.endlesscode.mimic.blocks/-block-provider/index.html diff --git a/mimic-bukkit/README.md b/mimic-bukkit/README.md index 17faf834..3e281bc7 100644 --- a/mimic-bukkit/README.md +++ b/mimic-bukkit/README.md @@ -30,7 +30,7 @@ You can configure in `config.yml` what APIs implementations should be used, or u | `/mimic classes` | Manage player's classes | | `/mimic resources` | Manage player's mana and similar | | `/mimic inventory` | Player's inventory info | -| `/mimic items` | Deal with items | +| `/mimic items` | Give, find and compare items | | `/mimic blocks` | Deal with blocks | Commands without arguments show info and list available subcommands: click a subcommand to use it, hover to see usage. @@ -74,21 +74,22 @@ You can find code of all built-in implementations [here](src/main/kotlin/impl). - **[Minecraft][minecraft-inv]** _(Default)_ - **[RPGInventory]** -### [Items Registries][BukkitItemsRegistry] +### [Item Providers][ItemProvider] -#### [MimicItemsRegistry] +Items of all providers are available via [Items], with the provider ID as a namespace of item IDs. +The namespace is required. +An item belongs to the provider with the highest priority that recognizes it, vanilla items belong to `minecraft`. -Items registry combining all others items registries. -It uses registry ID as a namespace for items IDs.\ -For example: `acacia_boat -> minecraft:acacia_boat`. +> The deprecated [ItemsRegistry][MimicItemsRegistry] API also accepts item ID without a namespace or with the `mimic` namespace +> and searches it over all providers. Plugins using this API accept MMOItems IDs without item type too, if only one type has the item. -> If you use item ID without a namespace or with the `mimic` namespace, it will search over all registries. +Providers marked with _(deprecated API)_ are provided by the plugin itself via the deprecated [ItemsRegistry][BukkitItemsRegistry] API. -#### [Minecraft][MinecraftItemsRegistry] +#### [Minecraft][MinecraftItemProvider] **ID Format:** `minecraft:[id]`\ **Payload:** [Item components][item-components] in the format of `/give` command, for example `[damage=10,unbreakable={}]`.\ -Alternatively, [ItemMetaPayload] in HOCON format with MiniMessage support for name and lore, for example `{name: "Sword", unbreakable: true}`. +[ItemMetaPayload] in HOCON format is deprecated: it still works, but logs a warning. #### [CraftEngine] @@ -102,20 +103,21 @@ Alternatively, [ItemMetaPayload] in HOCON format with MiniMessage support for na #### [MMOItems] -**ID Format:** `mmoitems:[id]`\ -**Payload:** *Not supported* +**ID Format:** `mmoitems:[type]/[id]`, for example `mmoitems:sword/excalibur`\ +**Payload:** *Not supported*\ +An item given to a player is built by MMOItems for this player. -#### [ProRPGItems] +#### [ProRPGItems] _(deprecated API)_ **ID Format:** `prorpgitems:[type]/[id]`\ **Payload:** *Not supported* -#### [RPGInventory] +#### [RPGInventory] _(deprecated API)_ **ID Format:** `rpginventory:[id]`\ **Payload:** *Not supported* -#### [ItemsAdder] +#### [ItemsAdder] _(deprecated API)_ **ID Format:** `ia:[id]`\ **Payload:** *Not supported* @@ -165,5 +167,7 @@ A block belongs to the provider with the highest priority that recognizes it, va [Blocks]: ../mimic-bukkit-api/src/main/kotlin/blocks/Blocks.kt [MinecraftBlockProvider]: src/main/kotlin/impl/vanilla/MinecraftBlockProvider.kt [MimicItemsRegistry]: src/main/kotlin/impl/mimic/MimicItemsRegistry.kt -[MinecraftItemsRegistry]: src/main/kotlin/impl/vanilla/MinecraftItemsRegistry.kt +[ItemProvider]: ../mimic-bukkit-api/src/main/kotlin/items/ItemProvider.kt +[Items]: ../mimic-bukkit-api/src/main/kotlin/items/Items.kt +[MinecraftItemProvider]: src/main/kotlin/impl/vanilla/MinecraftItemProvider.kt [ItemMetaPayload]: src/main/kotlin/impl/vanilla/ItemMetaPayload.kt