diff --git a/src/main/java/baubles/api/BaublesApi.java b/src/main/java/baubles/api/BaublesApi.java index 339afa9..4d68457 100644 --- a/src/main/java/baubles/api/BaublesApi.java +++ b/src/main/java/baubles/api/BaublesApi.java @@ -1,11 +1,19 @@ package baubles.api; import baubles.api.expanded.IBaubleSlotInventory; +import baubles.api.expanded.IBaubleSlotSettings; +import baubles.api.expanded.BaubleSlotResult; +import baubles.api.expanded.BaubleSlotContext; import cpw.mods.fml.common.FMLLog; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.function.Predicate; /** * @author Azanor @@ -14,6 +22,48 @@ public class BaublesApi { static Method getBaubles; + /** + * Returns optional type policies, activation and contextual slot access. + */ + public static IBaubleSlotSettings getBaubleSlotSettings(EntityPlayer player) { + IInventory inventory = getBaubles(player); + return inventory instanceof IBaubleSlotSettings settings ? settings : null; + } + + /** + * Finds active functional items. Results reference the inventory's real stacks. + */ + public static List findBaubles(EntityPlayer player, Predicate filter) { + List results = new ArrayList<>(); + IInventory inventory = getBaubles(player); + if (inventory == null) return results; + for (int slot = 0; slot < inventory.getSizeInventory(); slot++) { + BaubleSlotResult result = matchingBauble(player, inventory, slot, filter); + if (result != null) results.add(result); + } + return results; + } + + public static Optional findFirstBauble(EntityPlayer player, Predicate filter) { + IInventory inventory = getBaubles(player); + if (inventory != null) { + for (int slot = 0; slot < inventory.getSizeInventory(); slot++) { + BaubleSlotResult result = matchingBauble(player, inventory, slot, filter); + if (result != null) return Optional.of(result); + } + } + return Optional.empty(); + } + + private static BaubleSlotResult matchingBauble(EntityPlayer player, IInventory inventory, int slot, Predicate filter) { + if (inventory instanceof IBaubleSlotSettings settings && !settings.isSlotActive(slot)) return null; + ItemStack stack = inventory.getStackInSlot(slot); + if (stack == null || !filter.test(stack)) return null; + BaubleSlotContext context = inventory instanceof IBaubleSlotSettings settings ? settings.getSlotContext(slot, false) + : new BaubleSlotContext(player, "unknown", slot, slot, false, true, true); + return new BaubleSlotResult(context, stack); + } + /** * Returns dynamic slot support from the player's current baubles inventory. */ diff --git a/src/main/java/baubles/api/expanded/BaubleExpandedSlots.java b/src/main/java/baubles/api/expanded/BaubleExpandedSlots.java index a73d7eb..fa77fc3 100644 --- a/src/main/java/baubles/api/expanded/BaubleExpandedSlots.java +++ b/src/main/java/baubles/api/expanded/BaubleExpandedSlots.java @@ -312,6 +312,18 @@ public class BaubleExpandedSlots { } } + /** + * Publishes an already validated configuration on the server game thread. + * Existing registrations remain valid for downstream callers. + */ + public static void applyConfiguration(String[] layout, Iterable types) { + for (String type : types) { + if (!registeredTypes.contains(type)) registeredTypes.add(type); + } + assignedSlots.clear(); + for (String type : layout) assignedSlots.add(type); + } + private static final ArrayList assignedSlots = new ArrayList<>(); private static final ArrayList registeredTypes = new ArrayList<>(); static { diff --git a/src/main/java/baubles/api/expanded/BaubleSlotContext.java b/src/main/java/baubles/api/expanded/BaubleSlotContext.java new file mode 100644 index 0000000..b424c0c --- /dev/null +++ b/src/main/java/baubles/api/expanded/BaubleSlotContext.java @@ -0,0 +1,14 @@ +package baubles.api.expanded; + +import com.github.bsideup.jabel.Desugar; + +import net.minecraft.entity.player.EntityPlayer; + +/** + * A slot's context at the time of a callback. Slot is the stable inventory index; + * index is the position among slots of the same type. Do not retain the player. + */ +@Desugar +public record BaubleSlotContext(EntityPlayer player, String type, int slot, int index, + boolean cosmetic, boolean rendered, boolean active) { +} diff --git a/src/main/java/baubles/api/expanded/BaubleSlotResult.java b/src/main/java/baubles/api/expanded/BaubleSlotResult.java new file mode 100644 index 0000000..4e1ef29 --- /dev/null +++ b/src/main/java/baubles/api/expanded/BaubleSlotResult.java @@ -0,0 +1,12 @@ +package baubles.api.expanded; + +import com.github.bsideup.jabel.Desugar; + +import net.minecraft.item.ItemStack; + +/** + * A matching functional item and its slot context. The stack belongs to the inventory. + */ +@Desugar +public record BaubleSlotResult(BaubleSlotContext context, ItemStack stack) { +} diff --git a/src/main/java/baubles/api/expanded/BaubleSlotType.java b/src/main/java/baubles/api/expanded/BaubleSlotType.java new file mode 100644 index 0000000..d165dd8 --- /dev/null +++ b/src/main/java/baubles/api/expanded/BaubleSlotType.java @@ -0,0 +1,30 @@ +package baubles.api.expanded; + +import com.github.bsideup.jabel.Desugar; + +import java.util.Objects; + +/** + * Immutable slot policy. Empty icons and equal orders preserve the legacy presentation. + * Icons name standalone textures, for example "example:textures/gui/ring.png". + */ +@Desugar +public record BaubleSlotType(String id, int order, String icon, boolean cosmetic, boolean renderToggle, + boolean nativeGui, boolean enabled, int stackLimit, boolean fitsUniversal) { + + public BaubleSlotType { + Objects.requireNonNull(id, "id"); + Objects.requireNonNull(icon, "icon"); + if (id.isEmpty() || id.length() > 256) { + throw new IllegalArgumentException("Invalid slot type: " + id); + } + if (icon.length() > 512 || !icon.isEmpty() && !icon.matches("[a-z0-9_.-]+:[a-z0-9_./-]+")) { + throw new IllegalArgumentException("Invalid slot icon: " + icon); + } + if (stackLimit < 1) throw new IllegalArgumentException("Slot stack limit must be positive"); + } + + public static BaubleSlotType defaults(String id) { + return new BaubleSlotType(id, 0, "", true, true, true, true, 1, false); + } +} diff --git a/src/main/java/baubles/api/expanded/BaubleSlotTypes.java b/src/main/java/baubles/api/expanded/BaubleSlotTypes.java new file mode 100644 index 0000000..f37773a --- /dev/null +++ b/src/main/java/baubles/api/expanded/BaubleSlotTypes.java @@ -0,0 +1,32 @@ +package baubles.api.expanded; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +import cpw.mods.fml.common.Loader; +import cpw.mods.fml.common.LoaderState; + +/** + * Programmatic defaults registered during pre-initialization. Configuration can override them. + * Read a player's effective definitions through IBaubleSlotSettings instead of this registry. + */ +public class BaubleSlotTypes { + + private static final Map defaults = new LinkedHashMap<>(); + + public static boolean register(BaubleSlotType type) { + if (Loader.instance().getLoaderState() != LoaderState.PREINITIALIZATION) return false; + if (!BaubleExpandedSlots.tryRegisterType(type.id())) return false; + defaults.put(type.id(), type); + return true; + } + + public static Map getDefaults() { + Map result = new LinkedHashMap<>(); + for (String id : BaubleExpandedSlots.getCurrentlyRegisteredTypes()) { + result.put(id, defaults.getOrDefault(id, BaubleSlotType.defaults(id))); + } + return Collections.unmodifiableMap(result); + } +} diff --git a/src/main/java/baubles/api/expanded/IBaubleLifecycle.java b/src/main/java/baubles/api/expanded/IBaubleLifecycle.java new file mode 100644 index 0000000..20fd3b3 --- /dev/null +++ b/src/main/java/baubles/api/expanded/IBaubleLifecycle.java @@ -0,0 +1,50 @@ +package baubles.api.expanded; + +import baubles.api.IBauble; +import net.minecraft.item.ItemStack; + +/** + * Optional contextual callbacks. Defaults delegate to the original IBauble methods exactly once. + * Cosmetic contents never receive equipment callbacks or worn ticks. + */ +public interface IBaubleLifecycle extends IBauble { + + default void onBaubleTick(ItemStack stack, BaubleSlotContext context) { + onWornTick(stack, context.player()); + } + + /** + * Receives the live equipped stack and a detached copy of the previous contents, or null. + */ + default void onBaubleEquipped(ItemStack stack, BaubleSlotContext context, ItemStack previous) { + onEquipped(stack, context.player()); + } + + /** + * Receives the unequipped stack and a detached copy of its replacement, or null. + */ + default void onBaubleUnequipped(ItemStack stack, BaubleSlotContext context, ItemStack replacement) { + onUnequipped(stack, context.player()); + } + + default void onBaubleLoaded(ItemStack stack, BaubleSlotContext context) { + onPlayerLoad(stack, context.player()); + } + + /** + * Observes an in-place item change. Previous is a detached copy; this is not a new equip. + */ + default void onBaubleChanged(ItemStack stack, BaubleSlotContext context, ItemStack previous) {} + + default void onBaubleContentsChanged(ItemStack stack, BaubleSlotContext context) { + if (this instanceof IBaubleExpanded expanded) expanded.onSlotContentsChanged(stack, context.player()); + } + + default boolean canEquipBauble(ItemStack stack, BaubleSlotContext context) { + return context.cosmetic() || canEquip(stack, context.player()); + } + + default boolean canUnequipBauble(ItemStack stack, BaubleSlotContext context) { + return context.cosmetic() || canUnequip(stack, context.player()); + } +} diff --git a/src/main/java/baubles/api/expanded/IBaubleSlotSettings.java b/src/main/java/baubles/api/expanded/IBaubleSlotSettings.java new file mode 100644 index 0000000..2ea121f --- /dev/null +++ b/src/main/java/baubles/api/expanded/IBaubleSlotSettings.java @@ -0,0 +1,22 @@ +package baubles.api.expanded; + +import java.util.Map; + +/** + * Optional type policies and activation. Inactive slots retain their real inventory contents. + * Mutations belong on the server game thread and are deferred during item callbacks. + */ +public interface IBaubleSlotSettings extends IBaubleSlotInventory { + + Map getSlotDefinitions(); + + BaubleSlotType getSlotDefinition(String type); + + boolean isSlotActive(int slot); + + void setSlotActive(int slot, boolean active); + + void setSlotsActive(String type, boolean active); + + BaubleSlotContext getSlotContext(int slot, boolean cosmetic); +} diff --git a/src/main/java/baubles/client/gui/GuiPlayerExpanded.java b/src/main/java/baubles/client/gui/GuiPlayerExpanded.java index 2ab8e15..f443a5e 100644 --- a/src/main/java/baubles/client/gui/GuiPlayerExpanded.java +++ b/src/main/java/baubles/client/gui/GuiPlayerExpanded.java @@ -1,8 +1,6 @@ package baubles.client.gui; -import baubles.api.IBauble; import baubles.api.expanded.BaubleExpandedSlots; -import baubles.api.expanded.IBaubleExpanded; import baubles.common.Baubles; import baubles.common.BaublesConfig; import baubles.common.container.ContainerPlayerExpanded; @@ -28,6 +26,7 @@ import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; +import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector; @@ -37,7 +36,9 @@ import org.lwjgl.opengl.GL11; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; +import java.util.HashMap; import java.util.List; +import java.util.Map; import static net.minecraft.client.gui.inventory.GuiInventory.func_147046_a; @@ -83,6 +84,7 @@ public class GuiPlayerExpanded extends GuiContainer implements INEIGuiHandler { private int tooltipIndexCache = -1; private final List tooltipCache = new ArrayList<>(2); + private final Map slotIcons = new HashMap<>(); public GuiPlayerExpanded(EntityPlayer player) { super(new ContainerPlayerExpanded(player.inventory, !player.worldObj.isRemote, player)); @@ -142,6 +144,18 @@ public class GuiPlayerExpanded extends GuiContainer implements INEIGuiHandler { if (!useOldGuiRendering) { this.fontRendererObj.drawString(I18n.format("container.crafting"), 86, 16, 4210752); } + ContainerPlayerExpanded container = (ContainerPlayerExpanded) inventorySlots; + for (int i = 0; i < container.getBaubleSlotCount(); i++) { + SlotBauble slot = container.getBaubleSlot(i); + if (isVisibleBaubleSlot(slot) && !slot.isSlotActive()) { + drawRect(slot.xDisplayPosition, slot.yDisplayPosition, slot.xDisplayPosition + 16, slot.yDisplayPosition + 16, 0x88707070); + } + } + } + + private boolean isVisibleBaubleSlot(SlotBauble slot) { + return slot != null && slot.yDisplayPosition != -2000 + && !BaubleExpandedSlots.unknownType.equals(slot.getSlotType()); } @Override @@ -154,6 +168,7 @@ public class GuiPlayerExpanded extends GuiContainer implements INEIGuiHandler { } this.drawBaubleSlots(); + drawCustomSlotIcons(); if (showActivePotionEffects) { drawPotionEffects(); } @@ -162,6 +177,17 @@ public class GuiPlayerExpanded extends GuiContainer implements INEIGuiHandler { func_147046_a(guiLeft + 51, guiTop + 75, 30, (float) (guiLeft + 51) - xSizeFloat, (float) (guiTop + 25) - ySizeFloat, mc.thePlayer); } + private void drawCustomSlotIcons() { + ContainerPlayerExpanded container = (ContainerPlayerExpanded) inventorySlots; + for (int i = 0; i < container.getBaubleSlotCount(); i++) { + SlotBauble slot = container.getBaubleSlot(i); + String icon = slot.getSlotDefinition().icon(); + if (!isVisibleBaubleSlot(slot) || slot.getHasStack() || icon.isEmpty()) continue; + mc.getTextureManager().bindTexture(slotIcons.computeIfAbsent(icon, ResourceLocation::new)); + func_146110_a(guiLeft + slot.xDisplayPosition, guiTop + slot.yDisplayPosition, 0, 0, 16, 16, 16, 16); + } + } + private void drawBaubleSlots() { drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize); int columns = getColumns(); @@ -353,25 +379,12 @@ public class GuiPlayerExpanded extends GuiContainer implements INEIGuiHandler { // Strip formatting codes String strippedType = StatCollector.translateToLocal("slot." + slotType).replaceAll("§[0-9a-fklmnor]", ""); tooltipCache.add(strippedType); + if (!slot.isSlotActive()) tooltipCache.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("tooltip.baubles.inactive")); + ItemStack heldItem = mc.thePlayer.inventory.getItemStack(); if (heldItem != null && heldItem.stackSize > 0) { - boolean fitsInSlot = false; - if (heldItem.getItem() instanceof IBaubleExpanded baubleExpandedItem) { - String[] itemBaubleTypes = baubleExpandedItem.getBaubleTypes(heldItem); - for(String itemBaubleType : itemBaubleTypes) { - if (BaublesConfig.canTypeFitSlot(itemBaubleType, slotType)) { - fitsInSlot = true; - break; - } - } - } - else if(heldItem.getItem() instanceof IBauble baubleItem) { - String itemBaubleType = BaubleExpandedSlots.getTypeFromBaubleType(baubleItem.getBaubleType(heldItem)); - if (BaublesConfig.canTypeFitSlot(itemBaubleType, slotType)) { - fitsInSlot = true; - } - } + boolean fitsInSlot = slot.isItemValid(heldItem); tooltipCache.add(fitsInSlot ? StatCollector.translateToLocal("tooltip.fitsInSlot") diff --git a/src/main/java/baubles/common/BaubleSlotConfiguration.java b/src/main/java/baubles/common/BaubleSlotConfiguration.java new file mode 100644 index 0000000..cc7edfd --- /dev/null +++ b/src/main/java/baubles/common/BaubleSlotConfiguration.java @@ -0,0 +1,184 @@ +package baubles.common; + +import com.github.bsideup.jabel.Desugar; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.HashSet; + +import baubles.api.expanded.BaubleExpandedSlots; +import baubles.api.expanded.BaubleSlotType; +import baubles.api.expanded.BaubleSlotTypes; +import baubles.common.container.BaubleSlotState; +import baubles.common.container.InventoryBaubles; +import baubles.common.lib.PlayerHandler; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.server.MinecraftServer; +import net.minecraftforge.common.config.Configuration; + +/** + * Parses and preflights complete slot configurations before publishing them to online players. + * Player modifiers and activation remain independent of the configured baseline. + */ +public class BaubleSlotConfiguration { + + private static Map definitions = Collections.emptyMap(); + private static String[] baseline; + private static String[] publishedLayout; + private static File configFile; + + public static Map getDefinitions() { + return definitions.isEmpty() ? BaubleSlotTypes.getDefaults() : definitions; + } + + public static void initialize(Configuration config) { + configFile = config.getConfigFile(); + if (baseline == null) baseline = BaubleExpandedSlots.getCurrentSlotAssignments(); + publish(parse(config)); + } + + public static void reload() { + if (configFile == null) throw new IllegalStateException("Slot configuration has not been initialized"); + Configuration config = new Configuration(configFile); + config.load(); + Snapshot snapshot = parse(config); + Map updates = new LinkedHashMap<>(); + for (Object object : MinecraftServer.getServer().getConfigurationManager().playerEntityList) { + EntityPlayerMP player = (EntityPlayerMP) object; + InventoryBaubles inventory = PlayerHandler.getPlayerBaubles(player); + updates.put(inventory, inventory.prepareConfiguration(snapshot.assignments(), snapshot.definitions())); + } + publish(snapshot); + for (Map.Entry update : updates.entrySet()) { + update.getKey().applyConfiguration(update.getValue()); + } + } + + /** + * Retains initialization-time layout overrides made by downstream mods after Baubles initialized. + */ + public static void finishInitialization() { + String[] finalLayout = BaubleExpandedSlots.getCurrentSlotAssignments(); + if (!Arrays.equals(finalLayout, publishedLayout)) baseline = finalLayout; + } + + private static Snapshot parse(Configuration config) { + Map types = new LinkedHashMap<>(BaubleSlotTypes.getDefaults()); + boolean manual = config.get("menu", "manualSlotSelection", false).getBoolean(false); + String[] override = config.get("override", "slotTypeOverrides", baseline).getStringList(); + List layout = new ArrayList<>(Arrays.asList(manual ? override : baseline)); + for (String id : layout) { + if (id == null || id.trim().isEmpty()) throw new IllegalArgumentException("Empty slot type in layout"); + types.putIfAbsent(id, BaubleSlotType.defaults(id)); + } + String[] stackOverrides = config.get("override", "slotStackLimitOverrides", new String[0]).getStringList(); + String[] universalOverrides = config.get("override", "slotUniversalOverrides", new String[0]).getStringList(); + Map limits = new HashMap<>(); + for (String entry : stackOverrides) { + String[] pair = entry.split("=", 2); + try { + if (pair.length != 2 || pair[0].trim().isEmpty()) throw new NumberFormatException(); + int limit = Integer.parseInt(pair[1].trim()); + if (limit < 1) throw new NumberFormatException(); + limits.put(pair[0].trim(), limit); + } catch (NumberFormatException ignored) { + // Preserve the legacy handling of malformed override entries. + Baubles.log.warn("Ignoring invalid slotStackLimitOverrides entry '{}'", entry); + } + } + Set universal = new HashSet<>(); + for (String entry : universalOverrides) { + String type = entry.trim(); + if (!type.isEmpty() && !BaubleExpandedSlots.unknownType.equals(type) + && !BaubleExpandedSlots.universalType.equals(type)) universal.add(type); + } + for (Map.Entry entry : types.entrySet()) { + BaubleSlotType type = entry.getValue(); + entry.setValue(new BaubleSlotType(type.id(), type.order(), type.icon(), type.cosmetic(), type.renderToggle(), + type.nativeGui(), type.enabled(), limits.getOrDefault(type.id(), type.stackLimit()), + type.fitsUniversal() || universal.contains(type.id()))); + } + String[] rows = config.getStringList("slotDefinitions", "slots", new String[0], + "Type policies, one row per type: head;add_cosmetic=false;render_toggle=false\n" + + "Optional keys: order, icon, use_native_gui, enabled, size, stack_limit, fits_universal.\n" + + "Unspecified policies preserve existing behavior. size changes the configured baseline only.\n" + + "Icons are standalone textures such as example:textures/gui/head.png.\n" + + "Use /baubles reload after editing. Invalid definitions leave the running configuration unchanged."); + Map seen = new HashMap<>(); + for (String row : rows) { + String[] fields = row.split(";", -1); + String id = fields[0].trim(); + if (id.isEmpty() || BaubleExpandedSlots.unknownType.equals(id) || seen.put(id, true) != null) { + throw new IllegalArgumentException("Invalid or duplicate slot definition: " + id); + } + Map values = new HashMap<>(); + for (int i = 1; i < fields.length; i++) { + String[] pair = fields[i].split("=", 2); + if (pair.length != 2 || values.put(pair[0].trim(), pair[1].trim()) != null) { + throw new IllegalArgumentException("Invalid slot property: " + fields[i]); + } + } + BaubleSlotType fallback = types.getOrDefault(id, BaubleSlotType.defaults(id)); + BaubleSlotType type = new BaubleSlotType(id, number(values, "order", fallback.order()), + string(values, "icon", fallback.icon()), bool(values, "add_cosmetic", fallback.cosmetic()), + bool(values, "render_toggle", fallback.renderToggle()), bool(values, "use_native_gui", fallback.nativeGui()), + bool(values, "enabled", fallback.enabled()), number(values, "stack_limit", limits.getOrDefault(id, fallback.stackLimit())), + bool(values, "fits_universal", fallback.fitsUniversal() || universal.contains(id))); + types.put(id, type); + if (values.containsKey("size")) resize(layout, id, number(values, "size", 0)); + if (!values.isEmpty()) throw new IllegalArgumentException("Unknown properties for " + id + ": " + values.keySet()); + } + if (layout.size() > BaubleSlotState.MAX_SLOTS) throw new IllegalArgumentException("Too many configured slots"); + return new Snapshot(layout.toArray(new String[0]), Collections.unmodifiableMap(types), manual, override, + stackOverrides, universalOverrides); + } + + private static void resize(List layout, String id, int size) { + if (size < 0 || size > BaubleSlotState.MAX_SLOTS) throw new IllegalArgumentException("Invalid slot count: " + size); + int count = Collections.frequency(layout, id); + for (int slot = layout.size() - 1; slot >= 0 && count > size; slot--) { + if (id.equals(layout.get(slot))) { + layout.set(slot, BaubleExpandedSlots.unknownType); + count--; + } + } + while (count++ < size) layout.add(id); + } + + private static String string(Map values, String key, String fallback) { + return values.containsKey(key) ? values.remove(key) : fallback; + } + + private static int number(Map values, String key, int fallback) { + return values.containsKey(key) ? Integer.parseInt(values.remove(key)) : fallback; + } + + private static boolean bool(Map values, String key, boolean fallback) { + if (!values.containsKey(key)) return fallback; + String value = values.remove(key); + if (!"true".equals(value) && !"false".equals(value)) throw new IllegalArgumentException("Invalid " + key + ": " + value); + return Boolean.parseBoolean(value); + } + + private static void publish(Snapshot snapshot) { + definitions = snapshot.definitions(); + publishedLayout = snapshot.assignments().clone(); + BaublesConfig.manualSlotSelection = snapshot.manual(); + BaublesConfig.overrideSlotTypes = snapshot.override().clone(); + BaublesConfig.slotStackLimitOverrides = snapshot.stackOverrides().clone(); + BaublesConfig.slotUniversalOverrides = snapshot.universalOverrides().clone(); + BaubleExpandedSlots.applyConfiguration(snapshot.assignments(), definitions.keySet()); + } + + @Desugar + private record Snapshot(String[] assignments, Map definitions, boolean manual, String[] override, + String[] stackOverrides, String[] universalOverrides) { + } +} diff --git a/src/main/java/baubles/common/Baubles.java b/src/main/java/baubles/common/Baubles.java index 8ff54e2..dfa1201 100644 --- a/src/main/java/baubles/common/Baubles.java +++ b/src/main/java/baubles/common/Baubles.java @@ -13,6 +13,7 @@ import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; +import cpw.mods.fml.common.event.FMLLoadCompleteEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLServerStartingEvent; import cpw.mods.fml.common.event.FMLServerStoppedEvent; @@ -83,6 +84,11 @@ public class Baubles { PlayerHandler.clearServerPlayerBaubles(); } + @Mod.EventHandler + public void loadComplete(FMLLoadCompleteEvent event) { + BaubleSlotConfiguration.finishInitialization(); + } + @Mod.EventHandler public void onServerStarting(FMLServerStartingEvent event) { event.registerServerCommand(new CommandBaubles()); diff --git a/src/main/java/baubles/common/BaublesConfig.java b/src/main/java/baubles/common/BaublesConfig.java index b230495..4232589 100644 --- a/src/main/java/baubles/common/BaublesConfig.java +++ b/src/main/java/baubles/common/BaublesConfig.java @@ -1,11 +1,10 @@ package baubles.common; import java.util.ArrayList; -import java.util.HashMap; import java.util.LinkedHashSet; -import java.util.Map; import baubles.api.expanded.BaubleExpandedSlots; +import baubles.api.expanded.BaubleSlotType; import net.minecraftforge.common.config.Configuration; public class BaublesConfig { @@ -22,8 +21,6 @@ public class BaublesConfig { public static boolean displayTooltipOnHover = true; public static String[] slotStackLimitOverrides = new String[] {}; public static String[] slotUniversalOverrides = new String[] {}; - private static final Map stackLimitsByType = new HashMap<>(); - private static final ArrayList universalOverrideTypes = new ArrayList<>(); public static String[] overrideSlotTypes = new String[] { BaubleExpandedSlots.amuletType, @@ -90,50 +87,7 @@ public class BaublesConfig { currentlyRegisteredTypes.toArray(new String[0]) ); - stackLimitsByType.clear(); - universalOverrideTypes.clear(); - for (String type : slotUniversalOverrides) { - if (type == null) continue; - String trimmedType = type.trim(); - if (trimmedType.isEmpty()) continue; - if (!BaubleExpandedSlots.isTypeRegistered(trimmedType)) { - Baubles.log.warn("Ignoring slotUniversalOverrides entry '{}': unknown slot type '{}'", type, trimmedType); - continue; - } - if (trimmedType.equals(BaubleExpandedSlots.universalType) || trimmedType.equals(BaubleExpandedSlots.unknownType)) { - continue; - } - if (!universalOverrideTypes.contains(trimmedType)) { - universalOverrideTypes.add(trimmedType); - } - } - - for (String entry : slotStackLimitOverrides) { - if (entry == null) continue; - String[] split = entry.split("=", 2); - if (split.length != 2) { - Baubles.log.warn("Ignoring malformed slotStackLimitOverrides entry '{}'. Expected format: type=limit", entry); - continue; - } - String type = split[0].trim(); - String limitText = split[1].trim(); - if (!BaubleExpandedSlots.isTypeRegistered(type)) { - Baubles.log.warn("Ignoring slotStackLimitOverrides entry '{}': unknown slot type '{}'", entry, type); - continue; - } - try { - int limit = Integer.parseInt(limitText); - if (limit > 0) { - stackLimitsByType.put(type, limit); - } - } catch (NumberFormatException ignored) { - Baubles.log.warn("Ignoring slotStackLimitOverrides entry '{}': '{}' is not a valid integer", entry, limitText); - } - } - - if(manualSlotSelection) { - BaubleExpandedSlots.overrideSlots(overrideSlotTypes); - } + BaubleSlotConfiguration.initialize(config); if(config.hasChanged()) { config.save(); @@ -142,7 +96,8 @@ public class BaublesConfig { public static int getStackLimitForSlotType(String type) { if (type == null) return 1; - return stackLimitsByType.getOrDefault(type, 1); + BaubleSlotType definition = BaubleSlotConfiguration.getDefinitions().get(type); + return definition == null ? 1 : definition.stackLimit(); } public static boolean canTypeFitSlot(String itemType, String slotType) { @@ -152,7 +107,8 @@ public class BaublesConfig { if (itemType.equals(BaubleExpandedSlots.universalType) || itemType.equals(slotType)) { return true; } - return slotType.equals(BaubleExpandedSlots.universalType) && universalOverrideTypes.contains(itemType); + BaubleSlotType definition = BaubleSlotConfiguration.getDefinitions().get(itemType); + return slotType.equals(BaubleExpandedSlots.universalType) && definition != null && definition.fitsUniversal(); } public static String[] getDisplayTypesWithUniversalOverrides(String[] types) { @@ -165,7 +121,7 @@ public class BaublesConfig { String trimmed = type.trim(); if (trimmed.isEmpty()) continue; displayTypes.add(trimmed); - if (universalOverrideTypes.contains(trimmed)) { + if (canTypeFitSlot(trimmed, BaubleExpandedSlots.universalType)) { displayTypes.add(BaubleExpandedSlots.universalType); } } diff --git a/src/main/java/baubles/common/command/CommandBaubles.java b/src/main/java/baubles/common/command/CommandBaubles.java index 2ab2290..04db130 100644 --- a/src/main/java/baubles/common/command/CommandBaubles.java +++ b/src/main/java/baubles/common/command/CommandBaubles.java @@ -6,6 +6,8 @@ import java.util.List; import baubles.api.BaublesApi; import baubles.api.expanded.BaubleExpandedSlots; import baubles.api.expanded.IBaubleSlotInventory; +import baubles.api.expanded.IBaubleSlotSettings; +import baubles.common.BaubleSlotConfiguration; import baubles.common.container.BaubleSlotState; import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; @@ -38,6 +40,44 @@ public class CommandBaubles extends CommandBase { public void processCommand(ICommandSender sender, String[] args) { if (args.length == 0) throw new WrongUsageException(getCommandUsage(sender)); String operation = args[0]; + if ("reload".equals(operation)) { + if (args.length != 1) throw new WrongUsageException(getCommandUsage(sender)); + try { + BaubleSlotConfiguration.reload(); + } catch (IllegalArgumentException | IllegalStateException e) { + throw new CommandException("commands.baubles.invalid", e.getMessage()); + } + func_152373_a(sender, this, "commands.baubles.reloaded"); + return; + } + if (isActivationCommand(operation)) { + if (args.length < 3 || args.length > 4) throw new WrongUsageException(getCommandUsage(sender)); + validateType(args[1]); + EntityPlayerMP player = getPlayer(sender, args[2]); + IBaubleSlotSettings settings = BaublesApi.getBaubleSlotSettings(player); + if (settings == null) throw new CommandException("commands.baubles.unavailable"); + boolean active = "activate".equals(operation); + try { + if (args.length == 3) settings.setSlotsActive(args[1], active); + else { + int index = parseIntBounded(sender, args[3], 0, BaubleSlotState.MAX_SLOTS - 1); + int matching = 0; + int target = -1; + for (int slot = 0; slot < settings.getSizeInventory(); slot++) { + if (args[1].equals(settings.getSlotType(slot)) && matching++ == index) { + target = slot; + break; + } + } + if (target == -1) throw new IllegalArgumentException("Slot index is not present: " + index); + settings.setSlotActive(target, active); + } + } catch (IllegalArgumentException e) { + throw new CommandException("commands.baubles.invalid", e.getMessage()); + } + func_152373_a(sender, this, "commands.baubles.active", player.getCommandSenderName(), args[1], active); + return; + } if ("list".equals(operation)) { if (args.length > 2) throw new WrongUsageException(getCommandUsage(sender)); IBaubleSlotInventory inventory = args.length == 2 ? inventory(getPlayer(sender, args[1])) : null; @@ -104,11 +144,11 @@ public class CommandBaubles extends CommandBase { @Override public List addTabCompletionOptions(ICommandSender sender, String[] args) { - if (args.length == 1) return getListOfStringsMatchingLastWord(args, "list", "set", "add", "remove", "reset"); + if (args.length == 1) return getListOfStringsMatchingLastWord(args, "list", "set", "add", "remove", "reset", "reload", "activate", "deactivate"); if (isUsernameIndex(args, args.length - 1)) { return getListOfStringsMatchingLastWord(args, MinecraftServer.getServer().getAllUsernames()); } - if ((args.length == 2 && isCapacityCommand(args[0])) || (args.length == 3 && "reset".equals(args[0]))) { + if ((args.length == 2 && (isCapacityCommand(args[0]) || isActivationCommand(args[0]))) || (args.length == 3 && "reset".equals(args[0]))) { List types = new ArrayList<>(BaubleExpandedSlots.getCurrentlyRegisteredTypes()); types.remove(BaubleExpandedSlots.unknownType); return getListOfStringsFromIterableMatchingLastWord(args, types); @@ -119,7 +159,11 @@ public class CommandBaubles extends CommandBase { @Override public boolean isUsernameIndex(String[] args, int index) { return args.length > 0 && (index == 1 && ("list".equals(args[0]) || "reset".equals(args[0])) - || index == 2 && isCapacityCommand(args[0])); + || index == 2 && (isCapacityCommand(args[0]) || isActivationCommand(args[0]))); + } + + private boolean isActivationCommand(String operation) { + return "activate".equals(operation) || "deactivate".equals(operation); } private boolean isCapacityCommand(String operation) { diff --git a/src/main/java/baubles/common/container/BaubleLifecycle.java b/src/main/java/baubles/common/container/BaubleLifecycle.java new file mode 100644 index 0000000..f156448 --- /dev/null +++ b/src/main/java/baubles/common/container/BaubleLifecycle.java @@ -0,0 +1,46 @@ +package baubles.common.container; + +import baubles.api.IBauble; +import baubles.api.expanded.BaubleSlotContext; +import baubles.api.expanded.IBaubleLifecycle; +import net.minecraft.item.ItemStack; + +/** + * Selects contextual callbacks without changing the legacy interface or invoking it twice. + */ +public class BaubleLifecycle { + + public static void tick(ItemStack stack, BaubleSlotContext context) { + if (stack.getItem() instanceof IBaubleLifecycle item) item.onBaubleTick(stack, context); + else if (stack.getItem() instanceof IBauble item) item.onWornTick(stack, context.player()); + } + + public static void equipped(ItemStack stack, BaubleSlotContext context, ItemStack previous) { + if (stack.getItem() instanceof IBaubleLifecycle item) item.onBaubleEquipped(stack, context, ItemStack.copyItemStack(previous)); + else if (stack.getItem() instanceof IBauble item) item.onEquipped(stack, context.player()); + } + + public static void unequipped(ItemStack stack, BaubleSlotContext context, ItemStack replacement) { + if (stack.getItem() instanceof IBaubleLifecycle item) item.onBaubleUnequipped(stack, context, ItemStack.copyItemStack(replacement)); + else if (stack.getItem() instanceof IBauble item) item.onUnequipped(stack, context.player()); + } + + public static void loaded(ItemStack stack, BaubleSlotContext context) { + if (stack.getItem() instanceof IBaubleLifecycle item) item.onBaubleLoaded(stack, context); + else if (stack.getItem() instanceof IBauble item) item.onPlayerLoad(stack, context.player()); + } + + public static void changed(ItemStack stack, BaubleSlotContext context, ItemStack previous) { + if (stack.getItem() instanceof IBaubleLifecycle item) item.onBaubleChanged(stack, context, previous); + } + + public static boolean canEquip(ItemStack stack, BaubleSlotContext context) { + if (stack.getItem() instanceof IBaubleLifecycle item) return item.canEquipBauble(stack, context); + return stack.getItem() instanceof IBauble item && (context.cosmetic() || item.canEquip(stack, context.player())); + } + + public static boolean canUnequip(ItemStack stack, BaubleSlotContext context) { + if (stack.getItem() instanceof IBaubleLifecycle item) return item.canUnequipBauble(stack, context); + return !(stack.getItem() instanceof IBauble item) || context.cosmetic() || item.canUnequip(stack, context.player()); + } +} diff --git a/src/main/java/baubles/common/container/BaubleSlotState.java b/src/main/java/baubles/common/container/BaubleSlotState.java index 4d85c21..ca4d370 100644 --- a/src/main/java/baubles/common/container/BaubleSlotState.java +++ b/src/main/java/baubles/common/container/BaubleSlotState.java @@ -2,12 +2,15 @@ package baubles.common.container; import java.util.ArrayList; import java.util.Arrays; +import java.util.BitSet; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import baubles.api.expanded.BaubleExpandedSlots; +import baubles.api.expanded.BaubleSlotType; +import baubles.common.BaubleSlotConfiguration; public class BaubleSlotState { @@ -15,12 +18,29 @@ public class BaubleSlotState { private final String[] assignments; private final Map> modifiers; + private final Map definitions; + private final BitSet inactive; + private final int[] typeIndices; public BaubleSlotState(String[] assignments, Map> modifiers) { + this(assignments, modifiers, BaubleSlotConfiguration.getDefinitions(), new BitSet()); + } + + public BaubleSlotState(String[] assignments, Map> modifiers, + Map definitions, BitSet inactive) { if (assignments.length > MAX_SLOTS) { throw new IllegalArgumentException("Too many bauble slots: " + assignments.length); } this.assignments = assignments.clone(); + typeIndices = new int[assignments.length]; + Map counts = new LinkedHashMap<>(); + for (int slot = 0; slot < assignments.length; slot++) { + typeIndices[slot] = counts.getOrDefault(assignments[slot], 0); + counts.put(assignments[slot], typeIndices[slot] + 1); + } + this.definitions = Collections.unmodifiableMap(new LinkedHashMap<>(definitions)); + this.inactive = (BitSet) inactive.clone(); + this.inactive.clear(assignments.length, Math.max(assignments.length, this.inactive.length())); this.modifiers = new LinkedHashMap<>(); for (Map.Entry> entry : modifiers.entrySet()) { this.modifiers.put(entry.getKey(), Collections.unmodifiableMap(new LinkedHashMap<>(entry.getValue()))); @@ -51,6 +71,58 @@ public class BaubleSlotState { return modifiers.getOrDefault(type, Collections.emptyMap()); } + public Map getDefinitions() { + return definitions; + } + + public BaubleSlotType getDefinition(String type) { + BaubleSlotType definition = definitions.get(type); + return definition == null ? BaubleSlotType.defaults(type) : definition; + } + + public boolean isActive(int slot) { + return slot >= 0 && slot < assignments.length && !BaubleExpandedSlots.unknownType.equals(getType(slot)) + && getDefinition(getType(slot)).enabled() && !inactive.get(slot); + } + + public BitSet getInactiveSlots() { + return (BitSet) inactive.clone(); + } + + public int getTypeIndex(int slot) { + return slot >= 0 && slot < typeIndices.length ? typeIndices[slot] : -1; + } + + public BaubleSlotState withSlotActive(int slot, boolean active) { + if (slot < 0 || slot >= assignments.length || BaubleExpandedSlots.unknownType.equals(getType(slot))) { + throw new IllegalArgumentException("Invalid bauble slot: " + slot); + } + if (active && !getDefinition(getType(slot)).enabled()) { + throw new IllegalArgumentException("Slot type is disabled by configuration: " + getType(slot)); + } + BitSet changed = getInactiveSlots(); + changed.set(slot, !active); + return new BaubleSlotState(assignments, modifiers, definitions, changed); + } + + public BaubleSlotState rebase(String[] base, Map types) { + BaubleSlotState updated = resolve(base, assignments, modifiers, types); + BitSet retained = getInactiveSlots(); + for (int slot = retained.nextSetBit(0); slot >= 0; slot = retained.nextSetBit(slot + 1)) { + if (!getType(slot).equals(updated.getType(slot))) retained.clear(slot); + } + return new BaubleSlotState(updated.assignments, modifiers, types, retained); + } + + public BaubleSlotState withSlotsActive(String type, boolean active) { + if (active && !getDefinition(type).enabled()) throw new IllegalArgumentException("Slot type is disabled: " + type); + BitSet changed = getInactiveSlots(); + for (int slot = 0; slot < assignments.length; slot++) { + if (type.equals(assignments[slot])) changed.set(slot, !active); + } + return new BaubleSlotState(assignments, modifiers, definitions, changed); + } + public BaubleSlotState withModifier(String type, String source, int amount) { validateType(type); validateSource(source); @@ -60,7 +132,8 @@ public class BaubleSlotState { else values.put(source, amount); if (values.isEmpty()) updated.remove(type); else updated.put(type, values); - return resolve(BaubleExpandedSlots.getCurrentSlotAssignments(), assignments, updated); + return new BaubleSlotState(assignments, updated, definitions, inactive) + .rebase(BaubleExpandedSlots.getCurrentSlotAssignments(), definitions); } public BaubleSlotState withoutSource(String source) { @@ -71,7 +144,8 @@ public class BaubleSlotState { values.remove(source); if (!values.isEmpty()) updated.put(entry.getKey(), values); } - return resolve(BaubleExpandedSlots.getCurrentSlotAssignments(), assignments, updated); + return new BaubleSlotState(assignments, updated, definitions, inactive) + .rebase(BaubleExpandedSlots.getCurrentSlotAssignments(), definitions); } public static void validateType(String type) { @@ -88,6 +162,11 @@ public class BaubleSlotState { public static BaubleSlotState resolve(String[] base, String[] previous, Map> modifiers) { + return resolve(base, previous, modifiers, BaubleSlotConfiguration.getDefinitions()); + } + + private static BaubleSlotState resolve(String[] base, String[] previous, + Map> modifiers, Map definitions) { Map remaining = new LinkedHashMap<>(); for (String type : base) { if (!BaubleExpandedSlots.unknownType.equals(type)) { @@ -95,7 +174,7 @@ public class BaubleSlotState { } } for (Map.Entry> entry : modifiers.entrySet()) { - if (!BaubleExpandedSlots.isTypeRegistered(entry.getKey()) + if (!definitions.containsKey(entry.getKey()) || BaubleExpandedSlots.unknownType.equals(entry.getKey())) continue; long count = remaining.getOrDefault(entry.getKey(), 0L); for (int amount : entry.getValue().values()) count += amount; @@ -128,7 +207,7 @@ public class BaubleSlotState { && BaubleExpandedSlots.unknownType.equals(layout.get(layout.size() - 1))) { layout.remove(layout.size() - 1); } - return new BaubleSlotState(layout.toArray(new String[0]), modifiers); + return new BaubleSlotState(layout.toArray(new String[0]), modifiers, definitions, new BitSet()); } private static boolean consume(Map counts, String type) { diff --git a/src/main/java/baubles/common/container/BaubleSlotStorage.java b/src/main/java/baubles/common/container/BaubleSlotStorage.java index 4f89d5d..eb616ab 100644 --- a/src/main/java/baubles/common/container/BaubleSlotStorage.java +++ b/src/main/java/baubles/common/container/BaubleSlotStorage.java @@ -2,8 +2,10 @@ package baubles.common.container; import java.util.LinkedHashMap; import java.util.Map; +import java.util.BitSet; import baubles.api.expanded.BaubleExpandedSlots; +import baubles.common.BaubleSlotConfiguration; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagString; @@ -25,6 +27,7 @@ public class BaubleSlotStorage { } } tags.setTag("Baubles.SlotModifiers", modifiers); + tags.setIntArray("Baubles.InactiveSlots", state.getInactiveSlots().stream().toArray()); } public static BaubleSlotState read(NBTTagCompound tags) { @@ -46,6 +49,11 @@ public class BaubleSlotStorage { modifiers.computeIfAbsent(entry.getString("Type"), key -> new LinkedHashMap<>()) .put(source, entry.getInteger("Amount")); } - return new BaubleSlotState(assignments, modifiers); + BitSet inactive = new BitSet(); + for (int slot : tags.getIntArray("Baubles.InactiveSlots")) { + if (slot >= 0 && slot < assignments.length) inactive.set(slot); + } + return new BaubleSlotState(assignments, modifiers, + BaubleSlotConfiguration.getDefinitions(), inactive); } } diff --git a/src/main/java/baubles/common/container/ContainerPlayerExpanded.java b/src/main/java/baubles/common/container/ContainerPlayerExpanded.java index afe1f63..b2ea332 100644 --- a/src/main/java/baubles/common/container/ContainerPlayerExpanded.java +++ b/src/main/java/baubles/common/container/ContainerPlayerExpanded.java @@ -23,6 +23,7 @@ import net.minecraft.util.IIcon; import java.util.ArrayList; import java.util.List; +import java.util.Comparator; import static baubles.common.BaublesConfig.maxColumns; @@ -92,12 +93,12 @@ public class ContainerPlayerExpanded extends Container { baubleFirstSlotIndex = slotsAdded; String[] currentSlotAssignments = baubles.getSlotAssignments(); for (String type : currentSlotAssignments) { - if (BaublesConfig.showUnusedSlots || !BaubleExpandedSlots.unknownType.equals(type)) baubleSlotCount++; + if (isTypeVisible(type)) baubleSlotCount++; } int visibleIndex = 0; for (int index = 0; index < currentSlotAssignments.length; index++) { String type = currentSlotAssignments[index]; - boolean visible = BaublesConfig.showUnusedSlots || !BaubleExpandedSlots.unknownType.equals(type); + boolean visible = isTypeVisible(type); int x = useOldGuiRendering ? slotStartX + slotOffset * (visibleIndex / 4) : -18 - 18 * (visibleIndex % getColumns()); int y = useOldGuiRendering ? slotStartY + slotOffset * (visibleIndex % 4) : 12 + slotOffset * (visibleIndex / getColumns()); SlotBauble slot = new SlotBauble(baubles, type, index, x, y); @@ -107,6 +108,12 @@ public class ContainerPlayerExpanded extends Container { visibleIndex++; } else slot.yDisplayPosition = -2000; } + visibleBaubleSlots.sort(Comparator.comparingInt(slot -> slot.getSlotDefinition().order())); + for (int index = 0; index < visibleBaubleSlots.size(); index++) { + SlotBauble slot = visibleBaubleSlots.get(index); + slot.xDisplayPosition = useOldGuiRendering ? slotStartX + slotOffset * (index / 4) : -18 - 18 * (index % getColumns()); + slot.yDisplayPosition = useOldGuiRendering ? slotStartY + slotOffset * (index % 4) : 12 + slotOffset * (index / getColumns()); + } // Inventory slots for (i = 0; i < 3; ++i) { @@ -176,6 +183,11 @@ public class ContainerPlayerExpanded extends Container { return useOldGuiRendering; } + private boolean isTypeVisible(String type) { + return baubles.getSlotDefinition(type).nativeGui() + && (BaublesConfig.showUnusedSlots || !BaubleExpandedSlots.unknownType.equals(type)); + } + public void scrollTo(float offset) { if (!canScroll()) return; final int activeBaubleSlots = baubleSlotCount; @@ -226,6 +238,7 @@ public class ContainerPlayerExpanded extends Container { public ItemStack slotClick(int slot, int button, int mode, EntityPlayer player) { if (!canInteractWith(player) || slot >= inventorySlots.size() || slot < -1 && slot != -999 || mode < 0 || mode > 6 || button < 0) return null; + if (slot >= 0 && inventorySlots.get(slot) instanceof SlotBauble baubleSlot && !isTypeVisible(baubleSlot.getSlotType())) return null; if (mode == 2 ? button > 8 : mode == 3 ? button != 2 : mode == 5 ? button > 10 || (button & 3) > 2 : button > 1) return null; return super.slotClick(slot, button, mode, player); @@ -370,7 +383,7 @@ public class ContainerPlayerExpanded extends Container { if (type.equals(BaubleExpandedSlots.universalType) || type.equals(slotType)) { return 2; } - if (BaublesConfig.canTypeFitSlot(type, slotType)) { + if (baubles.canTypeFitSlot(type, slotType)) { best = 1; } } @@ -385,6 +398,7 @@ public class ContainerPlayerExpanded extends Container { sourceStack.stackSize > 0 && index >= startIndex && index < endIndex; index += reverse ? -1 : 1) { Slot targetSlot = (Slot) inventorySlots.get(index); + if (targetSlot instanceof SlotBauble baubleSlot && !isTypeVisible(baubleSlot.getSlotType())) continue; ItemStack targetStack = targetSlot.getStack(); if ((pass == 0) != (targetStack != null) || !targetSlot.isItemValid(sourceStack)) continue; int limit = Math.min(sourceStack.getMaxStackSize(), targetSlot.getSlotStackLimit()); diff --git a/src/main/java/baubles/common/container/InventoryBaubles.java b/src/main/java/baubles/common/container/InventoryBaubles.java index 671fb8c..874c404 100644 --- a/src/main/java/baubles/common/container/InventoryBaubles.java +++ b/src/main/java/baubles/common/container/InventoryBaubles.java @@ -5,12 +5,20 @@ import baubles.api.IBauble; import baubles.api.expanded.BaubleExpandedSlots; import baubles.api.expanded.IBaubleExpanded; import baubles.api.expanded.IBaubleSlotInventory; +import baubles.api.expanded.IBaubleSlotSettings; +import baubles.api.expanded.IBaubleLifecycle; +import baubles.api.expanded.BaubleSlotContext; +import baubles.api.expanded.BaubleSlotType; import baubles.common.Baubles; import baubles.common.BaublesConfig; +import baubles.common.BaubleSlotConfiguration; import baubles.common.lib.ItemStackHelper; import baubles.common.network.PacketHandler; import baubles.common.network.PacketSyncAllBauble; import baubles.common.network.PacketSyncBauble; +import baubles.common.network.BaubleSlotCodec; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; @@ -29,7 +37,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.Map; -public class InventoryBaubles implements IBaubleSlotInventory { +public class InventoryBaubles implements IBaubleSlotInventory, IBaubleSlotSettings { public ItemStack[] stackList; private Container eventHandler; public WeakReference player; @@ -43,6 +51,7 @@ public class InventoryBaubles implements IBaubleSlotInventory { private boolean oldGuiRendering = BaublesConfig.useOldGuiRendering; private WeakReference loadedPlayer = new WeakReference<>(null); private final ArrayDeque pendingReturns = new ArrayDeque<>(); + private ItemStack[] previousStacks = new ItemStack[0]; public InventoryBaubles(EntityPlayer player) { slotState = new BaubleSlotState(BaubleExpandedSlots.getCurrentSlotAssignments(), Collections.emptyMap()); @@ -74,6 +83,47 @@ public class InventoryBaubles implements IBaubleSlotInventory { return slotState; } + /** + * Exports effective rules for a detached container without exporting equipment or invoking callbacks. + */ + public NBTTagCompound writeContainerData() { + NBTTagCompound data = new NBTTagCompound(); + ByteBuf buffer = Unpooled.buffer(); + try { + BaubleSlotCodec.writeState(buffer, slotState); + byte[] state = new byte[buffer.readableBytes()]; + buffer.readBytes(state); + data.setByteArray("SlotState", state); + } finally { + buffer.release(); + } + data.setBoolean("OldGui", oldGuiRendering); + return data; + } + + /** + * Initializes a detached client inventory with server rules and no equipment side effects. + * Vanilla container packets supply the contents separately. + */ + public void readContainerData(NBTTagCompound data) { + EntityPlayer owner = player.get(); + if (owner == null || !owner.worldObj.isRemote || !blockEvents) { + throw new IllegalStateException("Container data requires a detached client inventory with events blocked"); + } + ByteBuf buffer = Unpooled.wrappedBuffer(data.getByteArray("SlotState")); + BaubleSlotState state; + try { + state = BaubleSlotCodec.readState(buffer); + if (buffer.isReadable()) throw new IllegalArgumentException("Trailing container slot data"); + } finally { + buffer.release(); + } + if (state.getAssignments().length != stackList.length) throw new IllegalArgumentException("Container slot count differs"); + slotState = state; + oldGuiRendering = data.getBoolean("OldGui"); + resetStackSnapshots(); + } + public long getLayoutRevision() { return layoutRevision; } @@ -82,6 +132,66 @@ public class InventoryBaubles implements IBaubleSlotInventory { return oldGuiRendering; } + private boolean isValidSlot(int slot) { + return slot >= 0 && slot < getSizeInventory() + && !BaubleExpandedSlots.unknownType.equals(getSlotType(slot)); + } + + @Override + public boolean isSlotActive(int slot) { + return slotState.isActive(slot); + } + + @Override + public void setSlotActive(int slot, boolean active) { + requireServerPlayer(); + updateSlots(getPendingSlotState().withSlotActive(slot, active)); + } + + @Override + public void setSlotsActive(String type, boolean active) { + requireServerPlayer(); + BaubleSlotState.validateType(type); + updateSlots(getPendingSlotState().withSlotsActive(type, active)); + } + + @Override + public Map getSlotDefinitions() { + return slotState.getDefinitions(); + } + + @Override + public BaubleSlotType getSlotDefinition(String type) { + return slotState.getDefinition(type); + } + + @Override + public BaubleSlotContext getSlotContext(int slot, boolean cosmetic) { + return context(slotState, slot, cosmetic); + } + + private BaubleSlotContext context(BaubleSlotState state, int slot, boolean cosmetic) { + boolean active = state.isActive(slot); + boolean rendered = active; + return new BaubleSlotContext(player.get(), state.getType(slot), slot, state.getTypeIndex(slot), cosmetic, rendered, active); + } + + public boolean canTypeFitSlot(String itemType, String slotType) { + if (itemType == null || slotType == null) return false; + return itemType.equals(slotType) || itemType.equals(BaubleExpandedSlots.universalType) + || slotType.equals(BaubleExpandedSlots.universalType) && getSlotDefinition(itemType).fitsUniversal(); + } + + public BaubleSlotState prepareConfiguration(String[] baseline, Map definitions) { + requireServerPlayer(); + if (callbackDepth > 0 || changingSlots || returningItems) throw new IllegalStateException("Inventory is busy"); + return getPendingSlotState().rebase(baseline, definitions); + } + + public void applyConfiguration(BaubleSlotState state) { + updateSlots(state); + } + @Override public void setSlotModifier(String type, String source, int amount) { requireServerPlayer(); @@ -132,25 +242,48 @@ public class InventoryBaubles implements IBaubleSlotInventory { pendingSlotState = null; String[] assignments = updated.getAssignments(); if (Arrays.equals(assignments, getSlotAssignments()) - && updated.getModifiers().equals(slotState.getModifiers())) return; + && updated.getModifiers().equals(slotState.getModifiers()) + && updated.getDefinitions().equals(slotState.getDefinitions()) + && updated.getInactiveSlots().equals(slotState.getInactiveSlots())) return; changingSlots = true; try { boolean closedBaubles = owner.openContainer instanceof ContainerPlayerExpanded; if (closedBaubles) owner.closeScreen(); ItemStack[] previous = stackList; BaubleSlotState previousState = slotState; + BaubleSlotContext[] oldContexts = new BaubleSlotContext[previous.length]; + for (int slot = 0; slot < previous.length; slot++) oldContexts[slot] = context(previousState, slot, false); slotState = updated; stackList = Arrays.copyOf(previous, assignments.length); layoutRevision++; for (int slot = 0; slot < previous.length; slot++) { - if (previousState.getType(slot).equals(updated.getType(slot)) && slot < stackList.length) continue; + boolean retained = previousState.getType(slot).equals(updated.getType(slot)) && slot < stackList.length; + if (retained) { + if (previous[slot] != null && !matchesSlotType(slot, previous[slot])) { + stackList[slot] = null; + if (previousState.isActive(slot)) notifyUnequipped(previous[slot], oldContexts[slot], null); + pendingReturns.add(previous[slot]); + continue; + } + if (previous[slot] != null && previous[slot].stackSize > getSlotDefinition(getSlotType(slot)).stackLimit()) { + ItemStack before = previous[slot].copy(); + pendingReturns.add(previous[slot].splitStack(previous[slot].stackSize - getSlotDefinition(getSlotType(slot)).stackLimit())); + if (updated.isActive(slot)) notifyStackChanged(slot, previous[slot], before); + } + if (previous[slot] != null && previousState.isActive(slot) != updated.isActive(slot)) { + if (previousState.isActive(slot)) notifyUnequipped(previous[slot], oldContexts[slot], previous[slot]); + else notifyEquipped(previous[slot], getSlotContext(slot, false), previous[slot]); + } + continue; + } ItemStack stack = previous[slot]; if (slot < stackList.length) stackList[slot] = null; if (stack != null) { - notifyUnequipped(stack, owner); + if (previousState.isActive(slot)) notifyUnequipped(stack, oldContexts[slot], null); pendingReturns.add(stack); } } + resetStackSnapshots(); returnOverflowItems(); markDirty(); if (owner instanceof EntityPlayerMP serverPlayer) { @@ -163,11 +296,11 @@ public class InventoryBaubles implements IBaubleSlotInventory { } } - private void notifyUnequipped(ItemStack stack, EntityPlayer owner) { + private void notifyUnequipped(ItemStack stack, BaubleSlotContext context, ItemStack replacement) { if (stack.getItem() instanceof IBauble bauble) { callbackDepth++; try { - bauble.onUnequipped(stack, owner); + BaubleLifecycle.unequipped(stack, context, replacement); } catch (Exception e) { Baubles.log.error("Error unequipping bauble {}", stack, e); } finally { @@ -176,11 +309,11 @@ public class InventoryBaubles implements IBaubleSlotInventory { } } - private void notifyEquipped(ItemStack stack, EntityPlayer owner) { - if (owner != null && stack.getItem() instanceof IBauble bauble) { + private void notifyEquipped(ItemStack stack, BaubleSlotContext context, ItemStack previous) { + if (context.player() != null && stack.getItem() instanceof IBauble) { callbackDepth++; try { - bauble.onEquipped(stack, owner); + BaubleLifecycle.equipped(stack, context, previous); } catch (Exception e) { Baubles.log.error("Error equipping bauble {}", stack, e); } finally { @@ -200,23 +333,86 @@ public class InventoryBaubles implements IBaubleSlotInventory { } for (int slot = 0; slot < getSizeInventory(); slot++) { ItemStack stack = getStackInSlot(slot); - if (stack == null || !(stack.getItem() instanceof IBauble bauble)) continue; + if (stack == null || !isSlotActive(slot) || !(stack.getItem() instanceof IBauble)) continue; callbackDepth++; try { - bauble.onWornTick(stack, owner); + BaubleLifecycle.tick(stack, getSlotContext(slot, false)); } finally { callbackDepth--; } } + if (!owner.worldObj.isRemote) { + detectStackChanges(); + } + } + + private void resetStackSnapshots() { + previousStacks = new ItemStack[stackList.length]; + for (int slot = 0; slot < stackList.length; slot++) previousStacks[slot] = ItemStack.copyItemStack(stackList[slot]); + } + + private void detectStackChanges() { + if (previousStacks.length != stackList.length) previousStacks = Arrays.copyOf(previousStacks, stackList.length); + for (int slot = 0; slot < stackList.length; slot++) { + ItemStack current = stackList[slot]; + ItemStack previous = previousStacks[slot]; + if (ItemStack.areItemStacksEqual(current, previous)) continue; + if (current != null && current.stackSize <= 0) current = stackList[slot] = null; + if (!blockEvents && isSlotActive(slot)) { + if (current != null && previous != null && current.getItem() == previous.getItem()) { + notifyStackChanged(slot, current, previous); + } else { + if (previous != null) notifyUnequipped(previous, getSlotContext(slot, false), current); + if (current != null) notifyEquipped(current, getSlotContext(slot, false), previous); + } + } + syncSlotToClients(slot); + } + } + + private void notifyStackChanged(int slot, ItemStack current, ItemStack previous) { + callbackDepth++; + try { + BaubleLifecycle.changed(current, getSlotContext(slot, false), ItemStack.copyItemStack(previous)); + } catch (Exception e) { + Baubles.log.error("Error updating bauble state {}", current, e); + } finally { + callbackDepth--; + } + } + + public void onPlayerLoaded() { + for (int slot = 0; slot < stackList.length; slot++) { + if (stackList[slot] == null || !isSlotActive(slot)) continue; + callbackDepth++; + try { + BaubleLifecycle.loaded(stackList[slot], getSlotContext(slot, false)); + } catch (Exception e) { + Baubles.log.error("Error loading bauble {}", stackList[slot], e); + } finally { + callbackDepth--; + } + } + resetStackSnapshots(); + } + + public void applyStackSync(int slot, ItemStack stack) { + if (player.get() == null || !player.get().worldObj.isRemote) return; + ItemStack previous = getStackInSlot(slot); + if (previous != null && stack != null && previous.getItem() == stack.getItem()) { + stackList[slot] = stack; + if (!blockEvents && isSlotActive(slot) && !ItemStack.areItemStacksEqual(previous, stack)) notifyStackChanged(slot, stack, previous); + } else setInventorySlotContents(slot, stack); } public void onSlotContentsChanged(int slot) { ItemStack stack = getStackInSlot(slot); EntityPlayer owner = player.get(); - if (!blockEvents && owner != null && stack != null && stack.getItem() instanceof IBaubleExpanded bauble) { + if (!blockEvents && isSlotActive(slot) && owner != null && stack != null) { callbackDepth++; try { - bauble.onSlotContentsChanged(stack, owner); + if (stack.getItem() instanceof IBaubleLifecycle item) item.onBaubleContentsChanged(stack, getSlotContext(slot, false)); + else if (stack.getItem() instanceof IBaubleExpanded item) item.onSlotContentsChanged(stack, owner); } catch (Exception e) { Baubles.log.error("Error updating bauble {}", stack, e); } finally { @@ -234,6 +430,9 @@ public class InventoryBaubles implements IBaubleSlotInventory { throw new IllegalArgumentException("Snapshot items and layout have different sizes"); } ItemStack[] previous = stackList; + BaubleSlotState previousState = slotState; + BaubleSlotContext[] previousContexts = new BaubleSlotContext[previous.length]; + for (int slot = 0; slot < previous.length; slot++) previousContexts[slot] = context(previousState, slot, false); boolean loadAll = loadedPlayer.get() != owner; loadedPlayer = new WeakReference<>(owner); slotState = state; @@ -243,16 +442,30 @@ public class InventoryBaubles implements IBaubleSlotInventory { for (int slot = 0; slot < Math.max(previous.length, stacks.length); slot++) { ItemStack before = slot < previous.length ? previous[slot] : null; ItemStack after = getStackInSlot(slot); - if (!loadAll && ItemStack.areItemStacksEqual(before, after)) continue; - if (before != null && !loadAll) notifyUnequipped(before, owner); - if (after != null && after.getItem() instanceof IBauble bauble) { + boolean wasActive = previousState.isActive(slot); + boolean active = isSlotActive(slot); + if (!loadAll && wasActive == active && ItemStack.areItemStacksEqual(before, after)) continue; + if (!loadAll && wasActive && active && before != null && after != null && before.getItem() == after.getItem()) { + notifyStackChanged(slot, after, before); + continue; + } + if (before != null && wasActive && !loadAll) notifyUnequipped(before, previousContexts[slot], after); + if (after != null && active) { + if (!loadAll && !wasActive) { + notifyEquipped(after, getSlotContext(slot, false), before); + continue; + } + callbackDepth++; try { - bauble.onPlayerLoad(after, owner); + BaubleLifecycle.loaded(after, getSlotContext(slot, false)); } catch (Exception e) { Baubles.log.error("Error loading bauble {}", after, e); + } finally { + callbackDepth--; } } } + resetStackSnapshots(); } public void returnOverflowItems() { @@ -351,7 +564,7 @@ public class InventoryBaubles implements IBaubleSlotInventory { stackList[slot] = null; } } - if (!blockEvents) notifyUnequipped(itemstack, player.get()); + if (!blockEvents && isSlotActive(slot)) notifyUnequipped(itemstack, getSlotContext(slot, false), stackList[slot]); if(eventHandler != null) eventHandler.onCraftMatrixChanged(this); @@ -373,9 +586,16 @@ public class InventoryBaubles implements IBaubleSlotInventory { ItemStack previous = stackList[slot]; boolean changed = !ItemStack.areItemStacksEqual(previous, stack); stackList[slot] = stack; - if (!blockEvents && changed) { - if (previous != null) notifyUnequipped(previous, player.get()); - if (stack != null) notifyEquipped(stack, player.get()); + if (!blockEvents && changed && isSlotActive(slot)) { + EntityPlayer owner = player.get(); + if (owner != null && owner.worldObj.isRemote && previous != null && stack != null + && previous.getItem() == stack.getItem()) { + // Vanilla container packets use the inventory setter for synchronized item data. + notifyStackChanged(slot, stack, previous); + } else { + if (previous != null) notifyUnequipped(previous, getSlotContext(slot, false), stack); + if (stack != null) notifyEquipped(stack, getSlotContext(slot, false), previous); + } } if (eventHandler != null) { eventHandler.onCraftMatrixChanged(this); @@ -427,13 +647,18 @@ public class InventoryBaubles implements IBaubleSlotInventory { */ @Override public boolean isItemValidForSlot(int slot, ItemStack stack) { + return stack != null && isSlotActive(slot) && matchesSlotType(slot, stack) + && BaubleLifecycle.canEquip(stack, getSlotContext(slot, false)); + } + + public boolean matchesSlotType(int slot, ItemStack stack) { String slotType = getSlotType(slot); - if (stack == null || slot < 0 || slot >= getSizeInventory() || BaubleExpandedSlots.unknownType.equals(slotType)) { + if (stack == null || !isValidSlot(slot)) { return false; } Item item = stack.getItem(); - if(!(item instanceof IBauble) || !((IBauble) item).canEquip(stack, player.get())) { + if(!(item instanceof IBauble)) { return false; } @@ -447,7 +672,7 @@ public class InventoryBaubles implements IBaubleSlotInventory { if (types == null) return false; for(String type : types) { - if (BaublesConfig.canTypeFitSlot(type, slotType)) { + if (canTypeFitSlot(type, slotType)) { return true; } } @@ -461,7 +686,8 @@ public class InventoryBaubles implements IBaubleSlotInventory { } public void saveNBT(NBTTagCompound tags) { - BaubleSlotStorage.write(tags, new BaubleSlotState(slotState.getAssignments(), getPendingSlotState().getModifiers())); + BaubleSlotStorage.write(tags, new BaubleSlotState(slotState.getAssignments(), getPendingSlotState().getModifiers(), + slotState.getDefinitions(), getPendingSlotState().getInactiveSlots())); NBTTagList tagList = new NBTTagList(); NBTTagCompound invSlot; for (int slot = 0; slot < stackList.length; ++slot) { @@ -487,8 +713,8 @@ public class InventoryBaubles implements IBaubleSlotInventory { public void readNBT(NBTTagCompound tags) { pendingSlotState = null; BaubleSlotState saved = BaubleSlotStorage.read(tags); - slotState = BaubleSlotState.resolve(BaubleExpandedSlots.getCurrentSlotAssignments(), - saved.getAssignments(), saved.getModifiers()); + slotState = saved.rebase(BaubleExpandedSlots.getCurrentSlotAssignments(), + BaubleSlotConfiguration.getDefinitions()); stackList = new ItemStack[slotState.getAssignments().length]; pendingReturns.clear(); NBTTagList tagList = tags.getTagList("Baubles.Inventory", 10); @@ -500,8 +726,10 @@ public class InventoryBaubles implements IBaubleSlotInventory { if (itemstack != null) { if (slot >= 0 && slot < stackList.length && stackList[slot] == null && !BaubleExpandedSlots.unknownType.equals(getSlotType(slot)) - && saved.getType(slot).equals(getSlotType(slot))) { + && saved.getType(slot).equals(getSlotType(slot)) && matchesSlotType(slot, itemstack)) { stackList[slot] = itemstack; + int limit = getSlotDefinition(getSlotType(slot)).stackLimit(); + if (itemstack.stackSize > limit) pendingReturns.add(itemstack.splitStack(itemstack.stackSize - limit)); } else { pendingReturns.add(itemstack); } @@ -512,6 +740,7 @@ public class InventoryBaubles implements IBaubleSlotInventory { ItemStack stack = ItemStack.loadItemStackFromNBT(overflow.getCompoundTagAt(i)); if (stack != null) pendingReturns.add(stack); } + resetStackSnapshots(); } public void dropItems(ArrayList drops) { @@ -555,6 +784,8 @@ public class InventoryBaubles implements IBaubleSlotInventory { public void syncSlotToClients(int slot) { if (changingSlots) return; + if (previousStacks.length != stackList.length) previousStacks = Arrays.copyOf(previousStacks, stackList.length); + if (slot >= 0 && slot < previousStacks.length) previousStacks[slot] = ItemStack.copyItemStack(stackList[slot]); try { final EntityPlayer entityPlayer = this.player.get(); if (entityPlayer instanceof EntityPlayerMP playerMP && !entityPlayer.worldObj.isRemote) { diff --git a/src/main/java/baubles/common/container/SlotBauble.java b/src/main/java/baubles/common/container/SlotBauble.java index 233c4e3..25797cd 100644 --- a/src/main/java/baubles/common/container/SlotBauble.java +++ b/src/main/java/baubles/common/container/SlotBauble.java @@ -1,9 +1,10 @@ package baubles.common.container; import baubles.api.BaubleType; -import baubles.api.IBauble; import baubles.api.expanded.BaubleExpandedSlots; -import baubles.api.expanded.IBaubleExpanded; +import baubles.api.expanded.BaubleSlotType; +import baubles.api.expanded.BaubleSlotContext; +import baubles.common.BaubleSlotConfiguration; import baubles.common.Baubles; import baubles.common.BaublesConfig; import baubles.common.ItemDebugger; @@ -12,7 +13,6 @@ import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; -import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; @@ -40,36 +40,31 @@ public class SlotBauble extends Slot { return slotType; } + public InventoryBaubles getBaublesInventory() { + return inventory instanceof InventoryBaubles baubles ? baubles : null; + } + + public BaubleSlotType getSlotDefinition() { + InventoryBaubles baubles = getBaublesInventory(); + return baubles != null ? baubles.getSlotDefinition(slotType) + : BaubleSlotConfiguration.getDefinitions().getOrDefault(slotType, BaubleSlotType.defaults(slotType)); + } + + public boolean isCosmeticSlot() { + return false; + } + + public boolean isSlotActive() { + InventoryBaubles baubles = getBaublesInventory(); + return baubles == null || baubles.isSlotActive(getSlotIndex()); + } + /** * Check if the stack is a valid item for this slot. Always true beside for the armor slots. */ @Override public boolean isItemValid(ItemStack stack) { - if (stack == null || BaubleExpandedSlots.unknownType.equals(slotType)) { - return false; - } - - Item item = stack.getItem(); - if(!(item instanceof IBauble) || !((IBauble)item).canEquip(stack, ((InventoryBaubles)inventory).player.get())) { - return false; - } - - String[] types; - if(item instanceof IBaubleExpanded) { - types = ((IBaubleExpanded)item).getBaubleTypes(stack); - } else { - BaubleType legacyType = ((IBauble)item).getBaubleType(stack); - types = new String[] {BaubleExpandedSlots.getTypeFromBaubleType(legacyType)}; - } - - if (types == null) return false; - for(String type : types) { - if (BaublesConfig.canTypeFitSlot(type, slotType)) { - return true; - } - } - - return false; + return inventory.isItemValidForSlot(getSlotIndex(), stack); } @Override @@ -84,25 +79,22 @@ public class SlotBauble extends Slot { @Override public boolean canTakeStack(EntityPlayer player) { ItemStack itemStack = getStack(); - if (itemStack == null) { - return false; - } else if (itemStack.getItem() instanceof IBauble bauble) { - return bauble.canUnequip(itemStack, player); - } else { - // Consider the rare case of an item that used to be a Bauble, but has this property later removed (no - // longer implements IBauble). The player should still be able to take it out of the slot. - return true; - } + InventoryBaubles baubles = getBaublesInventory(); + BaubleSlotContext context = baubles != null ? baubles.getSlotContext(getSlotIndex(), isCosmeticSlot()) + : new BaubleSlotContext(player, slotType, getSlotIndex(), getSlotIndex(), false, true, true); + return itemStack != null && isSlotActive() + && BaubleLifecycle.canUnequip(itemStack, context); } @Override public int getSlotStackLimit() { - return BaublesConfig.getStackLimitForSlotType(slotType); + return getSlotDefinition().stackLimit(); } @Override @SideOnly(Side.CLIENT) public IIcon getBackgroundIconIndex() { + if (!getSlotDefinition().icon().isEmpty()) return null; if (!BaublesConfig.useOldGuiRendering && BaubleExpandedSlots.unknownType.equals(slotType)) { return null; } diff --git a/src/main/java/baubles/common/event/EventHandlerNetwork.java b/src/main/java/baubles/common/event/EventHandlerNetwork.java index 3e37f82..3ecd269 100644 --- a/src/main/java/baubles/common/event/EventHandlerNetwork.java +++ b/src/main/java/baubles/common/event/EventHandlerNetwork.java @@ -1,7 +1,5 @@ package baubles.common.event; -import baubles.api.IBauble; -import baubles.common.Baubles; import baubles.common.container.InventoryBaubles; import baubles.common.lib.PlayerHandler; import baubles.common.network.PacketHandler; @@ -13,7 +11,6 @@ import cpw.mods.fml.common.network.FMLNetworkEvent; import cpw.mods.fml.relauncher.Side; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.item.ItemStack; public class EventHandlerNetwork { @@ -24,13 +21,8 @@ public class EventHandlerNetwork { // Apply all baubles InventoryBaubles baubles = PlayerHandler.getPlayerBaubles(event.player); baubles.returnOverflowItems(); + baubles.onPlayerLoaded(); PacketHandler.INSTANCE.sendTo(new PacketSyncAllBauble(event.player), ((EntityPlayerMP) event.player)); - for (int i = 0; i < baubles.getSizeInventory(); i++) { - ItemStack stack = baubles.getStackInSlot(i); - if (stack != null && stack.getItem() instanceof IBauble itemBauble) { - itemBauble.onPlayerLoad(stack, event.player); - } - } } } @@ -53,16 +45,7 @@ public class EventHandlerNetwork { if (event.player instanceof EntityPlayerMP playerMP) { InventoryBaubles baubles = PlayerHandler.getPlayerBaubles(playerMP); baubles.returnOverflowItems(); - for (int slot = 0; slot < baubles.getSizeInventory(); slot++) { - ItemStack stack = baubles.getStackInSlot(slot); - if (stack != null && stack.getItem() instanceof IBauble item) { - try { - item.onPlayerLoad(stack, playerMP); - } catch (Exception e) { - Baubles.log.error("Error restoring bauble after respawn {}", stack, e); - } - } - } + baubles.onPlayerLoaded(); PacketHandler.sendToTracking(new PacketSyncAllBauble(playerMP), playerMP, true); } } diff --git a/src/main/java/baubles/common/network/BaubleSlotCodec.java b/src/main/java/baubles/common/network/BaubleSlotCodec.java index 046cb44..173406f 100644 --- a/src/main/java/baubles/common/network/BaubleSlotCodec.java +++ b/src/main/java/baubles/common/network/BaubleSlotCodec.java @@ -2,7 +2,9 @@ package baubles.common.network; import java.util.LinkedHashMap; import java.util.Map; +import java.util.BitSet; +import baubles.api.expanded.BaubleSlotType; import baubles.common.container.BaubleSlotState; import cpw.mods.fml.common.network.ByteBufUtils; import io.netty.buffer.ByteBuf; @@ -23,6 +25,22 @@ public class BaubleSlotCodec { buffer.writeInt(source.getValue()); } } + writePolicies(buffer, state); + } + + private static void writePolicies(ByteBuf buffer, BaubleSlotState state) { + ByteBufUtils.writeVarInt(buffer, state.getDefinitions().size(), 5); + for (BaubleSlotType type : state.getDefinitions().values()) { + ByteBufUtils.writeUTF8String(buffer, type.id()); + buffer.writeInt(type.order()); + ByteBufUtils.writeUTF8String(buffer, type.icon()); + buffer.writeByte((type.cosmetic() ? 1 : 0) | (type.renderToggle() ? 2 : 0) | (type.nativeGui() ? 4 : 0) + | (type.enabled() ? 8 : 0) | (type.fitsUniversal() ? 16 : 0)); + buffer.writeInt(type.stackLimit()); + } + int[] inactive = state.getInactiveSlots().stream().toArray(); + ByteBufUtils.writeVarInt(buffer, inactive.length, 5); + for (int slot : inactive) ByteBufUtils.writeVarInt(buffer, slot, 5); } public static BaubleSlotState readState(ByteBuf buffer) { @@ -42,7 +60,31 @@ public class BaubleSlotCodec { } if (modifiers.put(type, values) != null) throw new DecoderException("Duplicate slot type"); } - return new BaubleSlotState(assignments, modifiers); + Map definitions = new LinkedHashMap<>(); + int definitionCount = readSize(buffer, buffer.readableBytes()); + for (int i = 0; i < definitionCount; i++) { + String id = ByteBufUtils.readUTF8String(buffer); + int order = buffer.readInt(); + String icon = ByteBufUtils.readUTF8String(buffer); + int flags = buffer.readUnsignedByte(); + if ((flags & ~31) != 0) throw new DecoderException("Invalid slot policy flags"); + BaubleSlotType type = new BaubleSlotType(id, order, icon, (flags & 1) != 0, (flags & 2) != 0, + (flags & 4) != 0, (flags & 8) != 0, buffer.readInt(), (flags & 16) != 0); + if (definitions.put(id, type) != null) throw new DecoderException("Duplicate slot definition"); + } + for (String type : assignments) { + if (!definitions.containsKey(type)) throw new DecoderException("Missing slot definition: " + type); + } + BitSet inactive = new BitSet(); + int inactiveCount = readSize(buffer, size); + int previous = -1; + for (int i = 0; i < inactiveCount; i++) { + int slot = readSize(buffer, size - 1); + if (slot <= previous) throw new DecoderException("Unordered inactive slots"); + inactive.set(slot); + previous = slot; + } + return new BaubleSlotState(assignments, modifiers, definitions, inactive); } public static int readSize(ByteBuf buffer, int maximum) { diff --git a/src/main/java/baubles/common/network/PacketSyncBauble.java b/src/main/java/baubles/common/network/PacketSyncBauble.java index f16e954..7850b8e 100644 --- a/src/main/java/baubles/common/network/PacketSyncBauble.java +++ b/src/main/java/baubles/common/network/PacketSyncBauble.java @@ -59,7 +59,7 @@ public class PacketSyncBauble implements IMessage, IMessageHandler [amount] | reset [slot] +commands.baubles.usage=/baubles list [player] | set/add/remove [amount] | reset [slot] | reload | activate/deactivate [index] commands.baubles.changed=%s now has %s slots: %s commands.baubles.reset=Reset command slot modifiers for %s commands.baubles.invalid=Cannot change slots: %s commands.baubles.type=Unknown bauble slot type: %s commands.baubles.unavailable=Dynamic bauble slots are not available for this player +tooltip.baubles.inactive=Inactive slot +commands.baubles.reloaded=Reloaded bauble slot configuration +commands.baubles.active=Set %s %s slots active: %s diff --git a/src/main/resources/assets/baubles/lang/zh_CN.lang b/src/main/resources/assets/baubles/lang/zh_CN.lang index 4bf97df..8d9fd73 100644 --- a/src/main/resources/assets/baubles/lang/zh_CN.lang +++ b/src/main/resources/assets/baubles/lang/zh_CN.lang @@ -32,9 +32,12 @@ slot.shield=§a盾牌§7 slot.unknown=§a未知§7 slot.wings=§a翅膀§7 -commands.baubles.usage=/baubles list [玩家] | set/add/remove <槽位类型> <玩家> [数量] | reset <玩家> [槽位类型] +commands.baubles.usage=/baubles list [玩家] | set/add/remove <槽位类型> <玩家> [数量] | reset <玩家> [槽位类型] | reload | activate/deactivate [index] commands.baubles.changed=%s 的 %s 槽位数量现为 %s commands.baubles.reset=已重置 %s 的指令槽位修饰器 commands.baubles.invalid=无法修改槽位:%s commands.baubles.type=未知的饰品槽位类型:%s commands.baubles.unavailable=此玩家的饰品背包不支持动态槽位 +tooltip.baubles.inactive=已停用的槽位 +commands.baubles.reloaded=已重新加载饰品槽位配置 +commands.baubles.active=已设置 %s 的 %s 槽位启用状态为 %s