Conversion between NMS and Sponge inventories

How can I convert an InventoryCrafting to a CraftingInventory or GridInventory and vice-versa?

Though I don’t know, I’m going to assume that the answer is ‘just cast them’. That’s how you convert most things in Sponge.

Casting works with some inventories, but not others. In this case, Sponge and Minecraft represent crafting inventories in two different ways.

Minecraft has a Container with an array of Slots. Each Slot has a reference to an InventoryCrafting and an index in that InventoryCrafting.

Sponge’s inventory API has three pieces, in addition to the Minecraft code: adapters, fabrics, and lenses. Adapters directly implement the SpongeAPI interfaces. Lenses simply represent the logical structure of the inventory and map it to numerical indexes. Fabrics connect the indexes to the IInventory slots.

To convert from CraftingInventory to InventoryCrafting:

CraftingInventoryAdapter adapter = (CraftingInventoryAdapter) spongeInventory;
SlotAdapter slotAdapter = (SlotAdapter) spongeInventory.getSlot();
Fabric<IInventory> fabric = slotAdapter.getInventory();
IInventory minecraftInventory = fabric.get(slotAdapter.getOrdinal());

If you want to go the other way around, and you don’t need the result to be traceable back to the original Container in the API, you can create a CraftingInventoryAdapter, passing in a custom subclass of MinecraftFabric (because Minecraft’s InventoryCrafting doesn’t contain the output slot, but Sponge’s CraftingInventory does) and a CraftingInventoryLensImpl.

1 Like

Does this mean that a better approach would be to convert InventoryCrafting to GridInventory and vice versa? I don’t need the output slot.

Yes. I believe you would use GridInventoryAdapter, DefaultInventoryFabric, and GridInventoryLensImpl for that.