diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index e4de351..f302f32 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,7 +1,15 @@ -# Attaches the jars (one per Minecraft version: 26.2 and 26.3) to the GitHub release whenever a release is -# published. Modrinth and CurseForge aren't set up yet; Shopping List's publish.yml shows how to add them. +# Publishes the mod to CurseForge and attaches the jars (one per Minecraft version: 26.2 and 26.3) to the GitHub +# release whenever a release is published. The release notes become the changelog, and CurseForge rejects files +# without one, so don't leave them empty. Modrinth isn't set up yet; Shopping List's publish.yml shows how to add it. # # Runs as three chained jobs: check the tag -> build (reusing build.yml) -> publish. +# +# Setup: +# 1. Create the project on CurseForge and add its Project ID as a repo secret named CURSEFORGE_ID. +# 2. Create a CurseForge API token (account settings > API tokens) and add it as a repo secret named +# CURSEFORGE_TOKEN. +# 3. The 26.3 jar goes to CurseForge only once it has been tested in a 26.3 client: then add a repo variable +# (Settings > Secrets and variables > Actions > Variables) named PUBLISH_26_3 set to true. name: publish @@ -39,13 +47,63 @@ jobs: permissions: contents: write steps: + - name: checkout repository + uses: actions/checkout@v7 + - name: download built jars uses: actions/download-artifact@v8 with: name: Artifacts path: build/libs/ + - name: read mod version + id: ver + run: echo "v=$(grep '^mod_version=' gradle.properties | cut -d= -f2 | tr -d '[:space:]')" >> "$GITHUB_OUTPUT" + - name: attach jars to the release env: GH_TOKEN: ${{ github.token }} run: gh release upload "$GITHUB_REF_NAME" build/libs/huddable-*+26.2.jar build/libs/huddable-*+26.3.jar --clobber --repo "$GITHUB_REPOSITORY" + + - name: publish 26.2 to curseforge + uses: Kir-Antipov/mc-publish@v3.3 + with: + curseforge-id: ${{ secrets.CURSEFORGE_ID }} + curseforge-token: ${{ secrets.CURSEFORGE_TOKEN }} + + files: | + build/libs/huddable-${{ steps.ver.outputs.v }}+26.2.jar + + name: Huddable ${{ steps.ver.outputs.v }} for 26.2 + version: ${{ steps.ver.outputs.v }}+26.2 + version-type: ${{ github.event.release.prerelease && 'beta' || 'release' }} + loaders: fabric + game-versions: | + 26.2 + java: | + 25 + + dependencies: | + fabric-api(required){curseforge:306612} + + - name: publish 26.3 to curseforge + if: vars.PUBLISH_26_3 == 'true' + uses: Kir-Antipov/mc-publish@v3.3 + with: + curseforge-id: ${{ secrets.CURSEFORGE_ID }} + curseforge-token: ${{ secrets.CURSEFORGE_TOKEN }} + + files: | + build/libs/huddable-${{ steps.ver.outputs.v }}+26.3.jar + + name: Huddable ${{ steps.ver.outputs.v }} for 26.3 + version: ${{ steps.ver.outputs.v }}+26.3 + version-type: ${{ github.event.release.prerelease && 'beta' || 'release' }} + loaders: fabric + game-versions: | + 26.3 + java: | + 25 + + dependencies: | + fabric-api(required){curseforge:306612} diff --git a/Icon.png b/Icon.png new file mode 100644 index 0000000..5a49deb Binary files /dev/null and b/Icon.png differ diff --git a/ROADMAP.md b/ROADMAP.md index aa1df32..409daa1 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -39,6 +39,14 @@ in game. v1 is the base: wrapping and moving the vanilla elements. mixin (`mixin.meowdding`, applied only with meowdding-lib loaded) moves its draw call inside meowdding's overlay loop. General Settings has an Advanced toggle to turn it off. - 0.4.1: overlays switched off in their own mod aren't listed in the editor (they showed as empty boxes). +- 0.5.0: frames. A profile frame and per-element frames (or None): vanilla tooltip / popup / button art from the + top pack or a chosen enabled pack (`PackFrames`, shared with Shopping List), drawn around what each element draws + (framed vanilla elements and mod layers are measured four times a second), at screen size. API `frameInset` / + `drawFrame` for elements drawn from `placement` (Shopping List uses them); `push` draws the frame itself. +- 0.6.0: container screen art. The background picture of each vanilla container screen comes from a chosen enabled + pack, for all screens or per screen (`ContainerArtMixin` swaps the texture id in `GuiGraphicsExtractor.innerBlit`; + art loaded through `PackFrames.packTexture`). +- 0.6.1: closed chat can be framed, around the messages it shows (measured like other framed elements). ## Untested in game - The whole editor: dragging, snapping, scaling, the options panel, and the profile buttons. @@ -65,6 +73,13 @@ in game. v1 is the base: wrapping and moving the vanilla elements. the Advanced toggle off and on, and meowdding's own editor still working alongside. 0.4.1: an overlay switched off in SkyCubed leaves the list and comes back, at its saved position, when switched on. +- 0.5.0: frames in game: each kind from the top pack and from a lower pack (HD packs too), vanilla elements + appearing and disappearing (boss bar, title, effects) with their frame, Skyblocker layers and SkyCubed overlays + framed, Shopping List's panels taking the frame, share codes keeping frames, a disabled pack falling back. + +- 0.6.0: container art in game: the inventory and chests (SkyBlock menus) from a lower pack, HD packs lining up + with slots, a per-screen choice over All screens, a disabled pack falling back, share codes keeping it. + ## Next (ElvUI direction) - Shopping List on Huddable: register its five panels through the API (resizable), hand its Move HUD to Huddable's editor and ignore its `sandbox_widget` layer. Waiting for Huddable on Modrinth, so Shopping List's CI diff --git a/gradle.properties b/gradle.properties index 9aae0d5..d1175d8 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,6 +9,6 @@ loader_version=0.19.5 # Minecraft, Fabric API and Mod Menu versions are per Minecraft version, in versions//gradle.properties. # Mod Properties -mod_version=0.4.1 +mod_version=0.6.1 maven_group=uk.toakan.tad archives_base_name=huddable diff --git a/modrinth.md b/modrinth.md index 4a1f0e8..65ac107 100644 --- a/modrinth.md +++ b/modrinth.md @@ -11,6 +11,9 @@ Rearrange the vanilla HUD in game, no resource packs needed. - Restyle health, hunger, armor and air as bars or numbers, in your own colours - Put the scoreboard, chat, tab list and other HUD text in any font from your resource packs, per profile or per element, with a font quality setting +- Frame any element with your resource packs' tooltip, popup or button art, from the top pack or any enabled + pack, per profile or per element +- Pick which resource pack's inventory, chest and other container art you see, for all screens or one by one - Named layout profiles, shared as copy-paste codes - Client-side, works on any server diff --git a/readme.md b/readme.md index d0f41d5..9c9a479 100644 --- a/readme.md +++ b/readme.md @@ -28,8 +28,15 @@ whatever you're placing; it stays where you left it until the game closes. - **GUI** (default): follows Minecraft's GUI Scale, like vanilla. - **Window:** grows and shrinks with the window height. - **Fixed:** the same size on screen at any GUI Scale. + + With Window and Fixed, positions move with the size too, so the layout keeps its shape when the window or GUI + Scale changes. Switching mode in the editor keeps elements where they are and only changes their size. - **Font:** the profile's font, picked from every font your resource packs provide (each shown in itself). Every element that draws text uses it unless you give that element its own (see Fonts below). +- **Frame:** the profile's frame, drawn around every element unless you give that element its own or None (see + Frames below). +- **Screens:** which resource pack's art the inventory, chests and other container screens use (see Container + screens below). - **Move:** drag an element. It snaps to the screen edges and centre and to other elements' edges and centres (cyan guide lines); hold Shift to place it freely. - **Scale:** drag one of an element's gold corner handles (25% to 400%). The element keeps its shape. @@ -44,6 +51,7 @@ whatever you're placing; it stays where you left it until the game closes. - Colour (for the non-vanilla styles). - Bar width, height and text (Bar style). - Font, for elements that draw text: Profile (the profile's font), Vanilla, or any pack font. + - Frame: Profile (the profile's frame), None, or any frame from the list. - Reset element. - **Done** saves, **Cancel** or Esc drops your changes. @@ -89,6 +97,38 @@ and share codes keep the font for players who have the pack. Chat in a new font re-wraps its lines to fit. Toasts drawn by another mod (Fancy Notify, for example) keep that mod's font; vanilla's toasts change. +### Frames +A frame is Minecraft's own tooltip, popup or button art drawn around an element, so a resource pack that decorates +those (corner pieces, patterned edges) decorates your HUD too. The list has each kind from the top pack (what the +rest of the game shows), then from every enabled pack that has its own art, for example "Tooltip (Faithful 64x)". +To use one pack's frame without its other textures, enable it and move it to the bottom of the pack list. Pick a +frame for the whole profile with the toolbar's **Frame** button, or per element in its options; an element set to +None has no frame even when the profile has one. + +Frames follow what each element draws: a boss bar, title or other mod's layer that isn't showing has no frame, and +one that grows (the scoreboard, a mod's list) has its frame grow with it, checked four times a second for framed +elements only. Frame art is drawn at screen size, so frames match across elements of any scale. Closed chat is +framed around the messages showing, so its frame goes when they fade; the open chat (T) has none. Toasts and the +crosshair have no frame; full-screen mod layers get none either. If a frame's pack is turned off, the top +pack's art is drawn until it's back, and share codes keep the choice for players who have the pack. + +Shopping List's panels use a Huddable frame in place of their own when one is set for them (it keeps its own look +otherwise). Other mods can do the same through the API (`frameInset`, `drawFrame`). + +### Container screens +Each container screen (inventory, chest, furnace, anvil and the rest) is one picture with the slots painted in, +and normally the top resource pack's picture is shown. The toolbar's **Screens** list picks another enabled pack's +picture instead: **All screens** for every screen, then a row for each screen that more than one of your packs +has art for, to give it its own choice (Profile follows All screens). Click a row for the next pack. For example, +keep a texture pack on top but use Faithful's inventory. Open a screen after Done to see it. + +- Server menus such as Hypixel's are chests, so they follow the Chest choice. +- Only the background picture changes. Small pieces drawn over it (the furnace's flame and arrow, the recipe book + button) still come from the top pack. +- Art drawn by other mods (tabs and side panels around the inventory) isn't changed. +- A screen the chosen pack has no art for, or a pack you've turned off, shows the top pack's picture. Share codes + keep the choice. + ### Styles - **Bar:** a filled bar with the value written on it. Health shows absorption and hunger shows saturation as a thin strip along the top. @@ -117,7 +157,8 @@ The top button in the editor's window shows the active profile; click it to swit - **Delete:** press twice. - **Export:** copies the layout to the clipboard as a code starting `HUD1:`. - **Import:** reads a code from the clipboard into a new profile. -- **Reset:** puts every element, the Size mode and the profile font back to vanilla. +- **Reset:** puts every element, the Size mode, the profile font and frame, and the container screens back to + vanilla. Profile actions save your current edits first. Profiles are in `config/huddable/profiles/`. @@ -151,7 +192,8 @@ public final class HuddableCompat implements HuddablePlugin { HuddableApi.register(PANEL, Component.literal("Example panel"), HuddableApi.Spec.of((screenWidth, screenHeight) -> new HuddableApi.Box(10, 10, 120, 40)) .withBaseScale(() -> MyHud.scale()) // optional: your own HUD scale - .resizable(60, 20)); // optional: edge grips, with a minimum size + .resizable(60, 20) // optional: edge grips, with a minimum size + .listedWhen(() -> MyHud.enabled())); // optional: left out of the editor while switched off // If the element is also a Fabric HUD layer, keep Huddable from wrapping that layer as well: // HuddableApi.ignoreLayer(MY_FABRIC_LAYER_ID); } diff --git a/src/main/java/uk/toakan/tad/huddable/Element.java b/src/main/java/uk/toakan/tad/huddable/Element.java index 5158243..ef81014 100644 --- a/src/main/java/uk/toakan/tad/huddable/Element.java +++ b/src/main/java/uk/toakan/tad/huddable/Element.java @@ -96,6 +96,12 @@ public boolean restyleable() { return restyleable; } + /** Toasts aren't drawn through {@link HudWrapper}; a frame on a crosshair is no use. Chat is framed while closed. */ + @Override + public boolean frameable() { + return this != TOASTS && this != CROSSHAIR; + } + /** Chat sizes itself to vanilla's chat width and height options; a Bar-style status bar to its bar size. */ @Override public boolean resizable(ElementLayout layout) { diff --git a/src/main/java/uk/toakan/tad/huddable/ElementLayout.java b/src/main/java/uk/toakan/tad/huddable/ElementLayout.java index 3418a14..b7ce3fa 100644 --- a/src/main/java/uk/toakan/tad/huddable/ElementLayout.java +++ b/src/main/java/uk/toakan/tad/huddable/ElementLayout.java @@ -34,6 +34,8 @@ public final class ElementLayout { * or null for the profile's font ({@link HudFonts}). */ public String font; + /** Frame id ({@link HudFrames}), {@code none} for no frame even when the profile has one, or null for the profile's. */ + public String frame; public ElementLayout copy() { ElementLayout c = new ElementLayout(); @@ -49,26 +51,29 @@ public ElementLayout copy() { c.width = width; c.height = height; c.font = font; + c.frame = frame; return c; } - /** True when this draws exactly like vanilla, so it needn't be saved. */ + /** True when this draws exactly like vanilla (or as the profile says), so it needn't be saved. */ public boolean isDefault() { return !hidden && dx == 0 && dy == 0 && scale == 100 && style == Style.VANILLA && width == 0 && height == 0 - && font == null; + && font == null && frame == null; } - /** Puts every field in range; a style or font the element can't use falls back to vanilla. */ + /** Puts every field in range; a style, font or frame the element can't use falls back to vanilla. */ public void clamp(HudPart part) { clamp(part.restyleable(), part.movable()); if (!HudFonts.fontable(part)) font = null; + if (!part.frameable()) frame = null; } /** As {@link #clamp(HudPart)}, for another mod's element that isn't loaded now (kept, not restyleable). */ public void clamp(boolean restyleable, boolean movable) { // An id that isn't loaded now is kept (a share code from someone with another pack); it draws as vanilla. font = HudFonts.cleanId(font); - scale = Math.clamp(scale, MIN_SCALE, MAX_SCALE); + frame = HudFrames.cleanId(frame); + scale =Math.clamp(scale, MIN_SCALE, MAX_SCALE); barWidth = Math.clamp(barWidth, MIN_BAR_WIDTH, MAX_BAR_WIDTH); barHeight = Math.clamp(barHeight, MIN_BAR_HEIGHT, MAX_BAR_HEIGHT); // Far enough to leave any screen, small enough that the maths can't overflow. diff --git a/src/main/java/uk/toakan/tad/huddable/ExternalPart.java b/src/main/java/uk/toakan/tad/huddable/ExternalPart.java index f63a73e..a00c81d 100644 --- a/src/main/java/uk/toakan/tad/huddable/ExternalPart.java +++ b/src/main/java/uk/toakan/tad/huddable/ExternalPart.java @@ -26,6 +26,8 @@ public final class ExternalPart implements HudPart { /** How often an element that drew nothing is measured again, while it matters. */ private static final long RETRY_MILLIS = 1000; + /** How often a framed layer is measured, so its frame follows what it draws. */ + static final long FRAME_MILLIS = 250; public final Identifier id; private final Component label; @@ -38,6 +40,8 @@ public final class ExternalPart implements HudPart { private int measuredWidth = -1; private int measuredHeight = -1; private long lastMeasure; + /** Fabric layers only: whether the last measure found anything drawn (the frame is left off while not). */ + private boolean drawing; /** Listed in the editor only while true: false while the element's own mod has it switched off. */ private BooleanSupplier listed = () -> true; @@ -145,36 +149,47 @@ public HuddableApi.Placement placement(int w, int h) { Minecraft mc = Minecraft.getInstance(); Geometry g = geometry(mc, w, h); int[] size = size(mc, g, layout); - return new HuddableApi.Placement(g.x() + layout.dx, g.y() + layout.dy, size[0], size[1], + float offsetScale = HudWrapper.offsetScale(); + return new HuddableApi.Placement(g.x() + Math.round(layout.dx * offsetScale), + g.y() + Math.round(layout.dy * offsetScale), size[0], size[1], HudWrapper.scale(this, layout), layout.hidden); } /** * Fabric layers: measures the box when the screen size changed, when nothing was found yet and it matters - * ({@code wanted}), and once a second while the editor is open (the element may have grown or moved). + * ({@code wanted}), once a second while the editor is open (the element may have grown or moved), and four + * times a second while it has a frame ({@code framed}), so the frame follows it. */ - void measureIfNeeded(GuiGraphicsExtractor graphics, DeltaTracker delta, boolean wanted) { + void measureIfNeeded(GuiGraphicsExtractor graphics, DeltaTracker delta, boolean wanted, boolean framed) { int w = graphics.guiWidth(); int h = graphics.guiHeight(); long now = Util.getMillis(); boolean resized = measured != null && (w != measuredWidth || h != measuredHeight); - boolean retry = (measured == null && wanted || Profiles.editing()) && now - lastMeasure >= RETRY_MILLIS; + long since = now - lastMeasure; + boolean retry = (measured == null && wanted || Profiles.editing()) && since >= RETRY_MILLIS + || framed && since >= FRAME_MILLIS; if (!resized && !retry) return; lastMeasure = now; measuredWidth = w; measuredHeight = h; - HuddableApi.Box box = measure(delta); + HuddableApi.Box box = measure(original, delta, id); + drawing = box != null; if (box != null || resized) measured = box; } - /** Draws the layer, unmoved, into a scratch render state and returns the bounds of what it drew. */ - private HuddableApi.Box measure(DeltaTracker delta) { + /** Fabric layers: the unmoved box it drew at the last measure, or null when it drew nothing then. */ + HuddableApi.Box drawnBox() { + return drawing ? measured : null; + } + + /** Draws {@code layer}, unmoved, into a scratch render state and returns the bounds of what it drew. */ + static HuddableApi.Box measure(HudElement layer, DeltaTracker delta, Object name) { Minecraft mc = Minecraft.getInstance(); GuiRenderState state = new GuiRenderState(); try { - original.extractRenderState(new GuiGraphicsExtractor(mc, state, -1, -1), delta); + layer.extractRenderState(new GuiGraphicsExtractor(mc, state, -1, -1), delta); } catch (RuntimeException e) { - HuddableClient.LOGGER.warn("Couldn't measure HUD element {}", id, e); + HuddableClient.LOGGER.warn("Couldn't measure HUD element {}", name, e); return null; } int[] b = {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE}; diff --git a/src/main/java/uk/toakan/tad/huddable/HudFrames.java b/src/main/java/uk/toakan/tad/huddable/HudFrames.java new file mode 100644 index 0000000..d0cc99a --- /dev/null +++ b/src/main/java/uk/toakan/tad/huddable/HudFrames.java @@ -0,0 +1,129 @@ +package uk.toakan.tad.huddable; + +import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.minecraft.client.resources.language.I18n; +import org.joml.Matrix3x2fStack; +import org.joml.Vector2f; + +import java.util.ArrayList; +import java.util.List; + +/** + * Frames drawn around HUD elements: vanilla's tooltip, popup or button art, from the top resource pack or a chosen + * one ({@link PackFrames}). A frame id is {@code kind} (the top pack's art) or {@code kind@packId}. The profile has + * one frame for every element ({@link Layout#frame}); an element may have its own or {@link #NONE}. An id whose pack + * isn't enabled draws from the top pack and is kept, so a share code still works for someone who has the pack. + * Frame art is drawn at screen size, not scaled with the element, so every frame on the HUD matches. + */ +public final class HudFrames { + private HudFrames() {} + + /** An element's choice of no frame, even when the profile has one. */ + public static final String NONE = "none"; + private static final int MAX_ID_LENGTH = 256; + + /** A frame: its kind and the pack its art comes from ("" = the top pack). */ + public record Choice(PackFrames.Kind kind, String pack) {} + + /** Every frame id the packs offer, listed once per resource reload (the editor rebuilds on every drag). */ + private static List available; + + /** {@code id} as a clean frame id ({@link #NONE} included), or null when it isn't one. */ + public static String cleanId(String id) { + if (id == null || id.isBlank() || id.length() > MAX_ID_LENGTH) return null; + String trimmed = id.trim(); + if (NONE.equals(trimmed)) return NONE; + return parse(trimmed) != null ? trimmed : null; + } + + /** The frame {@code id} names, or null ({@link #NONE} and unknown kinds). */ + public static Choice parse(String id) { + if (id == null) return null; + int at = id.indexOf('@'); + PackFrames.Kind kind = PackFrames.Kind.byId(at < 0 ? id : id.substring(0, at)); + if (kind == null) return null; + return new Choice(kind, at < 0 ? "" : id.substring(at + 1)); + } + + public static String id(PackFrames.Kind kind, String pack) { + return pack.isEmpty() ? kind.id : kind.id + "@" + pack; + } + + /** The frame {@code part} is drawn with in {@code layout}: its own, else the profile's; null for none. */ + public static Choice resolve(HudPart part, Layout layout) { + if (!part.frameable()) return null; + String id = layout.get(part).frame; + if (id == null) id = layout.frame; + return NONE.equals(id) ? null : parse(id); + } + + /** Each kind from the top pack, then from every enabled pack that has art for it. */ + public static List available() { + if (available == null) { + List ids = new ArrayList<>(); + for (PackFrames.Kind kind : PackFrames.Kind.values()) { + ids.add(kind.id); + for (String pack : PackFrames.packsWith(kind)) ids.add(id(kind, pack)); + } + available = List.copyOf(ids); + } + return available; + } + + /** A frame's name for the editor: "Tooltip (Faithful 64x)". */ + public static String name(String id) { + Choice choice = parse(id); + if (choice == null) return id; + String kind = I18n.get(switch (choice.kind()) { + case TOOLTIP -> "huddable.frame.tooltip"; + case POPUP -> "huddable.frame.popup"; + case BUTTON -> "huddable.frame.button"; + }); + String pack = choice.pack().isEmpty() ? I18n.get("huddable.frame.top_pack") : PackFrames.title(choice.pack()); + return I18n.get("huddable.frame.name", kind, pack); + } + + /** True when {@code id}'s art comes from a pack that isn't enabled now (it draws from the top pack). */ + public static boolean packOff(String id) { + Choice choice = parse(id); + return choice != null && !choice.pack().isEmpty() && !PackFrames.enabled(choice.pack()); + } + + /** Resource packs changed: which frames exist, and their art. */ + public static void reloaded() { + available = null; + PackFrames.reloaded(); + } + + /** + * Draws {@code choice} around an element's box (given in the current pose), far enough out that the element sits + * inside the edge art. Full-screen layers get none. + */ + public static void drawAround(GuiGraphicsExtractor graphics, Choice choice, float x, float y, float w, float h) { + draw(graphics, choice, x, y, w, h, choice.kind().inset, true); + } + + /** Draws {@code choice} over the box (given in the current pose): for API elements that keep their content inside. */ + public static void drawOver(GuiGraphicsExtractor graphics, Choice choice, float x, float y, float w, float h) { + draw(graphics, choice, x, y, w, h, 0, false); + } + + private static void draw(GuiGraphicsExtractor graphics, Choice choice, float x, float y, float w, float h, + int outset, boolean skipFullScreen) { + Matrix3x2fStack pose = graphics.pose(); + Vector2f a = pose.transformPosition(x, y, new Vector2f()); + Vector2f b = pose.transformPosition(x + w, y + h, new Vector2f()); + int left = Math.round(Math.min(a.x, b.x)) - outset; + int top = Math.round(Math.min(a.y, b.y)) - outset; + int right = Math.round(Math.max(a.x, b.x)) + outset; + int bottom = Math.round(Math.max(a.y, b.y)) + outset; + if (right <= left || bottom <= top) return; + if (skipFullScreen && right - left >= graphics.guiWidth() * 3 / 4 && bottom - top >= graphics.guiHeight() * 3 / 4) { + return; + } + pose.pushMatrix(); + pose.identity(); + PackFrames.drawFrame(graphics, choice.kind(), choice.pack(), left, top, right - left, bottom - top); + pose.popMatrix(); + } +} diff --git a/src/main/java/uk/toakan/tad/huddable/HudPart.java b/src/main/java/uk/toakan/tad/huddable/HudPart.java index 06653e1..de54ff7 100644 --- a/src/main/java/uk/toakan/tad/huddable/HudPart.java +++ b/src/main/java/uk/toakan/tad/huddable/HudPart.java @@ -20,6 +20,11 @@ record Geometry(int anchorX, int anchorY, int x, int y, int width, int height) { /** True for the status bars, which have {@link Style}s besides vanilla. */ boolean restyleable(); + /** True when a frame can be drawn around this element ({@link HudFrames}). */ + default boolean frameable() { + return true; + } + /** Where the element draws now, for a screen of {@code w} x {@code h} GUI pixels. */ Geometry geometry(Minecraft mc, int w, int h); diff --git a/src/main/java/uk/toakan/tad/huddable/HudScreenArt.java b/src/main/java/uk/toakan/tad/huddable/HudScreenArt.java new file mode 100644 index 0000000..f2e4e78 --- /dev/null +++ b/src/main/java/uk/toakan/tad/huddable/HudScreenArt.java @@ -0,0 +1,123 @@ +package uk.toakan.tad.huddable; + +import net.minecraft.client.resources.language.I18n; +import net.minecraft.resources.Identifier; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Container screens (inventory, chests, furnaces...) drawn with a chosen resource pack's background picture instead + * of the top pack's. Each screen's background is one fixed PNG with the slots painted in, so another pack's copy + * lines up the same. The profile has one pack for every screen ({@link Layout#screenArt}); a screen may have its own + * ({@link Layout#screenArtFor}, {@link #TOP} = the top pack's). A pack that isn't enabled, or hasn't got that + * screen, leaves the top pack's picture. Swapped in {@code ContainerArtMixin}; the art comes from {@link PackFrames}. + */ +public final class HudScreenArt { + private HudScreenArt() {} + + /** A screen's choice of the top pack's picture, even when the profile picks a pack. */ + public static final String TOP = "top"; + private static final String PREFIX = "textures/gui/container/"; + private static final String SUFFIX = ".png"; + private static final int MAX_ID_LENGTH = 256; + + /** Vanilla's container backgrounds (26.2 and 26.3), by the name saved in profiles. */ + public static final List SCREENS = List.of("inventory", "generic_54", "shulker_box", "crafting_table", + "furnace", "blast_furnace", "smoker", "dispenser", "hopper", "crafter", "brewing_stand", "enchanting_table", + "anvil", "grindstone", "smithing", "stonecutter", "loom", "cartography_table", "beacon", "villager", "horse", + "nautilus"); + + /** Per screen, the enabled packs that have its picture (top first); listed once per resource reload. */ + private static Map> packs; + + public static Identifier file(String screen) { + return Identifier.withDefaultNamespace(PREFIX + screen + SUFFIX); + } + + /** The texture to draw in place of {@code location} in the current layout; {@code location} when unchanged. */ + public static Identifier swap(Identifier location) { + Layout layout = Profiles.current(); + if (layout.screenArt == null && layout.screenArtFor.isEmpty()) return location; + if (!location.getNamespace().equals(Identifier.DEFAULT_NAMESPACE)) return location; + String path = location.getPath(); + if (!path.startsWith(PREFIX) || !path.endsWith(SUFFIX)) return location; + String pack = pack(layout, path.substring(PREFIX.length(), path.length() - SUFFIX.length())); + return pack == null ? location : PackFrames.packTexture(location, pack); + } + + /** The pack {@code screen} is drawn from in {@code layout}; null = the top pack's. */ + public static String pack(Layout layout, String screen) { + String own = layout.screenArtFor.get(screen); + String pack = own != null ? own : layout.screenArt; + return TOP.equals(pack) ? null : pack; + } + + /** The enabled packs that have {@code screen}'s picture, top first. */ + public static List packsWith(String screen) { + return packs().getOrDefault(screen, List.of()); + } + + /** The enabled packs that have any screen's picture, top first. */ + public static List packsWithAny() { + List files = new ArrayList<>(); + for (String screen : SCREENS) files.add(file(screen)); + return PackFrames.packsWithFiles(files); + } + + private static Map> packs() { + if (packs == null) { + Map> found = new LinkedHashMap<>(); + for (String screen : SCREENS) found.put(screen, PackFrames.packsWithFiles(List.of(file(screen)))); + packs = found; + } + return packs; + } + + /** A pack choice as the editor shows it: null and {@link #TOP} are the top pack. */ + public static String packName(String pack) { + return pack == null || TOP.equals(pack) ? I18n.get("huddable.screens.top_pack") : PackFrames.title(pack); + } + + /** {@code pack} as a clean pack choice ({@link #TOP} included), or null. */ + public static String cleanPack(String pack) { + if (pack == null || pack.isBlank() || pack.length() > MAX_ID_LENGTH) return null; + return pack.trim(); + } + + /** A screen's name for the editor. */ + public static String name(String screen) { + return I18n.get(switch (screen) { + case "inventory" -> "huddable.screen.inventory"; + case "generic_54" -> "huddable.screen.generic_54"; + case "shulker_box" -> "huddable.screen.shulker_box"; + case "crafting_table" -> "huddable.screen.crafting_table"; + case "furnace" -> "huddable.screen.furnace"; + case "blast_furnace" -> "huddable.screen.blast_furnace"; + case "smoker" -> "huddable.screen.smoker"; + case "dispenser" -> "huddable.screen.dispenser"; + case "hopper" -> "huddable.screen.hopper"; + case "crafter" -> "huddable.screen.crafter"; + case "brewing_stand" -> "huddable.screen.brewing_stand"; + case "enchanting_table" -> "huddable.screen.enchanting_table"; + case "anvil" -> "huddable.screen.anvil"; + case "grindstone" -> "huddable.screen.grindstone"; + case "smithing" -> "huddable.screen.smithing"; + case "stonecutter" -> "huddable.screen.stonecutter"; + case "loom" -> "huddable.screen.loom"; + case "cartography_table" -> "huddable.screen.cartography_table"; + case "beacon" -> "huddable.screen.beacon"; + case "villager" -> "huddable.screen.villager"; + case "horse" -> "huddable.screen.horse"; + case "nautilus" -> "huddable.screen.nautilus"; + default -> screen; + }); + } + + /** Resource packs changed: which packs have which screens. The art itself is dropped by {@link HudFrames}. */ + public static void reloaded() { + packs = null; + } +} diff --git a/src/main/java/uk/toakan/tad/huddable/HudWrapper.java b/src/main/java/uk/toakan/tad/huddable/HudWrapper.java index a7af3e2..528627f 100644 --- a/src/main/java/uk/toakan/tad/huddable/HudWrapper.java +++ b/src/main/java/uk/toakan/tad/huddable/HudWrapper.java @@ -6,9 +6,14 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.minecraft.util.Util; import net.minecraft.world.entity.player.Player; import org.joml.Matrix3x2f; import org.joml.Matrix3x2fStack; +import uk.toakan.tad.huddable.api.HuddableApi; + +import java.util.EnumMap; +import java.util.Map; /** * Wraps every {@link Element} through Fabric's {@link HudElementRegistry#replaceElement}, so vanilla (and any mod @@ -37,7 +42,13 @@ private static void render(Element element, HudElement original, GuiGraphicsExtr float scale = scale(element, layout); // Chat's font goes into its line styles instead (ChatComponentMixin). Font font = element == Element.CHAT ? null : HudFonts.wrapped(element, Profiles.current()); - if (element == Element.CHAT || layout.isDefault() && scale == 1f && font == null) { + HudFrames.Choice frame = HudFrames.resolve(element, Profiles.current()); + if (element == Element.CHAT || layout.isDefault() && scale == 1f && font == null && frame == null) { + if (element == Element.CHAT && frame != null) { + // Measured with ChatComponentMixin's move already applied, so the box is where chat draws now. + HuddableApi.Box drawn = drawnBox(element, original, delta, null); + if (drawn != null) HudFrames.drawAround(graphics, frame, drawn.x(), drawn.y(), drawn.width(), drawn.height()); + } original.extractRenderState(graphics, delta); return; } @@ -47,16 +58,45 @@ private static void render(Element element, HudElement original, GuiGraphicsExtr pose.pushMatrix(); transform(pose, anchor[0], anchor[1], layout, scale); if (layout.style == Style.VANILLA) { + if (frame != null) { + // Around what vanilla draws now (a boss bar or title may be gone, a scoreboard may have grown). + HuddableApi.Box drawn = drawnBox(element, original, delta, font); + if (drawn != null) HudFrames.drawAround(graphics, frame, drawn.x(), drawn.y(), drawn.width(), drawn.height()); + } drawInFont(font, () -> original.extractRenderState(graphics, delta)); } else if (mc.getCameraEntity() instanceof Player player) { BarRenderers.Reading reading = BarRenderers.read(element, player); if (reading != null) { - BarRenderers.draw(graphics, font != null ? font : mc.font, element, layout, anchor[0], anchor[1], reading); + Font barFont = font != null ? font : mc.font; + if (frame != null) { + int[] size = BarRenderers.size(element, layout, barFont, reading); + int x = element.rightAligned ? anchor[0] - size[0] : anchor[0]; + HudFrames.drawAround(graphics, frame, x, anchor[1] - size[1], size[0], size[1]); + } + BarRenderers.draw(graphics, barFont, element, layout, anchor[0], anchor[1], reading); } } pose.popMatrix(); } + /** A framed vanilla element's last measured box: unmoved, null while it draws nothing. */ + private record Drawn(HuddableApi.Box box, long at) {} + + private static final Map DRAWN = new EnumMap<>(Element.class); + + /** Where a framed vanilla element drew, measured at most four times a second (it is drawn once more to find out). */ + private static HuddableApi.Box drawnBox(Element element, HudElement original, DeltaTracker delta, Font font) { + long now = Util.getMillis(); + Drawn last = DRAWN.get(element); + if (last == null || now - last.at() >= ExternalPart.FRAME_MILLIS) { + HuddableApi.Box[] box = new HuddableApi.Box[1]; + drawInFont(font, () -> box[0] = ExternalPart.measure(original, delta, element)); + last = new Drawn(box[0], now); + DRAWN.put(element, last); + } + return last.box(); + } + /** Runs vanilla's drawing with {@code font} (null = vanilla's) in place of the game font ({@code HudFontMixin}). */ public static void drawInFont(Font font, Runnable draw) { if (font == null) { @@ -74,10 +114,13 @@ public static void drawInFont(Font font, Runnable draw) { /** Another mod's Fabric HUD layer ({@link HudDiscovery}): moved and scaled around its measured anchor. */ static void renderExternal(ExternalPart part, HudElement original, GuiGraphicsExtractor graphics, DeltaTracker delta) { ElementLayout layout = Profiles.current().get(part); - part.measureIfNeeded(graphics, delta, !layout.isDefault()); + HudFrames.Choice frame = layout.hidden ? null : HudFrames.resolve(part, Profiles.current()); + part.measureIfNeeded(graphics, delta, !layout.isDefault(), frame != null); if (layout.hidden) return; float scale = scale(part, layout); + HuddableApi.Box drawn = frame != null ? part.drawnBox() : null; if (layout.dx == 0 && layout.dy == 0 && scale == 1f) { + if (drawn != null) HudFrames.drawAround(graphics, frame, drawn.x(), drawn.y(), drawn.width(), drawn.height()); original.extractRenderState(graphics, delta); return; } @@ -85,6 +128,7 @@ static void renderExternal(ExternalPart part, HudElement original, GuiGraphicsEx Matrix3x2fStack pose = graphics.pose(); pose.pushMatrix(); transform(pose, anchor[0], anchor[1], layout, scale); + if (drawn != null) HudFrames.drawAround(graphics, frame, drawn.x(), drawn.y(), drawn.width(), drawn.height()); original.extractRenderState(graphics, delta); pose.popMatrix(); } @@ -94,9 +138,20 @@ public static float scale(HudPart part, ElementLayout layout) { return part.baseScale() * layout.scaleFactor() * Profiles.current().sizing.factor(); } + /** + * What offsets are multiplied by: Window and Fixed sizing move elements as well as sizing them, so a layout + * keeps its shape when the window or GUI Scale changes. + */ + public static float offsetScale() { + Layout layout = Profiles.current(); + if (layout.offsetFactor <= 0) Profiles.recordOffsetFactor(layout); + return layout.offsetScale(layout.sizing.factor()); + } + /** Moves the anchor by the layout's offset and scales around it. */ public static void transform(Matrix3x2f pose, int anchorX, int anchorY, ElementLayout layout, float scale) { - pose.translate(anchorX + layout.dx, anchorY + layout.dy); + float offsetScale = offsetScale(); + pose.translate(anchorX + layout.dx * offsetScale, anchorY + layout.dy * offsetScale); pose.scale(scale, scale); pose.translate(-anchorX, -anchorY); } @@ -121,8 +176,9 @@ public static Box box(HudPart part, ElementLayout layout, Minecraft mc, int w, i height = size[1]; } float scale = scale(part, layout); - int left = Math.round(g.anchorX() + layout.dx + (x - g.anchorX()) * scale); - int top = Math.round(g.anchorY() + layout.dy + (y - g.anchorY()) * scale); + float offsetScale = offsetScale(); + int left = Math.round(g.anchorX() + layout.dx * offsetScale + (x - g.anchorX()) * scale); + int top = Math.round(g.anchorY() + layout.dy * offsetScale + (y - g.anchorY()) * scale); return new Box(left, top, Math.max(1, Math.round(width * scale)), Math.max(1, Math.round(height * scale))); } } diff --git a/src/main/java/uk/toakan/tad/huddable/HuddableClient.java b/src/main/java/uk/toakan/tad/huddable/HuddableClient.java index 775f517..7639186 100644 --- a/src/main/java/uk/toakan/tad/huddable/HuddableClient.java +++ b/src/main/java/uk/toakan/tad/huddable/HuddableClient.java @@ -59,5 +59,11 @@ public void onInitializeClient() { ResourceLoader resources = ResourceLoader.get(PackType.CLIENT_RESOURCES); resources.registerReloadListener(fontsReloaded, (ResourceManagerReloadListener) manager -> HudFonts.reloaded()); resources.addListenerOrdering(ResourceReloaderKeys.Client.FONTS, fontsReloaded); + // Which packs have frame and container art, and the art read from them, may change too. + resources.registerReloadListener(Identifier.fromNamespaceAndPath(MOD_ID, "hud_frames"), + (ResourceManagerReloadListener) manager -> { + HudFrames.reloaded(); + HudScreenArt.reloaded(); + }); } } diff --git a/src/main/java/uk/toakan/tad/huddable/Layout.java b/src/main/java/uk/toakan/tad/huddable/Layout.java index 982e360..d7e3e94 100644 --- a/src/main/java/uk/toakan/tad/huddable/Layout.java +++ b/src/main/java/uk/toakan/tad/huddable/Layout.java @@ -8,7 +8,8 @@ /** * A whole HUD layout: one {@link ElementLayout} per changed element, keyed by {@link HudPart#key()} (the enum name - * for vanilla elements, {@code mod:path} for other mods'), plus the screen scale and the profile font. Elements + * for vanilla elements, {@code mod:path} for other mods'), plus the screen scale, the profile font and frame, and + * which pack container screens are drawn from. Elements * left out draw as vanilla. Gson POJO, saved as one profile file and packed into share codes. */ public final class Layout { @@ -21,8 +22,19 @@ public final class Layout { public Map elements = new LinkedHashMap<>(); public Sizing sizing = Sizing.GUI_SCALE; + /** + * The {@link Sizing#factor()} the offsets were placed at, so they grow and shrink with the elements when the + * window or GUI Scale changes; 0 = not recorded yet (files and codes from before), taken on the first frame. + */ + public float offsetFactor; /** The profile's font for every element that has no font of its own; null = vanilla's ({@link HudFonts}). */ public String font; + /** The profile's frame for every element that has no frame choice of its own; null = none ({@link HudFrames}). */ + public String frame; + /** The pack every container screen's picture comes from; null = the top pack's ({@link HudScreenArt}). */ + public String screenArt; + /** Per container screen ({@link HudScreenArt#SCREENS}), its own pack or {@link HudScreenArt#TOP}. */ + public Map screenArtFor = new LinkedHashMap<>(); /** The element's layout, or a shared vanilla one when it has none; don't change what this returns. */ public ElementLayout get(HudPart part) { @@ -60,10 +72,34 @@ public Layout copy() { Layout c = new Layout(); elements.forEach((k, v) -> c.elements.put(k, v.copy())); c.sizing = sizing; + c.offsetFactor = offsetFactor; c.font = font; + c.frame = frame; + c.screenArt = screenArt; + c.screenArtFor.putAll(screenArtFor); return c; } + /** What the saved offsets are multiplied by at sizing factor {@code current}. */ + public float offsetScale(float current) { + return offsetFactor > 0 ? current / offsetFactor : 1f; + } + + /** + * Rewrites the offsets as placed at sizing factor {@code current}, keeping where they draw, so the editor can + * work in plain GUI pixels. + */ + public void rebaseOffsets(float current) { + float ratio = offsetScale(current); + if (ratio != 1f) { + for (ElementLayout l : elements.values()) { + l.dx = Math.round(l.dx * ratio); + l.dy = Math.round(l.dy * ratio); + } + } + offsetFactor = current; + } + /** * Makes a loaded or imported layout safe to draw: unknown vanilla element names and vanilla-looking entries * are dropped, and every value is put in range. Other mods' entries ({@code mod:path}) are kept even when @@ -72,8 +108,21 @@ public Layout copy() { public Layout clamp() { if (elements == null) elements = new LinkedHashMap<>(); if (sizing == null) sizing = Sizing.GUI_SCALE; + if (!(offsetFactor >= 0.05f && offsetFactor <= 20f)) offsetFactor = 0; font = HudFonts.cleanId(font); if (HudFonts.DEFAULT_FONT.equals(font)) font = null; + frame = HudFrames.cleanId(frame); + if (HudFrames.NONE.equals(frame)) frame = null; + screenArt = HudScreenArt.cleanPack(screenArt); + if (HudScreenArt.TOP.equals(screenArt)) screenArt = null; + Map screens = new LinkedHashMap<>(); + if (screenArtFor != null) { + for (String screen : HudScreenArt.SCREENS) { + String pack = HudScreenArt.cleanPack(screenArtFor.get(screen)); + if (pack != null) screens.put(screen, pack); + } + } + screenArtFor = screens; Map kept = new LinkedHashMap<>(); for (Element element : Element.values()) { ElementLayout l = elements.get(element.name()); diff --git a/src/main/java/uk/toakan/tad/huddable/LayoutEditorScreen.java b/src/main/java/uk/toakan/tad/huddable/LayoutEditorScreen.java index 62b1d52..679c09a 100644 --- a/src/main/java/uk/toakan/tad/huddable/LayoutEditorScreen.java +++ b/src/main/java/uk/toakan/tad/huddable/LayoutEditorScreen.java @@ -40,7 +40,7 @@ public class LayoutEditorScreen extends Screen { private static final int TOOLBAR_WIDTH = 72; /** Title strip at the top of the controls; drag it to move them. */ private static final int GRIP = 12; - private static final int TOOLBAR_BUTTONS = 12; + private static final int TOOLBAR_BUTTONS = 14; private static final int TOOLBAR_HEIGHT = GRIP + TOOLBAR_BUTTONS * 22 + 2; private static final int HANDLE = 6; private static final int PANEL_WIDTH = 130; @@ -79,6 +79,13 @@ public class LayoutEditorScreen extends Screen { private boolean pickingFont; private HudPart fontTarget; private int fontPage; + /** The frame list: for {@link #frameTarget}, or the profile frame when that is null. */ + private boolean pickingFrame; + private HudPart frameTarget; + private int framePage; + /** The container screens list: which pack each screen's picture comes from. */ + private boolean pickingScreens; + private int screensPage; /** Where the controls were left, kept while the game runs; -1 = default (left edge, halfway down). */ private static int toolbarX = -1; private static int toolbarY = -1; @@ -107,12 +114,16 @@ private void loadWorking() { Profiles.setPreview(working); selected = null; pickingFont = false; + pickingFrame = false; + pickingScreens = false; } // ---- Widgets ---- @Override protected void init() { + // Offsets in plain GUI pixels while editing (opened, profile changed, window resized), so dragging is exact. + working.rebaseOffsets(working.sizing.factor()); // A rebuild (resize, toolbar moved) keeps a half-typed name. String draft = renaming && nameBox != null ? nameBox.getValue() : Profiles.activeName(); if (toolbarX < 0) { @@ -138,6 +149,8 @@ protected void init() { y = toolbarButton(x, y, I18n.get("huddable.editor.elements"), I18n.get("huddable.editor.elements.tooltip"), () -> { showList = !showList; pickingFont = false; + pickingFrame = false; + pickingScreens = false; selected = null; rebuildWidgets(); }); @@ -148,11 +161,36 @@ protected void init() { selected = null; openFontList(null); pickingFont = !open; + pickingFrame = false; + pickingScreens = false; + rebuildWidgets(); + }); + y = toolbarButton(x, y, I18n.get("huddable.editor.frame"), + I18n.get("huddable.editor.frame.tooltip", frameName(working.frame, false)), () -> { + boolean open = pickingFrame && frameTarget == null; + showList = false; + selected = null; + pickingFont = false; + openFrameList(null); + pickingFrame = !open; + pickingScreens = false; + rebuildWidgets(); + }); + y = toolbarButton(x, y, I18n.get("huddable.editor.screens"), I18n.get("huddable.editor.screens.tooltip"), () -> { + boolean open = pickingScreens; + showList = false; + selected = null; + pickingFont = false; + pickingFrame = false; + pickingScreens = !open; + screensPage = 0; rebuildWidgets(); }); y = toolbarButton(x, y, I18n.get("huddable.editor.size", working.sizing.label()), I18n.get("huddable.editor.size.tooltip"), () -> { working.sizing = working.sizing.next(); + // Elements stay where they are; only their size changes. + working.offsetFactor = working.sizing.factor(); rebuildWidgets(); }); y = toolbarButton(x, y, I18n.get("huddable.editor.new"), I18n.get("huddable.editor.new.tooltip"), this::newProfile); @@ -167,6 +205,8 @@ protected void init() { toolbarButton(x, y, I18n.get("huddable.editor.done"), I18n.get("huddable.editor.done.tooltip"), this::done); if (showList) buildList(); else if (pickingFont) buildFontList(); + else if (pickingFrame) buildFrameList(); + else if (pickingScreens) buildScreensList(); else if (selected != null) buildPanel(); } @@ -251,6 +291,10 @@ private void buildPanel() { if (HudFonts.fontable(selected, l)) { y = panelButton(x, y, w, I18n.get("huddable.editor.panel.font", fontName(l.font, true)), () -> openFontList(selected)); } + if (selected.frameable()) { + y = panelButton(x, y, w, I18n.get("huddable.editor.panel.frame", frameName(l.frame, true)), + () -> openFrameList(selected)); + } y = panelButton(x, y, w, I18n.get("huddable.editor.panel.reset"), () -> working.reset(selected)); y = panelButton(x, y, w, I18n.get("huddable.editor.close"), () -> selected = null); panelHeight = y - panelY + 2; @@ -340,6 +384,150 @@ private void setFont(String id) { if (fontTarget.movable()) keepOnScreen(fontTarget); } + private void openFrameList(HudPart target) { + pickingFrame = true; + frameTarget = target; + framePage = 0; + } + + /** A frame choice's name: {@code null} is the profile frame for an element, no frame for the profile. */ + private static String frameName(String id, boolean element) { + if (id == null) return I18n.get(element ? "huddable.editor.frame.profile" : "huddable.editor.frame.none"); + if (id.equals(HudFrames.NONE)) return I18n.get("huddable.editor.frame.none"); + return HudFrames.name(id); + } + + /** + * Every frame the resource packs offer (each kind from the top pack, then from each pack that has it), a page at + * a time; the current choice is gold. For an element the first choices are the profile frame and none. + */ + private void buildFrameList() { + placePanel(FONT_PANEL_WIDTH); + int x = panelX + 4; + int w = FONT_PANEL_WIDTH - 8; + List choices = new ArrayList<>(); + if (frameTarget != null) choices.add(null); + choices.add(HudFrames.NONE); + choices.addAll(HudFrames.available()); + String current = frameTarget != null ? working.get(frameTarget).frame + : working.frame != null ? working.frame : HudFrames.NONE; + if (current != null && !choices.contains(current)) choices.add(current); // set, but its pack is off now + int perPage = Math.max(1, (height - panelY - 16 - 2 * ROW - 2) / ROW); + int pages = (choices.size() + perPage - 1) / perPage; + framePage = Math.clamp(framePage, 0, pages - 1); + int y = panelY + 16; + for (int i = framePage * perPage; i < Math.min(choices.size(), (framePage + 1) * perPage); i++) { + String id = choices.get(i); + boolean chosen = id == null ? current == null : id.equals(current); + String name = font.plainSubstrByWidth(frameName(id, frameTarget != null), w - 16); + MutableComponent label = Component.literal(chosen ? "> " + name : name); + addRenderableWidget(Button.builder(chosen ? label.withStyle(ChatFormatting.GOLD) : label, b -> { + setFrame(id); + rebuildWidgets(); + }).tooltip(Tooltip.create(Component.literal(frameTip(id)))).bounds(x, y, w, 20).build()); + y += ROW; + } + if (pages > 1) { + addRenderableWidget(Button.builder(Component.literal("<"), b -> { + framePage--; + rebuildWidgets(); + }).bounds(x, y, 20, 20).build()).active = framePage > 0; + addRenderableWidget(Button.builder(Component.literal(">"), b -> { + framePage++; + rebuildWidgets(); + }).bounds(x + w - 20, y, 20, 20).build()).active = framePage < pages - 1; + y += ROW; + } + y = panelButton(x, y, w, I18n.get(frameTarget != null ? "huddable.editor.back" : "huddable.editor.close"), + () -> pickingFrame = false); + panelHeight = y - panelY + 2; + } + + private String frameTip(String id) { + if (id == null) return I18n.get("huddable.editor.frame.profile.tooltip"); + if (id.equals(HudFrames.NONE)) { + return I18n.get(frameTarget != null ? "huddable.editor.frame.none.element_tooltip" : "huddable.editor.frame.none.tooltip"); + } + return HudFrames.packOff(id) ? I18n.get("huddable.editor.frame.pack_off", HudFrames.name(id)) : HudFrames.name(id); + } + + private void setFrame(String id) { + if (frameTarget == null) { + working.frame = HudFrames.NONE.equals(id) ? null : id; + return; + } + working.edit(frameTarget).frame = id; + } + + /** + * Container screens, a page at a time: first every screen's pack, then each screen that more than one enabled + * pack has a picture for (or that has a choice of its own). Clicking a row moves to the next pack. + */ + private void buildScreensList() { + placePanel(FONT_PANEL_WIDTH); + int x = panelX + 4; + int w = FONT_PANEL_WIDTH - 8; + List rows = new ArrayList<>(); + rows.add(null); + for (String screen : HudScreenArt.SCREENS) { + if (HudScreenArt.packsWith(screen).size() > 1 || working.screenArtFor.containsKey(screen)) rows.add(screen); + } + int perPage = Math.max(1, (height - panelY - 16 - 2 * ROW - 2) / ROW); + int pages = (rows.size() + perPage - 1) / perPage; + screensPage = Math.clamp(screensPage, 0, pages - 1); + int y = panelY + 16; + for (int i = screensPage * perPage; i < Math.min(rows.size(), (screensPage + 1) * perPage); i++) { + String screen = rows.get(i); + String pack = screen == null ? working.screenArt : working.screenArtFor.get(screen); + String packName = screen != null && pack == null ? I18n.get("huddable.editor.screens.profile") + : HudScreenArt.packName(pack); + String label = I18n.get("huddable.editor.screens.row", + screen == null ? I18n.get("huddable.editor.screens.all") : HudScreenArt.name(screen), packName); + String tip = pack != null && !HudScreenArt.TOP.equals(pack) && !PackFrames.enabled(pack) + ? I18n.get("huddable.editor.screens.pack_off", PackFrames.title(pack)) + : I18n.get(screen == null ? "huddable.editor.screens.all.tooltip" : "huddable.editor.screens.screen.tooltip"); + addRenderableWidget(Button.builder(Component.literal(font.plainSubstrByWidth(label, w - 8)), b -> { + nextScreenPack(screen); + rebuildWidgets(); + }).tooltip(Tooltip.create(Component.literal(tip))).bounds(x, y, w, 20).build()); + y += ROW; + } + if (pages > 1) { + addRenderableWidget(Button.builder(Component.literal("<"), b -> { + screensPage--; + rebuildWidgets(); + }).bounds(x, y, 20, 20).build()).active = screensPage > 0; + addRenderableWidget(Button.builder(Component.literal(">"), b -> { + screensPage++; + rebuildWidgets(); + }).bounds(x + w - 20, y, 20, 20).build()).active = screensPage < pages - 1; + y += ROW; + } + y = panelButton(x, y, w, I18n.get("huddable.editor.close"), () -> pickingScreens = false); + panelHeight = y - panelY + 2; + } + + /** + * Moves {@code screen} (null = every screen) to the next pack: the top pack, then each enabled pack that has its + * picture; a single screen starts with the profile's choice. + */ + private void nextScreenPack(String screen) { + List choices = new ArrayList<>(); + if (screen == null) { + choices.add(null); + choices.addAll(HudScreenArt.packsWithAny()); + } else { + choices.add(null); + choices.add(HudScreenArt.TOP); + choices.addAll(HudScreenArt.packsWith(screen)); + } + String current = screen == null ? working.screenArt : working.screenArtFor.get(screen); + String next = choices.get((choices.indexOf(current) + 1) % choices.size()); + if (screen == null) working.screenArt = next; + else if (next == null) working.screenArtFor.remove(screen); + else working.screenArtFor.put(screen, next); + } + /** A full-width panel button; the panel is rebuilt after it runs, so labels show the new value. */ private int panelButton(int x, int y, int w, String label, Runnable action) { addRenderableWidget(Button.builder(Component.literal(label), b -> { @@ -428,9 +616,15 @@ private void importLayout() { private void resetAll() { working.elements.clear(); working.sizing = Sizing.GUI_SCALE; + working.offsetFactor = working.sizing.factor(); working.font = null; + working.frame = null; + working.screenArt = null; + working.screenArtFor.clear(); selected = null; pickingFont = false; + pickingFrame = false; + pickingScreens = false; rebuildWidgets(); } @@ -514,6 +708,16 @@ public void extractRenderState(GuiGraphicsExtractor context, int mouseX, int mou String title = fontTarget != null ? I18n.get("huddable.editor.panel.font", fontTarget.label()) : I18n.get("huddable.editor.font.profile_title"); context.text(font, font.plainSubstrByWidth(title, panelWidth - 8), panelX + 4, panelY + 4, GOLD, false); + } else if (pickingFrame) { + context.fill(panelX, panelY, panelX + panelWidth, panelY + panelHeight, PANEL_BG); + context.outline(panelX, panelY, panelWidth, panelHeight, HEADER_BORDER); + String title = frameTarget != null ? I18n.get("huddable.editor.panel.frame", frameTarget.label()) + : I18n.get("huddable.editor.frame.profile_title"); + context.text(font, font.plainSubstrByWidth(title, panelWidth - 8), panelX + 4, panelY + 4, GOLD, false); + } else if (pickingScreens) { + context.fill(panelX, panelY, panelX + panelWidth, panelY + panelHeight, PANEL_BG); + context.outline(panelX, panelY, panelWidth, panelHeight, HEADER_BORDER); + context.text(font, Component.translatable("huddable.editor.screens.title"), panelX + 4, panelY + 4, GOLD, false); } else if (selected != null) { ElementLayout l = working.get(selected); context.fill(panelX, panelY, panelX + panelWidth, panelY + panelHeight, PANEL_BG); @@ -594,7 +798,7 @@ private boolean inToolbar(int mouseX, int mouseY) { } private boolean inPanel(int mouseX, int mouseY) { - return (showList || pickingFont || selected != null) && mouseX >= panelX && mouseX < panelX + panelWidth + return (showList || pickingFont || pickingFrame || pickingScreens || selected != null) && mouseX >= panelX && mouseX < panelX + panelWidth && mouseY >= panelY && mouseY < panelY + panelHeight; } @@ -616,6 +820,8 @@ public boolean mouseClicked(MouseButtonEvent ctx, boolean doubleClick) { if (ctx.button() == mouseRight) { if (element != null) showList = false; pickingFont = false; + pickingFrame = false; + pickingScreens = false; selected = element; rebuildWidgets(); return true; @@ -624,6 +830,8 @@ public boolean mouseClicked(MouseButtonEvent ctx, boolean doubleClick) { if (selected != null && selected != element) { selected = element; pickingFont = false; + pickingFrame = false; + pickingScreens = false; rebuildWidgets(); } if (!element.movable()) return true; diff --git a/src/main/java/uk/toakan/tad/huddable/PackFrames.java b/src/main/java/uk/toakan/tad/huddable/PackFrames.java new file mode 100644 index 0000000..e4423fb --- /dev/null +++ b/src/main/java/uk/toakan/tad/huddable/PackFrames.java @@ -0,0 +1,267 @@ +package uk.toakan.tad.huddable; + +import com.mojang.blaze3d.platform.NativeImage; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.minecraft.client.renderer.RenderPipelines; +import net.minecraft.client.renderer.texture.DynamicTexture; +import net.minecraft.client.resources.metadata.animation.AnimationMetadataSection; +import net.minecraft.client.resources.metadata.animation.FrameSize; +import net.minecraft.client.resources.metadata.gui.GuiMetadataSection; +import net.minecraft.client.resources.metadata.gui.GuiSpriteScaling; +import net.minecraft.resources.FileToIdConverter; +import net.minecraft.resources.Identifier; +import net.minecraft.server.packs.repository.Pack; +import net.minecraft.server.packs.resources.Resource; +import net.minecraft.server.packs.resources.ResourceManager; +import net.minecraft.server.packs.resources.ResourceMetadata; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +/** + * Vanilla frame art (tooltip, popup, button) from a chosen resource pack. Vanilla's GUI atlas only holds the top + * pack's copy of a sprite, so a lower pack's copy is read from that pack and drawn here with the same stretch / tile + * / nine-slice rules. Plain textures (container screens) can be swapped for a pack's copy too ({@link #packTexture}). + * Only chosen art is loaded, on first draw; a resource reload drops it. Shared copy: Shopping + * List is the reference, Huddable has a copy (package, mod id and logger aside). + */ +public final class PackFrames { + private PackFrames() {} + + private static final FileToIdConverter SPRITES = new FileToIdConverter("textures/gui/sprites", ".png"); + + /** A loaded sprite: its texture, the texture's size, the first frame's size (animated sprites) and scaling. */ + private record Art(Identifier texture, int textureWidth, int textureHeight, int frameWidth, int frameHeight, + GuiSpriteScaling scaling) {} + + private record Key(Identifier file, String pack) {} + + /** + * Per file and pack, the art, or empty when that pack doesn't have it (or it failed to load). Keyed by pack too, + * so the Appearance preview and the HUD can use different packs without reloading each frame. + */ + private static final Map> LOADED = new HashMap<>(); + + /** The vanilla frames there are: their atlas sprites (bottom first) and where content goes inside them. */ + public enum Kind { + TOOLTIP("tooltip", Identifier.withDefaultNamespace("tooltip/background"), + Identifier.withDefaultNamespace("tooltip/frame"), 4, 9), + POPUP("popup", Identifier.withDefaultNamespace("popup/background"), null, 6, 0), + BUTTON("button", Identifier.withDefaultNamespace("widget/button"), null, 3, 0); + + /** The name saved in settings. */ + public final String id; + public final Identifier sprite; + /** Drawn over {@link #sprite} (the tooltip's frame), or null. */ + public final Identifier overlay; + /** Space from the box's edge that keeps content off the edge art. */ + public final int inset; + /** Empty border inside the sprites: tooltips are drawn 9 px out, as vanilla's TooltipRenderUtil does. */ + public final int margin; + + Kind(String id, Identifier sprite, Identifier overlay, int inset, int margin) { + this.id = id; + this.sprite = sprite; + this.overlay = overlay; + this.inset = inset; + this.margin = margin; + } + + /** The kind saved as {@code id}, or null. */ + public static Kind byId(String id) { + for (Kind kind : values()) { + if (kind.id.equals(id)) return kind; + } + return null; + } + + private List sprites() { + return overlay == null ? List.of(sprite) : List.of(sprite, overlay); + } + } + + /** Enabled packs that have art for any of {@code kinds}, top of the pack list first. */ + public static List packsWith(Kind... kinds) { + List files = new ArrayList<>(); + for (Kind kind : kinds) { + for (Identifier sprite : kind.sprites()) files.add(SPRITES.idToFile(sprite)); + } + return packsWithFiles(files); + } + + /** Enabled packs that have any of {@code files} (full paths, such as a container's PNG), top first. */ + public static List packsWithFiles(List files) { + Minecraft client = Minecraft.getInstance(); + ResourceManager manager = client.getResourceManager(); + Set found = new LinkedHashSet<>(); + for (Identifier file : files) { + for (Resource resource : manager.getResourceStack(file)) found.add(resource.sourcePackId()); + } + List packs = new ArrayList<>(); + for (Pack pack : client.getResourcePackRepository().getSelectedPacks()) { + if (found.contains(pack.getId())) packs.add(0, pack.getId()); + } + return packs; + } + + /** A pack's name as the pack list shows it, or its id when it is no longer there. */ + public static String title(String packId) { + Pack pack = Minecraft.getInstance().getResourcePackRepository().getPack(packId); + return pack == null ? packId : pack.getTitle().getString(); + } + + /** True when {@code packId} is an enabled pack. */ + public static boolean enabled(String packId) { + for (Pack pack : Minecraft.getInstance().getResourcePackRepository().getSelectedPacks()) { + if (pack.getId().equals(packId)) return true; + } + return false; + } + + /** + * Draws a {@code kind} frame over the box, each sprite from {@code packId} ("" = the top pack) or, when that pack + * doesn't have it, the top pack's. + */ + public static void drawFrame(GuiGraphicsExtractor context, Kind kind, String packId, int x, int y, int w, int h) { + int m = kind.margin; + for (Identifier sprite : kind.sprites()) { + if (packId.isEmpty() || !draw(context, sprite, packId, x - m, y - m, w + 2 * m, h + 2 * m)) { + context.blitSprite(RenderPipelines.GUI_TEXTURED, sprite, x - m, y - m, w + 2 * m, h + 2 * m); + } + } + } + + /** Draws {@code sprite} from {@code packId} over the box; false when that pack has no such sprite. */ + private static boolean draw(GuiGraphicsExtractor context, Identifier sprite, String packId, int x, int y, int w, int h) { + Optional art = art(SPRITES.idToFile(sprite), packId); + if (art.isEmpty()) return false; + Art a = art.get(); + switch (a.scaling()) { + case GuiSpriteScaling.Tile tile -> tile(context, a, x, y, w, h, 0, 0, tile.width(), tile.height(), + tile.width(), tile.height()); + case GuiSpriteScaling.NineSlice nineSlice -> nineSlice(context, a, nineSlice, x, y, w, h); + default -> region(context, a, x, y, w, h, 0, 0, 1, 1, 1, 1); + } + return true; + } + + /** Drops the loaded art (resource packs reloaded). */ + public static void reloaded() { + for (Optional art : LOADED.values()) { + art.ifPresent(a -> Minecraft.getInstance().getTextureManager().release(a.texture())); + } + LOADED.clear(); + } + + /** + * The texture to draw in place of {@code file} (a full path, such as {@code textures/gui/container/inventory.png}): + * {@code packId}'s copy, loaded on first use, or {@code file} itself when that pack doesn't have it. + */ + public static Identifier packTexture(Identifier file, String packId) { + return art(file, packId).map(Art::texture).orElse(file); + } + + /** {@code packId}'s copy of {@code file}, loaded once; empty when that pack doesn't have it. */ + private static Optional art(Identifier file, String packId) { + Key key = new Key(file, packId); + Optional art = LOADED.get(key); + if (art == null) { + art = load(file, packId, LOADED.size()); + LOADED.put(key, art); + } + return art; + } + + private static Optional load(Identifier file, String packId, int number) { + for (Resource resource : Minecraft.getInstance().getResourceManager().getResourceStack(file)) { + if (!resource.sourcePackId().equals(packId)) continue; + try (InputStream in = resource.open()) { + NativeImage image = NativeImage.read(in); + ResourceMetadata metadata = resource.metadata(); + GuiSpriteScaling scaling = metadata.getSection(GuiMetadataSection.TYPE) + .map(GuiMetadataSection::scaling).orElse(GuiSpriteScaling.DEFAULT); + // Animated sprites are a strip of frames; the first one is used. + FrameSize frame = metadata.getSection(AnimationMetadataSection.TYPE) + .map(anim -> anim.calculateFrameSize(image.getWidth(), image.getHeight())) + .orElse(new FrameSize(image.getWidth(), image.getHeight())); + Identifier id = Identifier.fromNamespaceAndPath(HuddableClient.MOD_ID, "pack_frame/" + number); + int width = image.getWidth(); + int height = image.getHeight(); + Minecraft.getInstance().getTextureManager().register(id, new DynamicTexture(id::toString, image)); + return Optional.of(new Art(id, width, height, frame.width(), frame.height(), scaling)); + } catch (IOException | RuntimeException e) { + HuddableClient.LOGGER.warn("Couldn't load {} from {}: {}", file, packId, e.toString()); + return Optional.empty(); + } + } + return Optional.empty(); + } + + /** + * Draws part of the sprite, given in sprite units ({@code u, v, uw, vh} out of {@code unitsW x unitsH}), over the + * box. Units are scaled to the texture's pixels, so a 64x pack's art stays sharp. + */ + private static void region(GuiGraphicsExtractor context, Art a, int x, int y, int w, int h, + float u, float v, float uw, float vh, int unitsW, int unitsH) { + if (w <= 0 || h <= 0 || uw <= 0 || vh <= 0) return; + float sx = (float) a.frameWidth() / unitsW; + float sy = (float) a.frameHeight() / unitsH; + context.blit(RenderPipelines.GUI_TEXTURED, a.texture(), x, y, u * sx, v * sy, w, h, + Math.max(1, Math.round(uw * sx)), Math.max(1, Math.round(vh * sy)), a.textureWidth(), a.textureHeight()); + } + + /** Repeats a sprite part across the box at 1 unit = 1 GUI pixel, cutting the last copy short. */ + private static void tile(GuiGraphicsExtractor context, Art a, int x, int y, int w, int h, + int u, int v, int uw, int vh, int unitsW, int unitsH) { + if (w <= 0 || h <= 0 || uw <= 0 || vh <= 0) return; + for (int dy = 0; dy < h; dy += vh) { + int ph = Math.min(vh, h - dy); + for (int dx = 0; dx < w; dx += uw) { + int pw = Math.min(uw, w - dx); + region(context, a, x + dx, y + dy, pw, ph, u, v, pw, ph, unitsW, unitsH); + } + } + } + + /** Fixed corners, tiled (or stretched) edges and centre, as vanilla draws nine-slice GUI sprites. */ + private static void nineSlice(GuiGraphicsExtractor context, Art a, GuiSpriteScaling.NineSlice slice, + int x, int y, int w, int h) { + GuiSpriteScaling.NineSlice.Border border = slice.border(); + int nw = slice.width(); + int nh = slice.height(); + int l = Math.min(border.left(), w / 2); + int r = Math.min(border.right(), w / 2); + int t = Math.min(border.top(), h / 2); + int b = Math.min(border.bottom(), h / 2); + int innerW = w - l - r; + int innerH = h - t - b; + int srcW = nw - l - r; + int srcH = nh - t - b; + region(context, a, x, y, l, t, 0, 0, l, t, nw, nh); + region(context, a, x + w - r, y, r, t, nw - r, 0, r, t, nw, nh); + region(context, a, x, y + h - b, l, b, 0, nh - b, l, b, nw, nh); + region(context, a, x + w - r, y + h - b, r, b, nw - r, nh - b, r, b, nw, nh); + inner(context, a, slice, x + l, y, innerW, t, l, 0, srcW, t); + inner(context, a, slice, x + l, y + h - b, innerW, b, l, nh - b, srcW, b); + inner(context, a, slice, x, y + t, l, innerH, 0, t, l, srcH); + inner(context, a, slice, x + w - r, y + t, r, innerH, nw - r, t, r, srcH); + inner(context, a, slice, x + l, y + t, innerW, innerH, l, t, srcW, srcH); + } + + private static void inner(GuiGraphicsExtractor context, Art a, GuiSpriteScaling.NineSlice slice, + int x, int y, int w, int h, int u, int v, int uw, int vh) { + if (slice.stretchInner()) { + region(context, a, x, y, w, h, u, v, uw, vh, slice.width(), slice.height()); + } else { + tile(context, a, x, y, w, h, u, v, uw, vh, slice.width(), slice.height()); + } + } +} diff --git a/src/main/java/uk/toakan/tad/huddable/Profiles.java b/src/main/java/uk/toakan/tad/huddable/Profiles.java index 259698d..e6a3c16 100644 --- a/src/main/java/uk/toakan/tad/huddable/Profiles.java +++ b/src/main/java/uk/toakan/tad/huddable/Profiles.java @@ -77,6 +77,12 @@ public static void saveActive(Layout layout) { JsonFiles.writeAsync(file(activeName), () -> snapshot); } + /** Records the sizing factor a layout from before offsets followed it was placed at: the one it draws at now. */ + static void recordOffsetFactor(Layout layout) { + layout.offsetFactor = layout.sizing.factor(); + if (layout == active) saveActive(active); + } + public static void switchTo(String name) { // A save of that profile may still be queued (switching away and straight back); read what it wrote. JsonFiles.flush(); diff --git a/src/main/java/uk/toakan/tad/huddable/api/HuddableApi.java b/src/main/java/uk/toakan/tad/huddable/api/HuddableApi.java index 9507026..6a02b0d 100644 --- a/src/main/java/uk/toakan/tad/huddable/api/HuddableApi.java +++ b/src/main/java/uk/toakan/tad/huddable/api/HuddableApi.java @@ -1,9 +1,11 @@ package uk.toakan.tad.huddable.api; import uk.toakan.tad.huddable.ExternalPart; +import uk.toakan.tad.huddable.HudFrames; import uk.toakan.tad.huddable.LayoutEditorScreen; import uk.toakan.tad.huddable.Parts; import uk.toakan.tad.huddable.Profiles; +import java.util.function.BooleanSupplier; import java.util.function.DoubleSupplier; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphicsExtractor; @@ -36,18 +38,24 @@ public interface BoxProvider { * How an element is placed. {@code defaultBox} is its unmoved box: position in GUI pixels, size in the * element's own units before {@code baseScale}. {@code baseScale} is the element's own scale (1 when it has * none). Resizable elements get edge grips and must lay themselves out to {@link Placement#width}/height. + * {@code listed} leaves the element out of the editor while false (switched off in its own mod); its layout is kept. */ - public record Spec(BoxProvider defaultBox, DoubleSupplier baseScale, boolean resizable, int minWidth, int minHeight) { + public record Spec(BoxProvider defaultBox, DoubleSupplier baseScale, boolean resizable, int minWidth, int minHeight, + BooleanSupplier listed) { public static Spec of(BoxProvider defaultBox) { - return new Spec(defaultBox, () -> 1.0, false, 1, 1); + return new Spec(defaultBox, () -> 1.0, false, 1, 1, () -> true); } public Spec withBaseScale(DoubleSupplier scale) { - return new Spec(defaultBox, scale, resizable, minWidth, minHeight); + return new Spec(defaultBox, scale, resizable, minWidth, minHeight, listed); } public Spec resizable(int minWidth, int minHeight) { - return new Spec(defaultBox, baseScale, true, Math.max(1, minWidth), Math.max(1, minHeight)); + return new Spec(defaultBox, baseScale, true, Math.max(1, minWidth), Math.max(1, minHeight), listed); + } + + public Spec listedWhen(BooleanSupplier listed) { + return new Spec(defaultBox, baseScale, resizable, minWidth, minHeight, listed); } } @@ -59,7 +67,7 @@ public record Placement(int x, int y, int width, int height, float scale, boolea /** Adds an element to the editor. Registering an ID twice replaces the first. */ public static void register(Identifier id, Component label, Spec spec) { - Parts.add(ExternalPart.api(id, label, spec)); + Parts.add(ExternalPart.api(id, label, spec).listedWhen(spec.listed())); } /** @@ -93,6 +101,35 @@ public static boolean push(GuiGraphicsExtractor graphics, Identifier id) { pose.translate(p.x(), p.y()); pose.scale(p.scale(), p.scale()); pose.translate(-box.x(), -box.y()); + HudFrames.Choice frame = HudFrames.resolve(part, Profiles.current()); + if (frame != null) HudFrames.drawAround(graphics, frame, box.x(), box.y(), p.width(), p.height()); + return true; + } + + /** + * Space, in the element's own units at this frame's scale, to keep its content off the frame the player gave it + * in Huddable; -1 when it has none. For elements drawn from {@link #placement}: lay out inside it, then call + * {@link #drawFrame}. ({@link #push} draws the frame itself.) + */ + public static int frameInset(Identifier id) { + ExternalPart part = Parts.external(id); + HudFrames.Choice frame = part == null ? null : HudFrames.resolve(part, Profiles.current()); + if (frame == null) return -1; + Minecraft mc = Minecraft.getInstance(); + float scale = part.placement(mc.getWindow().getGuiScaledWidth(), mc.getWindow().getGuiScaledHeight()).scale(); + // Frame art is drawn at screen size, so a smaller element needs more of its own units to clear it. + return (int) Math.ceil(frame.kind().inset / Math.max(0.05f, scale)); + } + + /** + * Draws the element's frame over the box, given in the current pose (usually the element's own 0, 0, width, + * height after moving to its placement). Draw it first, so the element draws over it. False when it has none. + */ + public static boolean drawFrame(GuiGraphicsExtractor graphics, Identifier id, int x, int y, int width, int height) { + ExternalPart part = Parts.external(id); + HudFrames.Choice frame = part == null ? null : HudFrames.resolve(part, Profiles.current()); + if (frame == null) return false; + HudFrames.drawOver(graphics, frame, x, y, width, height); return true; } diff --git a/src/main/java/uk/toakan/tad/huddable/compat/MeowddingCompat.java b/src/main/java/uk/toakan/tad/huddable/compat/MeowddingCompat.java index f7013e2..fee375a 100644 --- a/src/main/java/uk/toakan/tad/huddable/compat/MeowddingCompat.java +++ b/src/main/java/uk/toakan/tad/huddable/compat/MeowddingCompat.java @@ -15,8 +15,10 @@ import org.joml.Matrix3x2fStack; import uk.toakan.tad.huddable.ExternalPart; import uk.toakan.tad.huddable.GeneralSettings; +import uk.toakan.tad.huddable.HudFrames; import uk.toakan.tad.huddable.HuddableClient; import uk.toakan.tad.huddable.Parts; +import uk.toakan.tad.huddable.Profiles; import uk.toakan.tad.huddable.api.HuddableApi; import uk.toakan.tad.huddable.mixin.meowdding.OverlaysAccessor; @@ -87,6 +89,15 @@ public static void draw(Overlay overlay, GuiGraphicsExtractor graphics, Runnable HuddableApi.Placement p = part.placement(w, h); if (p.hidden()) return; HuddableApi.Box box = part.defaultBox(w, h); + HudFrames.Choice frame = HudFrames.resolve(part, Profiles.current()); + if (frame != null) { + // In screen space: the pose holds meowdding's own position, which the box already includes. + Matrix3x2fStack framePose = graphics.pose(); + framePose.pushMatrix(); + framePose.identity(); + HudFrames.drawAround(graphics, frame, p.x(), p.y(), p.width() * p.scale(), p.height() * p.scale()); + framePose.popMatrix(); + } if (p.x() == box.x() && p.y() == box.y() && p.scale() == 1f) { draw.run(); return; diff --git a/src/main/java/uk/toakan/tad/huddable/mixin/ContainerArtMixin.java b/src/main/java/uk/toakan/tad/huddable/mixin/ContainerArtMixin.java new file mode 100644 index 0000000..b98ae78 --- /dev/null +++ b/src/main/java/uk/toakan/tad/huddable/mixin/ContainerArtMixin.java @@ -0,0 +1,23 @@ +package uk.toakan.tad.huddable.mixin; + +import uk.toakan.tad.huddable.HudScreenArt; +import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.minecraft.resources.Identifier; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyArg; + +/** + * Container screen art: every {@code blit} of a texture by its id ends in the {@code innerBlit} overload that looks + * the id up here, so a container background ({@code textures/gui/container/*.png}) is swapped for the chosen + * pack's copy ({@link HudScreenArt}). UVs are already fractions of the texture, so a higher-resolution copy lines + * up the same. Targets the lookup call rather than the method's descriptor, whose pipeline class moved in 26.3. + */ +@Mixin(GuiGraphicsExtractor.class) +abstract class ContainerArtMixin { + @ModifyArg(method = "innerBlit", at = @At(value = "INVOKE", + target = "Lnet/minecraft/client/renderer/texture/TextureManager;getTexture(Lnet/minecraft/resources/Identifier;)Lnet/minecraft/client/renderer/texture/AbstractTexture;")) + private Identifier huddable$screenArt(Identifier location) { + return HudScreenArt.swap(location); + } +} diff --git a/src/main/resources/assets/huddable/icon.png b/src/main/resources/assets/huddable/icon.png new file mode 100644 index 0000000..a4cc226 Binary files /dev/null and b/src/main/resources/assets/huddable/icon.png differ diff --git a/src/main/resources/assets/huddable/lang/en_us.json b/src/main/resources/assets/huddable/lang/en_us.json index 706c922..ed9ec2b 100644 --- a/src/main/resources/assets/huddable/lang/en_us.json +++ b/src/main/resources/assets/huddable/lang/en_us.json @@ -63,7 +63,7 @@ "huddable.editor.import": "Import", "huddable.editor.import.tooltip": "Load a layout code from the clipboard as a new profile", "huddable.editor.reset": "Reset", - "huddable.editor.reset.tooltip": "Put every element back to vanilla", + "huddable.editor.reset.tooltip": "Put every element and screen back to vanilla", "huddable.editor.cancel": "Cancel", "huddable.editor.cancel.tooltip": "Close without saving", "huddable.editor.done": "Done", @@ -100,6 +100,54 @@ "huddable.editor.font.vanilla.element_tooltip": "Minecraft's own font, even when the profile has another", "huddable.editor.font.pack_off": "%s\nIts resource pack is off, so this draws in vanilla's font", + "huddable.editor.frame": "Frame", + "huddable.editor.frame.tooltip": "Profile frame: %s. Drawn around every element unless it has a frame choice of its own (right-click it). Frames are Minecraft's tooltip, popup and button art, from the top resource pack or any enabled pack that has its own", + "huddable.editor.panel.frame": "Frame: %s", + "huddable.editor.frame.profile": "Profile", + "huddable.editor.frame.none": "None", + "huddable.editor.frame.profile_title": "Profile frame", + "huddable.editor.frame.profile.tooltip": "Use the profile frame (toolbar Frame button)", + "huddable.editor.frame.none.tooltip": "No frame around elements", + "huddable.editor.frame.none.element_tooltip": "No frame, even when the profile has one", + "huddable.editor.frame.pack_off": "%s\nThat resource pack is off, so the top pack's art is drawn", + "huddable.frame.tooltip": "Tooltip", + "huddable.frame.popup": "Popup", + "huddable.frame.button": "Button", + "huddable.frame.top_pack": "Top pack", + "huddable.frame.name": "%s (%s)", + "huddable.editor.screens": "Screens", + "huddable.editor.screens.tooltip": "Which resource pack's art the inventory, chests and other container screens use. Open one after Done to see it", + "huddable.editor.screens.title": "Container screens", + "huddable.editor.screens.row": "%s: %s", + "huddable.editor.screens.all": "All screens", + "huddable.editor.screens.all.tooltip": "Click for the next pack. Every container screen uses this pack's art unless it has its own choice below; a screen the pack has no art for keeps the top pack's", + "huddable.editor.screens.screen.tooltip": "Click for the next pack: Profile (the All screens choice), the top pack, or a pack that has this screen's art", + "huddable.editor.screens.profile": "Profile", + "huddable.editor.screens.pack_off": "%s is off, so the top pack's art is drawn", + "huddable.screens.top_pack": "Top pack", + "huddable.screen.inventory": "Inventory", + "huddable.screen.generic_54": "Chest (and server menus)", + "huddable.screen.shulker_box": "Shulker box", + "huddable.screen.crafting_table": "Crafting table", + "huddable.screen.furnace": "Furnace", + "huddable.screen.blast_furnace": "Blast furnace", + "huddable.screen.smoker": "Smoker", + "huddable.screen.dispenser": "Dispenser and dropper", + "huddable.screen.hopper": "Hopper", + "huddable.screen.crafter": "Crafter", + "huddable.screen.brewing_stand": "Brewing stand", + "huddable.screen.enchanting_table": "Enchanting table", + "huddable.screen.anvil": "Anvil", + "huddable.screen.grindstone": "Grindstone", + "huddable.screen.smithing": "Smithing table", + "huddable.screen.stonecutter": "Stonecutter", + "huddable.screen.loom": "Loom", + "huddable.screen.cartography_table": "Cartography table", + "huddable.screen.beacon": "Beacon", + "huddable.screen.villager": "Villager trading", + "huddable.screen.horse": "Horse", + "huddable.screen.nautilus": "Nautilus", + "huddable.editor.status.name_taken": "That name is taken", "huddable.editor.status.deleted": "Profile deleted", "huddable.editor.status.exported": "Layout code copied to the clipboard", diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index 21d15fb..9840e01 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -3,11 +3,12 @@ "id": "huddable", "version": "${version}", "name": "Huddable", - "description": "Move, scale, hide and restyle the vanilla HUD in game. Drag health, hunger, the hotbar, the scoreboard and more where you want them, switch layout profiles, and share layouts as codes. Client-side; works on any server.", + "description": "Move, scale and hide every part of your HUD in an in-game editor. Works with vanilla elements and other mods' HUDs, with layout profiles you can share as codes.", "authors": [ "Tad" ], "license": "GPL-3.0-only", + "icon": "assets/huddable/icon.png", "environment": "client", "entrypoints": { "client": [ diff --git a/src/main/resources/huddable.mixins.json b/src/main/resources/huddable.mixins.json index 35b4583..70c220b 100644 --- a/src/main/resources/huddable.mixins.json +++ b/src/main/resources/huddable.mixins.json @@ -5,6 +5,7 @@ "compatibilityLevel": "JAVA_25", "client": [ "ChatComponentMixin", + "ContainerArtMixin", "FontAccessor", "GuiToastsMixin", "HudFontMixin", diff --git a/src/test/java/uk/toakan/tad/huddable/LayoutCodeTest.java b/src/test/java/uk/toakan/tad/huddable/LayoutCodeTest.java index ca80aa1..2449703 100644 --- a/src/test/java/uk/toakan/tad/huddable/LayoutCodeTest.java +++ b/src/test/java/uk/toakan/tad/huddable/LayoutCodeTest.java @@ -105,6 +105,39 @@ void sizingMatchesShoppingList() { assertEquals(2f, Sizing.WINDOW.factor(0, 1080)); // GUI Scale "auto" reads as at least 1 } + @Test + void offsetsFollowTheSizingFactor() { + Layout layout = new Layout(); + layout.edit(Element.HOTBAR).dx = -40; + layout.edit(Element.HOTBAR).dy = 15; + // Not recorded yet (files from before): offsets draw as saved. + assertEquals(1f, layout.offsetScale(1.5f)); + + layout.offsetFactor = 1f; + assertEquals(1.5f, layout.offsetScale(1.5f)); + layout.rebaseOffsets(1.5f); + assertEquals(-60, layout.get(Element.HOTBAR).dx); + assertEquals(23, layout.get(Element.HOTBAR).dy); // 22.5 rounds up + assertEquals(1.5f, layout.offsetFactor); + assertEquals(1f, layout.offsetScale(1.5f)); + + layout.rebaseOffsets(1.5f); // again at the same factor: no change + assertEquals(-60, layout.get(Element.HOTBAR).dx); + } + + @Test + void offsetFactorTravelsInCodes() { + Layout layout = new Layout(); + layout.edit(Element.HOTBAR).dy = -30; + layout.offsetFactor = 1.25f; + assertEquals(1.25f, Layout.fromCode(layout.toCode()).offsetFactor); + + layout.offsetFactor = Float.NaN; + assertEquals(0f, Layout.fromCode(layout.toCode()).offsetFactor); + layout.offsetFactor = 500f; + assertEquals(0f, Layout.fromCode(layout.toCode()).offsetFactor); + } + @Test void rejectsOtherCodes() { assertNull(Layout.fromCode("SSL1:abc"));