Scripts: keyboard/mouse prompt icons for the newer retail game (WIP) #1594

Open
zohaiblazuli wants to merge 3 commits from upstream-pr/1604 into main
zohaiblazuli commented 2026-11-24 18:10:03 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by zohaiblazuli on 2026-11-24T18:10:03Z.


NOT ready to merge. This is the first version of keyboard/mouse prompt icons in XCL. It works on the first screen of the newer retail game, but most screens are unchecked (see Not tested). Please don't merge until it has been checked across the game. This PR is the home for this work: if you want to change or extend it (icons, other screens, other layouts, a different approach), please do it here, as commits or comments on this PR, rather than in a separate one.

The newer retail game shows Xbox buttons (A, B, X, Y …) in every prompt, even when it is played with XCL's keyboard and mouse mapping. This PR adds a script that replaces the game's button-icon library with keycaps and mouse icons for the keys XCL actually maps (A = ENTER, B = ESC, X = Q, Y = E, …), and docs covering how it was worked out. It changes nothing in XCL: the icons reach the game through XCL's existing overlay, as a patched copy of one archive in the title's XCL data folder. The game folder is never written, and no game data is in the diff.

In-game, before and after: Xbox icons vs keycaps, at rest and with the button held

In the game under XCL (account prompt, 2560×1440 window). Top: the game's own icons. Bottom: this PR. Right: Y / E held; the game's own press animation and tint apply to the new icons.

Evidence: the Xbox build has no keyboard/mouse icons (checked so far)

From python scripts/kbm_icons/survey.py <game>\data.rpf <game>\packs.rpf (reads only; entries found by content):

Archive Scaleform movies Icon libraries Symbols Platform prefixes
data.rpf (481 MB) 87 1: input_icons 38 Main_Button_N, all Xbox pad buttons platform_xbsx only
packs.rpf (4.8 GB) 0 0 – –
  • The three movies that show prompts (generic_movie, hud, map_scripted_movie) all load that one library.
  • The icon class's device list (DEVICE_PREFIXES) starts with a single empty entry: one icon set, no second device.
  • No identifier names a keyboard icon. The "mouse" names are the UI framework's cursor functions; "kbm" occurs only by chance inside binary data; "key" is a car dashboard light.
  • In the game, with a keyboard reported to it through GameInput, the title reads the keyboard but keeps showing Xbox icons.
  • Not searched yet: the other archives (about 130 GB).

Press animation (the game's own, applied to the keycaps)

The game's ActionScript class InputIconV2 animates whatever icon it places, so the keycaps get the same motion with nothing added. The GIFs replay its per-frame tables at 30 fps, with the press colours measured in the game:

Press / release Hold prompt Mash prompt Hint Pressed while disabled
press hold mash hint disabled
snaps to 80 %, black → #ABABAB; back in 5 frames still 14 frames, sinks to 80 % by frame 27 dip to 80 % and back, 9 frames a dip about once a second no shrink; a sideways shake, 11 frames

Master copy of the icons

All 38 icons, as selected now

docs/kbm-icons/icons-master.svg is the master file: one <symbol id="Main_Button_N"> per icon the game exports, and it opens as the sheet above. The build reads it.

If you change the icons, please post your updated icons-master.svg (and a picture of it) in this PR, so everyone can see each icon set side by side.

Method (details and all numbers in docs/kbm-icons/README.md)

  1. Find the library. The game has no keyboard icons. Its only button icons are one Scaleform movie, platform_xbsx.input_icons, in data.rpf: 38 vector symbols Main_Button_N, no bitmaps. The archive's table of contents is encrypted, but each entry is a plain zlib stream, so the movie is found by content. Nothing is decrypted.
  2. Map the symbols. I drew each symbol from its shape records: #30–33 are A B X Y, #34–37 LB LT RB RT, #38 Menu, #39 View, and the rest are the d-pad and sticks.
  3. Measure the style. A 64-unit square, a white plate, a 3-unit black outline, a black legend, and unlit parts in #676767. The keycaps use the same grid. Keys have a bottom lip, so they never read as a pad disc.
  4. Read the animation. The constants and per-frame tables come from the game's InputIconV2 class (table above). The icons scale about the point (32, 32).
  5. Measure the colours in the game. At rest the icon is multiplied by #F9F9F9. Held, #ABABAB is added: black turns #ABABAB, the plate turns #FFFFFF, and a keycap's grey lip clips to white, so a pressed key loses its lip.
  6. Build. The master SVG becomes DefineShape3 records. Letters are outlined from Windows' Bahnschrift Bold Condensed, one shape per solid contour. Every other tag of the user's own movie is kept as it is, and the result is packed to the original entry's exact sizes (28,148 bytes unpacked, 9,644 packed).
  7. Test and fix. The game gives every icon a fixed 64-unit slot, whatever its width. A first 112-wide ENTER ran into its PLAYER1 label, so wide keys are now 88 units, from x = −6 to 82. PLAYER1 to ENTER is now 16 px; the game's A disc sits 20 px away.

Design system

The design system's components

docs/kbm-icons/design-system/ is the whole design system as plain files, so anyone can adjust it:

  • README.md: rules, the key mapping and the screens.
  • tokens.json / tokens.css: colours, type and spacing, measured from the game's 4K frames.
  • One folder per component (Keycap, MouseGlyph, PromptItem, PromptBar, PromptStack, Icon library, Prompt motion), each with guidelines and an HTML preview that opens in a browser.
  • The mouse assets.

What is in it

  • scripts/kbm_icons/build_library.py: finds the icon library in the user's data.rpf, rebuilds it from the master SVG and writes the patched copy. It resolves and checks both output paths before writing. Each output is staged in a unique temporary file.
  • scripts/test_kbm_icon_outputs.py covers both output flags, Windows junctions and pre-existing hard links.
  • scripts/kbm_icons/keycaps.py: the icon designs; writes icons-master.svg and the Icon library preview.
  • scripts/kbm_icons/motion.py: the Prompt motion preview, built from the game's tables.
  • scripts/kbm_icons/survey.py: lists the UI movies and icon libraries in an archive (the evidence above).
  • docs/kbm-icons/README.md: how to try it, the method, the measurements and what is unchecked.
  • docs/kbm-icons/icons-master.svg: the master copy of the icons.
  • docs/kbm-icons/design-system/: the design system.
  • README.md: one line under Controls pointing to the docs.

Try it (needs Python 3.10+ and pip install fonttools):

python scripts/kbm_icons/build_library.py --game D:\Game --out "$env:LOCALAPPDATA\XCL\<title folder>\overlay\data.rpf"

Delete that overlay\data.rpf to undo.

The scripts, docs, design system and generated master SVG put the diff over the usual size, and that's deliberate: this is one feature that has to be reviewed and iterated as a whole, and it is meant to stay a single draft where everyone working on it can find it. Splitting it into the usual parts can happen before anything is merged.

Tested

  • Hardware: NVIDIA GeForce RTX 3060 (driver 617.42), Intel Core i5-14600K, Windows 11 build 26300, rustc 1.94.0.
  • cargo build --workspace && cargo test --workspace -- --test-threads=4 at the base commit, upstream/main 9e3831e: 776 passed, 0 failed, 41 ignored (20 test binaries). SKIPPED on this adapter: gpu_geometry_wave32_prefix_count_over_a_mask (no wave64), gpu_wave32_program_in_wave64_hardware (no wave64), heap_window_out_of_memory_falls_back_to_the_switch_form (no heap windows). The PR changes no Rust code, so the counts are those of the tree it adds files to.
  • The newer retail game under XCL (release build, XCL_NETWORK=0), with the overlay copy written by build_library.py from this branch:
    • the account prompt shows E and ↵ ENTER in place of Y and A;
    • holding E or Enter shrinks the key to 80 % and greys it; on release it springs back;
    • the label spacing was measured from the captures.
  • The tool's output matches the build tested in the game byte for byte (the movie content before padding). With a wrong --offset it scans the archive and finds the entry (9 s).
  • Output guard follow-up at 11e95c8 on Windows, Python 3.12.6. python -B -m unittest discover -s scripts -p 'test_*.py' -v ran 19 tests with 19 passed, 0 failed and 0 skipped. Both output flags rejected paths into the game folder, including through a junction. The hard-link test verified the original file stayed intact.
  • Ran build_library.py with both output flags pointing into a temporary directory. Both outputs were created from the retail archive and the source SHA-256 stayed the same.

Regression run

  • None: the PR doesn't change crates/xcl/src.

Not tested

  • Every screen after the account prompt. Runs with and without the icons both crashed during the loading slides after PLAYER1, at game+0x23cf683 (a null write), at 568 s and 509 s. So the settings screens, the HUD and the map, which use the same library, were not reached. The crash isn't caused by this PR, but it blocks checking it.
  • SHIFT, TAB, CTRL, the mouse icons, the WASD and arrow clusters, and the hold ring around a wide key, in the game.
  • Other data.rpf versions, layouts other than QWERTY (Q, E and WASD are read by key position), and screen sizes other than a 2560×1440 window.
  • AMD and other GPUs. The maintainer's RDNA4 run.
  • macOS and Linux: not built, not tested (the tool needs Windows' Bahnschrift).

AI use

  • Claude Code with Claude Opus 5.5 did the original implementation under my direction: it found and decoded the icon library and the InputIconV2 animation, measured the colours and spacing in the game, designed the icons, wrote the scripts, docs and design system, ran the tests and wrote this description. I directed the design and reviewed the results from the in-game captures.
  • Codex (exact model identifier unavailable) wrote and tested the output guard follow-up.

🤖 Generated with Claude Code

<!-- greyfinch-sync:ivall/xcl:issue:5477728414 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1604). Originally posted by [zohaiblazuli](https://github.com/zohaiblazuli) on 2026-11-24T18:10:03Z. --- > **NOT ready to merge.** This is the first version of keyboard/mouse prompt icons in XCL. It works on the first screen of the newer retail game, but most screens are unchecked (see **Not tested**). Please don't merge until it has been checked across the game. **This PR is the home for this work:** if you want to change or extend it (icons, other screens, other layouts, a different approach), please do it here, as commits or comments on this PR, rather than in a separate one. The newer retail game shows Xbox buttons (A, B, X, Y …) in every prompt, even when it is played with XCL's keyboard and mouse mapping. This PR adds a script that replaces the game's button-icon library with keycaps and mouse icons for the keys XCL actually maps (A = ENTER, B = ESC, X = Q, Y = E, …), and docs covering how it was worked out. It changes nothing in XCL: the icons reach the game through XCL's existing overlay, as a patched **copy** of one archive in the title's XCL data folder. The game folder is never written, and no game data is in the diff. ![In-game, before and after: Xbox icons vs keycaps, at rest and with the button held](https://raw.githubusercontent.com/zohaiblazuli/xcl/5cf3607a54a0b126cbac6fc77b82e5ecdeb0480b/ingame-before-after.png) *In the game under XCL (account prompt, 2560×1440 window). Top: the game's own icons. Bottom: this PR. Right: Y / E held; the game's own press animation and tint apply to the new icons.* ### Evidence: the Xbox build has no keyboard/mouse icons (checked so far) From `python scripts/kbm_icons/survey.py <game>\data.rpf <game>\packs.rpf` (reads only; entries found by content): | Archive | Scaleform movies | Icon libraries | Symbols | Platform prefixes | |---|---|---|---|---| | `data.rpf` (481 MB) | 87 | 1: `input_icons` | 38 `Main_Button_N`, all Xbox pad buttons | `platform_xbsx` only | | `packs.rpf` (4.8 GB) | 0 | 0 | – | – | - The three movies that show prompts (`generic_movie`, `hud`, `map_scripted_movie`) all load that one library. - The icon class's device list (`DEVICE_PREFIXES`) starts with a single empty entry: one icon set, no second device. - No identifier names a keyboard icon. The "mouse" names are the UI framework's cursor functions; "kbm" occurs only by chance inside binary data; "_key_" is a car dashboard light. - In the game, with a keyboard reported to it through GameInput, the title reads the keyboard but keeps showing Xbox icons. - Not searched yet: the other archives (about 130 GB). ### Press animation (the game's own, applied to the keycaps) The game's ActionScript class `InputIconV2` animates whatever icon it places, so the keycaps get the same motion with nothing added. The GIFs replay its per-frame tables at 30 fps, with the press colours measured in the game: | Press / release | Hold prompt | Mash prompt | Hint | Pressed while disabled | |---|---|---|---|---| | ![press](https://raw.githubusercontent.com/zohaiblazuli/xcl/5cf3607a54a0b126cbac6fc77b82e5ecdeb0480b/motion-press.gif) | ![hold](https://raw.githubusercontent.com/zohaiblazuli/xcl/5cf3607a54a0b126cbac6fc77b82e5ecdeb0480b/motion-hold.gif) | ![mash](https://raw.githubusercontent.com/zohaiblazuli/xcl/5cf3607a54a0b126cbac6fc77b82e5ecdeb0480b/motion-mash.gif) | ![hint](https://raw.githubusercontent.com/zohaiblazuli/xcl/5cf3607a54a0b126cbac6fc77b82e5ecdeb0480b/motion-hint.gif) | ![disabled](https://raw.githubusercontent.com/zohaiblazuli/xcl/5cf3607a54a0b126cbac6fc77b82e5ecdeb0480b/motion-disabled.gif) | | snaps to 80 %, black → #ABABAB; back in 5 frames | still 14 frames, sinks to 80 % by frame 27 | dip to 80 % and back, 9 frames | a dip about once a second | no shrink; a sideways shake, 11 frames | ### Master copy of the icons ![All 38 icons, as selected now](https://raw.githubusercontent.com/zohaiblazuli/xcl/5cf3607a54a0b126cbac6fc77b82e5ecdeb0480b/icons-master.png) [`docs/kbm-icons/icons-master.svg`](https://github.com/zohaiblazuli/xcl/blob/kbm-icon-library/docs/kbm-icons/icons-master.svg) is the master file: one `<symbol id="Main_Button_N">` per icon the game exports, and it opens as the sheet above. The build reads it. **If you change the icons, please post your updated `icons-master.svg` (and a picture of it) in this PR**, so everyone can see each icon set side by side. ### Method (details and all numbers in [`docs/kbm-icons/README.md`](https://github.com/zohaiblazuli/xcl/blob/kbm-icon-library/docs/kbm-icons/README.md)) 1. **Find the library.** The game has no keyboard icons. Its only button icons are one Scaleform movie, `platform_xbsx.input_icons`, in `data.rpf`: 38 vector symbols `Main_Button_N`, no bitmaps. The archive's table of contents is encrypted, but each entry is a plain zlib stream, so the movie is found by content. Nothing is decrypted. 2. **Map the symbols.** I drew each symbol from its shape records: #30–33 are A B X Y, #34–37 LB LT RB RT, #38 Menu, #39 View, and the rest are the d-pad and sticks. 3. **Measure the style.** A 64-unit square, a white plate, a 3-unit black outline, a black legend, and unlit parts in #676767. The keycaps use the same grid. Keys have a bottom lip, so they never read as a pad disc. 4. **Read the animation.** The constants and per-frame tables come from the game's `InputIconV2` class (table above). The icons scale about the point (32, 32). 5. **Measure the colours in the game.** At rest the icon is multiplied by #F9F9F9. Held, #ABABAB is added: black turns #ABABAB, the plate turns #FFFFFF, and a keycap's grey lip clips to white, so a pressed key loses its lip. 6. **Build.** The master SVG becomes DefineShape3 records. Letters are outlined from Windows' Bahnschrift Bold Condensed, one shape per solid contour. Every other tag of the user's own movie is kept as it is, and the result is packed to the original entry's exact sizes (28,148 bytes unpacked, 9,644 packed). 7. **Test and fix.** The game gives every icon a fixed 64-unit slot, whatever its width. A first 112-wide ENTER ran into its PLAYER1 label, so wide keys are now 88 units, from x = −6 to 82. PLAYER1 to ENTER is now 16 px; the game's A disc sits 20 px away. ### Design system ![The design system's components](https://raw.githubusercontent.com/zohaiblazuli/xcl/5cf3607a54a0b126cbac6fc77b82e5ecdeb0480b/design-system.png) [`docs/kbm-icons/design-system/`](https://github.com/zohaiblazuli/xcl/tree/kbm-icon-library/docs/kbm-icons/design-system) is the whole design system as plain files, so anyone can adjust it: - `README.md`: rules, the key mapping and the screens. - `tokens.json` / `tokens.css`: colours, type and spacing, measured from the game's 4K frames. - One folder per component (Keycap, MouseGlyph, PromptItem, PromptBar, PromptStack, Icon library, Prompt motion), each with guidelines and an HTML preview that opens in a browser. - The mouse assets. **What is in it** - `scripts/kbm_icons/build_library.py`: finds the icon library in the user's `data.rpf`, rebuilds it from the master SVG and writes the patched copy. It resolves and checks both output paths before writing. Each output is staged in a unique temporary file. - `scripts/test_kbm_icon_outputs.py` covers both output flags, Windows junctions and pre-existing hard links. - `scripts/kbm_icons/keycaps.py`: the icon designs; writes `icons-master.svg` and the Icon library preview. - `scripts/kbm_icons/motion.py`: the Prompt motion preview, built from the game's tables. - `scripts/kbm_icons/survey.py`: lists the UI movies and icon libraries in an archive (the evidence above). - `docs/kbm-icons/README.md`: how to try it, the method, the measurements and what is unchecked. - `docs/kbm-icons/icons-master.svg`: the master copy of the icons. - `docs/kbm-icons/design-system/`: the design system. - `README.md`: one line under Controls pointing to the docs. Try it (needs Python 3.10+ and `pip install fonttools`): ```powershell python scripts/kbm_icons/build_library.py --game D:\Game --out "$env:LOCALAPPDATA\XCL\<title folder>\overlay\data.rpf" ``` Delete that `overlay\data.rpf` to undo. The scripts, docs, design system and generated master SVG put the diff over the usual size, and that's deliberate: this is one feature that has to be reviewed and iterated as a whole, and it is meant to stay a single draft where everyone working on it can find it. Splitting it into the usual parts can happen before anything is merged. **Tested** - Hardware: NVIDIA GeForce RTX 3060 (driver 617.42), Intel Core i5-14600K, Windows 11 build 26300, `rustc 1.94.0`. - `cargo build --workspace && cargo test --workspace -- --test-threads=4` at the base commit, `upstream/main` 9e3831e: **776 passed, 0 failed, 41 ignored** (20 test binaries). SKIPPED on this adapter: `gpu_geometry_wave32_prefix_count_over_a_mask` (no wave64), `gpu_wave32_program_in_wave64_hardware` (no wave64), `heap_window_out_of_memory_falls_back_to_the_switch_form` (no heap windows). The PR changes no Rust code, so the counts are those of the tree it adds files to. - The newer retail game under XCL (release build, `XCL_NETWORK=0`), with the overlay copy written by `build_library.py` from this branch: - the account prompt shows `E` and `↵ ENTER` in place of Y and A; - holding E or Enter shrinks the key to 80 % and greys it; on release it springs back; - the label spacing was measured from the captures. - The tool's output matches the build tested in the game byte for byte (the movie content before padding). With a wrong `--offset` it scans the archive and finds the entry (9 s). - Output guard follow-up at `11e95c8` on Windows, Python 3.12.6. `python -B -m unittest discover -s scripts -p 'test_*.py' -v` ran 19 tests with 19 passed, 0 failed and 0 skipped. Both output flags rejected paths into the game folder, including through a junction. The hard-link test verified the original file stayed intact. - Ran `build_library.py` with both output flags pointing into a temporary directory. Both outputs were created from the retail archive and the source SHA-256 stayed the same. **Regression run** - None: the PR doesn't change `crates/xcl/src`. **Not tested** - Every screen after the account prompt. Runs with and without the icons both crashed during the loading slides after PLAYER1, at `game+0x23cf683` (a null write), at 568 s and 509 s. So the settings screens, the HUD and the map, which use the same library, were not reached. The crash isn't caused by this PR, but it blocks checking it. - `SHIFT`, `TAB`, `CTRL`, the mouse icons, the WASD and arrow clusters, and the hold ring around a wide key, in the game. - Other `data.rpf` versions, layouts other than QWERTY (Q, E and WASD are read by key position), and screen sizes other than a 2560×1440 window. - AMD and other GPUs. The maintainer's RDNA4 run. - macOS and Linux: not built, not tested (the tool needs Windows' Bahnschrift). **AI use** - Claude Code with Claude Opus 5.5 did the original implementation under my direction: it found and decoded the icon library and the `InputIconV2` animation, measured the colours and spacing in the game, designed the icons, wrote the scripts, docs and design system, ran the tests and wrote this description. I directed the design and reviewed the results from the in-game captures. - Codex (exact model identifier unavailable) wrote and tested the output guard follow-up. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
gut0to commented 2026-11-24 18:15:36 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by gut0to on 2026-11-24T18:15:36Z.

Review: COMMENTED


AI-assisted review; I verified both output paths in the diff.

<!-- greyfinch-sync:ivall/xcl:review:6044867018 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1604#pullrequestreview-6044867018). Originally posted by [gut0to](https://github.com/gut0to) on 2026-11-24T18:15:36Z. **Review:** COMMENTED --- AI-assisted review; I verified both output paths in the diff.
gut0to commented 2026-11-24 18:24:40 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by gut0to on 2026-11-24T18:24:40Z.

Review: COMMENTED


Rechecked on this updated head; the issue is still present.

<!-- greyfinch-sync:ivall/xcl:review:6044998023 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1604#pullrequestreview-6044998023). Originally posted by [gut0to](https://github.com/gut0to) on 2026-11-24T18:24:40Z. **Review:** COMMENTED --- Rechecked on this updated head; the issue is still present.
zohaiblazuli commented 2026-11-24 19:06:42 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by zohaiblazuli on 2026-11-24T18:25:39Z.

Review: COMMENTED


No description provided.

<!-- greyfinch-sync:ivall/xcl:review:6045010944 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1604#pullrequestreview-6045010944). Originally posted by [zohaiblazuli](https://github.com/zohaiblazuli) on 2026-11-24T18:25:39Z. **Review:** COMMENTED --- _No description provided._
zohaiblazuli commented 2026-11-24 19:06:43 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by zohaiblazuli on 2026-11-24T18:30:59Z.

Review: COMMENTED


No description provided.

<!-- greyfinch-sync:ivall/xcl:review:6045082432 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1604#pullrequestreview-6045082432). Originally posted by [zohaiblazuli](https://github.com/zohaiblazuli) on 2026-11-24T18:30:59Z. **Review:** COMMENTED --- _No description provided._
gut0to commented 2026-11-24 19:08:00 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by gut0to on 2026-11-24T18:15:36Z.

Code review location: scripts/kbm_icons/build_library.py; line 444

@@ -0,0 +1,462 @@
+r"""Build the keyboard/mouse icon library for the retail title and write it into a COPY of its data.rpf.
+
+    python scripts/kbm_icons/build_library.py --game D:\Game --out %LOCALAPPDATA%\XCL\<title>\overlay\data.rpf
+
+XCL reads a game file from the title's overlay folder when one is there (crates/xcl/src/vfs.rs), so the
+patched copy replaces the original without touching the game folder. Delete the copy to undo.
+
+What it does (details and measurements: docs/kbm-icons/README.md):
+1. Finds the title's `platform_xbsx.input_icons` movie in data.rpf. Each archive entry is a plain zlib
+   stream; nothing is decrypted. The entry is at a known offset in the version we have, checked by content,
+   with a scan of the archive as a fallback.
+2. Rebuilds that movie: the 38 `Main_Button_N` sprites and their shapes come from icons-master.svg; every
+   other tag (the movie's own script, exports, symbol classes) is copied from the user's file as it is.
+3. Packs it to the original entry's exact sizes (unpacked and zlib), so the archive's table of contents
+   still describes it, and writes data.rpf with only that entry changed.
+
+Supported SVG in the master file: <g transform="translate(x y)">, <rect rx>, <polygon>, <path> with absolute
+M L H V Q A Z, <text> (outlined from Windows' Bahnschrift Bold Condensed), fill / stroke / stroke-width as
+attributes, #rgb or #rrggbb colours. Units are the library's (1 unit = 20 twips; a symbol is 64 tall).
+Needs Python 3.10+ and fontTools (MIT).
+"""
+import math, re, struct, sys, os, zlib
+import xml.etree.ElementTree as ET
+
+
+TW = 20
+
+# ── font ─────────────────────────────────────────────────────────────────────
+_font = None
+
+
+def font():
+    global _font
+    if _font is None:
+        from fontTools.ttLib import TTFont
+        from fontTools.varLib import instancer
+        f = TTFont(r"C:\Windows\Fonts\bahnschrift.ttf")
+        _font = instancer.instantiateVariableFont(f, {"wght": 700, "wdth": 75})
+    return _font
+
+
+def glyph_contours(ch):
+    """Contours of one glyph in font units, y-up, as lists of segments ('L', p0, p1) / ('Q', p0, c, p1)."""
+    from fontTools.pens.basePen import BasePen
+    f = font(); gs = f.getGlyphSet(); name = f.getBestCmap()[ord(ch)]
+
+    class P(BasePen):
+        def __init__(s): super().__init__(gs); s.cs = []; s.cur = None; s.start = None
+        def _moveTo(s, p): s.cs.append([]); s.cur = s.start = p
+        def _lineTo(s, p): s.cs[-1].append(("L", s.cur, p)); s.cur = p
+        def _qCurveToOne(s, c, p): s.cs[-1].append(("Q", s.cur, c, p)); s.cur = p
+        def _curveToOne(s, c1, c2, p):  # cubic → two quads (Bahnschrift is quadratic; kept for safety)
+            m = ((c1[0] + c2[0]) / 2, (c1[1] + c2[1]) / 2)
+            s._qCurveToOne(((s.cur[0] + 3 * c1[0]) / 4, (s.cur[1] + 3 * c1[1]) / 4), m)
+            s._qCurveToOne(((3 * c2[0] + p[0]) / 4, (3 * c2[1] + p[1]) / 4), p)
+        def _closePath(s):
+            if s.cur != s.start: s.cs[-1].append(("L", s.cur, s.start)); s.cur = s.start
+        _endPath = _closePath
+    pen = P(); gs[name].draw(pen)
+    return pen.cs, gs[name].width
+
+
+def text_contours(s, x, y, fs, anchor, text_length):
+    """SVG text → contours in symbol units (y-down). The cap height matches the SVG design (0.7 em)."""
+    f = font(); cap_font = f["OS/2"].sCapHeight
+    k = (fs * 0.7) / cap_font
+    adv = 0; glyphs = []
+    for ch in s:
+        cs, w = glyph_contours(ch); glyphs.append((adv, cs)); adv += w
+    width = adv * k
+    sx = k
+    if text_length:
+        sx = text_length / adv; width = text_length
+    x0 = x - width / 2 if anchor == "middle" else x
+    out = []
+    for gx, cs in glyphs:
+        for c in cs:
+            out.append([tuple([seg[0]] + [(x0 + (gx + px) * sx, y - py * k) for px, py in seg[1:]]) for seg in c])
+    return out
+
+
+# ── SVG geometry ─────────────────────────────────────────────────────────────
+
+def arc_to_quads(p0, rx, ry, rot, large, sweep, p1):
+    """SVG elliptical arc → quadratic segments (each ≤ 45°)."""
+    x1, y1 = p0; x2, y2 = p1
+    if rx == 0 or ry == 0: return [("L", p0, p1)]
+    phi = math.radians(rot); cp, sp = math.cos(phi), math.sin(phi)
+    dx, dy = (x1 - x2) / 2, (y1 - y2) / 2
+    x1p, y1p = cp * dx + sp * dy, -sp * dx + cp * dy
+    lam = (x1p / rx) ** 2 + (y1p / ry) ** 2
+    if lam > 1: rx *= math.sqrt(lam); ry *= math.sqrt(lam)
+    num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p
+    den = rx * rx * y1p * y1p + ry * ry * x1p * x1p
+    co = math.sqrt(max(0, num / den)) if den else 0
+    if large == sweep: co = -co
+    cxp, cyp = co * rx * y1p / ry, -co * ry * x1p / rx
+    cx = cp * cxp - sp * cyp + (x1 + x2) / 2; cy = sp * cxp + cp * cyp + (y1 + y2) / 2
+    ang = lambda ux, uy, vx, vy: math.atan2(ux * vy - uy * vx, ux * vx + uy * vy)
+    t1 = ang(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry)
+    dt = ang((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry)
+    if not sweep and dt > 0: dt -= 2 * math.pi
+    if sweep and dt < 0: dt += 2 * math.pi
+    n = max(1, math.ceil(abs(dt) / (math.pi / 2 if max(rx, ry) <= 14 else math.pi / 3) - 1e-9)); h = dt / n  # 90 deg pieces for corners, 60 for big rings
+    pt = lambda t: (cx + rx * math.cos(t) * cp - ry * math.sin(t) * sp, cy + rx * math.cos(t) * sp + ry * math.sin(t) * cp)
+    segs = []; cur = p0
+    for i in range(n):
+        ta, tb = t1 + i * h, t1 + (i + 1) * h; tm = (ta + tb) / 2
+        e = 1 / math.cos(h / 2)
+        c = (cx + rx * e * math.cos(tm) * cp - ry * e * math.sin(tm) * sp, cy + rx * e * math.cos(tm) * sp + ry * e * math.sin(tm) * cp)
+        nxt = p1 if i == n - 1 else pt(tb)
+        segs.append(("Q", cur, c, nxt)); cur = nxt
+    return segs
+
+
+def path_contours(d):
+    toks = re.findall(r"[MLHVAQZ]|-?\d*\.?\d+(?:e-?\d+)?", d)
+    i = 0; cs = []; cur = start = (0, 0); cmd = None
+    def num():
+        nonlocal i; v = float(toks[i]); i += 1; return v
+    while i < len(toks):
+        if re.match(r"[A-Z]", toks[i]): cmd = toks[i]; i += 1
+        if cmd == "M": cur = start = (num(), num()); cs.append([]); cmd = "L"; continue
+        if cmd == "Z":
+            if cs and cur != start: cs[-1].append(("L", cur, start))
+            cur = start; continue
+        if cmd == "L": p = (num(), num()); cs[-1].append(("L", cur, p)); cur = p
+        elif cmd == "H": p = (num(), cur[1]); cs[-1].append(("L", cur, p)); cur = p
+        elif cmd == "V": p = (cur[0], num()); cs[-1].append(("L", cur, p)); cur = p
+        elif cmd == "Q": c = (num(), num()); p = (num(), num()); cs[-1].append(("Q", cur, c, p)); cur = p
+        elif cmd == "A":
+            rx, ry, rot, la, sw = num(), num(), num(), num(), num(); p = (num(), num())
+            cs[-1].extend(arc_to_quads(cur, rx, ry, rot, int(la), int(sw), p)); cur = p
+        else: raise ValueError(cmd)
+    return [c for c in cs if c]
+
+
+def rect_contours(x, y, w, h, r):
+    r = min(r, w / 2, h / 2)
+    if r <= 0:
+        return path_contours(f"M{x} {y} H{x + w} V{y + h} H{x} Z")
+    return path_contours(f"M{x + r} {y} H{x + w - r} A{r} {r} 0 0 1 {x + w} {y + r} V{y + h - r} A{r} {r} 0 0 1 {x + w - r} {y + h} "
+                         f"H{x + r} A{r} {r} 0 0 1 {x} {y + h - r} V{y + r} A{r} {r} 0 0 1 {x + r} {y} Z")
+
+
+def color(v):
+    if not v or v == "none": return None
+    v = v.lstrip("#")
+    if len(v) == 3: v = "".join(c * 2 for c in v)
+    return (int(v[0:2], 16), int(v[2:4], 16), int(v[4:6], 16), 255)
+
+
+def elements(svg):
+    """Yield (contours, fill, stroke, stroke_width) for each drawable element, in paint order.
+    `svg` is an SVG fragment (text) or an element whose children are drawn (a master-file <symbol>)."""
+    root = ET.fromstring(f"<g>{svg}</g>") if isinstance(svg, str) else svg
+
+    def walk(el, dx, dy):
+        tag = el.tag.split("}")[-1]
+        if tag == "g":
+            m = re.match(r"translate\(([-\d.e]+)\s+([-\d.e]+)\)", el.get("transform", "translate(0 0)"))
+            for c in el: yield from walk(c, dx + float(m.group(1)), dy + float(m.group(2)))
+            return
+        fill = color(el.get("fill", "#000")); stroke = color(el.get("stroke")); sw = float(el.get("stroke-width", "1"))
+        if tag == "rect":
+            cs = rect_contours(float(el.get("x")), float(el.get("y")), float(el.get("width")), float(el.get("height")), float(el.get("rx", 0)))
+        elif tag == "path":
+            cs = path_contours(el.get("d"))
+        elif tag == "polygon":
+            pts = [tuple(map(float, p.split(","))) for p in el.get("points").split()]
+            cs = [[("L", pts[i], pts[(i + 1) % len(pts)]) for i in range(len(pts))]]
+        elif tag == "text":
+            tl = el.get("textLength")
+            cs = text_contours(el.text, float(el.get("x")), float(el.get("y")), float(el.get("font-size")),
+                               el.get("text-anchor", "start"), float(tl) if tl else None)
+            stroke = None
+        else:
+            raise ValueError(tag)
+        cs = [[tuple([s[0]] + [(px + dx, py + dy) for px, py in s[1:]]) for s in c] for c in cs]
+        if tag == "text":
+            # Variable-font glyphs overlap (an E is a stem plus bars). Give every solid contour its own
+            # shape, with the holes it contains, so overlaps add up instead of cancelling (even-odd).
+            areas = [shoelace(c) for c in cs]
+            solid_sign = 1 if areas[max(range(len(cs)), key=lambda i: abs(areas[i]))] > 0 else -1
+            solids = [i for i in range(len(cs)) if areas[i] * solid_sign > 0]
+            groups = {i: [cs[i]] for i in solids}
+            for i in range(len(cs)):
+                if i in groups: continue
+                p = cs[i][0][1]
+                owners = [j for j in solids if point_in([s[1] for s in cs[j]], p)]
+                if owners: groups[min(owners, key=lambda j: abs(areas[j]))].append(cs[i])
+            for i in solids: yield groups[i], fill, stroke, sw
+            return
+        yield cs, fill, stroke, sw
+
+    for el in root: yield from walk(el, 0, 0)
+
+
+# ── SWF writing ──────────────────────────────────────────────────────────────
+
+class BW:
+    def __init__(s): s.out = bytearray(); s.acc = 0; s.n = 0
+    def ub(s, v, n):
+        for i in range(n - 1, -1, -1):
+            s.acc = (s.acc << 1) | ((v >> i) & 1); s.n += 1
+            if s.n == 8: s.out.append(s.acc); s.acc = 0; s.n = 0
+    def sb(s, v, n): s.ub(v & ((1 << n) - 1), n)
+    def align(s):
+        if s.n: s.ub(0, 8 - s.n)
+    def bytes(s, b): s.align(); s.out += b
+
+
+def nbits_s(*vals):
+    n = 1
+    for v in vals:
+        while not (-(1 << (n - 1)) <= v < (1 << (n - 1))): n += 1
+    return n
+
+
+def write_rect(w, x0, x1, y0, y1):
+    n = nbits_s(x0, x1, y0, y1); w.ub(n, 5)
+    for v in (x0, x1, y0, y1): w.sb(v, n)
+    w.align()
+
+
+def shoelace(c):
+    a = 0
+    for s in c:
+        (x0, y0), (x1, y1) = s[1], s[-1]
+        a += x0 * y1 - x1 * y0
+    return a
+
+
+def point_in(poly, p):
+    x, y = p; inside = False; n = len(poly)
+    for i in range(n):
+        (x0, y0), (x1, y1) = poly[i], poly[(i + 1) % n]
+        if (y0 > y) != (y1 > y) and x < x0 + (y - y0) * (x1 - x0) / (y1 - y0): inside = not inside
+    return inside
+
+
+def define_shape3(sid, contours, fill, stroke, sw):
+    # integer twips, closing each contour exactly
+    q = lambda p: (round(p[0] * TW), round(p[1] * TW))
+    cs = [[tuple([s[0]] + [q(p) for p in s[1:]]) for s in c] for c in contours]
+    cs = [[s for s in c if not (s[0] == "L" and s[1] == s[2])] for c in cs]
+    cs = [c for c in cs if c]
+    closed = [c[0][1] == c[-1][-1] for c in cs]
+    polys = [[s[1] for s in c] for c in cs]
+    # nesting depth for even-odd fills
+    depth = []
+    for i, c in enumerate(cs):
+        t = c[0][1]; depth.append(sum(1 for j, pg in enumerate(polys) if j != i and closed[j] and point_in(pg, t)))
+    pad = round(sw * TW / 2) if stroke else 0
+    xs = [p[0] for c in cs for s in c for p in s[1:]]; ys = [p[1] for c in cs for s in c for p in s[1:]]
+    w = BW()
+    w.bytes(struct.pack("<H", sid))
+    write_rect(w, min(xs) - pad, max(xs) + pad, min(ys) - pad, max(ys) + pad)
+    fills = [fill] if fill else []; lines = [stroke] if stroke else []
+    w.bytes(bytes([len(fills)]))
+    for f in fills: w.bytes(bytes([0x00, *f]))
+    w.bytes(bytes([len(lines)]))
+    for l in lines: w.bytes(struct.pack("<H", round(sw * TW)) + bytes(l))
+    nf, nl = (1 if fills else 0), (1 if lines else 0)
+    w.ub(nf, 4); w.ub(nl, 4)
+    x = y = 0
+    for i, c in enumerate(cs):
+        f0 = f1 = 0
+        if fills and closed[i]:
+            interior_on_f0 = shoelace(c) > 0
+            filled_inside = depth[i] % 2 == 0
+            if interior_on_f0 == filled_inside: f0 = 1
+            else: f1 = 1
+        sx, sy = c[0][1]
+        # style change: moveTo + fill0 + fill1 (+ line)
+        flags = 0x01 | (0x02 if nf else 0) | (0x04 if nf else 0) | (0x08 if nl else 0)
+        w.ub(0, 1); w.ub(flags, 5)
+        n = nbits_s(sx, sy); w.ub(n, 5); w.sb(sx, n); w.sb(sy, n)
+        if nf: w.ub(f0, nf); w.ub(f1, nf)
+        if nl: w.ub(1, nl)
+        x, y = sx, sy
+        for s in c:
+            if s[0] == "L":
+                (ex, ey) = s[2]; dx, dy = ex - x, ey - y
+                n = max(nbits_s(dx, dy), 2)
+                w.ub(1, 1); w.ub(1, 1); w.ub(n - 2, 4); w.ub(1, 1); w.sb(dx, n); w.sb(dy, n)
+                x, y = ex, ey
+            else:
+                (cx, cy), (ex, ey) = s[2], s[3]
+                a, b, c2, d = cx - x, cy - y, ex - cx, ey - cy
+                n = max(nbits_s(a, b, c2, d), 2)
+                w.ub(1, 1); w.ub(0, 1); w.ub(n - 2, 4)
+                for v in (a, b, c2, d): w.sb(v, n)
+                x, y = ex, ey
+    w.ub(0, 6); w.align()
+    return bytes(w.out)
+
+
+def tag(code, body):
+    if len(body) < 63: return struct.pack("<H", code << 6 | len(body)) + body
+    return struct.pack("<HI", code << 6 | 63, len(body)) + body
+
+
+def read_tags(d, p, end):
+    while p < end:
+        h = struct.unpack_from("<H", d, p); hdr = p; p += 2; c, l = h[0] >> 6, h[0] & 63
+        if l == 63: l = struct.unpack_from("<I", d, p)[0]; p += 4
+        yield c, d[hdr:p + l], d[p:p + l]; p += l
+        if c == 0: break
+
+
+def build(d, symbols, target_len=None):
+    """d: the title's input_icons movie. symbols: {'Main_Button_N': SVG fragment or <symbol> element}.
+    Returns (new movie, its length before padding, number of shapes)."""
+    nb = d[8] >> 3; hdr_end = 8 + (5 + 4 * nb + 7) // 8 + 4
+    tags = list(read_tags(d, hdr_end, len(d)))
+    names = {}
+    for c, raw, body in tags:
+        if c == 76:
+            n = struct.unpack_from("<H", body)[0]; q = 2
+            for _ in range(n):
+                i = struct.unpack_from("<H", body, q)[0]; q += 2; e = body.index(b"\0", q); names[body[q:e].decode().split(".")[-1]] = i; q = e + 1
+    shapes = {}; shape_tags = []; sprite_tags = {}; next_id = 1
+    used = {struct.unpack_from("<H", body)[0] for c, _, body in tags if c == 39}
+    for nm, sid in sorted(((n, i) for n, i in names.items() if n.startswith("Main_Button_")), key=lambda kv: kv[1]):
+        if nm not in symbols: raise KeyError(f"no design for {nm}")
+        places = []
+        for cs, fill, stroke, sw in elements(symbols[nm]):
+            key = (repr(cs), fill, stroke, sw)
+            if key not in shapes:
+                while next_id in used: next_id += 1
+                shapes[key] = next_id; used.add(next_id)
+                shape_tags.append(tag(32, define_shape3(next_id, cs, fill, stroke, sw)))
+            places.append(shapes[key])
+        body = struct.pack("<HH", sid, 1)
+        for depth, ch in enumerate(places, 1):
+            body += tag(26, bytes([0x02]) + struct.pack("<HH", depth, ch))
+        body += tag(1, b"") + tag(0, b"")
+        sprite_tags[sid] = tag(39, body)
+    out = bytearray(d[:hdr_end]); inserted = False
+    for c, raw, body in tags:
+        if c == 32:
+            if not inserted: out += b"".join(shape_tags); inserted = True
+            continue
+        if c == 39:
+            sid = struct.unpack_from("<H", body)[0]
+            if not inserted: out += b"".join(shape_tags); inserted = True
+            out += sprite_tags[sid]; continue
+        out += raw
+    real = len(out)
+    if target_len:
+        if real > target_len: raise ValueError(f"movie is {real} bytes, over {target_len}")
+        out += bytes(target_len - real)
+    struct.pack_into("<I", out, 4, len(out))
+    return bytes(out), real, len(shape_tags)
+
+
+# ── data.rpf ────────────────────────────────────────────────────────────────
+
+KNOWN_OFFSET = 0x117d7000   # the entry in the data.rpf we have (481,544,304 bytes)
+MARK = b"platform_xbsx.input_icons"
+
+
+def read_stream(f, off, limit=1 << 20):
+    """Inflate the zlib stream at `off`. Returns (data, compressed size) or None."""
+    f.seek(off); buf = f.read(limit)
+    if len(buf) < 2 or buf[0] != 0x78: return None
+    d = zlib.decompressobj()
+    try: out = d.decompress(buf)
+    except zlib.error: return None
+    if not d.eof: return None
+    return out, len(buf) - len(d.unused_data)
+
+
+def is_icon_movie(data):
+    return data[:3] in (b"GFX", b"CFX") and MARK in data and b"Main_Button_" in data
+
+
+def find_entry(path, offset):
+    with open(path, "rb") as f:
+        hit = read_stream(f, offset)
+        if hit and is_icon_movie(hit[0]): return offset, hit[0], hit[1]
+        print(f"not at {offset:#x}; scanning {path} for the icon library...")
+        size = os.fstat(f.fileno()).st_size; base = 0; step = 64 << 20
+        while base < size:
+            f.seek(base); chunk = f.read(step + 16)
+            i = chunk.find(b"\x78\xda")
+            while 0 <= i < step:
+                off = base + i
+                if off % 16 == 0:
+                    hit = read_stream(f, off)
+                    if hit and is_icon_movie(hit[0]): return off, hit[0], hit[1]
+                i = chunk.find(b"\x78\xda", i + 1)
+            base += step
+    raise SystemExit("platform_xbsx.input_icons was not found in data.rpf")
+
+
+def pack_exact(movie, real, csize):
+    """A zlib stream of exactly `csize` bytes for `movie` (whose bytes after `real` are padding): the tail of the
+    padding gets seeded pseudo-random bytes until the compressed size lands on `csize`."""
+    import random
+    def comp(b):
+        c = zlib.compressobj(9, zlib.DEFLATED, 15, 9); return c.compress(b) + c.flush()
+    room = len(movie) - real
+    base = len(comp(movie))
+    if base > csize:
+        raise SystemExit(f"the new library packs to {base} bytes, over the original's {csize}: simplify the icons")
+    est = csize - base
+    for seed in range(400):
+        rnd = random.Random(seed); tail = bytes(rnd.getrandbits(8) for _ in range(room))
+        for n in range(max(0, est - 40), min(room, est + 40) + 1):
+            data = movie[:real] + bytes(room - n) + tail[:n]
+            c = comp(data)
+            if len(c) == csize: return c, data
+    raise SystemExit("could not pack the library to the original's exact compressed size")
+
+
+def load_master(path):
+    syms = {}
+    for el in ET.parse(path).getroot().iter():
+        if el.tag.split("}")[-1] == "symbol" and el.get("id", "").startswith("Main_Button_"):
+            syms[el.get("id")] = el
+    return syms
+
+
+def main():
+    import argparse, shutil
+    here = os.path.dirname(os.path.abspath(__file__))
+    ap = argparse.ArgumentParser(description="Build the keyboard/mouse icon library into a copy of data.rpf.")
+    ap.add_argument("--game", required=True, help="the title's game folder (holds data.rpf); only read")
+    ap.add_argument("--out", help="where to write the patched copy of data.rpf (the title's XCL overlay folder)")
+    ap.add_argument("--master", default=os.path.join(here, "..", "..", "docs", "kbm-icons", "icons-master.svg"))
+    ap.add_argument("--offset", type=lambda v: int(v, 0), default=KNOWN_OFFSET)
+    ap.add_argument("--movie-out", help="also write the rebuilt movie here (made from game data: keep it local)")
+    a = ap.parse_args()
+    src = os.path.join(a.game, "data.rpf")
+    off, orig, csize = find_entry(src, a.offset)
+    movie, real, nshapes = build(orig, load_master(a.master), target_len=len(orig))
+    c, data = pack_exact(movie, real, csize)
+    assert zlib.decompress(c) == data and len(data) == len(orig) and len(c) == csize
+    print(f"input_icons at {off:#x}: {len(orig)} bytes ({csize} packed); new library {real} bytes, "
+          f"{nshapes} shapes, packed to {len(c)} bytes")
+    if a.movie_out:
+        with open(a.movie_out, "wb") as f: f.write(data)

--movie-out is written before the game-folder check, which only validates --out, so pointing it into the game modifies the original installation despite the stated guarantee. The --out check also compares abspath strings without resolving symlinks, so a junction or symlink can target the game and bypass it. Please resolve and validate both destinations before either write. AI-assisted review; I checked both paths in this diff.

<!-- greyfinch-sync:ivall/xcl:review-comment:4684520120 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1604#discussion_r4684520120). Originally posted by [gut0to](https://github.com/gut0to) on 2026-11-24T18:15:36Z. **Code review location:** `scripts/kbm_icons/build_library.py`; line 444 ~~~~diff @@ -0,0 +1,462 @@ +r"""Build the keyboard/mouse icon library for the retail title and write it into a COPY of its data.rpf. + + python scripts/kbm_icons/build_library.py --game D:\Game --out %LOCALAPPDATA%\XCL\<title>\overlay\data.rpf + +XCL reads a game file from the title's overlay folder when one is there (crates/xcl/src/vfs.rs), so the +patched copy replaces the original without touching the game folder. Delete the copy to undo. + +What it does (details and measurements: docs/kbm-icons/README.md): +1. Finds the title's `platform_xbsx.input_icons` movie in data.rpf. Each archive entry is a plain zlib + stream; nothing is decrypted. The entry is at a known offset in the version we have, checked by content, + with a scan of the archive as a fallback. +2. Rebuilds that movie: the 38 `Main_Button_N` sprites and their shapes come from icons-master.svg; every + other tag (the movie's own script, exports, symbol classes) is copied from the user's file as it is. +3. Packs it to the original entry's exact sizes (unpacked and zlib), so the archive's table of contents + still describes it, and writes data.rpf with only that entry changed. + +Supported SVG in the master file: <g transform="translate(x y)">, <rect rx>, <polygon>, <path> with absolute +M L H V Q A Z, <text> (outlined from Windows' Bahnschrift Bold Condensed), fill / stroke / stroke-width as +attributes, #rgb or #rrggbb colours. Units are the library's (1 unit = 20 twips; a symbol is 64 tall). +Needs Python 3.10+ and fontTools (MIT). +""" +import math, re, struct, sys, os, zlib +import xml.etree.ElementTree as ET + + +TW = 20 + +# ── font ───────────────────────────────────────────────────────────────────── +_font = None + + +def font(): + global _font + if _font is None: + from fontTools.ttLib import TTFont + from fontTools.varLib import instancer + f = TTFont(r"C:\Windows\Fonts\bahnschrift.ttf") + _font = instancer.instantiateVariableFont(f, {"wght": 700, "wdth": 75}) + return _font + + +def glyph_contours(ch): + """Contours of one glyph in font units, y-up, as lists of segments ('L', p0, p1) / ('Q', p0, c, p1).""" + from fontTools.pens.basePen import BasePen + f = font(); gs = f.getGlyphSet(); name = f.getBestCmap()[ord(ch)] + + class P(BasePen): + def __init__(s): super().__init__(gs); s.cs = []; s.cur = None; s.start = None + def _moveTo(s, p): s.cs.append([]); s.cur = s.start = p + def _lineTo(s, p): s.cs[-1].append(("L", s.cur, p)); s.cur = p + def _qCurveToOne(s, c, p): s.cs[-1].append(("Q", s.cur, c, p)); s.cur = p + def _curveToOne(s, c1, c2, p): # cubic → two quads (Bahnschrift is quadratic; kept for safety) + m = ((c1[0] + c2[0]) / 2, (c1[1] + c2[1]) / 2) + s._qCurveToOne(((s.cur[0] + 3 * c1[0]) / 4, (s.cur[1] + 3 * c1[1]) / 4), m) + s._qCurveToOne(((3 * c2[0] + p[0]) / 4, (3 * c2[1] + p[1]) / 4), p) + def _closePath(s): + if s.cur != s.start: s.cs[-1].append(("L", s.cur, s.start)); s.cur = s.start + _endPath = _closePath + pen = P(); gs[name].draw(pen) + return pen.cs, gs[name].width + + +def text_contours(s, x, y, fs, anchor, text_length): + """SVG text → contours in symbol units (y-down). The cap height matches the SVG design (0.7 em).""" + f = font(); cap_font = f["OS/2"].sCapHeight + k = (fs * 0.7) / cap_font + adv = 0; glyphs = [] + for ch in s: + cs, w = glyph_contours(ch); glyphs.append((adv, cs)); adv += w + width = adv * k + sx = k + if text_length: + sx = text_length / adv; width = text_length + x0 = x - width / 2 if anchor == "middle" else x + out = [] + for gx, cs in glyphs: + for c in cs: + out.append([tuple([seg[0]] + [(x0 + (gx + px) * sx, y - py * k) for px, py in seg[1:]]) for seg in c]) + return out + + +# ── SVG geometry ───────────────────────────────────────────────────────────── + +def arc_to_quads(p0, rx, ry, rot, large, sweep, p1): + """SVG elliptical arc → quadratic segments (each ≤ 45°).""" + x1, y1 = p0; x2, y2 = p1 + if rx == 0 or ry == 0: return [("L", p0, p1)] + phi = math.radians(rot); cp, sp = math.cos(phi), math.sin(phi) + dx, dy = (x1 - x2) / 2, (y1 - y2) / 2 + x1p, y1p = cp * dx + sp * dy, -sp * dx + cp * dy + lam = (x1p / rx) ** 2 + (y1p / ry) ** 2 + if lam > 1: rx *= math.sqrt(lam); ry *= math.sqrt(lam) + num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p + den = rx * rx * y1p * y1p + ry * ry * x1p * x1p + co = math.sqrt(max(0, num / den)) if den else 0 + if large == sweep: co = -co + cxp, cyp = co * rx * y1p / ry, -co * ry * x1p / rx + cx = cp * cxp - sp * cyp + (x1 + x2) / 2; cy = sp * cxp + cp * cyp + (y1 + y2) / 2 + ang = lambda ux, uy, vx, vy: math.atan2(ux * vy - uy * vx, ux * vx + uy * vy) + t1 = ang(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry) + dt = ang((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry) + if not sweep and dt > 0: dt -= 2 * math.pi + if sweep and dt < 0: dt += 2 * math.pi + n = max(1, math.ceil(abs(dt) / (math.pi / 2 if max(rx, ry) <= 14 else math.pi / 3) - 1e-9)); h = dt / n # 90 deg pieces for corners, 60 for big rings + pt = lambda t: (cx + rx * math.cos(t) * cp - ry * math.sin(t) * sp, cy + rx * math.cos(t) * sp + ry * math.sin(t) * cp) + segs = []; cur = p0 + for i in range(n): + ta, tb = t1 + i * h, t1 + (i + 1) * h; tm = (ta + tb) / 2 + e = 1 / math.cos(h / 2) + c = (cx + rx * e * math.cos(tm) * cp - ry * e * math.sin(tm) * sp, cy + rx * e * math.cos(tm) * sp + ry * e * math.sin(tm) * cp) + nxt = p1 if i == n - 1 else pt(tb) + segs.append(("Q", cur, c, nxt)); cur = nxt + return segs + + +def path_contours(d): + toks = re.findall(r"[MLHVAQZ]|-?\d*\.?\d+(?:e-?\d+)?", d) + i = 0; cs = []; cur = start = (0, 0); cmd = None + def num(): + nonlocal i; v = float(toks[i]); i += 1; return v + while i < len(toks): + if re.match(r"[A-Z]", toks[i]): cmd = toks[i]; i += 1 + if cmd == "M": cur = start = (num(), num()); cs.append([]); cmd = "L"; continue + if cmd == "Z": + if cs and cur != start: cs[-1].append(("L", cur, start)) + cur = start; continue + if cmd == "L": p = (num(), num()); cs[-1].append(("L", cur, p)); cur = p + elif cmd == "H": p = (num(), cur[1]); cs[-1].append(("L", cur, p)); cur = p + elif cmd == "V": p = (cur[0], num()); cs[-1].append(("L", cur, p)); cur = p + elif cmd == "Q": c = (num(), num()); p = (num(), num()); cs[-1].append(("Q", cur, c, p)); cur = p + elif cmd == "A": + rx, ry, rot, la, sw = num(), num(), num(), num(), num(); p = (num(), num()) + cs[-1].extend(arc_to_quads(cur, rx, ry, rot, int(la), int(sw), p)); cur = p + else: raise ValueError(cmd) + return [c for c in cs if c] + + +def rect_contours(x, y, w, h, r): + r = min(r, w / 2, h / 2) + if r <= 0: + return path_contours(f"M{x} {y} H{x + w} V{y + h} H{x} Z") + return path_contours(f"M{x + r} {y} H{x + w - r} A{r} {r} 0 0 1 {x + w} {y + r} V{y + h - r} A{r} {r} 0 0 1 {x + w - r} {y + h} " + f"H{x + r} A{r} {r} 0 0 1 {x} {y + h - r} V{y + r} A{r} {r} 0 0 1 {x + r} {y} Z") + + +def color(v): + if not v or v == "none": return None + v = v.lstrip("#") + if len(v) == 3: v = "".join(c * 2 for c in v) + return (int(v[0:2], 16), int(v[2:4], 16), int(v[4:6], 16), 255) + + +def elements(svg): + """Yield (contours, fill, stroke, stroke_width) for each drawable element, in paint order. + `svg` is an SVG fragment (text) or an element whose children are drawn (a master-file <symbol>).""" + root = ET.fromstring(f"<g>{svg}</g>") if isinstance(svg, str) else svg + + def walk(el, dx, dy): + tag = el.tag.split("}")[-1] + if tag == "g": + m = re.match(r"translate\(([-\d.e]+)\s+([-\d.e]+)\)", el.get("transform", "translate(0 0)")) + for c in el: yield from walk(c, dx + float(m.group(1)), dy + float(m.group(2))) + return + fill = color(el.get("fill", "#000")); stroke = color(el.get("stroke")); sw = float(el.get("stroke-width", "1")) + if tag == "rect": + cs = rect_contours(float(el.get("x")), float(el.get("y")), float(el.get("width")), float(el.get("height")), float(el.get("rx", 0))) + elif tag == "path": + cs = path_contours(el.get("d")) + elif tag == "polygon": + pts = [tuple(map(float, p.split(","))) for p in el.get("points").split()] + cs = [[("L", pts[i], pts[(i + 1) % len(pts)]) for i in range(len(pts))]] + elif tag == "text": + tl = el.get("textLength") + cs = text_contours(el.text, float(el.get("x")), float(el.get("y")), float(el.get("font-size")), + el.get("text-anchor", "start"), float(tl) if tl else None) + stroke = None + else: + raise ValueError(tag) + cs = [[tuple([s[0]] + [(px + dx, py + dy) for px, py in s[1:]]) for s in c] for c in cs] + if tag == "text": + # Variable-font glyphs overlap (an E is a stem plus bars). Give every solid contour its own + # shape, with the holes it contains, so overlaps add up instead of cancelling (even-odd). + areas = [shoelace(c) for c in cs] + solid_sign = 1 if areas[max(range(len(cs)), key=lambda i: abs(areas[i]))] > 0 else -1 + solids = [i for i in range(len(cs)) if areas[i] * solid_sign > 0] + groups = {i: [cs[i]] for i in solids} + for i in range(len(cs)): + if i in groups: continue + p = cs[i][0][1] + owners = [j for j in solids if point_in([s[1] for s in cs[j]], p)] + if owners: groups[min(owners, key=lambda j: abs(areas[j]))].append(cs[i]) + for i in solids: yield groups[i], fill, stroke, sw + return + yield cs, fill, stroke, sw + + for el in root: yield from walk(el, 0, 0) + + +# ── SWF writing ────────────────────────────────────────────────────────────── + +class BW: + def __init__(s): s.out = bytearray(); s.acc = 0; s.n = 0 + def ub(s, v, n): + for i in range(n - 1, -1, -1): + s.acc = (s.acc << 1) | ((v >> i) & 1); s.n += 1 + if s.n == 8: s.out.append(s.acc); s.acc = 0; s.n = 0 + def sb(s, v, n): s.ub(v & ((1 << n) - 1), n) + def align(s): + if s.n: s.ub(0, 8 - s.n) + def bytes(s, b): s.align(); s.out += b + + +def nbits_s(*vals): + n = 1 + for v in vals: + while not (-(1 << (n - 1)) <= v < (1 << (n - 1))): n += 1 + return n + + +def write_rect(w, x0, x1, y0, y1): + n = nbits_s(x0, x1, y0, y1); w.ub(n, 5) + for v in (x0, x1, y0, y1): w.sb(v, n) + w.align() + + +def shoelace(c): + a = 0 + for s in c: + (x0, y0), (x1, y1) = s[1], s[-1] + a += x0 * y1 - x1 * y0 + return a + + +def point_in(poly, p): + x, y = p; inside = False; n = len(poly) + for i in range(n): + (x0, y0), (x1, y1) = poly[i], poly[(i + 1) % n] + if (y0 > y) != (y1 > y) and x < x0 + (y - y0) * (x1 - x0) / (y1 - y0): inside = not inside + return inside + + +def define_shape3(sid, contours, fill, stroke, sw): + # integer twips, closing each contour exactly + q = lambda p: (round(p[0] * TW), round(p[1] * TW)) + cs = [[tuple([s[0]] + [q(p) for p in s[1:]]) for s in c] for c in contours] + cs = [[s for s in c if not (s[0] == "L" and s[1] == s[2])] for c in cs] + cs = [c for c in cs if c] + closed = [c[0][1] == c[-1][-1] for c in cs] + polys = [[s[1] for s in c] for c in cs] + # nesting depth for even-odd fills + depth = [] + for i, c in enumerate(cs): + t = c[0][1]; depth.append(sum(1 for j, pg in enumerate(polys) if j != i and closed[j] and point_in(pg, t))) + pad = round(sw * TW / 2) if stroke else 0 + xs = [p[0] for c in cs for s in c for p in s[1:]]; ys = [p[1] for c in cs for s in c for p in s[1:]] + w = BW() + w.bytes(struct.pack("<H", sid)) + write_rect(w, min(xs) - pad, max(xs) + pad, min(ys) - pad, max(ys) + pad) + fills = [fill] if fill else []; lines = [stroke] if stroke else [] + w.bytes(bytes([len(fills)])) + for f in fills: w.bytes(bytes([0x00, *f])) + w.bytes(bytes([len(lines)])) + for l in lines: w.bytes(struct.pack("<H", round(sw * TW)) + bytes(l)) + nf, nl = (1 if fills else 0), (1 if lines else 0) + w.ub(nf, 4); w.ub(nl, 4) + x = y = 0 + for i, c in enumerate(cs): + f0 = f1 = 0 + if fills and closed[i]: + interior_on_f0 = shoelace(c) > 0 + filled_inside = depth[i] % 2 == 0 + if interior_on_f0 == filled_inside: f0 = 1 + else: f1 = 1 + sx, sy = c[0][1] + # style change: moveTo + fill0 + fill1 (+ line) + flags = 0x01 | (0x02 if nf else 0) | (0x04 if nf else 0) | (0x08 if nl else 0) + w.ub(0, 1); w.ub(flags, 5) + n = nbits_s(sx, sy); w.ub(n, 5); w.sb(sx, n); w.sb(sy, n) + if nf: w.ub(f0, nf); w.ub(f1, nf) + if nl: w.ub(1, nl) + x, y = sx, sy + for s in c: + if s[0] == "L": + (ex, ey) = s[2]; dx, dy = ex - x, ey - y + n = max(nbits_s(dx, dy), 2) + w.ub(1, 1); w.ub(1, 1); w.ub(n - 2, 4); w.ub(1, 1); w.sb(dx, n); w.sb(dy, n) + x, y = ex, ey + else: + (cx, cy), (ex, ey) = s[2], s[3] + a, b, c2, d = cx - x, cy - y, ex - cx, ey - cy + n = max(nbits_s(a, b, c2, d), 2) + w.ub(1, 1); w.ub(0, 1); w.ub(n - 2, 4) + for v in (a, b, c2, d): w.sb(v, n) + x, y = ex, ey + w.ub(0, 6); w.align() + return bytes(w.out) + + +def tag(code, body): + if len(body) < 63: return struct.pack("<H", code << 6 | len(body)) + body + return struct.pack("<HI", code << 6 | 63, len(body)) + body + + +def read_tags(d, p, end): + while p < end: + h = struct.unpack_from("<H", d, p); hdr = p; p += 2; c, l = h[0] >> 6, h[0] & 63 + if l == 63: l = struct.unpack_from("<I", d, p)[0]; p += 4 + yield c, d[hdr:p + l], d[p:p + l]; p += l + if c == 0: break + + +def build(d, symbols, target_len=None): + """d: the title's input_icons movie. symbols: {'Main_Button_N': SVG fragment or <symbol> element}. + Returns (new movie, its length before padding, number of shapes).""" + nb = d[8] >> 3; hdr_end = 8 + (5 + 4 * nb + 7) // 8 + 4 + tags = list(read_tags(d, hdr_end, len(d))) + names = {} + for c, raw, body in tags: + if c == 76: + n = struct.unpack_from("<H", body)[0]; q = 2 + for _ in range(n): + i = struct.unpack_from("<H", body, q)[0]; q += 2; e = body.index(b"\0", q); names[body[q:e].decode().split(".")[-1]] = i; q = e + 1 + shapes = {}; shape_tags = []; sprite_tags = {}; next_id = 1 + used = {struct.unpack_from("<H", body)[0] for c, _, body in tags if c == 39} + for nm, sid in sorted(((n, i) for n, i in names.items() if n.startswith("Main_Button_")), key=lambda kv: kv[1]): + if nm not in symbols: raise KeyError(f"no design for {nm}") + places = [] + for cs, fill, stroke, sw in elements(symbols[nm]): + key = (repr(cs), fill, stroke, sw) + if key not in shapes: + while next_id in used: next_id += 1 + shapes[key] = next_id; used.add(next_id) + shape_tags.append(tag(32, define_shape3(next_id, cs, fill, stroke, sw))) + places.append(shapes[key]) + body = struct.pack("<HH", sid, 1) + for depth, ch in enumerate(places, 1): + body += tag(26, bytes([0x02]) + struct.pack("<HH", depth, ch)) + body += tag(1, b"") + tag(0, b"") + sprite_tags[sid] = tag(39, body) + out = bytearray(d[:hdr_end]); inserted = False + for c, raw, body in tags: + if c == 32: + if not inserted: out += b"".join(shape_tags); inserted = True + continue + if c == 39: + sid = struct.unpack_from("<H", body)[0] + if not inserted: out += b"".join(shape_tags); inserted = True + out += sprite_tags[sid]; continue + out += raw + real = len(out) + if target_len: + if real > target_len: raise ValueError(f"movie is {real} bytes, over {target_len}") + out += bytes(target_len - real) + struct.pack_into("<I", out, 4, len(out)) + return bytes(out), real, len(shape_tags) + + +# ── data.rpf ──────────────────────────────────────────────────────────────── + +KNOWN_OFFSET = 0x117d7000 # the entry in the data.rpf we have (481,544,304 bytes) +MARK = b"platform_xbsx.input_icons" + + +def read_stream(f, off, limit=1 << 20): + """Inflate the zlib stream at `off`. Returns (data, compressed size) or None.""" + f.seek(off); buf = f.read(limit) + if len(buf) < 2 or buf[0] != 0x78: return None + d = zlib.decompressobj() + try: out = d.decompress(buf) + except zlib.error: return None + if not d.eof: return None + return out, len(buf) - len(d.unused_data) + + +def is_icon_movie(data): + return data[:3] in (b"GFX", b"CFX") and MARK in data and b"Main_Button_" in data + + +def find_entry(path, offset): + with open(path, "rb") as f: + hit = read_stream(f, offset) + if hit and is_icon_movie(hit[0]): return offset, hit[0], hit[1] + print(f"not at {offset:#x}; scanning {path} for the icon library...") + size = os.fstat(f.fileno()).st_size; base = 0; step = 64 << 20 + while base < size: + f.seek(base); chunk = f.read(step + 16) + i = chunk.find(b"\x78\xda") + while 0 <= i < step: + off = base + i + if off % 16 == 0: + hit = read_stream(f, off) + if hit and is_icon_movie(hit[0]): return off, hit[0], hit[1] + i = chunk.find(b"\x78\xda", i + 1) + base += step + raise SystemExit("platform_xbsx.input_icons was not found in data.rpf") + + +def pack_exact(movie, real, csize): + """A zlib stream of exactly `csize` bytes for `movie` (whose bytes after `real` are padding): the tail of the + padding gets seeded pseudo-random bytes until the compressed size lands on `csize`.""" + import random + def comp(b): + c = zlib.compressobj(9, zlib.DEFLATED, 15, 9); return c.compress(b) + c.flush() + room = len(movie) - real + base = len(comp(movie)) + if base > csize: + raise SystemExit(f"the new library packs to {base} bytes, over the original's {csize}: simplify the icons") + est = csize - base + for seed in range(400): + rnd = random.Random(seed); tail = bytes(rnd.getrandbits(8) for _ in range(room)) + for n in range(max(0, est - 40), min(room, est + 40) + 1): + data = movie[:real] + bytes(room - n) + tail[:n] + c = comp(data) + if len(c) == csize: return c, data + raise SystemExit("could not pack the library to the original's exact compressed size") + + +def load_master(path): + syms = {} + for el in ET.parse(path).getroot().iter(): + if el.tag.split("}")[-1] == "symbol" and el.get("id", "").startswith("Main_Button_"): + syms[el.get("id")] = el + return syms + + +def main(): + import argparse, shutil + here = os.path.dirname(os.path.abspath(__file__)) + ap = argparse.ArgumentParser(description="Build the keyboard/mouse icon library into a copy of data.rpf.") + ap.add_argument("--game", required=True, help="the title's game folder (holds data.rpf); only read") + ap.add_argument("--out", help="where to write the patched copy of data.rpf (the title's XCL overlay folder)") + ap.add_argument("--master", default=os.path.join(here, "..", "..", "docs", "kbm-icons", "icons-master.svg")) + ap.add_argument("--offset", type=lambda v: int(v, 0), default=KNOWN_OFFSET) + ap.add_argument("--movie-out", help="also write the rebuilt movie here (made from game data: keep it local)") + a = ap.parse_args() + src = os.path.join(a.game, "data.rpf") + off, orig, csize = find_entry(src, a.offset) + movie, real, nshapes = build(orig, load_master(a.master), target_len=len(orig)) + c, data = pack_exact(movie, real, csize) + assert zlib.decompress(c) == data and len(data) == len(orig) and len(c) == csize + print(f"input_icons at {off:#x}: {len(orig)} bytes ({csize} packed); new library {real} bytes, " + f"{nshapes} shapes, packed to {len(c)} bytes") + if a.movie_out: + with open(a.movie_out, "wb") as f: f.write(data) ~~~~ --- `--movie-out` is written before the game-folder check, which only validates `--out`, so pointing it into the game modifies the original installation despite the stated guarantee. The `--out` check also compares `abspath` strings without resolving symlinks, so a junction or symlink can target the game and bypass it. Please resolve and validate both destinations before either write. AI-assisted review; I checked both paths in this diff.
gut0to commented 2026-11-24 19:08:00 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by gut0to on 2026-11-24T18:24:41Z.

Code review location: scripts/kbm_icons/build_library.py; line 444

@@ -0,0 +1,462 @@
+r"""Build the keyboard/mouse icon library for the retail title and write it into a COPY of its data.rpf.
+
+    python scripts/kbm_icons/build_library.py --game D:\Game --out %LOCALAPPDATA%\XCL\<title>\overlay\data.rpf
+
+XCL reads a game file from the title's overlay folder when one is there (crates/xcl/src/vfs.rs), so the
+patched copy replaces the original without touching the game folder. Delete the copy to undo.
+
+What it does (details and measurements: docs/kbm-icons/README.md):
+1. Finds the title's `platform_xbsx.input_icons` movie in data.rpf. Each archive entry is a plain zlib
+   stream; nothing is decrypted. The entry is at a known offset in the version we have, checked by content,
+   with a scan of the archive as a fallback.
+2. Rebuilds that movie: the 38 `Main_Button_N` sprites and their shapes come from icons-master.svg; every
+   other tag (the movie's own script, exports, symbol classes) is copied from the user's file as it is.
+3. Packs it to the original entry's exact sizes (unpacked and zlib), so the archive's table of contents
+   still describes it, and writes data.rpf with only that entry changed.
+
+Supported SVG in the master file: <g transform="translate(x y)">, <rect rx>, <polygon>, <path> with absolute
+M L H V Q A Z, <text> (outlined from Windows' Bahnschrift Bold Condensed), fill / stroke / stroke-width as
+attributes, #rgb or #rrggbb colours. Units are the library's (1 unit = 20 twips; a symbol is 64 tall).
+Needs Python 3.10+ and fontTools (MIT).
+"""
+import math, re, struct, sys, os, zlib
+import xml.etree.ElementTree as ET
+
+
+TW = 20
+
+# ── font ─────────────────────────────────────────────────────────────────────
+_font = None
+
+
+def font():
+    global _font
+    if _font is None:
+        from fontTools.ttLib import TTFont
+        from fontTools.varLib import instancer
+        f = TTFont(r"C:\Windows\Fonts\bahnschrift.ttf")
+        _font = instancer.instantiateVariableFont(f, {"wght": 700, "wdth": 75})
+    return _font
+
+
+def glyph_contours(ch):
+    """Contours of one glyph in font units, y-up, as lists of segments ('L', p0, p1) / ('Q', p0, c, p1)."""
+    from fontTools.pens.basePen import BasePen
+    f = font(); gs = f.getGlyphSet(); name = f.getBestCmap()[ord(ch)]
+
+    class P(BasePen):
+        def __init__(s): super().__init__(gs); s.cs = []; s.cur = None; s.start = None
+        def _moveTo(s, p): s.cs.append([]); s.cur = s.start = p
+        def _lineTo(s, p): s.cs[-1].append(("L", s.cur, p)); s.cur = p
+        def _qCurveToOne(s, c, p): s.cs[-1].append(("Q", s.cur, c, p)); s.cur = p
+        def _curveToOne(s, c1, c2, p):  # cubic → two quads (Bahnschrift is quadratic; kept for safety)
+            m = ((c1[0] + c2[0]) / 2, (c1[1] + c2[1]) / 2)
+            s._qCurveToOne(((s.cur[0] + 3 * c1[0]) / 4, (s.cur[1] + 3 * c1[1]) / 4), m)
+            s._qCurveToOne(((3 * c2[0] + p[0]) / 4, (3 * c2[1] + p[1]) / 4), p)
+        def _closePath(s):
+            if s.cur != s.start: s.cs[-1].append(("L", s.cur, s.start)); s.cur = s.start
+        _endPath = _closePath
+    pen = P(); gs[name].draw(pen)
+    return pen.cs, gs[name].width
+
+
+def text_contours(s, x, y, fs, anchor, text_length):
+    """SVG text → contours in symbol units (y-down). The cap height matches the SVG design (0.7 em)."""
+    f = font(); cap_font = f["OS/2"].sCapHeight
+    k = (fs * 0.7) / cap_font
+    adv = 0; glyphs = []
+    for ch in s:
+        cs, w = glyph_contours(ch); glyphs.append((adv, cs)); adv += w
+    width = adv * k
+    sx = k
+    if text_length:
+        sx = text_length / adv; width = text_length
+    x0 = x - width / 2 if anchor == "middle" else x
+    out = []
+    for gx, cs in glyphs:
+        for c in cs:
+            out.append([tuple([seg[0]] + [(x0 + (gx + px) * sx, y - py * k) for px, py in seg[1:]]) for seg in c])
+    return out
+
+
+# ── SVG geometry ─────────────────────────────────────────────────────────────
+
+def arc_to_quads(p0, rx, ry, rot, large, sweep, p1):
+    """SVG elliptical arc → quadratic segments (each ≤ 45°)."""
+    x1, y1 = p0; x2, y2 = p1
+    if rx == 0 or ry == 0: return [("L", p0, p1)]
+    phi = math.radians(rot); cp, sp = math.cos(phi), math.sin(phi)
+    dx, dy = (x1 - x2) / 2, (y1 - y2) / 2
+    x1p, y1p = cp * dx + sp * dy, -sp * dx + cp * dy
+    lam = (x1p / rx) ** 2 + (y1p / ry) ** 2
+    if lam > 1: rx *= math.sqrt(lam); ry *= math.sqrt(lam)
+    num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p
+    den = rx * rx * y1p * y1p + ry * ry * x1p * x1p
+    co = math.sqrt(max(0, num / den)) if den else 0
+    if large == sweep: co = -co
+    cxp, cyp = co * rx * y1p / ry, -co * ry * x1p / rx
+    cx = cp * cxp - sp * cyp + (x1 + x2) / 2; cy = sp * cxp + cp * cyp + (y1 + y2) / 2
+    ang = lambda ux, uy, vx, vy: math.atan2(ux * vy - uy * vx, ux * vx + uy * vy)
+    t1 = ang(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry)
+    dt = ang((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry)
+    if not sweep and dt > 0: dt -= 2 * math.pi
+    if sweep and dt < 0: dt += 2 * math.pi
+    n = max(1, math.ceil(abs(dt) / (math.pi / 2 if max(rx, ry) <= 14 else math.pi / 3) - 1e-9)); h = dt / n  # 90 deg pieces for corners, 60 for big rings
+    pt = lambda t: (cx + rx * math.cos(t) * cp - ry * math.sin(t) * sp, cy + rx * math.cos(t) * sp + ry * math.sin(t) * cp)
+    segs = []; cur = p0
+    for i in range(n):
+        ta, tb = t1 + i * h, t1 + (i + 1) * h; tm = (ta + tb) / 2
+        e = 1 / math.cos(h / 2)
+        c = (cx + rx * e * math.cos(tm) * cp - ry * e * math.sin(tm) * sp, cy + rx * e * math.cos(tm) * sp + ry * e * math.sin(tm) * cp)
+        nxt = p1 if i == n - 1 else pt(tb)
+        segs.append(("Q", cur, c, nxt)); cur = nxt
+    return segs
+
+
+def path_contours(d):
+    toks = re.findall(r"[MLHVAQZ]|-?\d*\.?\d+(?:e-?\d+)?", d)
+    i = 0; cs = []; cur = start = (0, 0); cmd = None
+    def num():
+        nonlocal i; v = float(toks[i]); i += 1; return v
+    while i < len(toks):
+        if re.match(r"[A-Z]", toks[i]): cmd = toks[i]; i += 1
+        if cmd == "M": cur = start = (num(), num()); cs.append([]); cmd = "L"; continue
+        if cmd == "Z":
+            if cs and cur != start: cs[-1].append(("L", cur, start))
+            cur = start; continue
+        if cmd == "L": p = (num(), num()); cs[-1].append(("L", cur, p)); cur = p
+        elif cmd == "H": p = (num(), cur[1]); cs[-1].append(("L", cur, p)); cur = p
+        elif cmd == "V": p = (cur[0], num()); cs[-1].append(("L", cur, p)); cur = p
+        elif cmd == "Q": c = (num(), num()); p = (num(), num()); cs[-1].append(("Q", cur, c, p)); cur = p
+        elif cmd == "A":
+            rx, ry, rot, la, sw = num(), num(), num(), num(), num(); p = (num(), num())
+            cs[-1].extend(arc_to_quads(cur, rx, ry, rot, int(la), int(sw), p)); cur = p
+        else: raise ValueError(cmd)
+    return [c for c in cs if c]
+
+
+def rect_contours(x, y, w, h, r):
+    r = min(r, w / 2, h / 2)
+    if r <= 0:
+        return path_contours(f"M{x} {y} H{x + w} V{y + h} H{x} Z")
+    return path_contours(f"M{x + r} {y} H{x + w - r} A{r} {r} 0 0 1 {x + w} {y + r} V{y + h - r} A{r} {r} 0 0 1 {x + w - r} {y + h} "
+                         f"H{x + r} A{r} {r} 0 0 1 {x} {y + h - r} V{y + r} A{r} {r} 0 0 1 {x + r} {y} Z")
+
+
+def color(v):
+    if not v or v == "none": return None
+    v = v.lstrip("#")
+    if len(v) == 3: v = "".join(c * 2 for c in v)
+    return (int(v[0:2], 16), int(v[2:4], 16), int(v[4:6], 16), 255)
+
+
+def elements(svg):
+    """Yield (contours, fill, stroke, stroke_width) for each drawable element, in paint order.
+    `svg` is an SVG fragment (text) or an element whose children are drawn (a master-file <symbol>)."""
+    root = ET.fromstring(f"<g>{svg}</g>") if isinstance(svg, str) else svg
+
+    def walk(el, dx, dy):
+        tag = el.tag.split("}")[-1]
+        if tag == "g":
+            m = re.match(r"translate\(([-\d.e]+)\s+([-\d.e]+)\)", el.get("transform", "translate(0 0)"))
+            for c in el: yield from walk(c, dx + float(m.group(1)), dy + float(m.group(2)))
+            return
+        fill = color(el.get("fill", "#000")); stroke = color(el.get("stroke")); sw = float(el.get("stroke-width", "1"))
+        if tag == "rect":
+            cs = rect_contours(float(el.get("x")), float(el.get("y")), float(el.get("width")), float(el.get("height")), float(el.get("rx", 0)))
+        elif tag == "path":
+            cs = path_contours(el.get("d"))
+        elif tag == "polygon":
+            pts = [tuple(map(float, p.split(","))) for p in el.get("points").split()]
+            cs = [[("L", pts[i], pts[(i + 1) % len(pts)]) for i in range(len(pts))]]
+        elif tag == "text":
+            tl = el.get("textLength")
+            cs = text_contours(el.text, float(el.get("x")), float(el.get("y")), float(el.get("font-size")),
+                               el.get("text-anchor", "start"), float(tl) if tl else None)
+            stroke = None
+        else:
+            raise ValueError(tag)
+        cs = [[tuple([s[0]] + [(px + dx, py + dy) for px, py in s[1:]]) for s in c] for c in cs]
+        if tag == "text":
+            # Variable-font glyphs overlap (an E is a stem plus bars). Give every solid contour its own
+            # shape, with the holes it contains, so overlaps add up instead of cancelling (even-odd).
+            areas = [shoelace(c) for c in cs]
+            solid_sign = 1 if areas[max(range(len(cs)), key=lambda i: abs(areas[i]))] > 0 else -1
+            solids = [i for i in range(len(cs)) if areas[i] * solid_sign > 0]
+            groups = {i: [cs[i]] for i in solids}
+            for i in range(len(cs)):
+                if i in groups: continue
+                p = cs[i][0][1]
+                owners = [j for j in solids if point_in([s[1] for s in cs[j]], p)]
+                if owners: groups[min(owners, key=lambda j: abs(areas[j]))].append(cs[i])
+            for i in solids: yield groups[i], fill, stroke, sw
+            return
+        yield cs, fill, stroke, sw
+
+    for el in root: yield from walk(el, 0, 0)
+
+
+# ── SWF writing ──────────────────────────────────────────────────────────────
+
+class BW:
+    def __init__(s): s.out = bytearray(); s.acc = 0; s.n = 0
+    def ub(s, v, n):
+        for i in range(n - 1, -1, -1):
+            s.acc = (s.acc << 1) | ((v >> i) & 1); s.n += 1
+            if s.n == 8: s.out.append(s.acc); s.acc = 0; s.n = 0
+    def sb(s, v, n): s.ub(v & ((1 << n) - 1), n)
+    def align(s):
+        if s.n: s.ub(0, 8 - s.n)
+    def bytes(s, b): s.align(); s.out += b
+
+
+def nbits_s(*vals):
+    n = 1
+    for v in vals:
+        while not (-(1 << (n - 1)) <= v < (1 << (n - 1))): n += 1
+    return n
+
+
+def write_rect(w, x0, x1, y0, y1):
+    n = nbits_s(x0, x1, y0, y1); w.ub(n, 5)
+    for v in (x0, x1, y0, y1): w.sb(v, n)
+    w.align()
+
+
+def shoelace(c):
+    a = 0
+    for s in c:
+        (x0, y0), (x1, y1) = s[1], s[-1]
+        a += x0 * y1 - x1 * y0
+    return a
+
+
+def point_in(poly, p):
+    x, y = p; inside = False; n = len(poly)
+    for i in range(n):
+        (x0, y0), (x1, y1) = poly[i], poly[(i + 1) % n]
+        if (y0 > y) != (y1 > y) and x < x0 + (y - y0) * (x1 - x0) / (y1 - y0): inside = not inside
+    return inside
+
+
+def define_shape3(sid, contours, fill, stroke, sw):
+    # integer twips, closing each contour exactly
+    q = lambda p: (round(p[0] * TW), round(p[1] * TW))
+    cs = [[tuple([s[0]] + [q(p) for p in s[1:]]) for s in c] for c in contours]
+    cs = [[s for s in c if not (s[0] == "L" and s[1] == s[2])] for c in cs]
+    cs = [c for c in cs if c]
+    closed = [c[0][1] == c[-1][-1] for c in cs]
+    polys = [[s[1] for s in c] for c in cs]
+    # nesting depth for even-odd fills
+    depth = []
+    for i, c in enumerate(cs):
+        t = c[0][1]; depth.append(sum(1 for j, pg in enumerate(polys) if j != i and closed[j] and point_in(pg, t)))
+    pad = round(sw * TW / 2) if stroke else 0
+    xs = [p[0] for c in cs for s in c for p in s[1:]]; ys = [p[1] for c in cs for s in c for p in s[1:]]
+    w = BW()
+    w.bytes(struct.pack("<H", sid))
+    write_rect(w, min(xs) - pad, max(xs) + pad, min(ys) - pad, max(ys) + pad)
+    fills = [fill] if fill else []; lines = [stroke] if stroke else []
+    w.bytes(bytes([len(fills)]))
+    for f in fills: w.bytes(bytes([0x00, *f]))
+    w.bytes(bytes([len(lines)]))
+    for l in lines: w.bytes(struct.pack("<H", round(sw * TW)) + bytes(l))
+    nf, nl = (1 if fills else 0), (1 if lines else 0)
+    w.ub(nf, 4); w.ub(nl, 4)
+    x = y = 0
+    for i, c in enumerate(cs):
+        f0 = f1 = 0
+        if fills and closed[i]:
+            interior_on_f0 = shoelace(c) > 0
+            filled_inside = depth[i] % 2 == 0
+            if interior_on_f0 == filled_inside: f0 = 1
+            else: f1 = 1
+        sx, sy = c[0][1]
+        # style change: moveTo + fill0 + fill1 (+ line)
+        flags = 0x01 | (0x02 if nf else 0) | (0x04 if nf else 0) | (0x08 if nl else 0)
+        w.ub(0, 1); w.ub(flags, 5)
+        n = nbits_s(sx, sy); w.ub(n, 5); w.sb(sx, n); w.sb(sy, n)
+        if nf: w.ub(f0, nf); w.ub(f1, nf)
+        if nl: w.ub(1, nl)
+        x, y = sx, sy
+        for s in c:
+            if s[0] == "L":
+                (ex, ey) = s[2]; dx, dy = ex - x, ey - y
+                n = max(nbits_s(dx, dy), 2)
+                w.ub(1, 1); w.ub(1, 1); w.ub(n - 2, 4); w.ub(1, 1); w.sb(dx, n); w.sb(dy, n)
+                x, y = ex, ey
+            else:
+                (cx, cy), (ex, ey) = s[2], s[3]
+                a, b, c2, d = cx - x, cy - y, ex - cx, ey - cy
+                n = max(nbits_s(a, b, c2, d), 2)
+                w.ub(1, 1); w.ub(0, 1); w.ub(n - 2, 4)
+                for v in (a, b, c2, d): w.sb(v, n)
+                x, y = ex, ey
+    w.ub(0, 6); w.align()
+    return bytes(w.out)
+
+
+def tag(code, body):
+    if len(body) < 63: return struct.pack("<H", code << 6 | len(body)) + body
+    return struct.pack("<HI", code << 6 | 63, len(body)) + body
+
+
+def read_tags(d, p, end):
+    while p < end:
+        h = struct.unpack_from("<H", d, p); hdr = p; p += 2; c, l = h[0] >> 6, h[0] & 63
+        if l == 63: l = struct.unpack_from("<I", d, p)[0]; p += 4
+        yield c, d[hdr:p + l], d[p:p + l]; p += l
+        if c == 0: break
+
+
+def build(d, symbols, target_len=None):
+    """d: the title's input_icons movie. symbols: {'Main_Button_N': SVG fragment or <symbol> element}.
+    Returns (new movie, its length before padding, number of shapes)."""
+    nb = d[8] >> 3; hdr_end = 8 + (5 + 4 * nb + 7) // 8 + 4
+    tags = list(read_tags(d, hdr_end, len(d)))
+    names = {}
+    for c, raw, body in tags:
+        if c == 76:
+            n = struct.unpack_from("<H", body)[0]; q = 2
+            for _ in range(n):
+                i = struct.unpack_from("<H", body, q)[0]; q += 2; e = body.index(b"\0", q); names[body[q:e].decode().split(".")[-1]] = i; q = e + 1
+    shapes = {}; shape_tags = []; sprite_tags = {}; next_id = 1
+    used = {struct.unpack_from("<H", body)[0] for c, _, body in tags if c == 39}
+    for nm, sid in sorted(((n, i) for n, i in names.items() if n.startswith("Main_Button_")), key=lambda kv: kv[1]):
+        if nm not in symbols: raise KeyError(f"no design for {nm}")
+        places = []
+        for cs, fill, stroke, sw in elements(symbols[nm]):
+            key = (repr(cs), fill, stroke, sw)
+            if key not in shapes:
+                while next_id in used: next_id += 1
+                shapes[key] = next_id; used.add(next_id)
+                shape_tags.append(tag(32, define_shape3(next_id, cs, fill, stroke, sw)))
+            places.append(shapes[key])
+        body = struct.pack("<HH", sid, 1)
+        for depth, ch in enumerate(places, 1):
+            body += tag(26, bytes([0x02]) + struct.pack("<HH", depth, ch))
+        body += tag(1, b"") + tag(0, b"")
+        sprite_tags[sid] = tag(39, body)
+    out = bytearray(d[:hdr_end]); inserted = False
+    for c, raw, body in tags:
+        if c == 32:
+            if not inserted: out += b"".join(shape_tags); inserted = True
+            continue
+        if c == 39:
+            sid = struct.unpack_from("<H", body)[0]
+            if not inserted: out += b"".join(shape_tags); inserted = True
+            out += sprite_tags[sid]; continue
+        out += raw
+    real = len(out)
+    if target_len:
+        if real > target_len: raise ValueError(f"movie is {real} bytes, over {target_len}")
+        out += bytes(target_len - real)
+    struct.pack_into("<I", out, 4, len(out))
+    return bytes(out), real, len(shape_tags)
+
+
+# ── data.rpf ────────────────────────────────────────────────────────────────
+
+KNOWN_OFFSET = 0x117d7000   # the entry in the data.rpf we have (481,544,304 bytes)
+MARK = b"platform_xbsx.input_icons"
+
+
+def read_stream(f, off, limit=1 << 20):
+    """Inflate the zlib stream at `off`. Returns (data, compressed size) or None."""
+    f.seek(off); buf = f.read(limit)
+    if len(buf) < 2 or buf[0] != 0x78: return None
+    d = zlib.decompressobj()
+    try: out = d.decompress(buf)
+    except zlib.error: return None
+    if not d.eof: return None
+    return out, len(buf) - len(d.unused_data)
+
+
+def is_icon_movie(data):
+    return data[:3] in (b"GFX", b"CFX") and MARK in data and b"Main_Button_" in data
+
+
+def find_entry(path, offset):
+    with open(path, "rb") as f:
+        hit = read_stream(f, offset)
+        if hit and is_icon_movie(hit[0]): return offset, hit[0], hit[1]
+        print(f"not at {offset:#x}; scanning {path} for the icon library...")
+        size = os.fstat(f.fileno()).st_size; base = 0; step = 64 << 20
+        while base < size:
+            f.seek(base); chunk = f.read(step + 16)
+            i = chunk.find(b"\x78\xda")
+            while 0 <= i < step:
+                off = base + i
+                if off % 16 == 0:
+                    hit = read_stream(f, off)
+                    if hit and is_icon_movie(hit[0]): return off, hit[0], hit[1]
+                i = chunk.find(b"\x78\xda", i + 1)
+            base += step
+    raise SystemExit("platform_xbsx.input_icons was not found in data.rpf")
+
+
+def pack_exact(movie, real, csize):
+    """A zlib stream of exactly `csize` bytes for `movie` (whose bytes after `real` are padding): the tail of the
+    padding gets seeded pseudo-random bytes until the compressed size lands on `csize`."""
+    import random
+    def comp(b):
+        c = zlib.compressobj(9, zlib.DEFLATED, 15, 9); return c.compress(b) + c.flush()
+    room = len(movie) - real
+    base = len(comp(movie))
+    if base > csize:
+        raise SystemExit(f"the new library packs to {base} bytes, over the original's {csize}: simplify the icons")
+    est = csize - base
+    for seed in range(400):
+        rnd = random.Random(seed); tail = bytes(rnd.getrandbits(8) for _ in range(room))
+        for n in range(max(0, est - 40), min(room, est + 40) + 1):
+            data = movie[:real] + bytes(room - n) + tail[:n]
+            c = comp(data)
+            if len(c) == csize: return c, data
+    raise SystemExit("could not pack the library to the original's exact compressed size")
+
+
+def load_master(path):
+    syms = {}
+    for el in ET.parse(path).getroot().iter():
+        if el.tag.split("}")[-1] == "symbol" and el.get("id", "").startswith("Main_Button_"):
+            syms[el.get("id")] = el
+    return syms
+
+
+def main():
+    import argparse, shutil
+    here = os.path.dirname(os.path.abspath(__file__))
+    ap = argparse.ArgumentParser(description="Build the keyboard/mouse icon library into a copy of data.rpf.")
+    ap.add_argument("--game", required=True, help="the title's game folder (holds data.rpf); only read")
+    ap.add_argument("--out", help="where to write the patched copy of data.rpf (the title's XCL overlay folder)")
+    ap.add_argument("--master", default=os.path.join(here, "..", "..", "docs", "kbm-icons", "icons-master.svg"))
+    ap.add_argument("--offset", type=lambda v: int(v, 0), default=KNOWN_OFFSET)
+    ap.add_argument("--movie-out", help="also write the rebuilt movie here (made from game data: keep it local)")
+    a = ap.parse_args()
+    src = os.path.join(a.game, "data.rpf")
+    off, orig, csize = find_entry(src, a.offset)
+    movie, real, nshapes = build(orig, load_master(a.master), target_len=len(orig))
+    c, data = pack_exact(movie, real, csize)
+    assert zlib.decompress(c) == data and len(data) == len(orig) and len(c) == csize
+    print(f"input_icons at {off:#x}: {len(orig)} bytes ({csize} packed); new library {real} bytes, "
+          f"{nshapes} shapes, packed to {len(c)} bytes")
+    if a.movie_out:
+        with open(a.movie_out, "wb") as f: f.write(data)

--movie-out is still written before the game-folder guard, which only checks --out, so this option can write inside the game. The --out check also uses lexical abspath paths and can be bypassed through a junction/symlink into the game. Please resolve and validate both output destinations before either write. AI-assisted review; I rechecked both paths on this head.

<!-- greyfinch-sync:ivall/xcl:review-comment:4684629583 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1604#discussion_r4684629583). Originally posted by [gut0to](https://github.com/gut0to) on 2026-11-24T18:24:41Z. **Code review location:** `scripts/kbm_icons/build_library.py`; line 444 ~~~~diff @@ -0,0 +1,462 @@ +r"""Build the keyboard/mouse icon library for the retail title and write it into a COPY of its data.rpf. + + python scripts/kbm_icons/build_library.py --game D:\Game --out %LOCALAPPDATA%\XCL\<title>\overlay\data.rpf + +XCL reads a game file from the title's overlay folder when one is there (crates/xcl/src/vfs.rs), so the +patched copy replaces the original without touching the game folder. Delete the copy to undo. + +What it does (details and measurements: docs/kbm-icons/README.md): +1. Finds the title's `platform_xbsx.input_icons` movie in data.rpf. Each archive entry is a plain zlib + stream; nothing is decrypted. The entry is at a known offset in the version we have, checked by content, + with a scan of the archive as a fallback. +2. Rebuilds that movie: the 38 `Main_Button_N` sprites and their shapes come from icons-master.svg; every + other tag (the movie's own script, exports, symbol classes) is copied from the user's file as it is. +3. Packs it to the original entry's exact sizes (unpacked and zlib), so the archive's table of contents + still describes it, and writes data.rpf with only that entry changed. + +Supported SVG in the master file: <g transform="translate(x y)">, <rect rx>, <polygon>, <path> with absolute +M L H V Q A Z, <text> (outlined from Windows' Bahnschrift Bold Condensed), fill / stroke / stroke-width as +attributes, #rgb or #rrggbb colours. Units are the library's (1 unit = 20 twips; a symbol is 64 tall). +Needs Python 3.10+ and fontTools (MIT). +""" +import math, re, struct, sys, os, zlib +import xml.etree.ElementTree as ET + + +TW = 20 + +# ── font ───────────────────────────────────────────────────────────────────── +_font = None + + +def font(): + global _font + if _font is None: + from fontTools.ttLib import TTFont + from fontTools.varLib import instancer + f = TTFont(r"C:\Windows\Fonts\bahnschrift.ttf") + _font = instancer.instantiateVariableFont(f, {"wght": 700, "wdth": 75}) + return _font + + +def glyph_contours(ch): + """Contours of one glyph in font units, y-up, as lists of segments ('L', p0, p1) / ('Q', p0, c, p1).""" + from fontTools.pens.basePen import BasePen + f = font(); gs = f.getGlyphSet(); name = f.getBestCmap()[ord(ch)] + + class P(BasePen): + def __init__(s): super().__init__(gs); s.cs = []; s.cur = None; s.start = None + def _moveTo(s, p): s.cs.append([]); s.cur = s.start = p + def _lineTo(s, p): s.cs[-1].append(("L", s.cur, p)); s.cur = p + def _qCurveToOne(s, c, p): s.cs[-1].append(("Q", s.cur, c, p)); s.cur = p + def _curveToOne(s, c1, c2, p): # cubic → two quads (Bahnschrift is quadratic; kept for safety) + m = ((c1[0] + c2[0]) / 2, (c1[1] + c2[1]) / 2) + s._qCurveToOne(((s.cur[0] + 3 * c1[0]) / 4, (s.cur[1] + 3 * c1[1]) / 4), m) + s._qCurveToOne(((3 * c2[0] + p[0]) / 4, (3 * c2[1] + p[1]) / 4), p) + def _closePath(s): + if s.cur != s.start: s.cs[-1].append(("L", s.cur, s.start)); s.cur = s.start + _endPath = _closePath + pen = P(); gs[name].draw(pen) + return pen.cs, gs[name].width + + +def text_contours(s, x, y, fs, anchor, text_length): + """SVG text → contours in symbol units (y-down). The cap height matches the SVG design (0.7 em).""" + f = font(); cap_font = f["OS/2"].sCapHeight + k = (fs * 0.7) / cap_font + adv = 0; glyphs = [] + for ch in s: + cs, w = glyph_contours(ch); glyphs.append((adv, cs)); adv += w + width = adv * k + sx = k + if text_length: + sx = text_length / adv; width = text_length + x0 = x - width / 2 if anchor == "middle" else x + out = [] + for gx, cs in glyphs: + for c in cs: + out.append([tuple([seg[0]] + [(x0 + (gx + px) * sx, y - py * k) for px, py in seg[1:]]) for seg in c]) + return out + + +# ── SVG geometry ───────────────────────────────────────────────────────────── + +def arc_to_quads(p0, rx, ry, rot, large, sweep, p1): + """SVG elliptical arc → quadratic segments (each ≤ 45°).""" + x1, y1 = p0; x2, y2 = p1 + if rx == 0 or ry == 0: return [("L", p0, p1)] + phi = math.radians(rot); cp, sp = math.cos(phi), math.sin(phi) + dx, dy = (x1 - x2) / 2, (y1 - y2) / 2 + x1p, y1p = cp * dx + sp * dy, -sp * dx + cp * dy + lam = (x1p / rx) ** 2 + (y1p / ry) ** 2 + if lam > 1: rx *= math.sqrt(lam); ry *= math.sqrt(lam) + num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p + den = rx * rx * y1p * y1p + ry * ry * x1p * x1p + co = math.sqrt(max(0, num / den)) if den else 0 + if large == sweep: co = -co + cxp, cyp = co * rx * y1p / ry, -co * ry * x1p / rx + cx = cp * cxp - sp * cyp + (x1 + x2) / 2; cy = sp * cxp + cp * cyp + (y1 + y2) / 2 + ang = lambda ux, uy, vx, vy: math.atan2(ux * vy - uy * vx, ux * vx + uy * vy) + t1 = ang(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry) + dt = ang((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry) + if not sweep and dt > 0: dt -= 2 * math.pi + if sweep and dt < 0: dt += 2 * math.pi + n = max(1, math.ceil(abs(dt) / (math.pi / 2 if max(rx, ry) <= 14 else math.pi / 3) - 1e-9)); h = dt / n # 90 deg pieces for corners, 60 for big rings + pt = lambda t: (cx + rx * math.cos(t) * cp - ry * math.sin(t) * sp, cy + rx * math.cos(t) * sp + ry * math.sin(t) * cp) + segs = []; cur = p0 + for i in range(n): + ta, tb = t1 + i * h, t1 + (i + 1) * h; tm = (ta + tb) / 2 + e = 1 / math.cos(h / 2) + c = (cx + rx * e * math.cos(tm) * cp - ry * e * math.sin(tm) * sp, cy + rx * e * math.cos(tm) * sp + ry * e * math.sin(tm) * cp) + nxt = p1 if i == n - 1 else pt(tb) + segs.append(("Q", cur, c, nxt)); cur = nxt + return segs + + +def path_contours(d): + toks = re.findall(r"[MLHVAQZ]|-?\d*\.?\d+(?:e-?\d+)?", d) + i = 0; cs = []; cur = start = (0, 0); cmd = None + def num(): + nonlocal i; v = float(toks[i]); i += 1; return v + while i < len(toks): + if re.match(r"[A-Z]", toks[i]): cmd = toks[i]; i += 1 + if cmd == "M": cur = start = (num(), num()); cs.append([]); cmd = "L"; continue + if cmd == "Z": + if cs and cur != start: cs[-1].append(("L", cur, start)) + cur = start; continue + if cmd == "L": p = (num(), num()); cs[-1].append(("L", cur, p)); cur = p + elif cmd == "H": p = (num(), cur[1]); cs[-1].append(("L", cur, p)); cur = p + elif cmd == "V": p = (cur[0], num()); cs[-1].append(("L", cur, p)); cur = p + elif cmd == "Q": c = (num(), num()); p = (num(), num()); cs[-1].append(("Q", cur, c, p)); cur = p + elif cmd == "A": + rx, ry, rot, la, sw = num(), num(), num(), num(), num(); p = (num(), num()) + cs[-1].extend(arc_to_quads(cur, rx, ry, rot, int(la), int(sw), p)); cur = p + else: raise ValueError(cmd) + return [c for c in cs if c] + + +def rect_contours(x, y, w, h, r): + r = min(r, w / 2, h / 2) + if r <= 0: + return path_contours(f"M{x} {y} H{x + w} V{y + h} H{x} Z") + return path_contours(f"M{x + r} {y} H{x + w - r} A{r} {r} 0 0 1 {x + w} {y + r} V{y + h - r} A{r} {r} 0 0 1 {x + w - r} {y + h} " + f"H{x + r} A{r} {r} 0 0 1 {x} {y + h - r} V{y + r} A{r} {r} 0 0 1 {x + r} {y} Z") + + +def color(v): + if not v or v == "none": return None + v = v.lstrip("#") + if len(v) == 3: v = "".join(c * 2 for c in v) + return (int(v[0:2], 16), int(v[2:4], 16), int(v[4:6], 16), 255) + + +def elements(svg): + """Yield (contours, fill, stroke, stroke_width) for each drawable element, in paint order. + `svg` is an SVG fragment (text) or an element whose children are drawn (a master-file <symbol>).""" + root = ET.fromstring(f"<g>{svg}</g>") if isinstance(svg, str) else svg + + def walk(el, dx, dy): + tag = el.tag.split("}")[-1] + if tag == "g": + m = re.match(r"translate\(([-\d.e]+)\s+([-\d.e]+)\)", el.get("transform", "translate(0 0)")) + for c in el: yield from walk(c, dx + float(m.group(1)), dy + float(m.group(2))) + return + fill = color(el.get("fill", "#000")); stroke = color(el.get("stroke")); sw = float(el.get("stroke-width", "1")) + if tag == "rect": + cs = rect_contours(float(el.get("x")), float(el.get("y")), float(el.get("width")), float(el.get("height")), float(el.get("rx", 0))) + elif tag == "path": + cs = path_contours(el.get("d")) + elif tag == "polygon": + pts = [tuple(map(float, p.split(","))) for p in el.get("points").split()] + cs = [[("L", pts[i], pts[(i + 1) % len(pts)]) for i in range(len(pts))]] + elif tag == "text": + tl = el.get("textLength") + cs = text_contours(el.text, float(el.get("x")), float(el.get("y")), float(el.get("font-size")), + el.get("text-anchor", "start"), float(tl) if tl else None) + stroke = None + else: + raise ValueError(tag) + cs = [[tuple([s[0]] + [(px + dx, py + dy) for px, py in s[1:]]) for s in c] for c in cs] + if tag == "text": + # Variable-font glyphs overlap (an E is a stem plus bars). Give every solid contour its own + # shape, with the holes it contains, so overlaps add up instead of cancelling (even-odd). + areas = [shoelace(c) for c in cs] + solid_sign = 1 if areas[max(range(len(cs)), key=lambda i: abs(areas[i]))] > 0 else -1 + solids = [i for i in range(len(cs)) if areas[i] * solid_sign > 0] + groups = {i: [cs[i]] for i in solids} + for i in range(len(cs)): + if i in groups: continue + p = cs[i][0][1] + owners = [j for j in solids if point_in([s[1] for s in cs[j]], p)] + if owners: groups[min(owners, key=lambda j: abs(areas[j]))].append(cs[i]) + for i in solids: yield groups[i], fill, stroke, sw + return + yield cs, fill, stroke, sw + + for el in root: yield from walk(el, 0, 0) + + +# ── SWF writing ────────────────────────────────────────────────────────────── + +class BW: + def __init__(s): s.out = bytearray(); s.acc = 0; s.n = 0 + def ub(s, v, n): + for i in range(n - 1, -1, -1): + s.acc = (s.acc << 1) | ((v >> i) & 1); s.n += 1 + if s.n == 8: s.out.append(s.acc); s.acc = 0; s.n = 0 + def sb(s, v, n): s.ub(v & ((1 << n) - 1), n) + def align(s): + if s.n: s.ub(0, 8 - s.n) + def bytes(s, b): s.align(); s.out += b + + +def nbits_s(*vals): + n = 1 + for v in vals: + while not (-(1 << (n - 1)) <= v < (1 << (n - 1))): n += 1 + return n + + +def write_rect(w, x0, x1, y0, y1): + n = nbits_s(x0, x1, y0, y1); w.ub(n, 5) + for v in (x0, x1, y0, y1): w.sb(v, n) + w.align() + + +def shoelace(c): + a = 0 + for s in c: + (x0, y0), (x1, y1) = s[1], s[-1] + a += x0 * y1 - x1 * y0 + return a + + +def point_in(poly, p): + x, y = p; inside = False; n = len(poly) + for i in range(n): + (x0, y0), (x1, y1) = poly[i], poly[(i + 1) % n] + if (y0 > y) != (y1 > y) and x < x0 + (y - y0) * (x1 - x0) / (y1 - y0): inside = not inside + return inside + + +def define_shape3(sid, contours, fill, stroke, sw): + # integer twips, closing each contour exactly + q = lambda p: (round(p[0] * TW), round(p[1] * TW)) + cs = [[tuple([s[0]] + [q(p) for p in s[1:]]) for s in c] for c in contours] + cs = [[s for s in c if not (s[0] == "L" and s[1] == s[2])] for c in cs] + cs = [c for c in cs if c] + closed = [c[0][1] == c[-1][-1] for c in cs] + polys = [[s[1] for s in c] for c in cs] + # nesting depth for even-odd fills + depth = [] + for i, c in enumerate(cs): + t = c[0][1]; depth.append(sum(1 for j, pg in enumerate(polys) if j != i and closed[j] and point_in(pg, t))) + pad = round(sw * TW / 2) if stroke else 0 + xs = [p[0] for c in cs for s in c for p in s[1:]]; ys = [p[1] for c in cs for s in c for p in s[1:]] + w = BW() + w.bytes(struct.pack("<H", sid)) + write_rect(w, min(xs) - pad, max(xs) + pad, min(ys) - pad, max(ys) + pad) + fills = [fill] if fill else []; lines = [stroke] if stroke else [] + w.bytes(bytes([len(fills)])) + for f in fills: w.bytes(bytes([0x00, *f])) + w.bytes(bytes([len(lines)])) + for l in lines: w.bytes(struct.pack("<H", round(sw * TW)) + bytes(l)) + nf, nl = (1 if fills else 0), (1 if lines else 0) + w.ub(nf, 4); w.ub(nl, 4) + x = y = 0 + for i, c in enumerate(cs): + f0 = f1 = 0 + if fills and closed[i]: + interior_on_f0 = shoelace(c) > 0 + filled_inside = depth[i] % 2 == 0 + if interior_on_f0 == filled_inside: f0 = 1 + else: f1 = 1 + sx, sy = c[0][1] + # style change: moveTo + fill0 + fill1 (+ line) + flags = 0x01 | (0x02 if nf else 0) | (0x04 if nf else 0) | (0x08 if nl else 0) + w.ub(0, 1); w.ub(flags, 5) + n = nbits_s(sx, sy); w.ub(n, 5); w.sb(sx, n); w.sb(sy, n) + if nf: w.ub(f0, nf); w.ub(f1, nf) + if nl: w.ub(1, nl) + x, y = sx, sy + for s in c: + if s[0] == "L": + (ex, ey) = s[2]; dx, dy = ex - x, ey - y + n = max(nbits_s(dx, dy), 2) + w.ub(1, 1); w.ub(1, 1); w.ub(n - 2, 4); w.ub(1, 1); w.sb(dx, n); w.sb(dy, n) + x, y = ex, ey + else: + (cx, cy), (ex, ey) = s[2], s[3] + a, b, c2, d = cx - x, cy - y, ex - cx, ey - cy + n = max(nbits_s(a, b, c2, d), 2) + w.ub(1, 1); w.ub(0, 1); w.ub(n - 2, 4) + for v in (a, b, c2, d): w.sb(v, n) + x, y = ex, ey + w.ub(0, 6); w.align() + return bytes(w.out) + + +def tag(code, body): + if len(body) < 63: return struct.pack("<H", code << 6 | len(body)) + body + return struct.pack("<HI", code << 6 | 63, len(body)) + body + + +def read_tags(d, p, end): + while p < end: + h = struct.unpack_from("<H", d, p); hdr = p; p += 2; c, l = h[0] >> 6, h[0] & 63 + if l == 63: l = struct.unpack_from("<I", d, p)[0]; p += 4 + yield c, d[hdr:p + l], d[p:p + l]; p += l + if c == 0: break + + +def build(d, symbols, target_len=None): + """d: the title's input_icons movie. symbols: {'Main_Button_N': SVG fragment or <symbol> element}. + Returns (new movie, its length before padding, number of shapes).""" + nb = d[8] >> 3; hdr_end = 8 + (5 + 4 * nb + 7) // 8 + 4 + tags = list(read_tags(d, hdr_end, len(d))) + names = {} + for c, raw, body in tags: + if c == 76: + n = struct.unpack_from("<H", body)[0]; q = 2 + for _ in range(n): + i = struct.unpack_from("<H", body, q)[0]; q += 2; e = body.index(b"\0", q); names[body[q:e].decode().split(".")[-1]] = i; q = e + 1 + shapes = {}; shape_tags = []; sprite_tags = {}; next_id = 1 + used = {struct.unpack_from("<H", body)[0] for c, _, body in tags if c == 39} + for nm, sid in sorted(((n, i) for n, i in names.items() if n.startswith("Main_Button_")), key=lambda kv: kv[1]): + if nm not in symbols: raise KeyError(f"no design for {nm}") + places = [] + for cs, fill, stroke, sw in elements(symbols[nm]): + key = (repr(cs), fill, stroke, sw) + if key not in shapes: + while next_id in used: next_id += 1 + shapes[key] = next_id; used.add(next_id) + shape_tags.append(tag(32, define_shape3(next_id, cs, fill, stroke, sw))) + places.append(shapes[key]) + body = struct.pack("<HH", sid, 1) + for depth, ch in enumerate(places, 1): + body += tag(26, bytes([0x02]) + struct.pack("<HH", depth, ch)) + body += tag(1, b"") + tag(0, b"") + sprite_tags[sid] = tag(39, body) + out = bytearray(d[:hdr_end]); inserted = False + for c, raw, body in tags: + if c == 32: + if not inserted: out += b"".join(shape_tags); inserted = True + continue + if c == 39: + sid = struct.unpack_from("<H", body)[0] + if not inserted: out += b"".join(shape_tags); inserted = True + out += sprite_tags[sid]; continue + out += raw + real = len(out) + if target_len: + if real > target_len: raise ValueError(f"movie is {real} bytes, over {target_len}") + out += bytes(target_len - real) + struct.pack_into("<I", out, 4, len(out)) + return bytes(out), real, len(shape_tags) + + +# ── data.rpf ──────────────────────────────────────────────────────────────── + +KNOWN_OFFSET = 0x117d7000 # the entry in the data.rpf we have (481,544,304 bytes) +MARK = b"platform_xbsx.input_icons" + + +def read_stream(f, off, limit=1 << 20): + """Inflate the zlib stream at `off`. Returns (data, compressed size) or None.""" + f.seek(off); buf = f.read(limit) + if len(buf) < 2 or buf[0] != 0x78: return None + d = zlib.decompressobj() + try: out = d.decompress(buf) + except zlib.error: return None + if not d.eof: return None + return out, len(buf) - len(d.unused_data) + + +def is_icon_movie(data): + return data[:3] in (b"GFX", b"CFX") and MARK in data and b"Main_Button_" in data + + +def find_entry(path, offset): + with open(path, "rb") as f: + hit = read_stream(f, offset) + if hit and is_icon_movie(hit[0]): return offset, hit[0], hit[1] + print(f"not at {offset:#x}; scanning {path} for the icon library...") + size = os.fstat(f.fileno()).st_size; base = 0; step = 64 << 20 + while base < size: + f.seek(base); chunk = f.read(step + 16) + i = chunk.find(b"\x78\xda") + while 0 <= i < step: + off = base + i + if off % 16 == 0: + hit = read_stream(f, off) + if hit and is_icon_movie(hit[0]): return off, hit[0], hit[1] + i = chunk.find(b"\x78\xda", i + 1) + base += step + raise SystemExit("platform_xbsx.input_icons was not found in data.rpf") + + +def pack_exact(movie, real, csize): + """A zlib stream of exactly `csize` bytes for `movie` (whose bytes after `real` are padding): the tail of the + padding gets seeded pseudo-random bytes until the compressed size lands on `csize`.""" + import random + def comp(b): + c = zlib.compressobj(9, zlib.DEFLATED, 15, 9); return c.compress(b) + c.flush() + room = len(movie) - real + base = len(comp(movie)) + if base > csize: + raise SystemExit(f"the new library packs to {base} bytes, over the original's {csize}: simplify the icons") + est = csize - base + for seed in range(400): + rnd = random.Random(seed); tail = bytes(rnd.getrandbits(8) for _ in range(room)) + for n in range(max(0, est - 40), min(room, est + 40) + 1): + data = movie[:real] + bytes(room - n) + tail[:n] + c = comp(data) + if len(c) == csize: return c, data + raise SystemExit("could not pack the library to the original's exact compressed size") + + +def load_master(path): + syms = {} + for el in ET.parse(path).getroot().iter(): + if el.tag.split("}")[-1] == "symbol" and el.get("id", "").startswith("Main_Button_"): + syms[el.get("id")] = el + return syms + + +def main(): + import argparse, shutil + here = os.path.dirname(os.path.abspath(__file__)) + ap = argparse.ArgumentParser(description="Build the keyboard/mouse icon library into a copy of data.rpf.") + ap.add_argument("--game", required=True, help="the title's game folder (holds data.rpf); only read") + ap.add_argument("--out", help="where to write the patched copy of data.rpf (the title's XCL overlay folder)") + ap.add_argument("--master", default=os.path.join(here, "..", "..", "docs", "kbm-icons", "icons-master.svg")) + ap.add_argument("--offset", type=lambda v: int(v, 0), default=KNOWN_OFFSET) + ap.add_argument("--movie-out", help="also write the rebuilt movie here (made from game data: keep it local)") + a = ap.parse_args() + src = os.path.join(a.game, "data.rpf") + off, orig, csize = find_entry(src, a.offset) + movie, real, nshapes = build(orig, load_master(a.master), target_len=len(orig)) + c, data = pack_exact(movie, real, csize) + assert zlib.decompress(c) == data and len(data) == len(orig) and len(c) == csize + print(f"input_icons at {off:#x}: {len(orig)} bytes ({csize} packed); new library {real} bytes, " + f"{nshapes} shapes, packed to {len(c)} bytes") + if a.movie_out: + with open(a.movie_out, "wb") as f: f.write(data) ~~~~ --- `--movie-out` is still written before the game-folder guard, which only checks `--out`, so this option can write inside the game. The `--out` check also uses lexical `abspath` paths and can be bypassed through a junction/symlink into the game. Please resolve and validate both output destinations before either write. AI-assisted review; I rechecked both paths on this head.
zohaiblazuli commented 2026-11-24 19:08:00 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by zohaiblazuli on 2026-11-24T18:25:39Z.

Code review location: scripts/kbm_icons/build_library.py; line 444

@@ -0,0 +1,462 @@
+r"""Build the keyboard/mouse icon library for the retail title and write it into a COPY of its data.rpf.
+
+    python scripts/kbm_icons/build_library.py --game D:\Game --out %LOCALAPPDATA%\XCL\<title>\overlay\data.rpf
+
+XCL reads a game file from the title's overlay folder when one is there (crates/xcl/src/vfs.rs), so the
+patched copy replaces the original without touching the game folder. Delete the copy to undo.
+
+What it does (details and measurements: docs/kbm-icons/README.md):
+1. Finds the title's `platform_xbsx.input_icons` movie in data.rpf. Each archive entry is a plain zlib
+   stream; nothing is decrypted. The entry is at a known offset in the version we have, checked by content,
+   with a scan of the archive as a fallback.
+2. Rebuilds that movie: the 38 `Main_Button_N` sprites and their shapes come from icons-master.svg; every
+   other tag (the movie's own script, exports, symbol classes) is copied from the user's file as it is.
+3. Packs it to the original entry's exact sizes (unpacked and zlib), so the archive's table of contents
+   still describes it, and writes data.rpf with only that entry changed.
+
+Supported SVG in the master file: <g transform="translate(x y)">, <rect rx>, <polygon>, <path> with absolute
+M L H V Q A Z, <text> (outlined from Windows' Bahnschrift Bold Condensed), fill / stroke / stroke-width as
+attributes, #rgb or #rrggbb colours. Units are the library's (1 unit = 20 twips; a symbol is 64 tall).
+Needs Python 3.10+ and fontTools (MIT).
+"""
+import math, re, struct, sys, os, zlib
+import xml.etree.ElementTree as ET
+
+
+TW = 20
+
+# ── font ─────────────────────────────────────────────────────────────────────
+_font = None
+
+
+def font():
+    global _font
+    if _font is None:
+        from fontTools.ttLib import TTFont
+        from fontTools.varLib import instancer
+        f = TTFont(r"C:\Windows\Fonts\bahnschrift.ttf")
+        _font = instancer.instantiateVariableFont(f, {"wght": 700, "wdth": 75})
+    return _font
+
+
+def glyph_contours(ch):
+    """Contours of one glyph in font units, y-up, as lists of segments ('L', p0, p1) / ('Q', p0, c, p1)."""
+    from fontTools.pens.basePen import BasePen
+    f = font(); gs = f.getGlyphSet(); name = f.getBestCmap()[ord(ch)]
+
+    class P(BasePen):
+        def __init__(s): super().__init__(gs); s.cs = []; s.cur = None; s.start = None
+        def _moveTo(s, p): s.cs.append([]); s.cur = s.start = p
+        def _lineTo(s, p): s.cs[-1].append(("L", s.cur, p)); s.cur = p
+        def _qCurveToOne(s, c, p): s.cs[-1].append(("Q", s.cur, c, p)); s.cur = p
+        def _curveToOne(s, c1, c2, p):  # cubic → two quads (Bahnschrift is quadratic; kept for safety)
+            m = ((c1[0] + c2[0]) / 2, (c1[1] + c2[1]) / 2)
+            s._qCurveToOne(((s.cur[0] + 3 * c1[0]) / 4, (s.cur[1] + 3 * c1[1]) / 4), m)
+            s._qCurveToOne(((3 * c2[0] + p[0]) / 4, (3 * c2[1] + p[1]) / 4), p)
+        def _closePath(s):
+            if s.cur != s.start: s.cs[-1].append(("L", s.cur, s.start)); s.cur = s.start
+        _endPath = _closePath
+    pen = P(); gs[name].draw(pen)
+    return pen.cs, gs[name].width
+
+
+def text_contours(s, x, y, fs, anchor, text_length):
+    """SVG text → contours in symbol units (y-down). The cap height matches the SVG design (0.7 em)."""
+    f = font(); cap_font = f["OS/2"].sCapHeight
+    k = (fs * 0.7) / cap_font
+    adv = 0; glyphs = []
+    for ch in s:
+        cs, w = glyph_contours(ch); glyphs.append((adv, cs)); adv += w
+    width = adv * k
+    sx = k
+    if text_length:
+        sx = text_length / adv; width = text_length
+    x0 = x - width / 2 if anchor == "middle" else x
+    out = []
+    for gx, cs in glyphs:
+        for c in cs:
+            out.append([tuple([seg[0]] + [(x0 + (gx + px) * sx, y - py * k) for px, py in seg[1:]]) for seg in c])
+    return out
+
+
+# ── SVG geometry ─────────────────────────────────────────────────────────────
+
+def arc_to_quads(p0, rx, ry, rot, large, sweep, p1):
+    """SVG elliptical arc → quadratic segments (each ≤ 45°)."""
+    x1, y1 = p0; x2, y2 = p1
+    if rx == 0 or ry == 0: return [("L", p0, p1)]
+    phi = math.radians(rot); cp, sp = math.cos(phi), math.sin(phi)
+    dx, dy = (x1 - x2) / 2, (y1 - y2) / 2
+    x1p, y1p = cp * dx + sp * dy, -sp * dx + cp * dy
+    lam = (x1p / rx) ** 2 + (y1p / ry) ** 2
+    if lam > 1: rx *= math.sqrt(lam); ry *= math.sqrt(lam)
+    num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p
+    den = rx * rx * y1p * y1p + ry * ry * x1p * x1p
+    co = math.sqrt(max(0, num / den)) if den else 0
+    if large == sweep: co = -co
+    cxp, cyp = co * rx * y1p / ry, -co * ry * x1p / rx
+    cx = cp * cxp - sp * cyp + (x1 + x2) / 2; cy = sp * cxp + cp * cyp + (y1 + y2) / 2
+    ang = lambda ux, uy, vx, vy: math.atan2(ux * vy - uy * vx, ux * vx + uy * vy)
+    t1 = ang(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry)
+    dt = ang((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry)
+    if not sweep and dt > 0: dt -= 2 * math.pi
+    if sweep and dt < 0: dt += 2 * math.pi
+    n = max(1, math.ceil(abs(dt) / (math.pi / 2 if max(rx, ry) <= 14 else math.pi / 3) - 1e-9)); h = dt / n  # 90 deg pieces for corners, 60 for big rings
+    pt = lambda t: (cx + rx * math.cos(t) * cp - ry * math.sin(t) * sp, cy + rx * math.cos(t) * sp + ry * math.sin(t) * cp)
+    segs = []; cur = p0
+    for i in range(n):
+        ta, tb = t1 + i * h, t1 + (i + 1) * h; tm = (ta + tb) / 2
+        e = 1 / math.cos(h / 2)
+        c = (cx + rx * e * math.cos(tm) * cp - ry * e * math.sin(tm) * sp, cy + rx * e * math.cos(tm) * sp + ry * e * math.sin(tm) * cp)
+        nxt = p1 if i == n - 1 else pt(tb)
+        segs.append(("Q", cur, c, nxt)); cur = nxt
+    return segs
+
+
+def path_contours(d):
+    toks = re.findall(r"[MLHVAQZ]|-?\d*\.?\d+(?:e-?\d+)?", d)
+    i = 0; cs = []; cur = start = (0, 0); cmd = None
+    def num():
+        nonlocal i; v = float(toks[i]); i += 1; return v
+    while i < len(toks):
+        if re.match(r"[A-Z]", toks[i]): cmd = toks[i]; i += 1
+        if cmd == "M": cur = start = (num(), num()); cs.append([]); cmd = "L"; continue
+        if cmd == "Z":
+            if cs and cur != start: cs[-1].append(("L", cur, start))
+            cur = start; continue
+        if cmd == "L": p = (num(), num()); cs[-1].append(("L", cur, p)); cur = p
+        elif cmd == "H": p = (num(), cur[1]); cs[-1].append(("L", cur, p)); cur = p
+        elif cmd == "V": p = (cur[0], num()); cs[-1].append(("L", cur, p)); cur = p
+        elif cmd == "Q": c = (num(), num()); p = (num(), num()); cs[-1].append(("Q", cur, c, p)); cur = p
+        elif cmd == "A":
+            rx, ry, rot, la, sw = num(), num(), num(), num(), num(); p = (num(), num())
+            cs[-1].extend(arc_to_quads(cur, rx, ry, rot, int(la), int(sw), p)); cur = p
+        else: raise ValueError(cmd)
+    return [c for c in cs if c]
+
+
+def rect_contours(x, y, w, h, r):
+    r = min(r, w / 2, h / 2)
+    if r <= 0:
+        return path_contours(f"M{x} {y} H{x + w} V{y + h} H{x} Z")
+    return path_contours(f"M{x + r} {y} H{x + w - r} A{r} {r} 0 0 1 {x + w} {y + r} V{y + h - r} A{r} {r} 0 0 1 {x + w - r} {y + h} "
+                         f"H{x + r} A{r} {r} 0 0 1 {x} {y + h - r} V{y + r} A{r} {r} 0 0 1 {x + r} {y} Z")
+
+
+def color(v):
+    if not v or v == "none": return None
+    v = v.lstrip("#")
+    if len(v) == 3: v = "".join(c * 2 for c in v)
+    return (int(v[0:2], 16), int(v[2:4], 16), int(v[4:6], 16), 255)
+
+
+def elements(svg):
+    """Yield (contours, fill, stroke, stroke_width) for each drawable element, in paint order.
+    `svg` is an SVG fragment (text) or an element whose children are drawn (a master-file <symbol>)."""
+    root = ET.fromstring(f"<g>{svg}</g>") if isinstance(svg, str) else svg
+
+    def walk(el, dx, dy):
+        tag = el.tag.split("}")[-1]
+        if tag == "g":
+            m = re.match(r"translate\(([-\d.e]+)\s+([-\d.e]+)\)", el.get("transform", "translate(0 0)"))
+            for c in el: yield from walk(c, dx + float(m.group(1)), dy + float(m.group(2)))
+            return
+        fill = color(el.get("fill", "#000")); stroke = color(el.get("stroke")); sw = float(el.get("stroke-width", "1"))
+        if tag == "rect":
+            cs = rect_contours(float(el.get("x")), float(el.get("y")), float(el.get("width")), float(el.get("height")), float(el.get("rx", 0)))
+        elif tag == "path":
+            cs = path_contours(el.get("d"))
+        elif tag == "polygon":
+            pts = [tuple(map(float, p.split(","))) for p in el.get("points").split()]
+            cs = [[("L", pts[i], pts[(i + 1) % len(pts)]) for i in range(len(pts))]]
+        elif tag == "text":
+            tl = el.get("textLength")
+            cs = text_contours(el.text, float(el.get("x")), float(el.get("y")), float(el.get("font-size")),
+                               el.get("text-anchor", "start"), float(tl) if tl else None)
+            stroke = None
+        else:
+            raise ValueError(tag)
+        cs = [[tuple([s[0]] + [(px + dx, py + dy) for px, py in s[1:]]) for s in c] for c in cs]
+        if tag == "text":
+            # Variable-font glyphs overlap (an E is a stem plus bars). Give every solid contour its own
+            # shape, with the holes it contains, so overlaps add up instead of cancelling (even-odd).
+            areas = [shoelace(c) for c in cs]
+            solid_sign = 1 if areas[max(range(len(cs)), key=lambda i: abs(areas[i]))] > 0 else -1
+            solids = [i for i in range(len(cs)) if areas[i] * solid_sign > 0]
+            groups = {i: [cs[i]] for i in solids}
+            for i in range(len(cs)):
+                if i in groups: continue
+                p = cs[i][0][1]
+                owners = [j for j in solids if point_in([s[1] for s in cs[j]], p)]
+                if owners: groups[min(owners, key=lambda j: abs(areas[j]))].append(cs[i])
+            for i in solids: yield groups[i], fill, stroke, sw
+            return
+        yield cs, fill, stroke, sw
+
+    for el in root: yield from walk(el, 0, 0)
+
+
+# ── SWF writing ──────────────────────────────────────────────────────────────
+
+class BW:
+    def __init__(s): s.out = bytearray(); s.acc = 0; s.n = 0
+    def ub(s, v, n):
+        for i in range(n - 1, -1, -1):
+            s.acc = (s.acc << 1) | ((v >> i) & 1); s.n += 1
+            if s.n == 8: s.out.append(s.acc); s.acc = 0; s.n = 0
+    def sb(s, v, n): s.ub(v & ((1 << n) - 1), n)
+    def align(s):
+        if s.n: s.ub(0, 8 - s.n)
+    def bytes(s, b): s.align(); s.out += b
+
+
+def nbits_s(*vals):
+    n = 1
+    for v in vals:
+        while not (-(1 << (n - 1)) <= v < (1 << (n - 1))): n += 1
+    return n
+
+
+def write_rect(w, x0, x1, y0, y1):
+    n = nbits_s(x0, x1, y0, y1); w.ub(n, 5)
+    for v in (x0, x1, y0, y1): w.sb(v, n)
+    w.align()
+
+
+def shoelace(c):
+    a = 0
+    for s in c:
+        (x0, y0), (x1, y1) = s[1], s[-1]
+        a += x0 * y1 - x1 * y0
+    return a
+
+
+def point_in(poly, p):
+    x, y = p; inside = False; n = len(poly)
+    for i in range(n):
+        (x0, y0), (x1, y1) = poly[i], poly[(i + 1) % n]
+        if (y0 > y) != (y1 > y) and x < x0 + (y - y0) * (x1 - x0) / (y1 - y0): inside = not inside
+    return inside
+
+
+def define_shape3(sid, contours, fill, stroke, sw):
+    # integer twips, closing each contour exactly
+    q = lambda p: (round(p[0] * TW), round(p[1] * TW))
+    cs = [[tuple([s[0]] + [q(p) for p in s[1:]]) for s in c] for c in contours]
+    cs = [[s for s in c if not (s[0] == "L" and s[1] == s[2])] for c in cs]
+    cs = [c for c in cs if c]
+    closed = [c[0][1] == c[-1][-1] for c in cs]
+    polys = [[s[1] for s in c] for c in cs]
+    # nesting depth for even-odd fills
+    depth = []
+    for i, c in enumerate(cs):
+        t = c[0][1]; depth.append(sum(1 for j, pg in enumerate(polys) if j != i and closed[j] and point_in(pg, t)))
+    pad = round(sw * TW / 2) if stroke else 0
+    xs = [p[0] for c in cs for s in c for p in s[1:]]; ys = [p[1] for c in cs for s in c for p in s[1:]]
+    w = BW()
+    w.bytes(struct.pack("<H", sid))
+    write_rect(w, min(xs) - pad, max(xs) + pad, min(ys) - pad, max(ys) + pad)
+    fills = [fill] if fill else []; lines = [stroke] if stroke else []
+    w.bytes(bytes([len(fills)]))
+    for f in fills: w.bytes(bytes([0x00, *f]))
+    w.bytes(bytes([len(lines)]))
+    for l in lines: w.bytes(struct.pack("<H", round(sw * TW)) + bytes(l))
+    nf, nl = (1 if fills else 0), (1 if lines else 0)
+    w.ub(nf, 4); w.ub(nl, 4)
+    x = y = 0
+    for i, c in enumerate(cs):
+        f0 = f1 = 0
+        if fills and closed[i]:
+            interior_on_f0 = shoelace(c) > 0
+            filled_inside = depth[i] % 2 == 0
+            if interior_on_f0 == filled_inside: f0 = 1
+            else: f1 = 1
+        sx, sy = c[0][1]
+        # style change: moveTo + fill0 + fill1 (+ line)
+        flags = 0x01 | (0x02 if nf else 0) | (0x04 if nf else 0) | (0x08 if nl else 0)
+        w.ub(0, 1); w.ub(flags, 5)
+        n = nbits_s(sx, sy); w.ub(n, 5); w.sb(sx, n); w.sb(sy, n)
+        if nf: w.ub(f0, nf); w.ub(f1, nf)
+        if nl: w.ub(1, nl)
+        x, y = sx, sy
+        for s in c:
+            if s[0] == "L":
+                (ex, ey) = s[2]; dx, dy = ex - x, ey - y
+                n = max(nbits_s(dx, dy), 2)
+                w.ub(1, 1); w.ub(1, 1); w.ub(n - 2, 4); w.ub(1, 1); w.sb(dx, n); w.sb(dy, n)
+                x, y = ex, ey
+            else:
+                (cx, cy), (ex, ey) = s[2], s[3]
+                a, b, c2, d = cx - x, cy - y, ex - cx, ey - cy
+                n = max(nbits_s(a, b, c2, d), 2)
+                w.ub(1, 1); w.ub(0, 1); w.ub(n - 2, 4)
+                for v in (a, b, c2, d): w.sb(v, n)
+                x, y = ex, ey
+    w.ub(0, 6); w.align()
+    return bytes(w.out)
+
+
+def tag(code, body):
+    if len(body) < 63: return struct.pack("<H", code << 6 | len(body)) + body
+    return struct.pack("<HI", code << 6 | 63, len(body)) + body
+
+
+def read_tags(d, p, end):
+    while p < end:
+        h = struct.unpack_from("<H", d, p); hdr = p; p += 2; c, l = h[0] >> 6, h[0] & 63
+        if l == 63: l = struct.unpack_from("<I", d, p)[0]; p += 4
+        yield c, d[hdr:p + l], d[p:p + l]; p += l
+        if c == 0: break
+
+
+def build(d, symbols, target_len=None):
+    """d: the title's input_icons movie. symbols: {'Main_Button_N': SVG fragment or <symbol> element}.
+    Returns (new movie, its length before padding, number of shapes)."""
+    nb = d[8] >> 3; hdr_end = 8 + (5 + 4 * nb + 7) // 8 + 4
+    tags = list(read_tags(d, hdr_end, len(d)))
+    names = {}
+    for c, raw, body in tags:
+        if c == 76:
+            n = struct.unpack_from("<H", body)[0]; q = 2
+            for _ in range(n):
+                i = struct.unpack_from("<H", body, q)[0]; q += 2; e = body.index(b"\0", q); names[body[q:e].decode().split(".")[-1]] = i; q = e + 1
+    shapes = {}; shape_tags = []; sprite_tags = {}; next_id = 1
+    used = {struct.unpack_from("<H", body)[0] for c, _, body in tags if c == 39}
+    for nm, sid in sorted(((n, i) for n, i in names.items() if n.startswith("Main_Button_")), key=lambda kv: kv[1]):
+        if nm not in symbols: raise KeyError(f"no design for {nm}")
+        places = []
+        for cs, fill, stroke, sw in elements(symbols[nm]):
+            key = (repr(cs), fill, stroke, sw)
+            if key not in shapes:
+                while next_id in used: next_id += 1
+                shapes[key] = next_id; used.add(next_id)
+                shape_tags.append(tag(32, define_shape3(next_id, cs, fill, stroke, sw)))
+            places.append(shapes[key])
+        body = struct.pack("<HH", sid, 1)
+        for depth, ch in enumerate(places, 1):
+            body += tag(26, bytes([0x02]) + struct.pack("<HH", depth, ch))
+        body += tag(1, b"") + tag(0, b"")
+        sprite_tags[sid] = tag(39, body)
+    out = bytearray(d[:hdr_end]); inserted = False
+    for c, raw, body in tags:
+        if c == 32:
+            if not inserted: out += b"".join(shape_tags); inserted = True
+            continue
+        if c == 39:
+            sid = struct.unpack_from("<H", body)[0]
+            if not inserted: out += b"".join(shape_tags); inserted = True
+            out += sprite_tags[sid]; continue
+        out += raw
+    real = len(out)
+    if target_len:
+        if real > target_len: raise ValueError(f"movie is {real} bytes, over {target_len}")
+        out += bytes(target_len - real)
+    struct.pack_into("<I", out, 4, len(out))
+    return bytes(out), real, len(shape_tags)
+
+
+# ── data.rpf ────────────────────────────────────────────────────────────────
+
+KNOWN_OFFSET = 0x117d7000   # the entry in the data.rpf we have (481,544,304 bytes)
+MARK = b"platform_xbsx.input_icons"
+
+
+def read_stream(f, off, limit=1 << 20):
+    """Inflate the zlib stream at `off`. Returns (data, compressed size) or None."""
+    f.seek(off); buf = f.read(limit)
+    if len(buf) < 2 or buf[0] != 0x78: return None
+    d = zlib.decompressobj()
+    try: out = d.decompress(buf)
+    except zlib.error: return None
+    if not d.eof: return None
+    return out, len(buf) - len(d.unused_data)
+
+
+def is_icon_movie(data):
+    return data[:3] in (b"GFX", b"CFX") and MARK in data and b"Main_Button_" in data
+
+
+def find_entry(path, offset):
+    with open(path, "rb") as f:
+        hit = read_stream(f, offset)
+        if hit and is_icon_movie(hit[0]): return offset, hit[0], hit[1]
+        print(f"not at {offset:#x}; scanning {path} for the icon library...")
+        size = os.fstat(f.fileno()).st_size; base = 0; step = 64 << 20
+        while base < size:
+            f.seek(base); chunk = f.read(step + 16)
+            i = chunk.find(b"\x78\xda")
+            while 0 <= i < step:
+                off = base + i
+                if off % 16 == 0:
+                    hit = read_stream(f, off)
+                    if hit and is_icon_movie(hit[0]): return off, hit[0], hit[1]
+                i = chunk.find(b"\x78\xda", i + 1)
+            base += step
+    raise SystemExit("platform_xbsx.input_icons was not found in data.rpf")
+
+
+def pack_exact(movie, real, csize):
+    """A zlib stream of exactly `csize` bytes for `movie` (whose bytes after `real` are padding): the tail of the
+    padding gets seeded pseudo-random bytes until the compressed size lands on `csize`."""
+    import random
+    def comp(b):
+        c = zlib.compressobj(9, zlib.DEFLATED, 15, 9); return c.compress(b) + c.flush()
+    room = len(movie) - real
+    base = len(comp(movie))
+    if base > csize:
+        raise SystemExit(f"the new library packs to {base} bytes, over the original's {csize}: simplify the icons")
+    est = csize - base
+    for seed in range(400):
+        rnd = random.Random(seed); tail = bytes(rnd.getrandbits(8) for _ in range(room))
+        for n in range(max(0, est - 40), min(room, est + 40) + 1):
+            data = movie[:real] + bytes(room - n) + tail[:n]
+            c = comp(data)
+            if len(c) == csize: return c, data
+    raise SystemExit("could not pack the library to the original's exact compressed size")
+
+
+def load_master(path):
+    syms = {}
+    for el in ET.parse(path).getroot().iter():
+        if el.tag.split("}")[-1] == "symbol" and el.get("id", "").startswith("Main_Button_"):
+            syms[el.get("id")] = el
+    return syms
+
+
+def main():
+    import argparse, shutil
+    here = os.path.dirname(os.path.abspath(__file__))
+    ap = argparse.ArgumentParser(description="Build the keyboard/mouse icon library into a copy of data.rpf.")
+    ap.add_argument("--game", required=True, help="the title's game folder (holds data.rpf); only read")
+    ap.add_argument("--out", help="where to write the patched copy of data.rpf (the title's XCL overlay folder)")
+    ap.add_argument("--master", default=os.path.join(here, "..", "..", "docs", "kbm-icons", "icons-master.svg"))
+    ap.add_argument("--offset", type=lambda v: int(v, 0), default=KNOWN_OFFSET)
+    ap.add_argument("--movie-out", help="also write the rebuilt movie here (made from game data: keep it local)")
+    a = ap.parse_args()
+    src = os.path.join(a.game, "data.rpf")
+    off, orig, csize = find_entry(src, a.offset)
+    movie, real, nshapes = build(orig, load_master(a.master), target_len=len(orig))
+    c, data = pack_exact(movie, real, csize)
+    assert zlib.decompress(c) == data and len(data) == len(orig) and len(c) == csize
+    print(f"input_icons at {off:#x}: {len(orig)} bytes ({csize} packed); new library {real} bytes, "
+          f"{nshapes} shapes, packed to {len(c)} bytes")
+    if a.movie_out:
+        with open(a.movie_out, "wb") as f: f.write(data)

Have some patience

<!-- greyfinch-sync:ivall/xcl:review-comment:4684640764 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1604#discussion_r4684640764). Originally posted by [zohaiblazuli](https://github.com/zohaiblazuli) on 2026-11-24T18:25:39Z. **Code review location:** `scripts/kbm_icons/build_library.py`; line 444 ~~~~diff @@ -0,0 +1,462 @@ +r"""Build the keyboard/mouse icon library for the retail title and write it into a COPY of its data.rpf. + + python scripts/kbm_icons/build_library.py --game D:\Game --out %LOCALAPPDATA%\XCL\<title>\overlay\data.rpf + +XCL reads a game file from the title's overlay folder when one is there (crates/xcl/src/vfs.rs), so the +patched copy replaces the original without touching the game folder. Delete the copy to undo. + +What it does (details and measurements: docs/kbm-icons/README.md): +1. Finds the title's `platform_xbsx.input_icons` movie in data.rpf. Each archive entry is a plain zlib + stream; nothing is decrypted. The entry is at a known offset in the version we have, checked by content, + with a scan of the archive as a fallback. +2. Rebuilds that movie: the 38 `Main_Button_N` sprites and their shapes come from icons-master.svg; every + other tag (the movie's own script, exports, symbol classes) is copied from the user's file as it is. +3. Packs it to the original entry's exact sizes (unpacked and zlib), so the archive's table of contents + still describes it, and writes data.rpf with only that entry changed. + +Supported SVG in the master file: <g transform="translate(x y)">, <rect rx>, <polygon>, <path> with absolute +M L H V Q A Z, <text> (outlined from Windows' Bahnschrift Bold Condensed), fill / stroke / stroke-width as +attributes, #rgb or #rrggbb colours. Units are the library's (1 unit = 20 twips; a symbol is 64 tall). +Needs Python 3.10+ and fontTools (MIT). +""" +import math, re, struct, sys, os, zlib +import xml.etree.ElementTree as ET + + +TW = 20 + +# ── font ───────────────────────────────────────────────────────────────────── +_font = None + + +def font(): + global _font + if _font is None: + from fontTools.ttLib import TTFont + from fontTools.varLib import instancer + f = TTFont(r"C:\Windows\Fonts\bahnschrift.ttf") + _font = instancer.instantiateVariableFont(f, {"wght": 700, "wdth": 75}) + return _font + + +def glyph_contours(ch): + """Contours of one glyph in font units, y-up, as lists of segments ('L', p0, p1) / ('Q', p0, c, p1).""" + from fontTools.pens.basePen import BasePen + f = font(); gs = f.getGlyphSet(); name = f.getBestCmap()[ord(ch)] + + class P(BasePen): + def __init__(s): super().__init__(gs); s.cs = []; s.cur = None; s.start = None + def _moveTo(s, p): s.cs.append([]); s.cur = s.start = p + def _lineTo(s, p): s.cs[-1].append(("L", s.cur, p)); s.cur = p + def _qCurveToOne(s, c, p): s.cs[-1].append(("Q", s.cur, c, p)); s.cur = p + def _curveToOne(s, c1, c2, p): # cubic → two quads (Bahnschrift is quadratic; kept for safety) + m = ((c1[0] + c2[0]) / 2, (c1[1] + c2[1]) / 2) + s._qCurveToOne(((s.cur[0] + 3 * c1[0]) / 4, (s.cur[1] + 3 * c1[1]) / 4), m) + s._qCurveToOne(((3 * c2[0] + p[0]) / 4, (3 * c2[1] + p[1]) / 4), p) + def _closePath(s): + if s.cur != s.start: s.cs[-1].append(("L", s.cur, s.start)); s.cur = s.start + _endPath = _closePath + pen = P(); gs[name].draw(pen) + return pen.cs, gs[name].width + + +def text_contours(s, x, y, fs, anchor, text_length): + """SVG text → contours in symbol units (y-down). The cap height matches the SVG design (0.7 em).""" + f = font(); cap_font = f["OS/2"].sCapHeight + k = (fs * 0.7) / cap_font + adv = 0; glyphs = [] + for ch in s: + cs, w = glyph_contours(ch); glyphs.append((adv, cs)); adv += w + width = adv * k + sx = k + if text_length: + sx = text_length / adv; width = text_length + x0 = x - width / 2 if anchor == "middle" else x + out = [] + for gx, cs in glyphs: + for c in cs: + out.append([tuple([seg[0]] + [(x0 + (gx + px) * sx, y - py * k) for px, py in seg[1:]]) for seg in c]) + return out + + +# ── SVG geometry ───────────────────────────────────────────────────────────── + +def arc_to_quads(p0, rx, ry, rot, large, sweep, p1): + """SVG elliptical arc → quadratic segments (each ≤ 45°).""" + x1, y1 = p0; x2, y2 = p1 + if rx == 0 or ry == 0: return [("L", p0, p1)] + phi = math.radians(rot); cp, sp = math.cos(phi), math.sin(phi) + dx, dy = (x1 - x2) / 2, (y1 - y2) / 2 + x1p, y1p = cp * dx + sp * dy, -sp * dx + cp * dy + lam = (x1p / rx) ** 2 + (y1p / ry) ** 2 + if lam > 1: rx *= math.sqrt(lam); ry *= math.sqrt(lam) + num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p + den = rx * rx * y1p * y1p + ry * ry * x1p * x1p + co = math.sqrt(max(0, num / den)) if den else 0 + if large == sweep: co = -co + cxp, cyp = co * rx * y1p / ry, -co * ry * x1p / rx + cx = cp * cxp - sp * cyp + (x1 + x2) / 2; cy = sp * cxp + cp * cyp + (y1 + y2) / 2 + ang = lambda ux, uy, vx, vy: math.atan2(ux * vy - uy * vx, ux * vx + uy * vy) + t1 = ang(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry) + dt = ang((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry) + if not sweep and dt > 0: dt -= 2 * math.pi + if sweep and dt < 0: dt += 2 * math.pi + n = max(1, math.ceil(abs(dt) / (math.pi / 2 if max(rx, ry) <= 14 else math.pi / 3) - 1e-9)); h = dt / n # 90 deg pieces for corners, 60 for big rings + pt = lambda t: (cx + rx * math.cos(t) * cp - ry * math.sin(t) * sp, cy + rx * math.cos(t) * sp + ry * math.sin(t) * cp) + segs = []; cur = p0 + for i in range(n): + ta, tb = t1 + i * h, t1 + (i + 1) * h; tm = (ta + tb) / 2 + e = 1 / math.cos(h / 2) + c = (cx + rx * e * math.cos(tm) * cp - ry * e * math.sin(tm) * sp, cy + rx * e * math.cos(tm) * sp + ry * e * math.sin(tm) * cp) + nxt = p1 if i == n - 1 else pt(tb) + segs.append(("Q", cur, c, nxt)); cur = nxt + return segs + + +def path_contours(d): + toks = re.findall(r"[MLHVAQZ]|-?\d*\.?\d+(?:e-?\d+)?", d) + i = 0; cs = []; cur = start = (0, 0); cmd = None + def num(): + nonlocal i; v = float(toks[i]); i += 1; return v + while i < len(toks): + if re.match(r"[A-Z]", toks[i]): cmd = toks[i]; i += 1 + if cmd == "M": cur = start = (num(), num()); cs.append([]); cmd = "L"; continue + if cmd == "Z": + if cs and cur != start: cs[-1].append(("L", cur, start)) + cur = start; continue + if cmd == "L": p = (num(), num()); cs[-1].append(("L", cur, p)); cur = p + elif cmd == "H": p = (num(), cur[1]); cs[-1].append(("L", cur, p)); cur = p + elif cmd == "V": p = (cur[0], num()); cs[-1].append(("L", cur, p)); cur = p + elif cmd == "Q": c = (num(), num()); p = (num(), num()); cs[-1].append(("Q", cur, c, p)); cur = p + elif cmd == "A": + rx, ry, rot, la, sw = num(), num(), num(), num(), num(); p = (num(), num()) + cs[-1].extend(arc_to_quads(cur, rx, ry, rot, int(la), int(sw), p)); cur = p + else: raise ValueError(cmd) + return [c for c in cs if c] + + +def rect_contours(x, y, w, h, r): + r = min(r, w / 2, h / 2) + if r <= 0: + return path_contours(f"M{x} {y} H{x + w} V{y + h} H{x} Z") + return path_contours(f"M{x + r} {y} H{x + w - r} A{r} {r} 0 0 1 {x + w} {y + r} V{y + h - r} A{r} {r} 0 0 1 {x + w - r} {y + h} " + f"H{x + r} A{r} {r} 0 0 1 {x} {y + h - r} V{y + r} A{r} {r} 0 0 1 {x + r} {y} Z") + + +def color(v): + if not v or v == "none": return None + v = v.lstrip("#") + if len(v) == 3: v = "".join(c * 2 for c in v) + return (int(v[0:2], 16), int(v[2:4], 16), int(v[4:6], 16), 255) + + +def elements(svg): + """Yield (contours, fill, stroke, stroke_width) for each drawable element, in paint order. + `svg` is an SVG fragment (text) or an element whose children are drawn (a master-file <symbol>).""" + root = ET.fromstring(f"<g>{svg}</g>") if isinstance(svg, str) else svg + + def walk(el, dx, dy): + tag = el.tag.split("}")[-1] + if tag == "g": + m = re.match(r"translate\(([-\d.e]+)\s+([-\d.e]+)\)", el.get("transform", "translate(0 0)")) + for c in el: yield from walk(c, dx + float(m.group(1)), dy + float(m.group(2))) + return + fill = color(el.get("fill", "#000")); stroke = color(el.get("stroke")); sw = float(el.get("stroke-width", "1")) + if tag == "rect": + cs = rect_contours(float(el.get("x")), float(el.get("y")), float(el.get("width")), float(el.get("height")), float(el.get("rx", 0))) + elif tag == "path": + cs = path_contours(el.get("d")) + elif tag == "polygon": + pts = [tuple(map(float, p.split(","))) for p in el.get("points").split()] + cs = [[("L", pts[i], pts[(i + 1) % len(pts)]) for i in range(len(pts))]] + elif tag == "text": + tl = el.get("textLength") + cs = text_contours(el.text, float(el.get("x")), float(el.get("y")), float(el.get("font-size")), + el.get("text-anchor", "start"), float(tl) if tl else None) + stroke = None + else: + raise ValueError(tag) + cs = [[tuple([s[0]] + [(px + dx, py + dy) for px, py in s[1:]]) for s in c] for c in cs] + if tag == "text": + # Variable-font glyphs overlap (an E is a stem plus bars). Give every solid contour its own + # shape, with the holes it contains, so overlaps add up instead of cancelling (even-odd). + areas = [shoelace(c) for c in cs] + solid_sign = 1 if areas[max(range(len(cs)), key=lambda i: abs(areas[i]))] > 0 else -1 + solids = [i for i in range(len(cs)) if areas[i] * solid_sign > 0] + groups = {i: [cs[i]] for i in solids} + for i in range(len(cs)): + if i in groups: continue + p = cs[i][0][1] + owners = [j for j in solids if point_in([s[1] for s in cs[j]], p)] + if owners: groups[min(owners, key=lambda j: abs(areas[j]))].append(cs[i]) + for i in solids: yield groups[i], fill, stroke, sw + return + yield cs, fill, stroke, sw + + for el in root: yield from walk(el, 0, 0) + + +# ── SWF writing ────────────────────────────────────────────────────────────── + +class BW: + def __init__(s): s.out = bytearray(); s.acc = 0; s.n = 0 + def ub(s, v, n): + for i in range(n - 1, -1, -1): + s.acc = (s.acc << 1) | ((v >> i) & 1); s.n += 1 + if s.n == 8: s.out.append(s.acc); s.acc = 0; s.n = 0 + def sb(s, v, n): s.ub(v & ((1 << n) - 1), n) + def align(s): + if s.n: s.ub(0, 8 - s.n) + def bytes(s, b): s.align(); s.out += b + + +def nbits_s(*vals): + n = 1 + for v in vals: + while not (-(1 << (n - 1)) <= v < (1 << (n - 1))): n += 1 + return n + + +def write_rect(w, x0, x1, y0, y1): + n = nbits_s(x0, x1, y0, y1); w.ub(n, 5) + for v in (x0, x1, y0, y1): w.sb(v, n) + w.align() + + +def shoelace(c): + a = 0 + for s in c: + (x0, y0), (x1, y1) = s[1], s[-1] + a += x0 * y1 - x1 * y0 + return a + + +def point_in(poly, p): + x, y = p; inside = False; n = len(poly) + for i in range(n): + (x0, y0), (x1, y1) = poly[i], poly[(i + 1) % n] + if (y0 > y) != (y1 > y) and x < x0 + (y - y0) * (x1 - x0) / (y1 - y0): inside = not inside + return inside + + +def define_shape3(sid, contours, fill, stroke, sw): + # integer twips, closing each contour exactly + q = lambda p: (round(p[0] * TW), round(p[1] * TW)) + cs = [[tuple([s[0]] + [q(p) for p in s[1:]]) for s in c] for c in contours] + cs = [[s for s in c if not (s[0] == "L" and s[1] == s[2])] for c in cs] + cs = [c for c in cs if c] + closed = [c[0][1] == c[-1][-1] for c in cs] + polys = [[s[1] for s in c] for c in cs] + # nesting depth for even-odd fills + depth = [] + for i, c in enumerate(cs): + t = c[0][1]; depth.append(sum(1 for j, pg in enumerate(polys) if j != i and closed[j] and point_in(pg, t))) + pad = round(sw * TW / 2) if stroke else 0 + xs = [p[0] for c in cs for s in c for p in s[1:]]; ys = [p[1] for c in cs for s in c for p in s[1:]] + w = BW() + w.bytes(struct.pack("<H", sid)) + write_rect(w, min(xs) - pad, max(xs) + pad, min(ys) - pad, max(ys) + pad) + fills = [fill] if fill else []; lines = [stroke] if stroke else [] + w.bytes(bytes([len(fills)])) + for f in fills: w.bytes(bytes([0x00, *f])) + w.bytes(bytes([len(lines)])) + for l in lines: w.bytes(struct.pack("<H", round(sw * TW)) + bytes(l)) + nf, nl = (1 if fills else 0), (1 if lines else 0) + w.ub(nf, 4); w.ub(nl, 4) + x = y = 0 + for i, c in enumerate(cs): + f0 = f1 = 0 + if fills and closed[i]: + interior_on_f0 = shoelace(c) > 0 + filled_inside = depth[i] % 2 == 0 + if interior_on_f0 == filled_inside: f0 = 1 + else: f1 = 1 + sx, sy = c[0][1] + # style change: moveTo + fill0 + fill1 (+ line) + flags = 0x01 | (0x02 if nf else 0) | (0x04 if nf else 0) | (0x08 if nl else 0) + w.ub(0, 1); w.ub(flags, 5) + n = nbits_s(sx, sy); w.ub(n, 5); w.sb(sx, n); w.sb(sy, n) + if nf: w.ub(f0, nf); w.ub(f1, nf) + if nl: w.ub(1, nl) + x, y = sx, sy + for s in c: + if s[0] == "L": + (ex, ey) = s[2]; dx, dy = ex - x, ey - y + n = max(nbits_s(dx, dy), 2) + w.ub(1, 1); w.ub(1, 1); w.ub(n - 2, 4); w.ub(1, 1); w.sb(dx, n); w.sb(dy, n) + x, y = ex, ey + else: + (cx, cy), (ex, ey) = s[2], s[3] + a, b, c2, d = cx - x, cy - y, ex - cx, ey - cy + n = max(nbits_s(a, b, c2, d), 2) + w.ub(1, 1); w.ub(0, 1); w.ub(n - 2, 4) + for v in (a, b, c2, d): w.sb(v, n) + x, y = ex, ey + w.ub(0, 6); w.align() + return bytes(w.out) + + +def tag(code, body): + if len(body) < 63: return struct.pack("<H", code << 6 | len(body)) + body + return struct.pack("<HI", code << 6 | 63, len(body)) + body + + +def read_tags(d, p, end): + while p < end: + h = struct.unpack_from("<H", d, p); hdr = p; p += 2; c, l = h[0] >> 6, h[0] & 63 + if l == 63: l = struct.unpack_from("<I", d, p)[0]; p += 4 + yield c, d[hdr:p + l], d[p:p + l]; p += l + if c == 0: break + + +def build(d, symbols, target_len=None): + """d: the title's input_icons movie. symbols: {'Main_Button_N': SVG fragment or <symbol> element}. + Returns (new movie, its length before padding, number of shapes).""" + nb = d[8] >> 3; hdr_end = 8 + (5 + 4 * nb + 7) // 8 + 4 + tags = list(read_tags(d, hdr_end, len(d))) + names = {} + for c, raw, body in tags: + if c == 76: + n = struct.unpack_from("<H", body)[0]; q = 2 + for _ in range(n): + i = struct.unpack_from("<H", body, q)[0]; q += 2; e = body.index(b"\0", q); names[body[q:e].decode().split(".")[-1]] = i; q = e + 1 + shapes = {}; shape_tags = []; sprite_tags = {}; next_id = 1 + used = {struct.unpack_from("<H", body)[0] for c, _, body in tags if c == 39} + for nm, sid in sorted(((n, i) for n, i in names.items() if n.startswith("Main_Button_")), key=lambda kv: kv[1]): + if nm not in symbols: raise KeyError(f"no design for {nm}") + places = [] + for cs, fill, stroke, sw in elements(symbols[nm]): + key = (repr(cs), fill, stroke, sw) + if key not in shapes: + while next_id in used: next_id += 1 + shapes[key] = next_id; used.add(next_id) + shape_tags.append(tag(32, define_shape3(next_id, cs, fill, stroke, sw))) + places.append(shapes[key]) + body = struct.pack("<HH", sid, 1) + for depth, ch in enumerate(places, 1): + body += tag(26, bytes([0x02]) + struct.pack("<HH", depth, ch)) + body += tag(1, b"") + tag(0, b"") + sprite_tags[sid] = tag(39, body) + out = bytearray(d[:hdr_end]); inserted = False + for c, raw, body in tags: + if c == 32: + if not inserted: out += b"".join(shape_tags); inserted = True + continue + if c == 39: + sid = struct.unpack_from("<H", body)[0] + if not inserted: out += b"".join(shape_tags); inserted = True + out += sprite_tags[sid]; continue + out += raw + real = len(out) + if target_len: + if real > target_len: raise ValueError(f"movie is {real} bytes, over {target_len}") + out += bytes(target_len - real) + struct.pack_into("<I", out, 4, len(out)) + return bytes(out), real, len(shape_tags) + + +# ── data.rpf ──────────────────────────────────────────────────────────────── + +KNOWN_OFFSET = 0x117d7000 # the entry in the data.rpf we have (481,544,304 bytes) +MARK = b"platform_xbsx.input_icons" + + +def read_stream(f, off, limit=1 << 20): + """Inflate the zlib stream at `off`. Returns (data, compressed size) or None.""" + f.seek(off); buf = f.read(limit) + if len(buf) < 2 or buf[0] != 0x78: return None + d = zlib.decompressobj() + try: out = d.decompress(buf) + except zlib.error: return None + if not d.eof: return None + return out, len(buf) - len(d.unused_data) + + +def is_icon_movie(data): + return data[:3] in (b"GFX", b"CFX") and MARK in data and b"Main_Button_" in data + + +def find_entry(path, offset): + with open(path, "rb") as f: + hit = read_stream(f, offset) + if hit and is_icon_movie(hit[0]): return offset, hit[0], hit[1] + print(f"not at {offset:#x}; scanning {path} for the icon library...") + size = os.fstat(f.fileno()).st_size; base = 0; step = 64 << 20 + while base < size: + f.seek(base); chunk = f.read(step + 16) + i = chunk.find(b"\x78\xda") + while 0 <= i < step: + off = base + i + if off % 16 == 0: + hit = read_stream(f, off) + if hit and is_icon_movie(hit[0]): return off, hit[0], hit[1] + i = chunk.find(b"\x78\xda", i + 1) + base += step + raise SystemExit("platform_xbsx.input_icons was not found in data.rpf") + + +def pack_exact(movie, real, csize): + """A zlib stream of exactly `csize` bytes for `movie` (whose bytes after `real` are padding): the tail of the + padding gets seeded pseudo-random bytes until the compressed size lands on `csize`.""" + import random + def comp(b): + c = zlib.compressobj(9, zlib.DEFLATED, 15, 9); return c.compress(b) + c.flush() + room = len(movie) - real + base = len(comp(movie)) + if base > csize: + raise SystemExit(f"the new library packs to {base} bytes, over the original's {csize}: simplify the icons") + est = csize - base + for seed in range(400): + rnd = random.Random(seed); tail = bytes(rnd.getrandbits(8) for _ in range(room)) + for n in range(max(0, est - 40), min(room, est + 40) + 1): + data = movie[:real] + bytes(room - n) + tail[:n] + c = comp(data) + if len(c) == csize: return c, data + raise SystemExit("could not pack the library to the original's exact compressed size") + + +def load_master(path): + syms = {} + for el in ET.parse(path).getroot().iter(): + if el.tag.split("}")[-1] == "symbol" and el.get("id", "").startswith("Main_Button_"): + syms[el.get("id")] = el + return syms + + +def main(): + import argparse, shutil + here = os.path.dirname(os.path.abspath(__file__)) + ap = argparse.ArgumentParser(description="Build the keyboard/mouse icon library into a copy of data.rpf.") + ap.add_argument("--game", required=True, help="the title's game folder (holds data.rpf); only read") + ap.add_argument("--out", help="where to write the patched copy of data.rpf (the title's XCL overlay folder)") + ap.add_argument("--master", default=os.path.join(here, "..", "..", "docs", "kbm-icons", "icons-master.svg")) + ap.add_argument("--offset", type=lambda v: int(v, 0), default=KNOWN_OFFSET) + ap.add_argument("--movie-out", help="also write the rebuilt movie here (made from game data: keep it local)") + a = ap.parse_args() + src = os.path.join(a.game, "data.rpf") + off, orig, csize = find_entry(src, a.offset) + movie, real, nshapes = build(orig, load_master(a.master), target_len=len(orig)) + c, data = pack_exact(movie, real, csize) + assert zlib.decompress(c) == data and len(data) == len(orig) and len(c) == csize + print(f"input_icons at {off:#x}: {len(orig)} bytes ({csize} packed); new library {real} bytes, " + f"{nshapes} shapes, packed to {len(c)} bytes") + if a.movie_out: + with open(a.movie_out, "wb") as f: f.write(data) ~~~~ --- Have some patience
zohaiblazuli commented 2026-11-24 19:08:00 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by zohaiblazuli on 2026-11-24T18:30:58Z.

Code review location: scripts/kbm_icons/build_library.py; line 444

@@ -0,0 +1,462 @@
+r"""Build the keyboard/mouse icon library for the retail title and write it into a COPY of its data.rpf.
+
+    python scripts/kbm_icons/build_library.py --game D:\Game --out %LOCALAPPDATA%\XCL\<title>\overlay\data.rpf
+
+XCL reads a game file from the title's overlay folder when one is there (crates/xcl/src/vfs.rs), so the
+patched copy replaces the original without touching the game folder. Delete the copy to undo.
+
+What it does (details and measurements: docs/kbm-icons/README.md):
+1. Finds the title's `platform_xbsx.input_icons` movie in data.rpf. Each archive entry is a plain zlib
+   stream; nothing is decrypted. The entry is at a known offset in the version we have, checked by content,
+   with a scan of the archive as a fallback.
+2. Rebuilds that movie: the 38 `Main_Button_N` sprites and their shapes come from icons-master.svg; every
+   other tag (the movie's own script, exports, symbol classes) is copied from the user's file as it is.
+3. Packs it to the original entry's exact sizes (unpacked and zlib), so the archive's table of contents
+   still describes it, and writes data.rpf with only that entry changed.
+
+Supported SVG in the master file: <g transform="translate(x y)">, <rect rx>, <polygon>, <path> with absolute
+M L H V Q A Z, <text> (outlined from Windows' Bahnschrift Bold Condensed), fill / stroke / stroke-width as
+attributes, #rgb or #rrggbb colours. Units are the library's (1 unit = 20 twips; a symbol is 64 tall).
+Needs Python 3.10+ and fontTools (MIT).
+"""
+import math, re, struct, sys, os, zlib
+import xml.etree.ElementTree as ET
+
+
+TW = 20
+
+# ── font ─────────────────────────────────────────────────────────────────────
+_font = None
+
+
+def font():
+    global _font
+    if _font is None:
+        from fontTools.ttLib import TTFont
+        from fontTools.varLib import instancer
+        f = TTFont(r"C:\Windows\Fonts\bahnschrift.ttf")
+        _font = instancer.instantiateVariableFont(f, {"wght": 700, "wdth": 75})
+    return _font
+
+
+def glyph_contours(ch):
+    """Contours of one glyph in font units, y-up, as lists of segments ('L', p0, p1) / ('Q', p0, c, p1)."""
+    from fontTools.pens.basePen import BasePen
+    f = font(); gs = f.getGlyphSet(); name = f.getBestCmap()[ord(ch)]
+
+    class P(BasePen):
+        def __init__(s): super().__init__(gs); s.cs = []; s.cur = None; s.start = None
+        def _moveTo(s, p): s.cs.append([]); s.cur = s.start = p
+        def _lineTo(s, p): s.cs[-1].append(("L", s.cur, p)); s.cur = p
+        def _qCurveToOne(s, c, p): s.cs[-1].append(("Q", s.cur, c, p)); s.cur = p
+        def _curveToOne(s, c1, c2, p):  # cubic → two quads (Bahnschrift is quadratic; kept for safety)
+            m = ((c1[0] + c2[0]) / 2, (c1[1] + c2[1]) / 2)
+            s._qCurveToOne(((s.cur[0] + 3 * c1[0]) / 4, (s.cur[1] + 3 * c1[1]) / 4), m)
+            s._qCurveToOne(((3 * c2[0] + p[0]) / 4, (3 * c2[1] + p[1]) / 4), p)
+        def _closePath(s):
+            if s.cur != s.start: s.cs[-1].append(("L", s.cur, s.start)); s.cur = s.start
+        _endPath = _closePath
+    pen = P(); gs[name].draw(pen)
+    return pen.cs, gs[name].width
+
+
+def text_contours(s, x, y, fs, anchor, text_length):
+    """SVG text → contours in symbol units (y-down). The cap height matches the SVG design (0.7 em)."""
+    f = font(); cap_font = f["OS/2"].sCapHeight
+    k = (fs * 0.7) / cap_font
+    adv = 0; glyphs = []
+    for ch in s:
+        cs, w = glyph_contours(ch); glyphs.append((adv, cs)); adv += w
+    width = adv * k
+    sx = k
+    if text_length:
+        sx = text_length / adv; width = text_length
+    x0 = x - width / 2 if anchor == "middle" else x
+    out = []
+    for gx, cs in glyphs:
+        for c in cs:
+            out.append([tuple([seg[0]] + [(x0 + (gx + px) * sx, y - py * k) for px, py in seg[1:]]) for seg in c])
+    return out
+
+
+# ── SVG geometry ─────────────────────────────────────────────────────────────
+
+def arc_to_quads(p0, rx, ry, rot, large, sweep, p1):
+    """SVG elliptical arc → quadratic segments (each ≤ 45°)."""
+    x1, y1 = p0; x2, y2 = p1
+    if rx == 0 or ry == 0: return [("L", p0, p1)]
+    phi = math.radians(rot); cp, sp = math.cos(phi), math.sin(phi)
+    dx, dy = (x1 - x2) / 2, (y1 - y2) / 2
+    x1p, y1p = cp * dx + sp * dy, -sp * dx + cp * dy
+    lam = (x1p / rx) ** 2 + (y1p / ry) ** 2
+    if lam > 1: rx *= math.sqrt(lam); ry *= math.sqrt(lam)
+    num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p
+    den = rx * rx * y1p * y1p + ry * ry * x1p * x1p
+    co = math.sqrt(max(0, num / den)) if den else 0
+    if large == sweep: co = -co
+    cxp, cyp = co * rx * y1p / ry, -co * ry * x1p / rx
+    cx = cp * cxp - sp * cyp + (x1 + x2) / 2; cy = sp * cxp + cp * cyp + (y1 + y2) / 2
+    ang = lambda ux, uy, vx, vy: math.atan2(ux * vy - uy * vx, ux * vx + uy * vy)
+    t1 = ang(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry)
+    dt = ang((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry)
+    if not sweep and dt > 0: dt -= 2 * math.pi
+    if sweep and dt < 0: dt += 2 * math.pi
+    n = max(1, math.ceil(abs(dt) / (math.pi / 2 if max(rx, ry) <= 14 else math.pi / 3) - 1e-9)); h = dt / n  # 90 deg pieces for corners, 60 for big rings
+    pt = lambda t: (cx + rx * math.cos(t) * cp - ry * math.sin(t) * sp, cy + rx * math.cos(t) * sp + ry * math.sin(t) * cp)
+    segs = []; cur = p0
+    for i in range(n):
+        ta, tb = t1 + i * h, t1 + (i + 1) * h; tm = (ta + tb) / 2
+        e = 1 / math.cos(h / 2)
+        c = (cx + rx * e * math.cos(tm) * cp - ry * e * math.sin(tm) * sp, cy + rx * e * math.cos(tm) * sp + ry * e * math.sin(tm) * cp)
+        nxt = p1 if i == n - 1 else pt(tb)
+        segs.append(("Q", cur, c, nxt)); cur = nxt
+    return segs
+
+
+def path_contours(d):
+    toks = re.findall(r"[MLHVAQZ]|-?\d*\.?\d+(?:e-?\d+)?", d)
+    i = 0; cs = []; cur = start = (0, 0); cmd = None
+    def num():
+        nonlocal i; v = float(toks[i]); i += 1; return v
+    while i < len(toks):
+        if re.match(r"[A-Z]", toks[i]): cmd = toks[i]; i += 1
+        if cmd == "M": cur = start = (num(), num()); cs.append([]); cmd = "L"; continue
+        if cmd == "Z":
+            if cs and cur != start: cs[-1].append(("L", cur, start))
+            cur = start; continue
+        if cmd == "L": p = (num(), num()); cs[-1].append(("L", cur, p)); cur = p
+        elif cmd == "H": p = (num(), cur[1]); cs[-1].append(("L", cur, p)); cur = p
+        elif cmd == "V": p = (cur[0], num()); cs[-1].append(("L", cur, p)); cur = p
+        elif cmd == "Q": c = (num(), num()); p = (num(), num()); cs[-1].append(("Q", cur, c, p)); cur = p
+        elif cmd == "A":
+            rx, ry, rot, la, sw = num(), num(), num(), num(), num(); p = (num(), num())
+            cs[-1].extend(arc_to_quads(cur, rx, ry, rot, int(la), int(sw), p)); cur = p
+        else: raise ValueError(cmd)
+    return [c for c in cs if c]
+
+
+def rect_contours(x, y, w, h, r):
+    r = min(r, w / 2, h / 2)
+    if r <= 0:
+        return path_contours(f"M{x} {y} H{x + w} V{y + h} H{x} Z")
+    return path_contours(f"M{x + r} {y} H{x + w - r} A{r} {r} 0 0 1 {x + w} {y + r} V{y + h - r} A{r} {r} 0 0 1 {x + w - r} {y + h} "
+                         f"H{x + r} A{r} {r} 0 0 1 {x} {y + h - r} V{y + r} A{r} {r} 0 0 1 {x + r} {y} Z")
+
+
+def color(v):
+    if not v or v == "none": return None
+    v = v.lstrip("#")
+    if len(v) == 3: v = "".join(c * 2 for c in v)
+    return (int(v[0:2], 16), int(v[2:4], 16), int(v[4:6], 16), 255)
+
+
+def elements(svg):
+    """Yield (contours, fill, stroke, stroke_width) for each drawable element, in paint order.
+    `svg` is an SVG fragment (text) or an element whose children are drawn (a master-file <symbol>)."""
+    root = ET.fromstring(f"<g>{svg}</g>") if isinstance(svg, str) else svg
+
+    def walk(el, dx, dy):
+        tag = el.tag.split("}")[-1]
+        if tag == "g":
+            m = re.match(r"translate\(([-\d.e]+)\s+([-\d.e]+)\)", el.get("transform", "translate(0 0)"))
+            for c in el: yield from walk(c, dx + float(m.group(1)), dy + float(m.group(2)))
+            return
+        fill = color(el.get("fill", "#000")); stroke = color(el.get("stroke")); sw = float(el.get("stroke-width", "1"))
+        if tag == "rect":
+            cs = rect_contours(float(el.get("x")), float(el.get("y")), float(el.get("width")), float(el.get("height")), float(el.get("rx", 0)))
+        elif tag == "path":
+            cs = path_contours(el.get("d"))
+        elif tag == "polygon":
+            pts = [tuple(map(float, p.split(","))) for p in el.get("points").split()]
+            cs = [[("L", pts[i], pts[(i + 1) % len(pts)]) for i in range(len(pts))]]
+        elif tag == "text":
+            tl = el.get("textLength")
+            cs = text_contours(el.text, float(el.get("x")), float(el.get("y")), float(el.get("font-size")),
+                               el.get("text-anchor", "start"), float(tl) if tl else None)
+            stroke = None
+        else:
+            raise ValueError(tag)
+        cs = [[tuple([s[0]] + [(px + dx, py + dy) for px, py in s[1:]]) for s in c] for c in cs]
+        if tag == "text":
+            # Variable-font glyphs overlap (an E is a stem plus bars). Give every solid contour its own
+            # shape, with the holes it contains, so overlaps add up instead of cancelling (even-odd).
+            areas = [shoelace(c) for c in cs]
+            solid_sign = 1 if areas[max(range(len(cs)), key=lambda i: abs(areas[i]))] > 0 else -1
+            solids = [i for i in range(len(cs)) if areas[i] * solid_sign > 0]
+            groups = {i: [cs[i]] for i in solids}
+            for i in range(len(cs)):
+                if i in groups: continue
+                p = cs[i][0][1]
+                owners = [j for j in solids if point_in([s[1] for s in cs[j]], p)]
+                if owners: groups[min(owners, key=lambda j: abs(areas[j]))].append(cs[i])
+            for i in solids: yield groups[i], fill, stroke, sw
+            return
+        yield cs, fill, stroke, sw
+
+    for el in root: yield from walk(el, 0, 0)
+
+
+# ── SWF writing ──────────────────────────────────────────────────────────────
+
+class BW:
+    def __init__(s): s.out = bytearray(); s.acc = 0; s.n = 0
+    def ub(s, v, n):
+        for i in range(n - 1, -1, -1):
+            s.acc = (s.acc << 1) | ((v >> i) & 1); s.n += 1
+            if s.n == 8: s.out.append(s.acc); s.acc = 0; s.n = 0
+    def sb(s, v, n): s.ub(v & ((1 << n) - 1), n)
+    def align(s):
+        if s.n: s.ub(0, 8 - s.n)
+    def bytes(s, b): s.align(); s.out += b
+
+
+def nbits_s(*vals):
+    n = 1
+    for v in vals:
+        while not (-(1 << (n - 1)) <= v < (1 << (n - 1))): n += 1
+    return n
+
+
+def write_rect(w, x0, x1, y0, y1):
+    n = nbits_s(x0, x1, y0, y1); w.ub(n, 5)
+    for v in (x0, x1, y0, y1): w.sb(v, n)
+    w.align()
+
+
+def shoelace(c):
+    a = 0
+    for s in c:
+        (x0, y0), (x1, y1) = s[1], s[-1]
+        a += x0 * y1 - x1 * y0
+    return a
+
+
+def point_in(poly, p):
+    x, y = p; inside = False; n = len(poly)
+    for i in range(n):
+        (x0, y0), (x1, y1) = poly[i], poly[(i + 1) % n]
+        if (y0 > y) != (y1 > y) and x < x0 + (y - y0) * (x1 - x0) / (y1 - y0): inside = not inside
+    return inside
+
+
+def define_shape3(sid, contours, fill, stroke, sw):
+    # integer twips, closing each contour exactly
+    q = lambda p: (round(p[0] * TW), round(p[1] * TW))
+    cs = [[tuple([s[0]] + [q(p) for p in s[1:]]) for s in c] for c in contours]
+    cs = [[s for s in c if not (s[0] == "L" and s[1] == s[2])] for c in cs]
+    cs = [c for c in cs if c]
+    closed = [c[0][1] == c[-1][-1] for c in cs]
+    polys = [[s[1] for s in c] for c in cs]
+    # nesting depth for even-odd fills
+    depth = []
+    for i, c in enumerate(cs):
+        t = c[0][1]; depth.append(sum(1 for j, pg in enumerate(polys) if j != i and closed[j] and point_in(pg, t)))
+    pad = round(sw * TW / 2) if stroke else 0
+    xs = [p[0] for c in cs for s in c for p in s[1:]]; ys = [p[1] for c in cs for s in c for p in s[1:]]
+    w = BW()
+    w.bytes(struct.pack("<H", sid))
+    write_rect(w, min(xs) - pad, max(xs) + pad, min(ys) - pad, max(ys) + pad)
+    fills = [fill] if fill else []; lines = [stroke] if stroke else []
+    w.bytes(bytes([len(fills)]))
+    for f in fills: w.bytes(bytes([0x00, *f]))
+    w.bytes(bytes([len(lines)]))
+    for l in lines: w.bytes(struct.pack("<H", round(sw * TW)) + bytes(l))
+    nf, nl = (1 if fills else 0), (1 if lines else 0)
+    w.ub(nf, 4); w.ub(nl, 4)
+    x = y = 0
+    for i, c in enumerate(cs):
+        f0 = f1 = 0
+        if fills and closed[i]:
+            interior_on_f0 = shoelace(c) > 0
+            filled_inside = depth[i] % 2 == 0
+            if interior_on_f0 == filled_inside: f0 = 1
+            else: f1 = 1
+        sx, sy = c[0][1]
+        # style change: moveTo + fill0 + fill1 (+ line)
+        flags = 0x01 | (0x02 if nf else 0) | (0x04 if nf else 0) | (0x08 if nl else 0)
+        w.ub(0, 1); w.ub(flags, 5)
+        n = nbits_s(sx, sy); w.ub(n, 5); w.sb(sx, n); w.sb(sy, n)
+        if nf: w.ub(f0, nf); w.ub(f1, nf)
+        if nl: w.ub(1, nl)
+        x, y = sx, sy
+        for s in c:
+            if s[0] == "L":
+                (ex, ey) = s[2]; dx, dy = ex - x, ey - y
+                n = max(nbits_s(dx, dy), 2)
+                w.ub(1, 1); w.ub(1, 1); w.ub(n - 2, 4); w.ub(1, 1); w.sb(dx, n); w.sb(dy, n)
+                x, y = ex, ey
+            else:
+                (cx, cy), (ex, ey) = s[2], s[3]
+                a, b, c2, d = cx - x, cy - y, ex - cx, ey - cy
+                n = max(nbits_s(a, b, c2, d), 2)
+                w.ub(1, 1); w.ub(0, 1); w.ub(n - 2, 4)
+                for v in (a, b, c2, d): w.sb(v, n)
+                x, y = ex, ey
+    w.ub(0, 6); w.align()
+    return bytes(w.out)
+
+
+def tag(code, body):
+    if len(body) < 63: return struct.pack("<H", code << 6 | len(body)) + body
+    return struct.pack("<HI", code << 6 | 63, len(body)) + body
+
+
+def read_tags(d, p, end):
+    while p < end:
+        h = struct.unpack_from("<H", d, p); hdr = p; p += 2; c, l = h[0] >> 6, h[0] & 63
+        if l == 63: l = struct.unpack_from("<I", d, p)[0]; p += 4
+        yield c, d[hdr:p + l], d[p:p + l]; p += l
+        if c == 0: break
+
+
+def build(d, symbols, target_len=None):
+    """d: the title's input_icons movie. symbols: {'Main_Button_N': SVG fragment or <symbol> element}.
+    Returns (new movie, its length before padding, number of shapes)."""
+    nb = d[8] >> 3; hdr_end = 8 + (5 + 4 * nb + 7) // 8 + 4
+    tags = list(read_tags(d, hdr_end, len(d)))
+    names = {}
+    for c, raw, body in tags:
+        if c == 76:
+            n = struct.unpack_from("<H", body)[0]; q = 2
+            for _ in range(n):
+                i = struct.unpack_from("<H", body, q)[0]; q += 2; e = body.index(b"\0", q); names[body[q:e].decode().split(".")[-1]] = i; q = e + 1
+    shapes = {}; shape_tags = []; sprite_tags = {}; next_id = 1
+    used = {struct.unpack_from("<H", body)[0] for c, _, body in tags if c == 39}
+    for nm, sid in sorted(((n, i) for n, i in names.items() if n.startswith("Main_Button_")), key=lambda kv: kv[1]):
+        if nm not in symbols: raise KeyError(f"no design for {nm}")
+        places = []
+        for cs, fill, stroke, sw in elements(symbols[nm]):
+            key = (repr(cs), fill, stroke, sw)
+            if key not in shapes:
+                while next_id in used: next_id += 1
+                shapes[key] = next_id; used.add(next_id)
+                shape_tags.append(tag(32, define_shape3(next_id, cs, fill, stroke, sw)))
+            places.append(shapes[key])
+        body = struct.pack("<HH", sid, 1)
+        for depth, ch in enumerate(places, 1):
+            body += tag(26, bytes([0x02]) + struct.pack("<HH", depth, ch))
+        body += tag(1, b"") + tag(0, b"")
+        sprite_tags[sid] = tag(39, body)
+    out = bytearray(d[:hdr_end]); inserted = False
+    for c, raw, body in tags:
+        if c == 32:
+            if not inserted: out += b"".join(shape_tags); inserted = True
+            continue
+        if c == 39:
+            sid = struct.unpack_from("<H", body)[0]
+            if not inserted: out += b"".join(shape_tags); inserted = True
+            out += sprite_tags[sid]; continue
+        out += raw
+    real = len(out)
+    if target_len:
+        if real > target_len: raise ValueError(f"movie is {real} bytes, over {target_len}")
+        out += bytes(target_len - real)
+    struct.pack_into("<I", out, 4, len(out))
+    return bytes(out), real, len(shape_tags)
+
+
+# ── data.rpf ────────────────────────────────────────────────────────────────
+
+KNOWN_OFFSET = 0x117d7000   # the entry in the data.rpf we have (481,544,304 bytes)
+MARK = b"platform_xbsx.input_icons"
+
+
+def read_stream(f, off, limit=1 << 20):
+    """Inflate the zlib stream at `off`. Returns (data, compressed size) or None."""
+    f.seek(off); buf = f.read(limit)
+    if len(buf) < 2 or buf[0] != 0x78: return None
+    d = zlib.decompressobj()
+    try: out = d.decompress(buf)
+    except zlib.error: return None
+    if not d.eof: return None
+    return out, len(buf) - len(d.unused_data)
+
+
+def is_icon_movie(data):
+    return data[:3] in (b"GFX", b"CFX") and MARK in data and b"Main_Button_" in data
+
+
+def find_entry(path, offset):
+    with open(path, "rb") as f:
+        hit = read_stream(f, offset)
+        if hit and is_icon_movie(hit[0]): return offset, hit[0], hit[1]
+        print(f"not at {offset:#x}; scanning {path} for the icon library...")
+        size = os.fstat(f.fileno()).st_size; base = 0; step = 64 << 20
+        while base < size:
+            f.seek(base); chunk = f.read(step + 16)
+            i = chunk.find(b"\x78\xda")
+            while 0 <= i < step:
+                off = base + i
+                if off % 16 == 0:
+                    hit = read_stream(f, off)
+                    if hit and is_icon_movie(hit[0]): return off, hit[0], hit[1]
+                i = chunk.find(b"\x78\xda", i + 1)
+            base += step
+    raise SystemExit("platform_xbsx.input_icons was not found in data.rpf")
+
+
+def pack_exact(movie, real, csize):
+    """A zlib stream of exactly `csize` bytes for `movie` (whose bytes after `real` are padding): the tail of the
+    padding gets seeded pseudo-random bytes until the compressed size lands on `csize`."""
+    import random
+    def comp(b):
+        c = zlib.compressobj(9, zlib.DEFLATED, 15, 9); return c.compress(b) + c.flush()
+    room = len(movie) - real
+    base = len(comp(movie))
+    if base > csize:
+        raise SystemExit(f"the new library packs to {base} bytes, over the original's {csize}: simplify the icons")
+    est = csize - base
+    for seed in range(400):
+        rnd = random.Random(seed); tail = bytes(rnd.getrandbits(8) for _ in range(room))
+        for n in range(max(0, est - 40), min(room, est + 40) + 1):
+            data = movie[:real] + bytes(room - n) + tail[:n]
+            c = comp(data)
+            if len(c) == csize: return c, data
+    raise SystemExit("could not pack the library to the original's exact compressed size")
+
+
+def load_master(path):
+    syms = {}
+    for el in ET.parse(path).getroot().iter():
+        if el.tag.split("}")[-1] == "symbol" and el.get("id", "").startswith("Main_Button_"):
+            syms[el.get("id")] = el
+    return syms
+
+
+def main():
+    import argparse, shutil
+    here = os.path.dirname(os.path.abspath(__file__))
+    ap = argparse.ArgumentParser(description="Build the keyboard/mouse icon library into a copy of data.rpf.")
+    ap.add_argument("--game", required=True, help="the title's game folder (holds data.rpf); only read")
+    ap.add_argument("--out", help="where to write the patched copy of data.rpf (the title's XCL overlay folder)")
+    ap.add_argument("--master", default=os.path.join(here, "..", "..", "docs", "kbm-icons", "icons-master.svg"))
+    ap.add_argument("--offset", type=lambda v: int(v, 0), default=KNOWN_OFFSET)
+    ap.add_argument("--movie-out", help="also write the rebuilt movie here (made from game data: keep it local)")
+    a = ap.parse_args()
+    src = os.path.join(a.game, "data.rpf")
+    off, orig, csize = find_entry(src, a.offset)
+    movie, real, nshapes = build(orig, load_master(a.master), target_len=len(orig))
+    c, data = pack_exact(movie, real, csize)
+    assert zlib.decompress(c) == data and len(data) == len(orig) and len(c) == csize
+    print(f"input_icons at {off:#x}: {len(orig)} bytes ({csize} packed); new library {real} bytes, "
+          f"{nshapes} shapes, packed to {len(c)} bytes")
+    if a.movie_out:
+        with open(a.movie_out, "wb") as f: f.write(data)

Thanks for catching both write paths. Commit 11e95c8 resolves and validates --out and --movie-out before writing either file. Both outputs now use uniquely created temporary files.

The new regression tests cover both flags, a Windows junction into the game folder, and pre-existing hard links. I also generated both outputs from the retail archive in a temporary directory and verified that the source SHA-256 stayed the same.

<!-- greyfinch-sync:ivall/xcl:review-comment:4684701258 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1604#discussion_r4684701258). Originally posted by [zohaiblazuli](https://github.com/zohaiblazuli) on 2026-11-24T18:30:58Z. **Code review location:** `scripts/kbm_icons/build_library.py`; line 444 ~~~~diff @@ -0,0 +1,462 @@ +r"""Build the keyboard/mouse icon library for the retail title and write it into a COPY of its data.rpf. + + python scripts/kbm_icons/build_library.py --game D:\Game --out %LOCALAPPDATA%\XCL\<title>\overlay\data.rpf + +XCL reads a game file from the title's overlay folder when one is there (crates/xcl/src/vfs.rs), so the +patched copy replaces the original without touching the game folder. Delete the copy to undo. + +What it does (details and measurements: docs/kbm-icons/README.md): +1. Finds the title's `platform_xbsx.input_icons` movie in data.rpf. Each archive entry is a plain zlib + stream; nothing is decrypted. The entry is at a known offset in the version we have, checked by content, + with a scan of the archive as a fallback. +2. Rebuilds that movie: the 38 `Main_Button_N` sprites and their shapes come from icons-master.svg; every + other tag (the movie's own script, exports, symbol classes) is copied from the user's file as it is. +3. Packs it to the original entry's exact sizes (unpacked and zlib), so the archive's table of contents + still describes it, and writes data.rpf with only that entry changed. + +Supported SVG in the master file: <g transform="translate(x y)">, <rect rx>, <polygon>, <path> with absolute +M L H V Q A Z, <text> (outlined from Windows' Bahnschrift Bold Condensed), fill / stroke / stroke-width as +attributes, #rgb or #rrggbb colours. Units are the library's (1 unit = 20 twips; a symbol is 64 tall). +Needs Python 3.10+ and fontTools (MIT). +""" +import math, re, struct, sys, os, zlib +import xml.etree.ElementTree as ET + + +TW = 20 + +# ── font ───────────────────────────────────────────────────────────────────── +_font = None + + +def font(): + global _font + if _font is None: + from fontTools.ttLib import TTFont + from fontTools.varLib import instancer + f = TTFont(r"C:\Windows\Fonts\bahnschrift.ttf") + _font = instancer.instantiateVariableFont(f, {"wght": 700, "wdth": 75}) + return _font + + +def glyph_contours(ch): + """Contours of one glyph in font units, y-up, as lists of segments ('L', p0, p1) / ('Q', p0, c, p1).""" + from fontTools.pens.basePen import BasePen + f = font(); gs = f.getGlyphSet(); name = f.getBestCmap()[ord(ch)] + + class P(BasePen): + def __init__(s): super().__init__(gs); s.cs = []; s.cur = None; s.start = None + def _moveTo(s, p): s.cs.append([]); s.cur = s.start = p + def _lineTo(s, p): s.cs[-1].append(("L", s.cur, p)); s.cur = p + def _qCurveToOne(s, c, p): s.cs[-1].append(("Q", s.cur, c, p)); s.cur = p + def _curveToOne(s, c1, c2, p): # cubic → two quads (Bahnschrift is quadratic; kept for safety) + m = ((c1[0] + c2[0]) / 2, (c1[1] + c2[1]) / 2) + s._qCurveToOne(((s.cur[0] + 3 * c1[0]) / 4, (s.cur[1] + 3 * c1[1]) / 4), m) + s._qCurveToOne(((3 * c2[0] + p[0]) / 4, (3 * c2[1] + p[1]) / 4), p) + def _closePath(s): + if s.cur != s.start: s.cs[-1].append(("L", s.cur, s.start)); s.cur = s.start + _endPath = _closePath + pen = P(); gs[name].draw(pen) + return pen.cs, gs[name].width + + +def text_contours(s, x, y, fs, anchor, text_length): + """SVG text → contours in symbol units (y-down). The cap height matches the SVG design (0.7 em).""" + f = font(); cap_font = f["OS/2"].sCapHeight + k = (fs * 0.7) / cap_font + adv = 0; glyphs = [] + for ch in s: + cs, w = glyph_contours(ch); glyphs.append((adv, cs)); adv += w + width = adv * k + sx = k + if text_length: + sx = text_length / adv; width = text_length + x0 = x - width / 2 if anchor == "middle" else x + out = [] + for gx, cs in glyphs: + for c in cs: + out.append([tuple([seg[0]] + [(x0 + (gx + px) * sx, y - py * k) for px, py in seg[1:]]) for seg in c]) + return out + + +# ── SVG geometry ───────────────────────────────────────────────────────────── + +def arc_to_quads(p0, rx, ry, rot, large, sweep, p1): + """SVG elliptical arc → quadratic segments (each ≤ 45°).""" + x1, y1 = p0; x2, y2 = p1 + if rx == 0 or ry == 0: return [("L", p0, p1)] + phi = math.radians(rot); cp, sp = math.cos(phi), math.sin(phi) + dx, dy = (x1 - x2) / 2, (y1 - y2) / 2 + x1p, y1p = cp * dx + sp * dy, -sp * dx + cp * dy + lam = (x1p / rx) ** 2 + (y1p / ry) ** 2 + if lam > 1: rx *= math.sqrt(lam); ry *= math.sqrt(lam) + num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p + den = rx * rx * y1p * y1p + ry * ry * x1p * x1p + co = math.sqrt(max(0, num / den)) if den else 0 + if large == sweep: co = -co + cxp, cyp = co * rx * y1p / ry, -co * ry * x1p / rx + cx = cp * cxp - sp * cyp + (x1 + x2) / 2; cy = sp * cxp + cp * cyp + (y1 + y2) / 2 + ang = lambda ux, uy, vx, vy: math.atan2(ux * vy - uy * vx, ux * vx + uy * vy) + t1 = ang(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry) + dt = ang((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry) + if not sweep and dt > 0: dt -= 2 * math.pi + if sweep and dt < 0: dt += 2 * math.pi + n = max(1, math.ceil(abs(dt) / (math.pi / 2 if max(rx, ry) <= 14 else math.pi / 3) - 1e-9)); h = dt / n # 90 deg pieces for corners, 60 for big rings + pt = lambda t: (cx + rx * math.cos(t) * cp - ry * math.sin(t) * sp, cy + rx * math.cos(t) * sp + ry * math.sin(t) * cp) + segs = []; cur = p0 + for i in range(n): + ta, tb = t1 + i * h, t1 + (i + 1) * h; tm = (ta + tb) / 2 + e = 1 / math.cos(h / 2) + c = (cx + rx * e * math.cos(tm) * cp - ry * e * math.sin(tm) * sp, cy + rx * e * math.cos(tm) * sp + ry * e * math.sin(tm) * cp) + nxt = p1 if i == n - 1 else pt(tb) + segs.append(("Q", cur, c, nxt)); cur = nxt + return segs + + +def path_contours(d): + toks = re.findall(r"[MLHVAQZ]|-?\d*\.?\d+(?:e-?\d+)?", d) + i = 0; cs = []; cur = start = (0, 0); cmd = None + def num(): + nonlocal i; v = float(toks[i]); i += 1; return v + while i < len(toks): + if re.match(r"[A-Z]", toks[i]): cmd = toks[i]; i += 1 + if cmd == "M": cur = start = (num(), num()); cs.append([]); cmd = "L"; continue + if cmd == "Z": + if cs and cur != start: cs[-1].append(("L", cur, start)) + cur = start; continue + if cmd == "L": p = (num(), num()); cs[-1].append(("L", cur, p)); cur = p + elif cmd == "H": p = (num(), cur[1]); cs[-1].append(("L", cur, p)); cur = p + elif cmd == "V": p = (cur[0], num()); cs[-1].append(("L", cur, p)); cur = p + elif cmd == "Q": c = (num(), num()); p = (num(), num()); cs[-1].append(("Q", cur, c, p)); cur = p + elif cmd == "A": + rx, ry, rot, la, sw = num(), num(), num(), num(), num(); p = (num(), num()) + cs[-1].extend(arc_to_quads(cur, rx, ry, rot, int(la), int(sw), p)); cur = p + else: raise ValueError(cmd) + return [c for c in cs if c] + + +def rect_contours(x, y, w, h, r): + r = min(r, w / 2, h / 2) + if r <= 0: + return path_contours(f"M{x} {y} H{x + w} V{y + h} H{x} Z") + return path_contours(f"M{x + r} {y} H{x + w - r} A{r} {r} 0 0 1 {x + w} {y + r} V{y + h - r} A{r} {r} 0 0 1 {x + w - r} {y + h} " + f"H{x + r} A{r} {r} 0 0 1 {x} {y + h - r} V{y + r} A{r} {r} 0 0 1 {x + r} {y} Z") + + +def color(v): + if not v or v == "none": return None + v = v.lstrip("#") + if len(v) == 3: v = "".join(c * 2 for c in v) + return (int(v[0:2], 16), int(v[2:4], 16), int(v[4:6], 16), 255) + + +def elements(svg): + """Yield (contours, fill, stroke, stroke_width) for each drawable element, in paint order. + `svg` is an SVG fragment (text) or an element whose children are drawn (a master-file <symbol>).""" + root = ET.fromstring(f"<g>{svg}</g>") if isinstance(svg, str) else svg + + def walk(el, dx, dy): + tag = el.tag.split("}")[-1] + if tag == "g": + m = re.match(r"translate\(([-\d.e]+)\s+([-\d.e]+)\)", el.get("transform", "translate(0 0)")) + for c in el: yield from walk(c, dx + float(m.group(1)), dy + float(m.group(2))) + return + fill = color(el.get("fill", "#000")); stroke = color(el.get("stroke")); sw = float(el.get("stroke-width", "1")) + if tag == "rect": + cs = rect_contours(float(el.get("x")), float(el.get("y")), float(el.get("width")), float(el.get("height")), float(el.get("rx", 0))) + elif tag == "path": + cs = path_contours(el.get("d")) + elif tag == "polygon": + pts = [tuple(map(float, p.split(","))) for p in el.get("points").split()] + cs = [[("L", pts[i], pts[(i + 1) % len(pts)]) for i in range(len(pts))]] + elif tag == "text": + tl = el.get("textLength") + cs = text_contours(el.text, float(el.get("x")), float(el.get("y")), float(el.get("font-size")), + el.get("text-anchor", "start"), float(tl) if tl else None) + stroke = None + else: + raise ValueError(tag) + cs = [[tuple([s[0]] + [(px + dx, py + dy) for px, py in s[1:]]) for s in c] for c in cs] + if tag == "text": + # Variable-font glyphs overlap (an E is a stem plus bars). Give every solid contour its own + # shape, with the holes it contains, so overlaps add up instead of cancelling (even-odd). + areas = [shoelace(c) for c in cs] + solid_sign = 1 if areas[max(range(len(cs)), key=lambda i: abs(areas[i]))] > 0 else -1 + solids = [i for i in range(len(cs)) if areas[i] * solid_sign > 0] + groups = {i: [cs[i]] for i in solids} + for i in range(len(cs)): + if i in groups: continue + p = cs[i][0][1] + owners = [j for j in solids if point_in([s[1] for s in cs[j]], p)] + if owners: groups[min(owners, key=lambda j: abs(areas[j]))].append(cs[i]) + for i in solids: yield groups[i], fill, stroke, sw + return + yield cs, fill, stroke, sw + + for el in root: yield from walk(el, 0, 0) + + +# ── SWF writing ────────────────────────────────────────────────────────────── + +class BW: + def __init__(s): s.out = bytearray(); s.acc = 0; s.n = 0 + def ub(s, v, n): + for i in range(n - 1, -1, -1): + s.acc = (s.acc << 1) | ((v >> i) & 1); s.n += 1 + if s.n == 8: s.out.append(s.acc); s.acc = 0; s.n = 0 + def sb(s, v, n): s.ub(v & ((1 << n) - 1), n) + def align(s): + if s.n: s.ub(0, 8 - s.n) + def bytes(s, b): s.align(); s.out += b + + +def nbits_s(*vals): + n = 1 + for v in vals: + while not (-(1 << (n - 1)) <= v < (1 << (n - 1))): n += 1 + return n + + +def write_rect(w, x0, x1, y0, y1): + n = nbits_s(x0, x1, y0, y1); w.ub(n, 5) + for v in (x0, x1, y0, y1): w.sb(v, n) + w.align() + + +def shoelace(c): + a = 0 + for s in c: + (x0, y0), (x1, y1) = s[1], s[-1] + a += x0 * y1 - x1 * y0 + return a + + +def point_in(poly, p): + x, y = p; inside = False; n = len(poly) + for i in range(n): + (x0, y0), (x1, y1) = poly[i], poly[(i + 1) % n] + if (y0 > y) != (y1 > y) and x < x0 + (y - y0) * (x1 - x0) / (y1 - y0): inside = not inside + return inside + + +def define_shape3(sid, contours, fill, stroke, sw): + # integer twips, closing each contour exactly + q = lambda p: (round(p[0] * TW), round(p[1] * TW)) + cs = [[tuple([s[0]] + [q(p) for p in s[1:]]) for s in c] for c in contours] + cs = [[s for s in c if not (s[0] == "L" and s[1] == s[2])] for c in cs] + cs = [c for c in cs if c] + closed = [c[0][1] == c[-1][-1] for c in cs] + polys = [[s[1] for s in c] for c in cs] + # nesting depth for even-odd fills + depth = [] + for i, c in enumerate(cs): + t = c[0][1]; depth.append(sum(1 for j, pg in enumerate(polys) if j != i and closed[j] and point_in(pg, t))) + pad = round(sw * TW / 2) if stroke else 0 + xs = [p[0] for c in cs for s in c for p in s[1:]]; ys = [p[1] for c in cs for s in c for p in s[1:]] + w = BW() + w.bytes(struct.pack("<H", sid)) + write_rect(w, min(xs) - pad, max(xs) + pad, min(ys) - pad, max(ys) + pad) + fills = [fill] if fill else []; lines = [stroke] if stroke else [] + w.bytes(bytes([len(fills)])) + for f in fills: w.bytes(bytes([0x00, *f])) + w.bytes(bytes([len(lines)])) + for l in lines: w.bytes(struct.pack("<H", round(sw * TW)) + bytes(l)) + nf, nl = (1 if fills else 0), (1 if lines else 0) + w.ub(nf, 4); w.ub(nl, 4) + x = y = 0 + for i, c in enumerate(cs): + f0 = f1 = 0 + if fills and closed[i]: + interior_on_f0 = shoelace(c) > 0 + filled_inside = depth[i] % 2 == 0 + if interior_on_f0 == filled_inside: f0 = 1 + else: f1 = 1 + sx, sy = c[0][1] + # style change: moveTo + fill0 + fill1 (+ line) + flags = 0x01 | (0x02 if nf else 0) | (0x04 if nf else 0) | (0x08 if nl else 0) + w.ub(0, 1); w.ub(flags, 5) + n = nbits_s(sx, sy); w.ub(n, 5); w.sb(sx, n); w.sb(sy, n) + if nf: w.ub(f0, nf); w.ub(f1, nf) + if nl: w.ub(1, nl) + x, y = sx, sy + for s in c: + if s[0] == "L": + (ex, ey) = s[2]; dx, dy = ex - x, ey - y + n = max(nbits_s(dx, dy), 2) + w.ub(1, 1); w.ub(1, 1); w.ub(n - 2, 4); w.ub(1, 1); w.sb(dx, n); w.sb(dy, n) + x, y = ex, ey + else: + (cx, cy), (ex, ey) = s[2], s[3] + a, b, c2, d = cx - x, cy - y, ex - cx, ey - cy + n = max(nbits_s(a, b, c2, d), 2) + w.ub(1, 1); w.ub(0, 1); w.ub(n - 2, 4) + for v in (a, b, c2, d): w.sb(v, n) + x, y = ex, ey + w.ub(0, 6); w.align() + return bytes(w.out) + + +def tag(code, body): + if len(body) < 63: return struct.pack("<H", code << 6 | len(body)) + body + return struct.pack("<HI", code << 6 | 63, len(body)) + body + + +def read_tags(d, p, end): + while p < end: + h = struct.unpack_from("<H", d, p); hdr = p; p += 2; c, l = h[0] >> 6, h[0] & 63 + if l == 63: l = struct.unpack_from("<I", d, p)[0]; p += 4 + yield c, d[hdr:p + l], d[p:p + l]; p += l + if c == 0: break + + +def build(d, symbols, target_len=None): + """d: the title's input_icons movie. symbols: {'Main_Button_N': SVG fragment or <symbol> element}. + Returns (new movie, its length before padding, number of shapes).""" + nb = d[8] >> 3; hdr_end = 8 + (5 + 4 * nb + 7) // 8 + 4 + tags = list(read_tags(d, hdr_end, len(d))) + names = {} + for c, raw, body in tags: + if c == 76: + n = struct.unpack_from("<H", body)[0]; q = 2 + for _ in range(n): + i = struct.unpack_from("<H", body, q)[0]; q += 2; e = body.index(b"\0", q); names[body[q:e].decode().split(".")[-1]] = i; q = e + 1 + shapes = {}; shape_tags = []; sprite_tags = {}; next_id = 1 + used = {struct.unpack_from("<H", body)[0] for c, _, body in tags if c == 39} + for nm, sid in sorted(((n, i) for n, i in names.items() if n.startswith("Main_Button_")), key=lambda kv: kv[1]): + if nm not in symbols: raise KeyError(f"no design for {nm}") + places = [] + for cs, fill, stroke, sw in elements(symbols[nm]): + key = (repr(cs), fill, stroke, sw) + if key not in shapes: + while next_id in used: next_id += 1 + shapes[key] = next_id; used.add(next_id) + shape_tags.append(tag(32, define_shape3(next_id, cs, fill, stroke, sw))) + places.append(shapes[key]) + body = struct.pack("<HH", sid, 1) + for depth, ch in enumerate(places, 1): + body += tag(26, bytes([0x02]) + struct.pack("<HH", depth, ch)) + body += tag(1, b"") + tag(0, b"") + sprite_tags[sid] = tag(39, body) + out = bytearray(d[:hdr_end]); inserted = False + for c, raw, body in tags: + if c == 32: + if not inserted: out += b"".join(shape_tags); inserted = True + continue + if c == 39: + sid = struct.unpack_from("<H", body)[0] + if not inserted: out += b"".join(shape_tags); inserted = True + out += sprite_tags[sid]; continue + out += raw + real = len(out) + if target_len: + if real > target_len: raise ValueError(f"movie is {real} bytes, over {target_len}") + out += bytes(target_len - real) + struct.pack_into("<I", out, 4, len(out)) + return bytes(out), real, len(shape_tags) + + +# ── data.rpf ──────────────────────────────────────────────────────────────── + +KNOWN_OFFSET = 0x117d7000 # the entry in the data.rpf we have (481,544,304 bytes) +MARK = b"platform_xbsx.input_icons" + + +def read_stream(f, off, limit=1 << 20): + """Inflate the zlib stream at `off`. Returns (data, compressed size) or None.""" + f.seek(off); buf = f.read(limit) + if len(buf) < 2 or buf[0] != 0x78: return None + d = zlib.decompressobj() + try: out = d.decompress(buf) + except zlib.error: return None + if not d.eof: return None + return out, len(buf) - len(d.unused_data) + + +def is_icon_movie(data): + return data[:3] in (b"GFX", b"CFX") and MARK in data and b"Main_Button_" in data + + +def find_entry(path, offset): + with open(path, "rb") as f: + hit = read_stream(f, offset) + if hit and is_icon_movie(hit[0]): return offset, hit[0], hit[1] + print(f"not at {offset:#x}; scanning {path} for the icon library...") + size = os.fstat(f.fileno()).st_size; base = 0; step = 64 << 20 + while base < size: + f.seek(base); chunk = f.read(step + 16) + i = chunk.find(b"\x78\xda") + while 0 <= i < step: + off = base + i + if off % 16 == 0: + hit = read_stream(f, off) + if hit and is_icon_movie(hit[0]): return off, hit[0], hit[1] + i = chunk.find(b"\x78\xda", i + 1) + base += step + raise SystemExit("platform_xbsx.input_icons was not found in data.rpf") + + +def pack_exact(movie, real, csize): + """A zlib stream of exactly `csize` bytes for `movie` (whose bytes after `real` are padding): the tail of the + padding gets seeded pseudo-random bytes until the compressed size lands on `csize`.""" + import random + def comp(b): + c = zlib.compressobj(9, zlib.DEFLATED, 15, 9); return c.compress(b) + c.flush() + room = len(movie) - real + base = len(comp(movie)) + if base > csize: + raise SystemExit(f"the new library packs to {base} bytes, over the original's {csize}: simplify the icons") + est = csize - base + for seed in range(400): + rnd = random.Random(seed); tail = bytes(rnd.getrandbits(8) for _ in range(room)) + for n in range(max(0, est - 40), min(room, est + 40) + 1): + data = movie[:real] + bytes(room - n) + tail[:n] + c = comp(data) + if len(c) == csize: return c, data + raise SystemExit("could not pack the library to the original's exact compressed size") + + +def load_master(path): + syms = {} + for el in ET.parse(path).getroot().iter(): + if el.tag.split("}")[-1] == "symbol" and el.get("id", "").startswith("Main_Button_"): + syms[el.get("id")] = el + return syms + + +def main(): + import argparse, shutil + here = os.path.dirname(os.path.abspath(__file__)) + ap = argparse.ArgumentParser(description="Build the keyboard/mouse icon library into a copy of data.rpf.") + ap.add_argument("--game", required=True, help="the title's game folder (holds data.rpf); only read") + ap.add_argument("--out", help="where to write the patched copy of data.rpf (the title's XCL overlay folder)") + ap.add_argument("--master", default=os.path.join(here, "..", "..", "docs", "kbm-icons", "icons-master.svg")) + ap.add_argument("--offset", type=lambda v: int(v, 0), default=KNOWN_OFFSET) + ap.add_argument("--movie-out", help="also write the rebuilt movie here (made from game data: keep it local)") + a = ap.parse_args() + src = os.path.join(a.game, "data.rpf") + off, orig, csize = find_entry(src, a.offset) + movie, real, nshapes = build(orig, load_master(a.master), target_len=len(orig)) + c, data = pack_exact(movie, real, csize) + assert zlib.decompress(c) == data and len(data) == len(orig) and len(c) == csize + print(f"input_icons at {off:#x}: {len(orig)} bytes ({csize} packed); new library {real} bytes, " + f"{nshapes} shapes, packed to {len(c)} bytes") + if a.movie_out: + with open(a.movie_out, "wb") as f: f.write(data) ~~~~ --- Thanks for catching both write paths. Commit `11e95c8` resolves and validates `--out` and `--movie-out` before writing either file. Both outputs now use uniquely created temporary files. The new regression tests cover both flags, a Windows junction into the game folder, and pre-existing hard links. I also generated both outputs from the retail archive in a temporary directory and verified that the source SHA-256 stayed the same.
DavidM1911 commented 2026-11-24 21:09:27 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by DavidM1911 on 2026-11-24T20:22:02Z.


Verification on RTX 3060 Ti (Windows 11), branch merged with current main:

  • cargo test -p xcl --lib: all passed, 0 failed, ~22 ignored. (Intermittent 0xc0000005 abort under parallel scheduling; clean on single-threaded rerun — same flake seen on unmodified main.)

Thanks!

<!-- greyfinch-sync:ivall/xcl:comment:7143435978 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1604#issuecomment-7143435978). Originally posted by [DavidM1911](https://github.com/DavidM1911) on 2026-11-24T20:22:02Z. --- Verification on RTX 3060 Ti (Windows 11), branch merged with current `main`: - `cargo test -p xcl --lib`: all passed, 0 failed, ~22 ignored. (Intermittent 0xc0000005 abort under parallel scheduling; clean on single-threaded rerun — same flake seen on unmodified `main`.) Thanks!
github-actions[bot] commented 2026-11-28 20:18:19 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by github-actions[bot] on 2026-11-28T20:18:19Z.


Nothing has happened on this PR for 3 days, so it is marked stale and will be closed in 4 days. A push or a comment takes the mark off: rebase it onto main if it conflicts, and say in one line what it still fixes. If it only waits for a maintainer, a comment saying so is enough.

<!-- greyfinch-sync:ivall/xcl:comment:7245188144 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1604#issuecomment-7245188144). Originally posted by [github-actions[bot]](https://github.com/apps/github-actions) on 2026-11-28T20:18:19Z. --- Nothing has happened on this PR for 3 days, so it is marked `stale` and will be closed in 4 days. A push or a comment takes the mark off: rebase it onto `main` if it conflicts, and say in one line what it still fixes. If it only waits for a maintainer, a comment saying so is enough.
Foniass commented 2026-12-01 06:15:10 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T06:15:10Z.


Triage (#1607) – head 11e95c8

No open or merged PR makes the same change. The PR does not change the runtime: it adds scripts, docs and a README line for an overlay copy of one archive, and it commits no game data. The description says it is WIP and not ready to merge.
Minor: scripts/kbm_icons/survey.py's movies() reads the whole archive into memory with f.read(), which is about 4.8 GB for packs.rpf as the README suggests running it.
Recommendation: keep open.

AI review: Claude Code (Claude Opus 5.5), diffs read only, not built or run; not checked by a human.

<!-- greyfinch-sync:ivall/xcl:comment:7302662870 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1604#issuecomment-7302662870). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T06:15:10Z. --- **Triage (#1607)** – head 11e95c8 No open or merged PR makes the same change. The PR does not change the runtime: it adds scripts, docs and a README line for an overlay copy of one archive, and it commits no game data. The description says it is WIP and not ready to merge. Minor: `scripts/kbm_icons/survey.py`'s `movies()` reads the whole archive into memory with `f.read()`, which is about 4.8 GB for `packs.rpf` as the README suggests running it. Recommendation: keep open. AI review: Claude Code (Claude Opus 5.5), diffs read only, not built or run; not checked by a human.
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/1604:upstream-pr/1604'
git switch 'upstream-pr/1604'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/1604'
git switch 'upstream-pr/1604'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/1604'
git switch 'upstream-pr/1604'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/1604'
git switch 'main'
git merge --squash 'upstream-pr/1604'
git switch 'main'
git merge --ff-only 'upstream-pr/1604'
git switch 'main'
git merge 'upstream-pr/1604'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
xcl-dev/xcl!1594
No description provided.