使い方と制約

ItemStackの個数とは独立にコンポーネントから正確なキーを作ります。表示名ではなくレジストリ対応コーデックを使い、復元スタックの個数・データ上限を守ります。

ItemResourceCodec

ItemResourceCodec
package dev.nebulastorage.api.platform

import dev.nebulastorage.api.resource.ResourceKey
import dev.nebulastorage.api.resource.ResourceTypeId
import net.minecraft.core.HolderLookup
import net.minecraft.core.registries.BuiltInRegistries
import net.minecraft.nbt.CompoundTag
import net.minecraft.nbt.TagParser
import net.minecraft.world.item.ItemStack

/** Registry-aware, count-independent item identities preserving the exact component patch. */
class ItemResourceCodec(internal val registries: HolderLookup.Provider) {
    /** Tests the current Nebula transfer-size bound; larger identities may be encoded but cannot be transferred. */
    fun transferable(key: ResourceKey): Boolean = CanonicalComponents.transferable(key.components)

    fun key(stack: ItemStack): ResourceKey {
        require(!stack.isEmpty)
        val encoded = stack.copyWithCount(1).save(registries) as CompoundTag
        val components = encoded.get("components")?.let(CanonicalComponents::encode) ?: ""
        return ResourceKey(ResourceTypeId.ITEM, BuiltInRegistries.ITEM.getKey(stack.item).toString(), components)
    }

    /** Returns a fresh stack. Unknown identities and counts outside one legal stack are rejected. */
    fun stack(key: ResourceKey, count: Int = 1): ItemStack {
        require(key.type == ResourceTypeId.ITEM && count > 0)
        val data = CompoundTag().apply {
            putString("id", key.id)
            putInt("count", 1)
            if (key.components.isNotEmpty()) put("components", TagParser.parseTag(key.components))
        }
        val decoded = ItemStack.parse(registries, data).orElseThrow { IllegalArgumentException("Unknown item or components: ${key.id}") }
        require(!decoded.isEmpty && count <= decoded.maxStackSize)
        return decoded.copyWithCount(count)
    }

}
ソース

src/main/kotlin/dev/nebulastorage/api/platform/ItemResourceCodec.kt; editorial/ja.json

43b4d12d69e6033c24fa8c39dac383ef2429b446