Archive incari-client (client, 26.3, clean)

This commit is contained in:
2026-11-28 00:54:38 -06:00
parent 7a6174687f
commit 12838e838c
2383 changed files with 280266 additions and 0 deletions
+28
View File
@@ -0,0 +1,28 @@
# rust
- **Hook by name** where Horizon has stamped the hook: each injection names `hook` and
`hook_version` from Horizon's `native-hooks.json`, so a mod keeps building when Horizon moves
(ADR 0068). A pending hook (a fork fragment) is targeted by function until it's stamped. A hook Horizon lacks
goes into the fork (`native_hooks.rs` and `native-hooks.json`), offered upstream; then bump
`horizon.revision`.
- **Never edit `work/horizon`** or carry patches to it: a change no mod can make is a commit to the
fork and a pin bump.
- **It's the same client as the Java one** (ADR 0069): a screen of Incari's is a port of the Java
screen, a mod a port of the Java module, with its README as the spec: same names, settings, text
and layout. Mod ids are `incari_<module>`.
- **The client is `mods/incari`**: `core/` (`incari_core`) has no game types and is tested here;
`glue.rs` (module `incari_client`) is its game side. Features read their settings with
`incari_client::settings(id, ...)` and draw HUD elements with `incari_client::element(...)`
(`PORTING.md`); every module, setting and HUD element is declared in `core/src/modules.rs` with
the Java ids, so profiles read the same in both builds.
- **`runtime.rs` uses no game types**, so `rust/lib.rs` tests it alone. Helpers are a line or two
over `incari_client`, Horizon's `native_*` helpers and the mod's runtime.
- **Hot paths don't allocate**: the `hud`, `frame` and `tick` hooks run every frame or tick. Cache
in thread-locals, never in locks: in the browser the window's thread is the page's, where a lock
that waits traps.
- **Write it, don't copy it.** Horizon's own mods (horizon-rust/horizon-mods) are MIT; read them
for the API, write Incari's own.
- Add a mod to `rust/lib.rs`, the table in `README.md`, and its module's row in
`features/README.md`; its module to `core/src/modules.rs` if it's new.
- Test: `cargo test` and `cargo clippy --all-targets -- -D warnings` in `rust/`; the build with
`./incari build --only rust`.
+234
View File
@@ -0,0 +1,234 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "ab_glyph"
version = "0.2.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2"
dependencies = [
"ab_glyph_rasterizer",
"owned_ttf_parser",
]
[[package]]
name = "ab_glyph_rasterizer"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618"
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "crc32fast"
version = "1.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64"
dependencies = [
"cfg-if",
]
[[package]]
name = "fdeflate"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
dependencies = [
"simd-adler32",
]
[[package]]
name = "flate2"
version = "1.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"
dependencies = [
"crc32fast",
"miniz_oxide 0.9.1",
"zlib-rs",
]
[[package]]
name = "incari-core"
version = "0.1.0"
dependencies = [
"ab_glyph",
"png",
"serde_json",
]
[[package]]
name = "incari-rust-mods"
version = "0.1.0"
[[package]]
name = "itoa"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "miniz_oxide"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "miniz_oxide"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "owned_ttf_parser"
version = "0.25.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b"
dependencies = [
"ttf-parser",
]
[[package]]
name = "png"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
dependencies = [
"bitflags",
"crc32fast",
"fdeflate",
"flate2",
"miniz_oxide 0.8.9",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "simd-adler32"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "ttf-parser"
version = "0.25.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "zlib-rs"
version = "0.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+14
View File
@@ -0,0 +1,14 @@
# The Rust build's mods' own logic, for `cargo test` (ADR 0068). Each mod's runtime.rs is the module
# horizon-mixins adds to the game, and uses no game types, so it compiles here alone.
[package]
name = "incari-rust-mods"
version = "0.1.0"
edition = "2024"
license = "GPL-3.0-or-later"
publish = false
[lib]
path = "lib.rs"
[workspace]
members = [".", "mods/incari/core"]
@@ -0,0 +1,44 @@
# Porting a Java screen or subsystem to the Rust client (ADR 0069)
The Rust build (Horizon, `rust/`) runs Incari's own client, `incari_core`
(`rust/mods/incari/core/`, no game types), with its game side in `rust/mods/incari/glue.rs`. The
Java client is the spec: same layout, text, behaviour and files. Read first:
- `docs/adr/0069-incari-client-on-horizon.md`, `rust/README.md`, `rust/AGENTS.md`.
- `incari_core`: `src/screen.rs` (`Screen`, `Cx`, `Go`, the `Host` trait the game side
implements), `src/client.rs` (the screen stack, `Client::frame`/`input`/`hud_element`),
`src/ui.rs` (buttons, menu buttons, entries, switch, slider, text field, scrolling, tooltips),
`src/paint.rs` (`Painter`: round boxes, icons, text that fits/wraps, shapes, images on the
canvas), `src/panels.rs`, `src/screens/` (ported screens: `list.rs` is ListScreen,
`module_settings.rs`, `hud_editor.rs`, `incari_settings.rs`, `title.rs`, `grid.rs`),
`src/framework/` (modules, settings, profiles), `src/modules.rs` (every module, Java ids).
- The Java source of what you port (paths in your task), its ADR, and the matching
`run/smoke-*/incari-smoke/screenshots/*.png` if there is one.
## Rules
- **Only new files, plus one-line registrations**: you may create files under
`rust/mods/incari/core/src/` (new modules, `screens/<name>.rs`) and new mod folders
`rust/mods/<name>/`, and add their `pub mod` lines to `core/src/lib.rs`,
`core/src/screens/mod.rs` and `rust/lib.rs`. Other agents are doing the same right now, so
re-read a file just before editing it and keep edits to those single lines.
- **Don't edit** `client.rs`, `screen.rs`, `glue.rs`, `modules.rs`, other screens, other mods, or
the Horizon fork (`/home/bedrock/Documents/horizon-web-development`). When you need something
there (a `Host` method, a glue helper, a fork hook point, a button wired to your screen, a new
setting), write it down precisely in your report: the signature, what it does, and the exact
code to add, so it can be applied as is. Write your screens against those planned APIs (use
`todo!()`-free code: e.g. take the data as constructor arguments or a trait you define in your
own module, so your code compiles now).
- No game types in `incari_core`; no `std::fs`, `std::time`, `std::thread` there either (the
browser has none): files and time come through `Host`/your own trait.
- Hot paths don't allocate; thread-locals, never locks, on the window's thread.
- Tests: pure logic gets unit tests (codecs, layout maths, state machines). From
`/home/bedrock/Documents/incari-client/rust`: `cargo test --workspace` and
`cargo clippy --workspace --all-targets -- -D warnings` must pass. Errors in files that aren't
yours: ignore and mention. Don't run `./incari build` or anything in `work/`. Don't commit.
## Report
What you ported (files), what matches Java and what differs, then the integration list: every
change to a file you couldn't edit, as exact code, and every fork hook point you need with its
signature and what it must do in Horizon.
+66
View File
@@ -0,0 +1,66 @@
# Porting a feature mod onto the Incari client (ADR 0069)
You're moving some of the Rust build's feature mods (`rust/mods/<name>/`) off Horizon's own
Options > Mods pages and onto Incari's own framework, so the Rust build looks and works exactly
like the Java client: settings in Incari's module menu with the Java ids, HUD elements placed by
anchor in Incari's HUD editor and drawn in Incari's Frost look.
## What exists
- `rust/mods/incari/core/` — crate `incari_core` (no game types): the framework, the look, the
screens. Read `src/modules.rs` (every module's id, settings and HUD elements, exactly as the
Java ones declare them), `src/framework/setting.rs` (`Settings::bool/int/float/choice/color/key`
by Java setting id; `choice` returns the stored key, e.g. `"left"`), `src/hud.rs` (`HudCanvas`:
`text`, `text_argb`, `fill(.., Tone)`, `fill_argb`, `round`, `item`, `sprite`, `shape`,
`color(tone)` (honours the element's custom colour), `text_element(text, widest, tone) ->
[w, h]` = Java's TextElement), `src/theme.rs` (`Tone`), `src/input.rs` (`Key`, `Key::from_name`).
- `rust/mods/incari/glue.rs` — module `crate::game::incari_client` in the game, the helpers your
hook files call:
- `settings(module_id, |s: &Settings| ...) -> Option<R>`: None while the module is off.
- `on(module_id) -> bool`.
- `element(game: &Game, batch, module_id, element_id, |canvas| -> Option<[f32; 2]>)`: draws a
HUD element at its own origin and scale (return its unscaled size, None to hide it) and puts
it where the player placed it. Call it from the `hud` hook. `canvas.module` is the module's
settings, `canvas.element` the element's, `canvas.editing` true in the HUD editor (show a
sample when there's nothing to say, as Java's elements do).
- The template, already ported: `rust/mods/cps/` (`runtime.rs`, `hud.rs`, `horizon-mixin.toml`).
Compare it with `git diff HEAD -- rust/mods/cps` / the old version in git (`git show HEAD:rust/mods/cps/...`
may not exist: the old files were `list.rs`, `settings.rs`, `click.rs`, which `incari_glue` used).
## For each of your mods
1. Read the Java module: `features/<name>/src/main/java/**` and `features/<name>/README.md`.
That is the spec: same behaviour, same text, same defaults. Read the mod's current Rust files.
2. Delete `list.rs`, `settings.rs`, `click.rs` and their `[[injection]]`s (`mods`, `settings`,
`settings_click` hooks) from `horizon-mixin.toml`. Keep every other hook the mod needs; add
ones it needs to do what the Java module does, if Horizon has them (`native-hooks.json` in
`/home/bedrock/Documents/horizon-web-development`, and the fork's pending fragments in
`tools/native-hook-fragments/`, targeted by `target = "..."` path as `rust/mods/nohurtcam`
does). Don't edit the fork.
3. `runtime.rs` (no game types, tested by `rust/lib.rs`): the module's logic, keyed by the Java
setting ids/choice keys instead of the old `Def`/`Values`/`SETTINGS` tables. Remove its use of
`super::incari` (the old common module) unless something there is still truly needed. Keep it
allocation-free on hot paths (thread-local caches like cps's `with_text`).
4. Hook files: read settings with `crate::game::incari_client::settings(ID, |s| ...)`, draw HUD
with `crate::game::incari_client::element(...)` using the Java element ids and the Java
drawing (text elements via `text_element`; custom elements drawn with the canvas as the Java
`draw(HudCanvas)` does). The `corners` binding of the `hud` hook is no longer used (`let _ =
corners;`). Remove uses of `crate::game::incari_glue` and `crate::game::incari`.
5. Keys a module binds itself (Zoom's key, Freelook's key...) are `key` settings: compare in the
`key` hook with `incari_core::input::Key::from_name(key)`. Toggle keys are handled by the client.
6. Update the mod's row in `rust/README.md`'s table ("Not here yet" column: what still differs
from Java) — only your rows.
## Checks
From `/home/bedrock/Documents/incari-client/rust`: `cargo test` and
`cargo clippy --all-targets -- -D warnings` must pass for the whole workspace (other agents are
editing other mods at the same time: if an error is in a mod that isn't yours, ignore it and say
so). You can't compile the game helpers (`hud.rs` etc.) here — only `runtime.rs` is compiled by
`rust/lib.rs` — so write them carefully against the signatures in `glue.rs`, the existing hook
signatures in each mod's `horizon-mixin.toml`, and the fork's `native_hooks.rs`. Don't run
`./incari build` or anything in `work/` (another build may be running). Don't touch
`rust/lib.rs`, `rust/mods/incari/`, `rust/mods/common/` or other mods. Don't commit.
Report: per mod, what now matches Java, what still differs and why, any hook point Horizon lacks
that the Java behaviour needs, and anything in `glue.rs`/`incari_core` you needed but wasn't there.
+121
View File
@@ -0,0 +1,121 @@
# rust: the experimental Rust build
Incari on [Horizon](https://github.com/horizon-rust/horizon), the game rewritten in Rust, through
the browser port in [horizon-web](https://github.com/nobuildersnotools/horizon-web) (ADR 0068). It
draws with WebGPU, and the loading screen offers it as **Rust** beside Fast and Compatible where
WebGPU works.
None of Incari's Java runs in it, but it is the same client (ADR 0069): the Frost look over every
screen (Horizon's own Graphics, Controls and Shaders screens too, under Incari's mark: the fork's
`graphics_style` asks the skin for `horizon/settings/` parts and takes the theme's text colours), Incari's own title, pause menu, module menu, module settings, HUD editor, Incari Settings
and profiles, every module with the Java ids, and the profiles in the Java client's files. The
client is the `incari_core` crate; Incari's features are Horizon **native mods** that read its
settings and draw their HUD through it: horizon-mixins bundles that hook Horizon's named hook
points (`native-hooks.json`), applied to Horizon's source before it's compiled. Horizon itself is
never committed: `incari.properties` pins a commit, and `./incari setup` clones it into
`work/horizon`.
| Folder | What |
| --- | --- |
| `mods/incari/` | The client: crate `core/` (`incari_core`, no game types: the look, the screens, the framework, `modules.rs`), and its game side `glue.rs` (module `incari_client`) with the hook helpers that draw its screens over the game's |
| `mods/<name>/` | One bundle a feature: `horizon-mixin.toml`, `runtime.rs` (its logic, no game types) and one helper `.rs` a hook |
| `lib.rs`, `Cargo.toml` | Every `runtime.rs` as one crate, and `incari_core` as a workspace member, so their tests run without Horizon |
| `PORTING.md` | How a feature mod reads its settings and draws its HUD through the client |
## Mods
Each mod's settings and HUD elements are its module's in `incari_core::modules` (the Java ids):
the module menu shows them, the HUD editor places them by anchor, the profiles keep them. Crosshair
Editor and Theme Editor have no mod: the client draws the crosshair in the skin and takes its
colours from Theme's settings.
| Mod | Incari module | Hooks | Not here yet |
| --- | --- | --- | --- |
| [`armorpotionview`](mods/armorpotionview/) | [Armor & Potion View](../features/armorpotionview/README.md) | hud | Neutral effects count as harmful; effects the game hides are listed, in Horizon's order; unbreakable items show durability |
| [`blockoutline`](mods/blockoutline/) | [Block Outline](../features/blockoutline/README.md) | block highlight, visuals | Fill; widths past 4; the game's own colour under High Contrast |
| [`clearchat`](mods/clearchat/) | [Clear Chat](../features/clearchat/README.md) | frame | Holds the chat box clear itself, not the game's slider, so moving Text Background Opacity doesn't turn it off |
| [`cooldownindicator`](mods/cooldownindicator/) | [Cooldown Indicator](../features/cooldownindicator/README.md) | hud | Holding the game's Attack Indicator off (turn it off in Options) |
| [`coordinates`](mods/coordinates/) | [Coordinates](../features/coordinates/README.md) | hud | Biome |
| [`cosmetics`](mods/cosmetics/) | Cosmetics (ADR 0061) | player look\*, mob layer, name tag\*, tab list name\*, chat message\*, frame, tick, key | Preview drawn by the client, not the game's renderer; others' trails only in view; wheel key fixed to G |
| [`cps`](mods/cps/) | [CPS](../features/cps/README.md) | hud | |
| [`customsky`](mods/customsky/) | [Custom Sky](../features/customsky/README.md) | frame, resources reloaded, sky layers\* | Nearest-sampled textures; not in Horizon's own packs' water reflection; a shader pack's own sky shows under the layers; biomes, heights, days, transition, sun and moon_phases not read (as Java) |
| [`customscoreboard`](mods/customscoreboard/) | [Custom Scoreboard](../features/customscoreboard/README.md) | sidebar place\*, hud | Placed by the size it had the frame before; the editor's sample is drawn by the mod, not the game |
| [`fastcrystal`](mods/fastcrystal/) | [Fast Crystal](../features/fastcrystal/README.md) | object attacked\*, block used\*, tick | Waits for the server in whole ticks, not milliseconds |
| [`fpsdisplay`](mods/fpsdisplay/) | [FPS Display](../features/fpsdisplay/README.md) | hud | |
| [`freelook`](mods/freelook/) | [Freelook](../features/freelook/README.md) | key, tick, turn\*, camera rotation\* | Billboards and the in-water fog check follow the player's facing |
| [`fullbright`](mods/fullbright/) | [Fullbright](../features/fullbright/README.md) | frame | Brightness below 100%: Horizon lights fully or not at all |
| [`glintcolor`](mods/glintcolor/) | [Enchant Glint](../features/glintcolor/README.md) | glint color\* | Repainting the glint in the colour: Horizon tints the game's purple glint by it |
| [`hitboxes`](mods/hitboxes/) | [Hitboxes](../features/hitboxes/README.md) | lines\* | Everything (items, arrows); your own box; widths past 4; giving way to F3+B |
| [`hitcolor`](mods/hitcolor/) | [Hit Color](../features/hitcolor/README.md) | hit color\* | Shader packs' entities keep vanilla's red |
| [`hiteffects`](mods/hiteffects/) | [Hit & Kill Effects](../features/hiteffects/README.md) | player attacked\*, mob died\*, frame | |
| [`keystrokes`](mods/keystrokes/) | [Keystrokes](../features/keystrokes/README.md) | hud | |
| [`lowfire`](mods/lowfire/) | [Low Fire](../features/lowfire/README.md) | fire overlay\* | |
| [`lowshield`](mods/lowshield/) | [Low Shield](../features/lowshield/README.md) | hand pose\* | Lowered after the swing's turn, not before it (mid-swing it moves a little differently) |
| [`minimap`](mods/minimap/) | [Minimap](../features/minimap/README.md) | minimap, frame, key, hud | The world map's land (Horizon's map colours); round at 48 and 32 blocks across shows 64; north up, a dot shows the way you face (no turned arrow) |
| [`nohurtcam`](mods/nohurtcam/) | [No Hurt Cam](../features/nohurtcam/README.md) | hurt tilt\* | Holding the game's Damage Tilt option: the hook sets the tilt a frame at a time, so the game's slider doesn't show it or hand control back |
| [`norender`](mods/norender/) | [No Render](../features/norender/README.md) | no render\* | Items being picked up still bob and spin when Still; already-made particles finish their life when a kind is turned off |
| [`oldanimations`](mods/oldanimations/) | [1.7 Animations](../features/oldanimations/README.md) | tick, block highlight, hand pose\* | 1.7 positions for flat items other than tools, weapons, sticks and the bow (the hook doesn't say which are blocks or which model an item has); a left-handed main arm (the main hand is taken as the right); the block-hit with the off hand in use |
| [`oldtextures`](mods/oldtextures/) | [Old Textures](../features/oldtextures/README.md) | frame (Programmer Art helpers\*) | Switching the pack in Resource Packs doesn't turn the module with it |
| [`reachdisplay`](mods/reachdisplay/) | [Reach Display](../features/reachdisplay/README.md) | attack reach\*, frame, hud | Hits on LAN players |
| [`saturation`](mods/saturation/) | [Saturation](../features/saturation/README.md) | health hud, hud | Outlines are the shank's box, not traced from its sprite |
| [`schematics`](mods/schematics/) | [Schematics](../features/schematics/README.md) | tick, key, hud, lines\*, ghosts\*, ghost revision\*, ghost section\* | Old block names aren't upgraded (Horizon has no data fixer: such blocks are left out); no dropping files on the window; the chooser lists no sizes; a problem box's edges only while Horizon's 1024 lines a frame hold out (its fill always shows); messages go to chat, not a toast |
| [`shieldtotem`](mods/shieldtotem/) | [Shield & Totem HUD](../features/shieldtotem/README.md) | hud | |
| [`shortitems`](mods/shortitems/) | [Short Items](../features/shortitems/README.md) | hand pose\* | Next to 1.7 item positions, scaled before or after them as Horizon orders the two mods' hooks |
| [`shulkertooltips`](mods/shulkertooltips/) | [Shulker Tooltips](../features/shulkertooltips/README.md) | tooltip, tooltip component, key | Shulker boxes only, not other items holding items |
| [`togglesprint`](mods/togglesprint/) | [Toggle Sprint](../features/togglesprint/README.md) | movement keys\*, tick, hud | Leaving the game's own Toggle options to the game; two presses within a tick count as one |
| [`waypoints`](mods/waypoints/) | [Waypoints](../features/waypoints/README.md) | tick, frame, key, hud | Beams drawn on the HUD over terrain (no beacon-beam hook); the world map's land (Horizon doesn't hand its map colours over yet); right-click adds at your height |
| [`weatherchanger`](mods/weatherchanger/) | [Weather Changer](../features/weatherchanger/README.md) | seen weather\*, seen day time\* | Snow: rain's levels, which Horizon snows only where the biome is cold |
| [`zoom`](mods/zoom/) | [Zoom](../features/zoom/README.md) | zoom, key | Smooth (cinematic) turning: Horizon has no cinematic camera for a mod, so Smooth turns slower, as Slower does; easing is Horizon's spyglass easing |
\* A hook point Horizon hasn't stamped into `native-hooks.json` yet (a fragment in its
`tools/native-hook-fragments/`): the bundle targets its function by path, and its manifest says the
one-line change for when it's stamped. Block highlight is Horizon's own; the rest, and the player
state helpers (`native_attack_strength`, `native_effect`, `native_equipped`...), are Incari's, in
the fork's `incari_client_hooks.json`, to offer upstream.
An Eaglercraft server's own pause menu (its `pause_menu.yml`: server info and Discord buttons, and
pictures beside the menu's buttons and title) shows in Incari's pause menu in place of the game's
Server Links button, as in the Java build. Horizon reads it (the fork's `eagler::pause_menu`,
`native_eagler_pause_menu`); a server info button that shows a web view isn't shown.
F then a digit types that function key (F+3 is F3, F+0 is F10) for Chromebooks, as in the Java build. It's in the Horizon fork (`game/f_chord.rs`), not a mod: a mod's `key` hook can't swallow or remake a key. Needs the pin bumped to the fork commit that has it.
Everything of the Java client's is here. What runs differently: the screen recorder records in the
browser build only (the page's `MediaRecorder`), as Java's; Incari's online service works only in
the threaded browser build (the others have no WebSocket client); the world map remembers land
while the minimap shows; the Wardrobe's and the title card's player is drawn by the client, not the
game's renderer; the Theme Editor's font choice stays Red Hat Display.
## Build
Needs, beside Incari's own: Rust's nightly that Horizon's `web/build.sh` names, with `rust-src` and
the `wasm32-unknown-unknown` target; the `wasm-bindgen-cli` of Horizon's `Cargo.lock`; binaryen's
`wasm-opt`; and Python 3. `./incari build` says which are missing.
```sh
./incari build --only rust # Horizon's resources, the mods, both wasm builds -> app-web/build/rust/
./gradlew :app-web:serve # serves it at /rust/; the page offers it
INCARI_HORIZON_DIR=~/horizon-web ./incari build --only rust # another Horizon checkout
```
The first build compiles `horizon-prepare` and the game: long.
Under `work/`:
| Folder | What |
| --- | --- |
| `horizon/` | The pinned Horizon commit, never edited here |
| `horizon-override/` | With `INCARI_HORIZON_DIR`: that checkout's files as git sees them (its ignored builds left out) |
| `horizon-resources/<version>/` | Horizon's resources, prepared from the jars and assets `./incari setup` and `./incari assets` fetched |
| `horizon-stage/` | Horizon with `rust/mods` applied (horizon-mixins keeps unchanged files' times, so rebuilds are incremental) |
| `horizon-target/`, `horizon-out/` | Cargo's output, and `web/package.py`'s folder before it's copied to `app-web/build/rust/` |
| `cache/horizon-mixins/<commit>/` | horizon-mixins, built once |
## How to test
```sh
cargo test --manifest-path rust/Cargo.toml # each mod's logic
cargo clippy --manifest-path rust/Cargo.toml --all-targets -- -D warnings
./incari build --only rust && ./gradlew :app-web:serve # then open http://localhost:8080/?build=rust
```
The game itself needs WebGPU: a real GPU, or Chrome with `--enable-unsafe-webgpu`.
+73
View File
@@ -0,0 +1,73 @@
// Every Incari mod's `runtime.rs` (no game types) as one crate, so their tests run without Horizon.
// In the game each is a module of `game.rs`; the client they read their settings from is
// `mods/incari` (crate `incari_core`, a workspace member here).
#[path = "mods/armorpotionview/runtime.rs"]
pub mod incari_armorpotionview;
#[path = "mods/blockoutline/runtime.rs"]
pub mod incari_blockoutline;
#[path = "mods/clearchat/runtime.rs"]
pub mod incari_clearchat;
#[path = "mods/cooldownindicator/runtime.rs"]
pub mod incari_cooldownindicator;
#[path = "mods/coordinates/runtime.rs"]
pub mod incari_coordinates;
#[path = "mods/cosmetics/runtime.rs"]
pub mod incari_cosmetics;
#[path = "mods/cps/runtime.rs"]
pub mod incari_cps;
#[path = "mods/customscoreboard/runtime.rs"]
pub mod incari_customscoreboard;
#[path = "mods/customsky/runtime.rs"]
pub mod incari_customsky;
#[path = "mods/fastcrystal/runtime.rs"]
pub mod incari_fastcrystal;
#[path = "mods/fpsdisplay/runtime.rs"]
pub mod incari_fpsdisplay;
#[path = "mods/freelook/runtime.rs"]
pub mod incari_freelook;
#[path = "mods/fullbright/runtime.rs"]
pub mod incari_fullbright;
#[path = "mods/glintcolor/runtime.rs"]
pub mod incari_glintcolor;
#[path = "mods/hitboxes/runtime.rs"]
pub mod incari_hitboxes;
#[path = "mods/hitcolor/runtime.rs"]
pub mod incari_hitcolor;
#[path = "mods/hiteffects/runtime.rs"]
pub mod incari_hiteffects;
#[path = "mods/keystrokes/runtime.rs"]
pub mod incari_keystrokes;
#[path = "mods/lowfire/runtime.rs"]
pub mod incari_lowfire;
#[path = "mods/lowshield/runtime.rs"]
pub mod incari_lowshield;
#[path = "mods/minimap/runtime.rs"]
pub mod incari_minimap;
#[path = "mods/nohurtcam/runtime.rs"]
pub mod incari_nohurtcam;
#[path = "mods/norender/runtime.rs"]
pub mod incari_norender;
#[path = "mods/oldanimations/runtime.rs"]
pub mod incari_oldanimations;
#[path = "mods/oldtextures/runtime.rs"]
pub mod incari_oldtextures;
#[path = "mods/reachdisplay/runtime.rs"]
pub mod incari_reachdisplay;
#[path = "mods/saturation/runtime.rs"]
pub mod incari_saturation;
#[path = "mods/schematics/runtime.rs"]
pub mod incari_schematics;
#[path = "mods/shieldtotem/runtime.rs"]
pub mod incari_shieldtotem;
#[path = "mods/shortitems/runtime.rs"]
pub mod incari_shortitems;
#[path = "mods/shulkertooltips/runtime.rs"]
pub mod incari_shulkertooltips;
#[path = "mods/togglesprint/runtime.rs"]
pub mod incari_togglesprint;
#[path = "mods/waypoints/runtime.rs"]
pub mod incari_waypoints;
#[path = "mods/weatherchanger/runtime.rs"]
pub mod incari_weatherchanger;
#[path = "mods/zoom/runtime.rs"]
pub mod incari_zoom;
@@ -0,0 +1,25 @@
# Incari's Armor & Potion View (features/armorpotionview) for the Rust build (ADR 0068, 0069). Hooks by name only
# (native-hooks.json). Its settings and HUD elements are the client's (rust/mods/incari): the module
# menu shows them and the HUD editor places them.
[mod]
id = "incari_armorpotionview"
version = "0.1.0"
priority = 100
[[module]]
id = "runtime"
file = "crates/horizon-client/src/game.rs"
name = "incari_armorpotionview"
source = "runtime.rs"
[[injection]]
id = "hud"
hook = "hud"
hook_version = 1
kind = "HEAD"
helper = "hud.rs"
bindings = [
{ name = "game", ty = "&mut crate::game::Game<'_>", value = "&mut *self" },
{ name = "batch", ty = "&mut horizon_client::hud::HudBatch", value = "&mut *batch" },
{ name = "corners", ty = "&mut horizon_client::extras_hud::Corners", value = "&mut *corners" },
]
@@ -0,0 +1,157 @@
// The armor and the effects on the glass, each where the player placed it (the Java module's
// ArmorElement and EffectsElement).
fn incari_armorpotionview_hud(
game: &mut crate::game::Game<'_>,
batch: &mut horizon_client::hud::HudBatch,
corners: &mut horizon_client::extras_hud::Corners,
) {
use crate::game::{incari_armorpotionview as m, incari_client as c};
use incari_core::hud::{HudCanvas, LINE};
use incari_core::theme::Tone;
let _ = corners;
let game = &*game;
let tone = |t: m::Tone| match t {
m::Tone::Text => Tone::Text,
m::Tone::Muted => Tone::Muted,
m::Tone::Positive => Tone::Positive,
m::Tone::Warning => Tone::Warning,
m::Tone::Negative => Tone::Negative,
};
let in_world = game.native_player().is_some();
c::element(game, batch, m::ID, m::ARMOR, |canvas| {
let s = canvas.module;
if !s.bool("show-armor") {
return None;
}
let held = s.bool("show-held");
let worn = |slot: usize| {
let stack = game.native_equipped(m::SLOTS[slot]).filter(|st| in_world && st.count > 0)?;
Some(m::Item {
id: &stack.item,
damage: stack.damage,
max: game.native_max_damage(&stack.item),
})
};
let mut items = [m::Item { id: "", damage: 0, max: 0 }; m::SLOTS.len()];
let mut count = 0;
for slot in (0..m::SLOTS.len()).filter(|&slot| slot != m::HELD || held) {
if let Some(item) = worn(slot) {
items[count] = item;
count += 1;
}
}
if count == 0 && canvas.editing {
for slot in (0..m::SLOTS.len()).filter(|&slot| slot != m::HELD || held) {
items[count] = m::SAMPLE_ITEMS[slot];
count += 1;
}
}
let items = &items[..count];
if items.is_empty() {
return None;
}
let durability = s.choice("durability");
let colors = s.bool("wear-colors");
let horizontal = s.choice("layout") == "horizontal";
let cell = |canvas: &HudCanvas<'_, '_>, row: usize, item: m::Item<'_>| {
m::with_item_text(row, item, durability, |text| {
text.map_or(m::ITEM_ICON, |t| m::ITEM_ICON + m::ITEM_TEXT_GAP + canvas.text_width(t))
})
};
let cells = items.iter().enumerate().map(|(row, item)| cell(&*canvas, row, *item));
let size = if horizontal {
[cells.sum::<f32>() + m::CELL_GAP * (count - 1) as f32, m::ITEM_ICON]
} else {
[cells.fold(0.0, f32::max), count as f32 * (m::ITEM_ICON + m::ROW_GAP) - m::ROW_GAP]
};
let text_y = ((m::ITEM_ICON - LINE) / 2.0).floor() + 1.0;
let (mut x, mut y) = (0.0, 0.0);
for (row, item) in items.iter().enumerate() {
canvas.item(item.id, x, y);
// The game's durability bar, as the item's decorations draw it.
if let Some((width, rgb)) = m::bar(*item) {
canvas.fill_argb(x + 2.0, y + 13.0, 13.0, 2.0, 0xFF00_0000);
canvas.fill_argb(x + 2.0, y + 13.0, width, 1.0, 0xFF00_0000 | rgb);
}
m::with_item_text(row, *item, durability, |text| {
if let Some(text) = text {
let at = x + m::ITEM_ICON + m::ITEM_TEXT_GAP;
canvas.text(text, at, y + text_y, tone(m::wear(*item, colors)));
}
});
if horizontal {
x += cell(&*canvas, row, *item) + m::CELL_GAP;
} else {
y += m::ITEM_ICON + m::ROW_GAP;
}
}
Some(size)
});
c::element(game, batch, m::ID, m::EFFECTS, |canvas| {
let s = canvas.module;
if !s.bool("show-effects") {
return None;
}
// The real effects, or in the HUD editor the sample when there are none.
let real = in_world && game.native_effect(0).is_some();
let sample = !real && canvas.editing;
let effect = |i: usize| {
if real {
game.native_effect(i).map(|e| m::Effect {
id: e.id,
amplifier: e.amplifier,
duration: e.duration,
beneficial: e.beneficial,
})
} else if sample {
m::SAMPLE_EFFECTS.get(i).copied()
} else {
None
}
};
let count = (0..m::MAX_EFFECTS).take_while(|&i| effect(i).is_some()).count();
if count == 0 {
return None;
}
let names = s.bool("effect-names");
let by_kind = s.bool("kind-colors");
let right = s.choice("side") == "right";
let mut text = 0.0_f32;
for (i, e) in (0..count).filter_map(|i| effect(i).map(|e| (i, e))) {
if names {
let w = m::with_name(i, e, |k| game.native_translate(k), |t| canvas.text_width(t));
text = text.max(w);
}
text = text.max(m::with_time(i, e.duration, |t| canvas.text_width(t)));
}
let width = m::EFFECT_ICON + m::EFFECT_TEXT_GAP + text;
let height = count as f32 * (m::EFFECT_ICON + m::EFFECT_ROW_GAP) - m::EFFECT_ROW_GAP;
let line = |canvas: &mut HudCanvas<'_, '_>, text: &str, y: f32, t: Tone| {
let x = if right {
width - m::EFFECT_ICON - m::EFFECT_TEXT_GAP - canvas.text_width(text)
} else {
m::EFFECT_ICON + m::EFFECT_TEXT_GAP
};
canvas.text(text, x, y, t);
};
for (i, e) in (0..count).filter_map(|i| effect(i).map(|e| (i, e))) {
let y = i as f32 * (m::EFFECT_ICON + m::EFFECT_ROW_GAP);
let icon_x = if right { width - m::EFFECT_ICON } else { 0.0 };
m::with_icon(i, e.id, |sprite| {
canvas.sprite(sprite, icon_x, y, m::EFFECT_ICON, m::EFFECT_ICON);
});
let time_tone = tone(m::time_tone(e.duration));
if names {
let name_tone = tone(m::name_tone(e, by_kind));
m::with_name(i, e, |k| game.native_translate(k), |t| line(&mut *canvas, t, y, name_tone));
m::with_time(i, e.duration, |t| line(&mut *canvas, t, y + LINE, time_tone));
} else {
let ty = y + ((m::EFFECT_ICON - LINE) / 2.0).floor() + 1.0;
m::with_time(i, e.duration, |t| line(&mut *canvas, t, ty, time_tone));
}
}
Some([width, height])
});
}
@@ -0,0 +1,423 @@
// Incari's Armor & Potion View for the Rust build (ADR 0068, 0069), as features/armorpotionview
// does it: two HUD elements, placed apart. One shows the armor you wear (and what you hold), each
// icon with the game's durability bar and its durability beside it; the other lists your active
// effects with their level and the time left. Its settings and HUD elements are the module's in
// `incari_core::modules` (the Java ids). No game types: rust/lib.rs tests it.
/// The module's id, as the Java client's profiles name it.
pub const ID: &str = "armorpotionview";
/// Its HUD elements' ids.
pub const ARMOR: &str = "armor";
pub const EFFECTS: &str = "effects";
/// Helmet first, then the held item.
pub const SLOTS: [&str; 5] = ["head", "chest", "legs", "feet", "mainhand"];
/// The held item's place in `SLOTS`.
pub const HELD: usize = 4;
/// An item's icon.
pub const ITEM_ICON: f32 = 16.0;
/// Between an item's icon and its text.
pub const ITEM_TEXT_GAP: f32 = 2.0;
/// Between armor rows (vertical).
pub const ROW_GAP: f32 = 1.0;
/// Between armor cells (horizontal).
pub const CELL_GAP: f32 = 4.0;
/// An effect's icon.
pub const EFFECT_ICON: f32 = 18.0;
pub const EFFECT_TEXT_GAP: f32 = 3.0;
pub const EFFECT_ROW_GAP: f32 = 2.0;
/// Ticks left from which the time turns amber: ten seconds.
pub const ENDING: i32 = 200;
/// The most effects listed.
pub const MAX_EFFECTS: usize = 32;
/// The text's tone (`incari_core::theme::Tone`'s of the same names).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Tone {
Text,
Muted,
Positive,
Warning,
Negative,
}
/// An item as the armor element shows it: its id, its wear and the most it takes (0 for one that
/// doesn't wear).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Item<'a> {
pub id: &'a str,
pub damage: u32,
pub max: u32,
}
/// The Java sample player's: diamond armor at a few levels of wear and a sword, for the HUD editor
/// when you wear nothing.
pub const SAMPLE_ITEMS: [Item<'static>; 5] = [
Item {
id: "minecraft:diamond_helmet",
damage: 36,
max: 363,
},
Item {
id: "minecraft:diamond_chestplate",
damage: 185,
max: 528,
},
Item {
id: "minecraft:diamond_leggings",
damage: 297,
max: 495,
},
Item {
id: "minecraft:diamond_boots",
damage: 365,
max: 429,
},
Item {
id: "minecraft:diamond_sword",
damage: 312,
max: 1561,
},
];
/// An effect as the effects element shows it: its id (vanilla's without its namespace), its
/// amplifier (0 is level I), its ticks left (-1 for none) and whether it helps.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Effect {
pub id: &'static str,
pub amplifier: i32,
pub duration: i32,
pub beneficial: bool,
}
/// The Java sample player's effects, for the HUD editor when you have none.
pub const SAMPLE_EFFECTS: [Effect; 3] = [
Effect {
id: "speed",
amplifier: 1,
duration: 1660,
beneficial: true,
},
Effect {
id: "strength",
amplifier: 0,
duration: 3600,
beneficial: true,
},
Effect {
id: "fire_resistance",
amplifier: 0,
duration: 160,
beneficial: true,
},
];
/// Whole percent left, rounded down, but 1 while anything's left: 0% is broken.
pub fn percent(remaining: u32, max: u32) -> u32 {
if max == 0 || remaining == 0 {
return 0;
}
(u64::from(remaining) * 100 / u64::from(max)).max(1) as u32
}
/// "86%", "312", "312/363", or nothing for the bar alone, by the `durability` setting's key.
pub fn format(durability: &str, remaining: u32, max: u32) -> String {
match durability {
"remaining" => remaining.to_string(),
"remaining_of_max" => format!("{remaining}/{max}"),
"bar" => String::new(),
_ => format!("{}%", percent(remaining, max)),
}
}
/// Durability's tone: green, amber below half, red below a fifth; the theme's text when not
/// coloured or for an item that doesn't wear.
pub fn wear(item: Item<'_>, colors: bool) -> Tone {
if !colors || item.max == 0 {
return Tone::Text;
}
let (remaining, max) = (
u64::from(item.max.saturating_sub(item.damage)),
u64::from(item.max),
);
if remaining * 5 < max {
Tone::Negative
} else if remaining * 2 < max {
Tone::Warning
} else {
Tone::Positive
}
}
/// The game's durability bar on an item's icon (`ItemStack.getBarWidth`/`getBarColor`): its width
/// of 13 and its RGB, None while the item is unworn.
pub fn bar(item: Item<'_>) -> Option<(f32, u32)> {
if item.max == 0 || item.damage == 0 {
return None;
}
let (damage, max) = (item.damage as f32, item.max as f32);
let width = (13.0 - damage * 13.0 / max + 0.5).floor().clamp(0.0, 13.0);
let left = ((max - damage) / max).max(0.0);
Some((width, hsv(left / 3.0)))
}
/// `Mth.hsvToRgb(hue, 1, 1)`.
fn hsv(hue: f32) -> u32 {
let h = (hue * 6.0) as i32 % 6;
let f = hue * 6.0 - (hue * 6.0).floor();
let (q, t) = (1.0 - f, f);
let (r, g, b) = match h {
0 => (1.0, t, 0.0),
1 => (q, 1.0, 0.0),
2 => (0.0, 1.0, t),
3 => (0.0, q, 1.0),
4 => (t, 0.0, 1.0),
_ => (1.0, 0.0, q),
};
let byte = |v: f32| ((v * 255.0) as u32).min(255);
byte(r) << 16 | byte(g) << 8 | byte(b)
}
/// " II" for amplifier 1; nothing for level I; numbers past X.
pub fn level(amplifier: i32) -> String {
const NUMERALS: [&str; 10] = [
"", " II", " III", " IV", " V", " VI", " VII", " VIII", " IX", " X",
];
usize::try_from(amplifier)
.ok()
.and_then(|a| NUMERALS.get(a))
.map_or_else(|| format!(" {}", amplifier + 1), |n| (*n).to_owned())
}
/// "0:08", "1:23", "1:02:03".
pub fn clock(seconds: i32) -> String {
let (hours, minutes, secs) = (seconds / 3600, seconds / 60 % 60, seconds % 60);
if hours > 0 {
format!("{hours}:{minutes:02}:{secs:02}")
} else {
format!("{minutes}:{secs:02}")
}
}
/// An effect's time left: "1:23", "∞" for one without end.
pub fn time(duration: i32) -> String {
if duration < 0 {
"∞".to_owned()
} else {
clock(duration / 20)
}
}
/// The time's tone: amber in its last ten seconds.
pub fn time_tone(duration: i32) -> Tone {
if (0..ENDING).contains(&duration) {
Tone::Warning
} else {
Tone::Muted
}
}
/// The name's tone: helpful in green, harmful in red, when coloured by kind.
pub fn name_tone(effect: Effect, by_kind: bool) -> Tone {
match (by_kind, effect.beneficial) {
(false, _) => Tone::Text,
(true, true) => Tone::Positive,
(true, false) => Tone::Negative,
}
}
/// Effect `id`'s translation key: `effect.minecraft.speed`, a mod's `effect.<ns>.<path>`.
pub fn name_key(id: &str) -> String {
match id.split_once(':') {
Some((ns, path)) => format!("effect.{ns}.{path}"),
None => format!("effect.minecraft.{id}"),
}
}
/// "Jump Boost" for `jump_boost`: an effect's name when the language has none.
pub fn fallback_name(id: &str) -> String {
let path = id.rsplit(':').next().unwrap_or(id);
let mut name = String::with_capacity(path.len());
for word in path.split('_').filter(|w| !w.is_empty()) {
if !name.is_empty() {
name.push(' ');
}
let mut c = word.chars();
if let Some(first) = c.next() {
name.extend(first.to_uppercase());
name.push_str(c.as_str());
}
}
name
}
/// What a row's text was made from, and the text.
type Cached<K> = (Option<K>, String);
/// An armor row's text, by the wear, the most and the format it was made for.
type ItemText = Cached<(u32, u32, &'static str)>;
// Hot path, don't allocate: each row's text is made again only when what it says changes.
thread_local! {
static ITEM_TEXT: std::cell::RefCell<[ItemText; 5]> =
std::cell::RefCell::new(Default::default());
static NAMES: std::cell::RefCell<[Cached<(usize, i32)>; MAX_EFFECTS]> =
std::cell::RefCell::new(std::array::from_fn(|_| (None, String::new())));
static TIMES: std::cell::RefCell<[Cached<i32>; MAX_EFFECTS]> =
std::cell::RefCell::new(std::array::from_fn(|_| (None, String::new())));
static ICONS: std::cell::RefCell<[Cached<usize>; MAX_EFFECTS]> =
std::cell::RefCell::new(std::array::from_fn(|_| (None, String::new())));
}
/// Calls `f` with armor row `row`'s durability text in `durability`'s format, None when nothing is
/// written beside it (an item that doesn't wear, or the bar alone).
pub fn with_item_text<R>(
row: usize,
item: Item<'_>,
durability: &'static str,
f: impl FnOnce(Option<&str>) -> R,
) -> R {
if item.max == 0 || durability == "bar" {
return f(None);
}
ITEM_TEXT.with(|cell| {
let mut rows = cell.borrow_mut();
let slot = &mut rows[row.min(4)];
let key = (item.damage, item.max, durability);
if slot.0 != Some(key) {
*slot = (
Some(key),
format(durability, item.max.saturating_sub(item.damage), item.max),
);
}
f(Some(&slot.1))
})
}
/// Calls `f` with effect row `row`'s "Speed II", its name from `translate` (the key to the
/// language's name), made again only when the row's effect changes. Ids are the game's static
/// strings: the address names one.
pub fn with_name<R>(
row: usize,
effect: Effect,
translate: impl FnOnce(&str) -> String,
f: impl FnOnce(&str) -> R,
) -> R {
NAMES.with(|cell| {
let mut rows = cell.borrow_mut();
let slot = &mut rows[row.min(MAX_EFFECTS - 1)];
let key = (effect.id.as_ptr() as usize, effect.amplifier);
if slot.0 != Some(key) {
let lang = name_key(effect.id);
let mut name = translate(&lang);
if name.is_empty() || name == lang {
name = fallback_name(effect.id);
}
name.push_str(&level(effect.amplifier));
*slot = (Some(key), name);
}
f(&slot.1)
})
}
/// Calls `f` with effect row `row`'s time left, made again only when the second changes.
pub fn with_time<R>(row: usize, duration: i32, f: impl FnOnce(&str) -> R) -> R {
let seconds = if duration < 0 { -1 } else { duration / 20 };
TIMES.with(|cell| {
let mut rows = cell.borrow_mut();
let slot = &mut rows[row.min(MAX_EFFECTS - 1)];
if slot.0 != Some(seconds) {
*slot = (Some(seconds), time(duration));
}
f(&slot.1)
})
}
/// Calls `f` with effect `id`'s icon sprite, `mob_effect/<id>`, for row `row`.
pub fn with_icon<R>(row: usize, id: &'static str, f: impl FnOnce(&str) -> R) -> R {
ICONS.with(|cell| {
let mut rows = cell.borrow_mut();
let slot = &mut rows[row.min(MAX_EFFECTS - 1)];
let key = id.as_ptr() as usize;
if slot.0 != Some(key) {
*slot = (Some(key), format!("mob_effect/{id}"));
}
f(&slot.1)
})
}
#[cfg(test)]
mod tests {
use super::*;
fn item(damage: u32, max: u32) -> Item<'static> {
Item {
id: "minecraft:diamond_helmet",
damage,
max,
}
}
#[test]
fn writes_durability_as_the_java_module_does() {
assert_eq!(format("percent", 217, 250), "86%");
assert_eq!(format("remaining", 217, 250), "217");
assert_eq!(format("remaining_of_max", 217, 250), "217/250");
assert_eq!(format("bar", 217, 250), "");
assert_eq!(percent(1, 1000), 1);
assert_eq!(percent(0, 1000), 0);
assert_eq!(
with_item_text(0, item(1, 4), "percent", |t| t.map(str::to_owned)),
Some("75%".into())
);
assert!(with_item_text(0, item(1, 4), "bar", |t| t.is_none()));
assert!(with_item_text(1, item(0, 0), "percent", |t| t.is_none()));
}
#[test]
fn colours_by_wear() {
assert_eq!(wear(item(0, 100), true), Tone::Positive);
assert_eq!(wear(item(51, 100), true), Tone::Warning);
assert_eq!(wear(item(81, 100), true), Tone::Negative);
assert_eq!(wear(item(81, 100), false), Tone::Text);
assert_eq!(wear(item(0, 0), true), Tone::Text);
}
#[test]
fn draws_the_games_bar() {
assert_eq!(bar(item(0, 100)), None);
assert_eq!(bar(item(50, 100)).map(|b| b.0), Some(7.0));
assert_eq!(bar(item(1, 1000)), Some((13.0, 0x00FF00)));
assert_eq!(bar(item(999, 1000)).map(|b| b.1 >> 16), Some(0xFF));
}
#[test]
fn names_effects_as_the_java_module_does() {
assert_eq!(level(0), "");
assert_eq!(level(1), " II");
assert_eq!(level(11), " 12");
assert_eq!(clock(8), "0:08");
assert_eq!(clock(83), "1:23");
assert_eq!(clock(3723), "1:02:03");
assert_eq!(time(-1), "∞");
assert_eq!(time_tone(199), Tone::Warning);
assert_eq!(time_tone(-1), Tone::Muted);
assert_eq!(name_key("speed"), "effect.minecraft.speed");
assert_eq!(name_key("mymod:frost_bite"), "effect.mymod.frost_bite");
assert_eq!(fallback_name("mymod:frost_bite"), "Frost Bite");
let speed = SAMPLE_EFFECTS[0];
assert_eq!(
with_name(0, speed, |_| "Speed".into(), str::to_owned),
"Speed II"
);
let strength = SAMPLE_EFFECTS[1];
assert_eq!(
with_name(1, strength, str::to_owned, str::to_owned),
"Strength"
);
assert_eq!(with_time(0, 1660, str::to_owned), "1:23");
assert_eq!(with_icon(0, "speed", str::to_owned), "mob_effect/speed");
assert_eq!(name_tone(speed, true), Tone::Positive);
}
}
@@ -0,0 +1,9 @@
// The game's own outline skipped, and the block kept for the mod's.
fn incari_blockoutline_highlight(game: &crate::game::Game<'_>, pos: [i32; 3], canceled: &mut bool) {
use crate::game::{incari_blockoutline as m, incari_client as c};
let _ = game;
if c::on(m::ID) {
m::aim(pos);
*canceled = true;
}
}
@@ -0,0 +1,36 @@
# Incari's Block Outline (features/blockoutline) for the Rust build (ADR 0068, 0069). Hooks by name
# only (native-hooks.json). Its settings are the client's (rust/mods/incari), shown in the module
# menu.
[mod]
id = "incari_blockoutline"
version = "0.1.0"
priority = 100
[[module]]
id = "runtime"
file = "crates/horizon-client/src/game.rs"
name = "incari_blockoutline"
source = "runtime.rs"
[[injection]]
id = "highlight"
hook = "block_highlight"
hook_version = 1
kind = "HEAD"
helper = "highlight.rs"
bindings = [
{ name = "game", ty = "&crate::game::Game<'_>", value = "self" },
{ name = "pos", ty = "[i32; 3]", value = "pos" },
{ name = "canceled", ty = "&mut bool", value = "&mut *canceled" },
]
[[injection]]
id = "visuals"
hook = "visuals"
hook_version = 1
kind = "HEAD"
helper = "visuals.rs"
bindings = [
{ name = "game", ty = "&crate::game::Game<'_>", value = "self" },
{ name = "rims", ty = "&mut Vec<crate::game::native_hooks::NativeBlockRim>", value = "&mut *rims" },
]
@@ -0,0 +1,58 @@
// Incari's Block Outline for the Rust build (ADR 0068, 0069), as features/blockoutline does it: the
// block you look at outlined in your colour, opacity and width, for you only. Its settings are the
// module's in `incari_core::modules`. Horizon draws a mod's outline (a "rim") along the block's
// selection shape, depth-tested, 0.5 to 4 pixels wide, and has no fill, so widths past 4 draw at 4
// and Fill does nothing yet. No game types: rust/lib.rs tests it.
/// The module's id, as the Java client's profiles name it.
pub const ID: &str = "blockoutline";
/// The widest rim Horizon draws.
pub const MAX_WIDTH: f32 = 4.0;
/// `rgb` (the "color" setting) at `percent` opacity, never fully clear, as the Java module's.
pub fn argb(rgb: u32, percent: i32) -> u32 {
let alpha = ((percent.clamp(0, 100) as f32 * 255.0 / 100.0).round() as u32).max(1);
alpha << 24 | (rgb & 0xFF_FFFF)
}
/// The rim's width in pixels: the "width" setting, as far as Horizon goes.
pub fn width(setting: f32) -> f32 {
setting.clamp(0.5, MAX_WIDTH)
}
// The block the game would outline, kept from its highlight hook (where the game's own outline is
// skipped) for the next frame's visuals hook, which comes first in a frame: a frame late, and
// gone a frame after the player looks away.
thread_local! {
static TARGET: std::cell::Cell<Option<[i32; 3]>> = const { std::cell::Cell::new(None) };
}
pub fn aim(pos: [i32; 3]) {
TARGET.with(|t| t.set(Some(pos)));
}
pub fn take() -> Option<[i32; 3]> {
TARGET.with(std::cell::Cell::take)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn starts_as_the_java_module_does() {
assert_eq!(argb(0xFFA9_DCFF, 90), 0xE6A9_DCFF);
assert_eq!(argb(0x00_0000, 100), 0xFF00_0000);
assert_eq!(argb(0xFF_FFFF, 0) >> 24, 1);
assert_eq!(width(2.5), 2.5);
assert_eq!(width(6.0), MAX_WIDTH);
}
#[test]
fn draws_each_aim_once() {
aim([1, 2, 3]);
assert_eq!(take(), Some([1, 2, 3]));
assert_eq!(take(), None);
}
}
@@ -0,0 +1,20 @@
// The mod's outline on the block the game would have outlined.
fn incari_blockoutline_rim(
game: &crate::game::Game<'_>,
rims: &mut Vec<crate::game::native_hooks::NativeBlockRim>,
) {
use crate::game::{incari_blockoutline as m, incari_client as c};
let _ = game;
let Some(pos) = m::take() else {
return;
};
let Some((argb, width)) = c::settings(m::ID, |s| {
(
m::argb(s.color("color"), s.int("opacity")),
m::width(s.float("width")),
)
}) else {
return;
};
rims.push(crate::game::native_hooks::NativeBlockRim { pos, argb, width });
}
@@ -0,0 +1,5 @@
// Each frame: the chat box cleared while on, and the game's own back once off.
fn incari_clearchat_frame(game: &mut crate::game::Game<'_>) {
use crate::game::{incari_clearchat as m, incari_client as c};
game.native_set_chat_background(m::opacity(c::on(m::ID)));
}
@@ -0,0 +1,23 @@
# Incari's Clear Chat (features/clearchat) for the Rust build (ADR 0068, 0069). Hooks by name where Horizon
# has stamped the hook point (native-hooks.json), by function where it's still pending. Its
# settings are the client's (rust/mods/incari): the module menu shows them.
[mod]
id = "incari_clearchat"
version = "0.1.0"
priority = 100
[[module]]
id = "runtime"
file = "crates/horizon-client/src/game.rs"
name = "incari_clearchat"
source = "runtime.rs"
[[injection]]
id = "frame"
hook = "frame"
hook_version = 1
kind = "HEAD"
helper = "frame.rs"
bindings = [
{ name = "game", ty = "&mut crate::game::Game<'_>", value = "&mut *self" },
]
@@ -0,0 +1,23 @@
// Incari's Clear Chat for the Rust build (ADR 0068, 0069), as features/clearchat does it: no dark
// box behind chat. The Java module holds the game's Text Background Opacity at 0%; here the box is
// cleared each frame and options.txt is untouched, so the player's own value is back once it's
// off. Its toggle is the module's in `incari_core::modules`. No game types: rust/lib.rs tests it.
/// The module's id, as the Java client's profiles name it.
pub const ID: &str = "clearchat";
/// The chat box's opacity while on; off gives it back to the game's option.
pub fn opacity(on: bool) -> Option<f64> {
on.then_some(0.0)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn clears_only_while_on() {
assert_eq!(opacity(true), Some(0.0));
assert_eq!(opacity(false), None);
}
}
@@ -0,0 +1,25 @@
# Incari's Cooldown Indicator (features/cooldownindicator) for the Rust build (ADR 0068, 0069). Hooks by
# name only (native-hooks.json). Its settings and HUD elements are the client's (rust/mods/incari):
# the module menu shows them and the HUD editor places them.
[mod]
id = "incari_cooldownindicator"
version = "0.1.0"
priority = 100
[[module]]
id = "runtime"
file = "crates/horizon-client/src/game.rs"
name = "incari_cooldownindicator"
source = "runtime.rs"
[[injection]]
id = "hud"
hook = "hud"
hook_version = 1
kind = "HEAD"
helper = "hud.rs"
bindings = [
{ name = "game", ty = "&mut crate::game::Game<'_>", value = "&mut *self" },
{ name = "batch", ty = "&mut horizon_client::hud::HudBatch", value = "&mut *batch" },
{ name = "corners", ty = "&mut horizon_client::extras_hud::Corners", value = "&mut *corners" },
]
@@ -0,0 +1,76 @@
// The cooldown as a bar, a percentage or a ring, where the player placed it.
fn incari_cooldownindicator_hud(
game: &mut crate::game::Game<'_>,
batch: &mut horizon_client::hud::HudBatch,
corners: &mut horizon_client::extras_hud::Corners,
) {
use crate::game::{incari_client as c, incari_cooldownindicator as m};
use incari_core::theme::Tone;
let _ = corners;
if game.native_player().is_none() {
return;
}
let strength = game.native_attack_strength();
let Some(targets) = c::settings(m::ID, |s| {
s.bool("hide-when-ready") && s.bool("ready-on-target")
}) else {
return;
};
// The crosshair's target only matters once charged.
let on_target = targets && strength >= 1.0 && game.native_targeted_entity().is_some();
// The charge, and its colour: the custom one, else the tone's.
let look = |s: &incari_core::framework::setting::Settings, editing: bool| {
let charge = m::charge(strength, s.bool("hide-when-ready"), on_target, editing)?;
let custom = s.bool("custom-colors");
let color = if m::ready(charge) {
s.color("ready-color")
} else {
s.color("charging-color")
};
let tone = if m::ready(charge) {
Tone::Positive
} else {
Tone::Accent
};
Some((charge, custom.then_some(color), tone))
};
c::element(game, batch, m::ID, "bar", |canvas| {
let style = canvas.module.choice("style");
if style == "ring" {
return None;
}
let (charge, color, tone) = look(canvas.module, canvas.editing)?;
let argb = color.unwrap_or_else(|| canvas.p.theme.tone(tone));
if style == "number" {
let width = canvas.text_width(m::WIDEST);
return m::with_percent(charge, |text| {
let x = ((width - canvas.text_width(text)) / 2.0).floor();
canvas.text_argb(text, x, 0.0, argb);
Some([width, incari_core::hud::LINE])
});
}
let (w, h) = (
canvas.module.int("bar-width") as f32,
canvas.module.int("bar-height") as f32,
);
canvas.fill(0.0, 0.0, w, h, Tone::Background);
canvas.fill_argb(0.0, 0.0, m::filled(w, charge), h, argb);
Some([w, h])
});
c::element(game, batch, m::ID, "ring", |canvas| {
if canvas.module.choice("style") != "ring" {
return None;
}
let (charge, color, tone) = look(canvas.module, canvas.editing)?;
let argb = color.unwrap_or_else(|| canvas.p.theme.tone(tone));
let r = canvas.module.int("ring-size") as f32;
let background = canvas.p.theme.tone(Tone::Background);
canvas.p.ring(r, r, r, m::RING_WIDTH, background);
// A screen pixel a strip.
let step = 1.0 / (canvas.p.scale * canvas.p.zoom).max(1.0);
m::arc(r, m::RING_WIDTH, charge, step, |[x, y, w, h]| {
canvas.fill_argb(x, y, w, h, argb)
});
Some([r * 2.0, r * 2.0])
});
}
@@ -0,0 +1,161 @@
// Incari's Cooldown Indicator for the Rust build (ADR 0068, 0069), as features/cooldownindicator
// does it: the attack cooldown as a bar, a ring round the crosshair or a percentage, hidden once
// charged unless the crosshair is on a target. Its settings and HUD elements ("bar", "ring") are
// the module's in `incari_core::modules`. Horizon can't hold the game's own Attack Indicator off,
// so the player turns it off in Options. No game types: rust/lib.rs tests it.
/// The module's id, as the Java client's profiles name it.
pub const ID: &str = "cooldownindicator";
/// The ring's thickness, in GUI units.
pub const RING_WIDTH: f32 = 1.5;
/// The charge the HUD editor shows.
pub const SAMPLE: f32 = 0.6;
/// The widest the percentage says.
pub const WIDEST: &str = "100%";
/// The charge to draw, or None to draw nothing: `strength` the game's (0 to 1), `hide` the
/// "hide-when-ready" setting, `on_target` "ready-on-target" with the crosshair on a mob or player.
pub fn charge(strength: f32, hide: bool, on_target: bool, editing: bool) -> Option<f32> {
let strength = strength.min(1.0);
if strength >= 1.0 && hide && !on_target {
return editing.then_some(SAMPLE);
}
Some(strength)
}
/// Whether the charge counts as charged (the Positive tone, or the "ready-color").
pub fn ready(charge: f32) -> bool {
charge >= 1.0
}
/// The bar's filled width.
pub fn filled(width: f32, charge: f32) -> f32 {
(width * charge.clamp(0.0, 1.0)).round()
}
// Hot path, don't allocate: "73%" made again only when the percentage changes.
thread_local! {
static TEXT: std::cell::RefCell<(i32, String)> = const { std::cell::RefCell::new((-1, String::new())) };
}
/// Calls `f` with "60%" for `charge`.
pub fn with_percent<R>(charge: f32, f: impl FnOnce(&str) -> R) -> R {
let percent = (charge * 100.0).round() as i32;
TEXT.with(|cell| {
let mut cached = cell.borrow_mut();
if cached.0 != percent {
*cached = (percent, format!("{percent}%"));
}
f(&cached.1)
})
}
/// The arc of a ring `radius` to its outer edge and `width` thick, centred on (`radius`,
/// `radius`), from straight up `fraction` of the way round clockwise: as rectangles `[x, y, w, h]`
/// of `step` (a screen pixel) across, for `fill`. Allocation-free.
pub fn arc(radius: f32, width: f32, fraction: f32, step: f32, mut fill: impl FnMut([f32; 4])) {
use std::f32::consts::FRAC_PI_2;
let fraction = fraction.clamp(0.0, 1.0);
if radius <= 0.0 || width <= 0.0 || step <= 0.0 || fraction <= 0.0 {
return;
}
let (outer, inner) = (radius, (radius - width).max(0.0));
// Clockwise from up, on screen (y down): up, right, down, left.
const DIRS: [[f32; 2]; 4] = [[0.0, -1.0], [1.0, 0.0], [0.0, 1.0], [-1.0, 0.0]];
let angle = fraction * 4.0 * FRAC_PI_2;
let strips = (outer / step).ceil() as usize;
let span = |at: f32| {
(
(inner * inner - at * at).max(0.0).sqrt(),
(outer * outer - at * at).max(0.0).sqrt(),
)
};
for q in 0..4 {
let phi = angle - q as f32 * FRAC_PI_2;
if phi <= 0.0 {
break;
}
let (s, t) = (DIRS[q], DIRS[(q + 1) % 4]);
// A rectangle `a0..a1` along `s` and `b0..b1` along `t`, from the centre.
let mut rect = |a0: f32, a1: f32, b0: f32, b1: f32| {
if a1 <= a0 || b1 <= b0 {
return;
}
let p = |a: f32, b: f32| [radius + a * s[0] + b * t[0], radius + a * s[1] + b * t[1]];
let (p0, p1) = (p(a0, b0), p(a1, b1));
let (x, y) = (p0[0].min(p1[0]), p0[1].min(p1[1]));
fill([x, y, (p0[0] - p1[0]).abs(), (p0[1] - p1[1]).abs()]);
};
let full = phi >= FRAC_PI_2;
// Below 45 degrees the edge is steep across `s`: strips along `s`, else along `t`, so a
// strip's error stays under a step.
let along_s = full || phi <= FRAC_PI_2 / 2.0;
for n in 0..strips {
let (c0, c1) = (n as f32 * step, ((n + 1) as f32 * step).min(outer));
let mid = (c0 + c1) / 2.0;
let (lo, hi) = span(mid);
if along_s {
let limit = if full { hi } else { mid * phi.tan() };
rect(c0, c1, lo, hi.min(limit));
} else {
let start = mid / phi.tan();
rect(lo.max(start), hi, c0, c1);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hides_when_charged_as_the_java_module_does() {
assert_eq!(charge(1.0, true, false, false), None);
assert_eq!(charge(1.0, true, false, true), Some(SAMPLE));
assert_eq!(charge(1.2, true, true, false), Some(1.0));
assert_eq!(charge(1.0, false, false, false), Some(1.0));
assert_eq!(charge(0.4, true, false, false), Some(0.4));
assert!(ready(1.0) && !ready(0.99));
assert_eq!(filled(24.0, 0.5), 12.0);
assert_eq!(with_percent(0.734, str::to_owned), "73%");
assert_eq!(with_percent(0.6, str::to_owned), "60%");
}
fn area(fraction: f32) -> (f32, [f32; 4]) {
let (mut total, mut bounds) = (0.0, [f32::MAX, f32::MAX, f32::MIN, f32::MIN]);
arc(10.0, 1.5, fraction, 0.5, |[x, y, w, h]| {
total += w * h;
bounds = [
bounds[0].min(x),
bounds[1].min(y),
bounds[2].max(x + w),
bounds[3].max(y + h),
];
});
(total, bounds)
}
#[test]
fn fills_the_ring_as_far_round_as_charged() {
let ring = std::f32::consts::PI * (100.0 - 8.5f32.powi(2));
let (full, bounds) = area(1.0);
assert!((full - ring).abs() / ring < 0.05, "{full} {ring}");
assert_eq!(bounds, [0.0, 0.0, 20.0, 20.0]);
let (quarter, bounds) = area(0.25);
assert!((quarter - ring / 4.0).abs() / ring < 0.02);
// The top right quarter: right of the centre, above it.
assert!(bounds[0] >= 10.0 && bounds[3] <= 10.0);
for f in [0.1, 0.3, 0.6, 0.9] {
let (part, _) = area(f);
assert!(
(part - ring * f).abs() / ring < 0.03,
"{f}: {part} of {ring}"
);
}
assert_eq!(area(0.0).0, 0.0);
}
}
@@ -0,0 +1,25 @@
# Incari's Coordinates (features/coordinates) for the Rust build (ADR 0068, 0069). Hooks by name only
# (native-hooks.json). Its settings and HUD elements are the client's (rust/mods/incari): the module
# menu shows them and the HUD editor places them.
[mod]
id = "incari_coordinates"
version = "0.1.0"
priority = 100
[[module]]
id = "runtime"
file = "crates/horizon-client/src/game.rs"
name = "incari_coordinates"
source = "runtime.rs"
[[injection]]
id = "hud"
hook = "hud"
hook_version = 1
kind = "HEAD"
helper = "hud.rs"
bindings = [
{ name = "game", ty = "&mut crate::game::Game<'_>", value = "&mut *self" },
{ name = "batch", ty = "&mut horizon_client::hud::HudBatch", value = "&mut *batch" },
{ name = "corners", ty = "&mut horizon_client::extras_hud::Corners", value = "&mut *corners" },
]
@@ -0,0 +1,58 @@
// The position rows on the glass, where the player placed them (the Java module's Position).
fn incari_coordinates_hud(
game: &mut crate::game::Game<'_>,
batch: &mut horizon_client::hud::HudBatch,
corners: &mut horizon_client::extras_hud::Corners,
) {
use crate::game::{incari_client as c, incari_coordinates as m};
use incari_core::hud::{LINE, PAD_X, PAD_Y};
use incari_core::theme::Tone;
let _ = corners;
let spot = game.native_player().map(|p| m::Spot {
at: [m::block(p.x), m::block(p.y), m::block(p.z)],
overworld_at: [m::overworld_block(p.x), m::overworld_block(p.z)],
sector: m::sector(p.yaw),
nether: p.dimension == m::NETHER,
overworld: p.dimension == m::OVERWORLD,
});
c::element(game, batch, m::ID, m::ELEMENT, |canvas| {
let spot = spot.or(canvas.editing.then_some(m::SAMPLE))?;
let s = canvas.module;
let shown = m::Shown {
one_line: s.choice("layout") == "line",
facing: s.bool("show-facing"),
other: s.bool("show-other"),
};
let background = s.bool("background");
m::with_rows(spot, shown, |rows| {
if rows.is_empty() {
return None;
}
let (pad, pad_y) = if background { (PAD_X, PAD_Y) } else { (0.0, 0.0) };
let label_width = |canvas: &incari_core::hud::HudCanvas<'_, '_>, label: &str| {
if label.is_empty() { 0.0 } else { canvas.text_width(label) + m::LABEL_GAP }
};
let width = rows
.iter()
.map(|(label, value)| label_width(&*canvas, label) + canvas.text_width(value))
.fold(0.0, f32::max);
let w = width + pad * 2.0;
let h = rows.len() as f32 * LINE + if background { pad_y * 2.0 - 1.0 } else { -1.0 };
if background {
canvas.fill(0.0, 0.0, w, h, Tone::Background);
}
let mut y = pad_y;
for (i, (label, value)) in rows.iter().enumerate() {
let mut x = pad;
if !label.is_empty() {
canvas.text(label, x, y, Tone::Accent);
x += label_width(&*canvas, label);
}
let tone = if m::muted(i, label) { Tone::Muted } else { Tone::Text };
canvas.text(value, x, y, tone);
y += LINE;
}
Some([w, h])
})
});
}
@@ -0,0 +1,227 @@
// Incari's Coordinates for the Rust build (ADR 0068, 0069), as features/coordinates does it: the
// block you're in, which way you face, and the matching spot in the other dimension, label beside
// value on the glass. Horizon's native API has no biome yet, so that row isn't here. Its settings
// and HUD element are the module's in `incari_core::modules` (the Java ids). No game types:
// rust/lib.rs tests it.
/// The module's id, as the Java client's profiles name it.
pub const ID: &str = "coordinates";
/// Its HUD element's id.
pub const ELEMENT: &str = "position";
pub const NETHER: &str = "minecraft:the_nether";
pub const OVERWORLD: &str = "minecraft:overworld";
/// Between a row's label and its value.
pub const LABEL_GAP: f32 = 4.0;
/// The block a coordinate is in: rounded down, so -0.5 is block -1.
pub fn block(coordinate: f64) -> i32 {
coordinate.floor() as i32
}
/// Which eighth of the compass the player faces, 0 north, 2 east, from Minecraft's yaw (0 faces
/// south, 90 west): the Java module's bearing, yaw + 180.
pub fn sector(yaw: f32) -> usize {
let heading = (yaw + 180.0).rem_euclid(360.0);
((heading / 45.0).round() as usize) % 8
}
/// The compass point of `sector`, with the axis that way runs along.
pub fn facing(sector: usize) -> &'static str {
[
"North (-Z)",
"Northeast",
"East (+X)",
"Southeast",
"South (+Z)",
"Southwest",
"West (-X)",
"Northwest",
][sector % 8]
}
/// The Overworld block matching a Nether position: from the exact position, as a Nether block
/// spans 8 Overworld ones (x 100.9 is 807, not 800).
pub fn overworld_block(nether: f64) -> i32 {
block(nether * 8.0)
}
/// What the rows are made from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Spot {
pub at: [i32; 3],
/// The Overworld x and z matching the exact position, for a player in the Nether.
pub overworld_at: [i32; 2],
pub sector: usize,
pub nether: bool,
pub overworld: bool,
}
/// The HUD editor's stand-in with no world: the Java sample player, at 0 0 0 in the Overworld
/// facing north.
pub const SAMPLE: Spot = Spot {
at: [0, 0, 0],
overworld_at: [0, 0],
sector: 0,
nether: false,
overworld: true,
};
/// What the settings ask for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Shown {
pub one_line: bool,
pub facing: bool,
pub other: bool,
}
pub const MAX_ROWS: usize = 5;
/// A row: its label ("" for none) and its value.
pub type Row = (&'static str, String);
/// The rows for `spot`, up to `MAX_ROWS`.
pub fn rows(spot: Spot, shown: Shown) -> Vec<Row> {
let [x, y, z] = spot.at;
let mut rows = Vec::with_capacity(MAX_ROWS);
if shown.one_line {
rows.push(("", format!("X {x} Y {y} Z {z}")));
} else {
rows.extend([
("X", x.to_string()),
("Y", y.to_string()),
("Z", z.to_string()),
]);
}
if shown.facing {
rows.push(("", facing(spot.sector).to_owned()));
}
if shown.other && spot.nether {
let [ox, oz] = spot.overworld_at;
rows.push(("Overworld", format!("{ox}, {oz}")));
} else if shown.other && spot.overworld {
rows.push((
"Nether",
format!("{}, {}", x.div_euclid(8), z.div_euclid(8)),
));
}
rows
}
/// A value's tone: a row without a label after the first is quieter (the facing, as the Java
/// module draws it).
pub fn muted(row: usize, label: &str) -> bool {
label.is_empty() && row >= 1
}
type Cached = (Option<(Spot, Shown)>, Vec<Row>);
// Hot path, don't allocate: made again only when the block, the facing or a setting changes.
thread_local! {
static ROWS: std::cell::RefCell<Cached> = const { std::cell::RefCell::new((None, Vec::new())) };
}
/// Calls `f` with `rows(spot, shown)`, made again only when one of them changed.
pub fn with_rows<R>(spot: Spot, shown: Shown, f: impl FnOnce(&[Row]) -> R) -> R {
ROWS.with(|cell| {
let mut cached = cell.borrow_mut();
if cached.0 != Some((spot, shown)) {
*cached = (Some((spot, shown)), rows(spot, shown));
}
f(&cached.1)
})
}
#[cfg(test)]
mod tests {
use super::*;
fn spot(at: [i32; 3], nether: bool) -> Spot {
Spot {
at,
overworld_at: [at[0] * 8, at[2] * 8],
sector: 0,
nether,
overworld: !nether,
}
}
const ALL: Shown = Shown {
one_line: false,
facing: true,
other: true,
};
#[test]
fn faces_as_the_java_module_does() {
// Minecraft's yaw: 180 faces north, -90 east, 0 south, 90 west.
assert_eq!(facing(sector(180.0)), "North (-Z)");
assert_eq!(facing(sector(-90.0)), "East (+X)");
assert_eq!(facing(sector(0.0)), "South (+Z)");
assert_eq!(facing(sector(90.0)), "West (-X)");
assert_eq!(facing(sector(-135.0)), "Northeast");
assert_eq!(facing(sector(-180.0 - 720.0)), "North (-Z)");
}
#[test]
fn rounds_down_to_the_block() {
assert_eq!([block(-0.5), block(0.5), block(-16.0)], [-1, 0, -16]);
}
#[test]
fn shows_the_other_dimension() {
let rows = rows(spot([-9, 64, 17], false), ALL);
assert_eq!(rows.len(), MAX_ROWS);
assert_eq!(rows[4], ("Nether", "-2, 2".to_owned()));
let line = Shown {
one_line: true,
facing: false,
other: true,
};
assert_eq!(
super::rows(spot([3, 70, -1], true), line),
[
("", "X 3 Y 70 Z -1".to_owned()),
("Overworld", "24, -8".to_owned())
]
);
let end = Spot {
overworld: false,
..spot([0, 0, 0], false)
};
assert_eq!(super::rows(end, line).len(), 1);
assert_eq!(super::rows(SAMPLE, ALL)[3], ("", "North (-Z)".to_owned()));
}
#[test]
fn the_overworlds_spot_is_from_the_exact_position() {
// Block 100 and -1 in the Nether, but 807 and -4 in the Overworld: not 800 and -8.
assert_eq!([overworld_block(100.9), overworld_block(-0.5)], [807, -4]);
let there = Spot {
overworld_at: [807, -4],
..spot([100, 70, -1], true)
};
assert_eq!(rows(there, ALL)[4], ("Overworld", "807, -4".to_owned()));
}
#[test]
fn quietens_the_unlabelled_rows_after_the_first() {
assert!(!muted(0, ""));
assert!(muted(1, ""));
assert!(!muted(3, "Nether"));
}
#[test]
fn makes_the_rows_again_only_when_something_changed() {
let s = spot([1, 2, 3], false);
let first = with_rows(s, ALL, |r| r.as_ptr());
assert_eq!(with_rows(s, ALL, |r| r.as_ptr()), first);
let line = Shown {
one_line: true,
facing: false,
other: false,
};
assert_eq!(with_rows(s, line, <[_]>::len), 1);
}
}
@@ -0,0 +1,42 @@
// A chat line (ADR 0062; `Cosmetics.chatMessage`, `Badges.badgedInChat`): Incari's badge before
// the first mention of each Incari player in it who shows it. Players are found by their names,
// since most servers send chat as plain text with no sender. Once a line.
fn incari_cosmetics_chat_message(game: &crate::game::Game<'_>, message: &mut horizon_client::text::Text) {
use horizon_client::text::{Style, Text};
use incari_core::cosmetics::badges::{self, Piece};
use incari_core::online::Status;
let own = game.native_player_name();
let show_badges = crate::game::incari_cosmetics::with(|s| s.show_badges);
let positions = incari_core::online::with(|o| {
if o.status() != Status::SignedIn {
return Vec::new();
}
let text: String = message.spans.iter().map(|s| s.text.as_str()).collect();
badges::chat_positions(&text, |name| {
if name == own {
o.shows_badge()
} else {
show_badges && o.world_players().get(name).is_some_and(|p| p.badge)
}
})
});
if positions.is_empty() {
return;
}
let texts: Vec<&str> = message.spans.iter().map(|s| s.text.as_str()).collect();
let pieces = badges::badged_pieces(&texts, &positions);
let mut out = Text::empty();
for piece in pieces {
match piece {
Piece::Text(i, text) => out.push(Text::styled(text, message.spans[i].style.clone())),
Piece::Badge => {
out.push(Text::styled(
badges::GLYPH,
Style { font: Some(badges::FONT.into()), color: Some(badges::COLOR), ..Style::default() },
));
out.push(Text::literal(" "));
}
}
}
*message = out;
}
@@ -0,0 +1,62 @@
// Once a frame: the wardrobe read the first time and saved when it changed, kept in step with the
// online service, and the cosmetics' pictures painted into the entity canvas: the still ones once
// (again after a new atlas), moving capes ten times a second while one was drawn lately.
fn incari_cosmetics_frame(game: &mut crate::game::Game<'_>) {
use crate::game::incari_cosmetics as m;
use incari_core::cosmetics::{Slot, art, catalog, models, wardrobe};
thread_local! {
static START: std::cell::Cell<Option<horizon_os::time::Instant>> = const { std::cell::Cell::new(None) };
}
let now = START.with(|s| {
let start = s.get().unwrap_or_else(|| {
let now = horizon_os::time::Instant::now();
s.set(Some(now));
now
});
start.elapsed().as_secs_f64() * 1000.0
});
m::with(|s| s.now_ms = now);
let folder = horizon_os::env::current_dir().unwrap_or_default().join("incari");
wardrobe::ensure_loaded(|| horizon_os::fs::read(folder.join(wardrobe::FILE)).ok());
wardrobe::with(|w| incari_core::online::with(|o| w.sync(o, now)));
if let Some(text) = wardrobe::with(|w| w.take_unsaved()) {
let path = folder.join(wardrobe::FILE);
if let Some(dir) = path.parent() {
let _ = horizon_os::fs::create_dir_all(dir);
}
if let Err(e) = horizon_os::fs::write(&path, text.as_bytes()) {
log::warn!("Incari: couldn't save the wardrobe: {e}");
}
}
let (still, moving) = m::with(|s| (!s.painted, s.capes_due()));
if !still && !moving {
return;
}
let t = (now / 1000.0) as f32;
let mut pixels = vec![0u32; art::CAPE_WIDTH * art::CAPE_HEIGHT];
let mut all = true;
for (n, cape) in catalog::in_slot(Slot::Cape).enumerate().take(m::CAPES) {
let due = still || (art::animated(cape.id) && m::with(|s| s.cape_moving(n)));
if !due {
continue;
}
art::cape(cape.id, t, &mut pixels);
all &= game.native_entity_canvas_upload(m::cape_slot(n), m::CAPE, art::rgba(&pixels));
}
if still {
let mut texture = vec![0u32; models::TEXTURE * models::TEXTURE];
for cosmetic in catalog::all() {
let (Some(n), Some(spec)) = (models::number(cosmetic), models::spec(cosmetic.id)) else {
continue;
};
if n >= m::MODELS {
continue;
}
models::texture(cosmetic.id, &spec, &mut texture);
all &= game.native_entity_canvas_upload(m::model_slot(n), [m::MODEL, m::MODEL], art::rgba(&texture));
}
// No canvas yet (the boot screen's atlas): again next frame.
m::with(|s| s.painted = all);
}
}
@@ -0,0 +1,128 @@
# Incari's cosmetics in the world for the Rust build (ADR 0061, 0069): worn capes, hats, wings and
# back items on players, name tag styles and Incari's badge (name tags, the tab list, chat),
# trails, and emotes with the emote wheel (G). What's worn and how it looks is the client's
# (`incari_core::cosmetics`, rust/mods/incari); the Wardrobe is its screen. Hooks by name where
# Horizon has stamped the hook point (native-hooks.json), by function where it's still pending:
# the fork's `incari_shell_hooks.json` (player_look, name_tag, tab_list_name, chat_message).
[mod]
id = "incari_cosmetics"
version = "0.1.0"
priority = 100
[[module]]
id = "runtime"
file = "crates/horizon-client/src/game.rs"
name = "incari_cosmetics"
source = "runtime.rs"
[[injection]]
id = "listened"
hook = "player_render_listened"
hook_version = 1
kind = "HEAD"
helper = "listened.rs"
bindings = [
{ name = "listened", ty = "&mut bool", value = "&mut *listened" },
]
[[injection]]
id = "look"
# Pending in the fork's incari_shell_hooks.json: make it `hook = "player_look"` and
# `hook_version = 1` once Horizon stamps it.
target = "horizon_client::game::native_hooks::Game<'_>::native_player_look"
kind = "HEAD"
helper = "look.rs"
bindings = [
{ name = "game", ty = "&crate::game::Game<'_>", value = "self" },
{ name = "player", ty = "&crate::game::native_mob_draw::NativeMobRender<'_>", value = "player" },
{ name = "look", ty = "&mut crate::game::native_mob_draw::NativePlayerLook<'_>", value = "&mut *look" },
]
[[injection]]
id = "layer"
hook = "mob_layer"
hook_version = 1
kind = "HEAD"
helper = "layer.rs"
bindings = [
{ name = "game", ty = "&crate::game::Game<'_>", value = "self" },
{ name = "mob", ty = "&crate::game::native_mob_draw::NativeMobRender<'_>", value = "mob" },
{ name = "who", ty = "Option<&crate::game::native_mob_draw::NativePlayerRender<'_>>", value = "who" },
{ name = "draw", ty = "&mut crate::game::native_block_entity_draw::BlockEntityDraw", value = "&mut *draw" },
]
[[injection]]
id = "name_tag"
# Pending (incari_shell_hooks.json): `hook = "name_tag"`, `hook_version = 1` once stamped.
target = "horizon_client::game::native_hooks::Game<'_>::native_name_tag"
kind = "HEAD"
helper = "name_tag.rs"
bindings = [
{ name = "game", ty = "&crate::game::Game<'_>", value = "self" },
{ name = "who", ty = "&crate::game::native_mob_draw::NativeNameTag<'_>", value = "who" },
{ name = "tag", ty = "&mut horizon_client::text::Text", value = "&mut *tag" },
]
[[injection]]
id = "tab_list_name"
# Pending (incari_shell_hooks.json): `hook = "tab_list_name"`, `hook_version = 1` once stamped.
target = "horizon_client::game::native_hooks::Game<'_>::native_tab_list_name"
kind = "HEAD"
helper = "tab_list_name.rs"
bindings = [
{ name = "game", ty = "&crate::game::Game<'_>", value = "self" },
{ name = "uuid", ty = "u128", value = "uuid" },
{ name = "local", ty = "bool", value = "local" },
{ name = "name", ty = "&mut horizon_client::text::Text", value = "&mut *name" },
]
[[injection]]
id = "chat_message"
# Pending (incari_shell_hooks.json): `hook = "chat_message"`, `hook_version = 1` once stamped.
target = "horizon_client::game::native_hooks::Game<'_>::native_chat_message"
kind = "HEAD"
helper = "chat_message.rs"
bindings = [
{ name = "game", ty = "&crate::game::Game<'_>", value = "self" },
{ name = "message", ty = "&mut horizon_client::text::Text", value = "&mut *message" },
]
[[injection]]
id = "frame"
hook = "frame"
hook_version = 1
kind = "HEAD"
helper = "frame.rs"
bindings = [
{ name = "game", ty = "&mut crate::game::Game<'_>", value = "&mut *self" },
]
[[injection]]
id = "tick"
hook = "tick"
hook_version = 1
kind = "HEAD"
helper = "tick.rs"
bindings = [
{ name = "game", ty = "&mut crate::game::Game<'_>", value = "&mut *self" },
]
[[injection]]
id = "key"
hook = "key"
hook_version = 1
kind = "HEAD"
helper = "key.rs"
bindings = [
{ name = "game", ty = "&mut crate::game::Game<'_>", value = "&mut *self" },
{ name = "key", ty = "&str", value = "key" },
{ name = "pressed", ty = "bool", value = "pressed" },
]
[[injection]]
id = "reloaded"
hook = "client_resources_reloaded"
hook_version = 1
kind = "HEAD"
helper = "reloaded.rs"
bindings = []
@@ -0,0 +1,13 @@
// The emote wheel's key (G): held, the wheel shows over the game; let go, the emote pointed at
// plays (`incari_core::screens::emote_wheel`).
fn incari_cosmetics_key(game: &mut crate::game::Game<'_>, key: &str, pressed: bool) {
use incari_core::screens::emote_wheel as wheel;
if key != wheel::KEY_NAME {
return;
}
wheel::key_held(pressed);
// The wheel opens with its key over the game, not over another screen.
if pressed && game.native_playing() && game.native_player().is_some() {
crate::game::incari_client::open(game, Box::new(wheel::EmoteWheel::new()));
}
}
@@ -0,0 +1,52 @@
// After a player's model: their hat on the head and their back cosmetic on the body (ADR 0061,
// `CosmeticsLayer`), as `look` found them this frame, from the entity canvas.
fn incari_cosmetics_layer(
game: &crate::game::Game<'_>,
mob: &crate::game::native_mob_draw::NativeMobRender<'_>,
who: Option<&crate::game::native_mob_draw::NativePlayerRender<'_>>,
draw: &mut crate::game::native_block_entity_draw::BlockEntityDraw,
) {
use crate::game::incari_cosmetics as m;
use crate::game::native_block_entity_draw::HumanoidPart;
use incari_core::cosmetics::{catalog, models};
if who.is_none() {
return;
}
let Some(job) = m::with(|s| s.job(mob.id)) else {
return;
};
let state = models::State {
age: job.age,
crouching: job.crouching,
fall_flying: job.fall_flying,
chest_armor: job.chest_armor,
cape_swing: job.cape_swing,
};
for (index, part) in [(job.hat, HumanoidPart::Head), (job.back, HumanoidPart::Body)] {
let Some(cosmetic) = index.and_then(|i| catalog::all().get(i)) else {
continue;
};
let Some(slot) = models::number(cosmetic).map(m::model_slot) else {
continue;
};
draw.push();
if !draw.attach(part) {
draw.pop();
return;
}
let light = draw.light;
models::with_mesh(cosmetic, &state, |spec, quads| {
if spec.look == models::Look::Glow {
// Lit by itself, at full brightness.
draw.light = 0xF0 | 0xF0 << 8;
}
for q in quads {
let (corners, uv) = models::quad_for_rect(q);
let corners = corners.map(|c| c.map(|v| v / 16.0));
game.native_draw_quad(draw, horizon_client::hud::MOD_ENTITY_CANVAS_SPRITE, corners, m::uv16(slot, uv), 0xFF_FFFF);
}
});
draw.light = light;
draw.pop();
}
}
@@ -0,0 +1,12 @@
// Players are posed for the mods only while there's something to show: the player wears
// something, others' cosmetics show and Incari players are about, or an emote plays.
fn incari_cosmetics_listened(listened: &mut bool) {
use incari_core::cosmetics::{wardrobe, world};
let (own, others) = wardrobe::with(|w| (!w.worn().is_empty(), w.show_others()));
if own
|| world::with(|w| w.any_playing())
|| (others && incari_core::online::with(|o| !o.world_players().is_empty()))
{
*listened = true;
}
}
@@ -0,0 +1,82 @@
// Before a player is drawn: what they wear and the emote they play (ADR 0061, `Cosmetics.extract`
// and `dress`): the cape as the player's own, a backpack hiding it, the emote's pose, and the
// hat and back cosmetic for `layer` right after. Per player per frame: nothing is made.
fn incari_cosmetics_look(
game: &crate::game::Game<'_>,
player: &crate::game::native_mob_draw::NativeMobRender<'_>,
look: &mut crate::game::native_mob_draw::NativePlayerLook<'_>,
) {
use crate::game::incari_cosmetics as m;
use crate::game::native_mob_draw::NativeCape;
use horizon_client::mobs::anim::{PartBlend, PoseBlend};
use incari_core::cosmetics::{Slot, catalog, wardrobe, world};
let _ = game;
// The player's own is kept under 0: a world without a server has no UUIDs.
let key = if look.local { 0 } else { match look.uuid { Some(u) => u, None => return } };
let (own, show_others) = wardrobe::with(|w| (w.worn(), w.show_others()));
let (worn, now) = incari_core::online::with(|o| {
let ids = if look.local { None } else { o.player(key).map(|p| p.cosmetics.as_slice()) };
world::with(|w| {
if !look.local {
w.walking(key, player.walk_speed);
}
(w.worn_by(key, look.local, own, ids, show_others), w.now(player.partial))
})
});
if worn.is_empty() {
return;
}
// The emote's pose over the model's: the legs still walk.
if let Some(p) = worn.pose(now) {
let part = |r: Option<[f32; 3]>| r.map_or(PartBlend::default(), |rotation| PartBlend { weight: p.weight, rotation });
look.pose = PoseBlend { head: part(p.head), right_arm: part(p.right_arm), left_arm: part(p.left_arm), ..PoseBlend::default() };
}
let backpack = worn.loadout.in_slot(Slot::Back).is_some_and(|b| b.id == "back.backpack");
let cape = worn.loadout.in_slot(Slot::Cape);
if backpack {
// A backpack and a cape would go through each other.
look.hide_cape = true;
} else if let Some(c) = cape {
let n = catalog::index(c);
let [x, y] = m::cape_slot(n);
look.cape = Some(NativeCape {
sprite: horizon_client::hud::MOD_ENTITY_CANVAS_SPRITE,
rect: [x as f32, y as f32, m::CAPE[0] as f32, m::CAPE[1] as f32],
});
m::with(|s| s.cape_drawn(n));
}
// Others' trails go by where they're drawn; the player's own by where they are (`tick`).
let mob = player.id;
if !look.local {
let trail = worn.loadout.in_slot(Slot::Trail).map(catalog::index);
let position = look.position;
m::with(|s| s.saw(mob, trail, position));
}
if look.invisible || look.distance_sq > world::MAX_DISTANCE * world::MAX_DISTANCE {
return;
}
// A hat hides under a helmet (the halo floats above one); a back cosmetic under an elytra.
let hat = worn
.loadout
.in_slot(Slot::Hat)
.filter(|h| look.head_item.is_none() || h.id == "hat.halo")
.map(catalog::index);
let back = worn.loadout.in_slot(Slot::Back).filter(|_| !look.chest_wings).map(catalog::index);
if hat.is_none() && back.is_none() {
return;
}
let cape_shown = !backpack && !look.chest_wings && (cape.is_some() || look.has_cape);
let [flap, lean, _] = look.cape_angles;
let job = m::Job {
mob,
hat,
back,
age: player.age,
crouching: look.crouching,
fall_flying: look.fall_flying,
chest_armor: look.chest_armor,
cape_swing: cape_shown.then(|| (6.0 + lean / 2.0 + flap).to_radians()),
};
m::with(|s| s.set_job(job));
look.parts = true;
}
@@ -0,0 +1,41 @@
// A player's name tag (ADR 0061, 0062; `NameTags.style`, `Badges.badged`): in their name tag
// cosmetic's colours unless the server coloured it (a team's colour means something), with
// Incari's badge before an Incari player's name while they show it and the player wants badges.
fn incari_cosmetics_name_tag(
game: &crate::game::Game<'_>,
who: &crate::game::native_mob_draw::NativeNameTag<'_>,
tag: &mut horizon_client::text::Text,
) {
use crate::game::incari_cosmetics as m;
use horizon_client::text::{Style, Text};
use incari_core::cosmetics::{Slot, badges, nametags, wardrobe, world};
let _ = game;
let key = if who.local { 0 } else { match who.uuid { Some(u) => u, None => return } };
let (own, show_others) = wardrobe::with(|w| (w.worn(), w.show_others()));
let show_badges = m::with(|s| s.show_badges);
let (style, badge) = incari_core::online::with(|o| {
let incari = if who.local { None } else { o.player(key) };
let ids = incari.map(|p| p.cosmetics.as_slice());
let worn = world::with(|w| w.worn_by(key, who.local, own, ids, show_others));
(worn.loadout.in_slot(Slot::Nametag), incari.is_some_and(|p| p.badge) && show_badges)
});
if let Some(style) = style
&& !tag.spans.iter().any(|s| s.style.color.is_some() && !s.text.is_empty())
{
let plain = tag.plain();
let mut styled = Text::empty();
for (piece, rgb) in nametags::styled(&plain, style) {
styled.push(Text::colored(piece, rgb));
}
*tag = styled;
}
if badge {
let mut badged = Text::styled(
badges::GLYPH,
Style { font: Some(badges::FONT.into()), color: Some(badges::COLOR), ..Style::default() },
);
badged.push(Text::literal(" "));
badged.push(std::mem::take(tag));
*tag = badged;
}
}
@@ -0,0 +1,4 @@
// A new atlas: the entity canvas is blank again.
fn incari_cosmetics_reloaded() {
crate::game::incari_cosmetics::with(|s| s.painted = false);
}
@@ -0,0 +1,244 @@
// Incari's cosmetics in the world for the Rust build (ADR 0061, 0069): worn capes, hats, wings and
// back items, name tag styles, Incari's badge, trails and emotes on the players Horizon draws. What
// they are and how they look is `incari_core::cosmetics` (the client's, no game types); this is
// the game side's own bookkeeping between its hooks: where each picture is on the fork's entity
// canvas, what each player drawn this frame wears, and the frame's timing. No game types either:
// rust/lib.rs tests it.
/// The entity canvas's size (the fork's `MOD_ENTITY_CANVAS_SIZE`).
pub const CANVAS: [u32; 2] = [512, 256];
/// A cape's picture: the game's 64x32 cape layout.
pub const CAPE: [u32; 2] = [64, 32];
/// A model's texture (`incari_core::cosmetics::models::TEXTURE`).
pub const MODEL: u32 = 64;
/// How many capes and models the canvas holds.
pub const CAPES: usize = 8;
pub const MODELS: usize = 12;
/// A moving cape's frames a second, and how long it goes on moving after it was last drawn.
pub const CAPE_FPS: f64 = 10.0;
pub const CAPE_IDLE_MS: f64 = 2_000.0;
/// How often the client's `show-badges` setting is read again, in ticks.
pub const SETTINGS_TICKS: u64 = 100;
/// Where cape `n` (its place among the capes) is on the canvas: the top row.
pub fn cape_slot(n: usize) -> [u32; 2] {
[n as u32 * CAPE[0], 0]
}
/// Where model `n` (its place among the hats and back cosmetics) is: rows of eight under the capes.
pub fn model_slot(n: usize) -> [u32; 2] {
[(n % 8) as u32 * MODEL, CAPE[1] + (n / 8) as u32 * MODEL]
}
/// A texture rectangle `[u0, v0, u1, v1]` in pixels of a picture at `slot`, as `native_draw_quad`
/// takes it: texels of 16 per side of the whole canvas.
pub fn uv16(slot: [u32; 2], uv: [f32; 4]) -> [f32; 4] {
let (x, y) = (slot[0] as f32, slot[1] as f32);
let (w, h) = (CANVAS[0] as f32, CANVAS[1] as f32);
[
(x + uv[0]) * 16.0 / w,
(y + uv[1]) * 16.0 / h,
(x + uv[2]) * 16.0 / w,
(y + uv[3]) * 16.0 / h,
]
}
/// What `look` found a player drawn this frame wears on their model, for `layer` right after.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Job {
pub mob: u32,
/// The hat's and back cosmetic's places in the catalog, when they're drawn.
pub hat: Option<usize>,
pub back: Option<usize>,
pub age: f32,
pub crouching: bool,
pub fall_flying: bool,
pub chest_armor: bool,
/// The cape's turn back (radians), when one hangs.
pub cape_swing: Option<f32>,
}
/// A player seen this frame, for the trails left once a tick.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Seen {
pub mob: u32,
/// The trail's place in the catalog.
pub trail: Option<usize>,
pub position: [f64; 3],
/// Where they were at the last tick's trail.
pub ticked: Option<[f64; 3]>,
/// The tick they were last seen.
pub tick: u64,
}
#[derive(Default)]
pub struct State {
pub jobs: Vec<Job>,
pub seen: Vec<Seen>,
/// The canvas holds the still pictures (a new atlas starts blank).
pub painted: bool,
/// When each cape was last drawn, and when moving ones were last painted (ms).
pub cape_drawn: [f64; CAPES],
pub capes_painted: f64,
/// The player's own feet at the last tick.
pub own: Option<[f64; 3]>,
pub ticks: u64,
/// The client's "Show Incari badges" (`settings.txt`'s `show-badges`).
pub show_badges: bool,
/// Milliseconds since the game started, as the last frame said.
pub now_ms: f64,
}
impl State {
/// `look`'s job for `job.mob`, in place of last frame's.
pub fn set_job(&mut self, job: Job) {
match self.jobs.iter_mut().find(|j| j.mob == job.mob) {
Some(j) => *j = job,
None => {
if self.jobs.len() >= 256 {
self.jobs.clear();
}
self.jobs.push(job);
}
}
}
pub fn job(&self, mob: u32) -> Option<Job> {
self.jobs.iter().find(|j| j.mob == mob).copied()
}
/// Player `mob` was drawn at `position`, wearing `trail`.
pub fn saw(&mut self, mob: u32, trail: Option<usize>, position: [f64; 3]) {
let tick = self.ticks;
match self.seen.iter_mut().find(|s| s.mob == mob) {
Some(s) => {
s.trail = trail;
s.position = position;
s.tick = tick;
}
None => self.seen.push(Seen {
mob,
trail,
position,
ticked: None,
tick,
}),
}
}
/// Once a tick: players not drawn for two seconds forgotten.
pub fn tick(&mut self) {
self.ticks += 1;
let ticks = self.ticks;
self.seen.retain(|s| ticks - s.tick < 40);
}
/// Cape `n` was drawn now.
pub fn cape_drawn(&mut self, n: usize) {
if n < CAPES {
self.cape_drawn[n] = self.now_ms;
}
}
/// Whether moving capes are due another frame; marks them painted.
pub fn capes_due(&mut self) -> bool {
if self.now_ms - self.capes_painted < 1000.0 / CAPE_FPS {
return false;
}
self.capes_painted = self.now_ms;
true
}
/// Whether cape `n` was drawn lately enough to move.
pub fn cape_moving(&self, n: usize) -> bool {
n < CAPES && self.cape_drawn[n] > 0.0 && self.now_ms - self.cape_drawn[n] < CAPE_IDLE_MS
}
}
thread_local! {
// The window's thread only.
static STATE: std::cell::RefCell<State> = std::cell::RefCell::new(State { show_badges: true, ..State::default() });
}
pub fn with<R>(f: impl FnOnce(&mut State) -> R) -> R {
STATE.with(|s| f(&mut s.borrow_mut()))
}
/// `settings.txt`'s `show-badges` (on unless it says false).
pub fn show_badges(settings: &str) -> bool {
!settings
.lines()
.filter_map(|l| l.split_once('='))
.any(|(k, v)| k.trim() == "show-badges" && v.trim() == "false")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pictures_fit_the_canvas_apart() {
let mut rects = Vec::new();
for n in 0..CAPES {
let [x, y] = cape_slot(n);
rects.push([x, y, CAPE[0], CAPE[1]]);
}
for n in 0..MODELS {
let [x, y] = model_slot(n);
rects.push([x, y, MODEL, MODEL]);
}
for (i, a) in rects.iter().enumerate() {
assert!(
a[0] + a[2] <= CANVAS[0] && a[1] + a[3] <= CANVAS[1],
"{a:?}"
);
for b in &rects[..i] {
let apart = a[0] + a[2] <= b[0]
|| b[0] + b[2] <= a[0]
|| a[1] + a[3] <= b[1]
|| b[1] + b[3] <= a[1];
assert!(apart, "{a:?} {b:?}");
}
}
assert_eq!(
uv16([0, 0], [0.0, 0.0, 512.0, 256.0]),
[0.0, 0.0, 16.0, 16.0]
);
}
#[test]
fn jobs_and_sightings_are_kept_per_player() {
let mut s = State::default();
s.set_job(Job {
mob: 3,
hat: Some(8),
..Job::default()
});
s.set_job(Job {
mob: 3,
hat: None,
..Job::default()
});
assert_eq!(s.jobs.len(), 1);
assert_eq!(s.job(3).unwrap().hat, None);
s.saw(5, Some(26), [1.0, 2.0, 3.0]);
for _ in 0..40 {
s.tick();
}
assert!(s.seen.is_empty(), "not drawn for two seconds: forgotten");
assert!(show_badges("copy-screenshots=true\n") && !show_badges("show-badges=false\n"));
}
#[test]
fn moving_capes_paint_ten_times_a_second_while_seen() {
let mut s = State {
now_ms: 1_000.0,
..State::default()
};
s.cape_drawn(1);
assert!(s.capes_due() && !s.capes_due());
assert!(s.cape_moving(1) && !s.cape_moving(2));
s.now_ms = 3_500.0;
assert!(!s.cape_moving(1));
}
}
@@ -0,0 +1,29 @@
// A name in the tab list (ADR 0062; `Cosmetics.tabListName`): Incari's badge before it, as the
// player's name tag has it. The player's own has it too while they show others they use Incari.
fn incari_cosmetics_tab_list_name(
game: &crate::game::Game<'_>,
uuid: u128,
local: bool,
name: &mut horizon_client::text::Text,
) {
use horizon_client::text::{Style, Text};
use incari_core::cosmetics::badges;
use incari_core::online::Status;
let _ = game;
let show_badges = crate::game::incari_cosmetics::with(|s| s.show_badges);
let shows = incari_core::online::with(|o| {
if o.status() != Status::SignedIn {
return false;
}
if local { o.shows_badge() } else { o.player(uuid).is_some_and(|p| p.badge) && show_badges }
});
if shows {
let mut badged = Text::styled(
badges::GLYPH,
Style { font: Some(badges::FONT.into()), color: Some(badges::COLOR), ..Style::default() },
);
badged.push(Text::literal(" "));
badged.push(std::mem::take(name));
*name = badged;
}
}
@@ -0,0 +1,68 @@
// Once a tick (ADR 0061, `Cosmetics.tick`): emotes start and end (the wheel's own turning the
// camera to face the player while it plays), and trails are left behind moving players.
fn incari_cosmetics_tick(game: &mut crate::game::Game<'_>) {
use crate::game::incari_cosmetics as m;
use incari_core::cosmetics::{Slot, catalog, wardrobe, world};
let ticks = m::with(|s| {
s.tick();
s.ticks
});
if ticks % m::SETTINGS_TICKS == 1 {
let path = horizon_os::env::current_dir().unwrap_or_default().join("incari").join("settings.txt");
let text = horizon_os::fs::read(path).ok().and_then(|b| String::from_utf8(b).ok()).unwrap_or_default();
m::with(|s| s.show_badges = m::show_badges(&text));
}
let played: Vec<(u128, String)> =
incari_core::online::with(|o| o.take_emotes()).into_iter().map(|e| (e.player, e.emote)).collect();
let feet = game.native_player().map(|p| [p.x, p.y, p.z]);
let distance_sq = |a: [f64; 3], b: [f64; 3]| (0..3).map(|i| (a[i] - b[i]) * (a[i] - b[i])).sum::<f64>();
let moved_sq = match (feet, m::with(|s| s.own)) {
(Some(a), Some(b)) => distance_sq(a, b),
_ => 0.0,
};
m::with(|s| s.own = feet);
let camera = game.native_camera_type();
let (show_others, own_trail) = wardrobe::with(|w| (w.show_others(), w.worn().in_slot(Slot::Trail)));
let mut view = None;
let mut spawn = Vec::new();
world::with(|w| {
// The wheel's emote, now the player and the camera are known. The player's own is kept
// under 0, as `look` keeps it.
if let Some(emote) = w.take_own()
&& feet.is_some()
{
view = w.play_own(0, emote, camera);
}
// Moving (the player's keys, a jump, being pushed) cuts the player's own emote short.
if let Some(v) = w.tick(feet.is_some(), show_others, &played, moved_sq > 0.0004, camera) {
view = Some(v);
}
let Some(me) = feet else { return };
if let Some(trail) = own_trail
&& let Some(p) = w.trail(trail, 0, 0.0, moved_sq)
{
spawn.push((me, p));
}
m::with(|s| {
let ticks = s.ticks;
for seen in &mut s.seen {
let moved = seen.ticked.map_or(0.0, |b| distance_sq(seen.position, b));
seen.ticked = Some(seen.position);
let Some(trail) = seen.trail.and_then(|i| catalog::all().get(i)) else { continue };
if seen.tick + 1 < ticks {
continue;
}
if let Some(p) = w.trail(trail, seen.mob, distance_sq(seen.position, me), moved) {
spawn.push((seen.position, p));
}
}
});
});
if let Some(v) = view {
game.native_set_camera_type(v);
}
for (at, p) in spawn {
let at = [at[0] + p.offset[0], at[1] + p.offset[1], at[2] + p.offset[2]];
game.native_spawn_particle(p.kind, at, p.velocity);
}
}
@@ -0,0 +1,25 @@
# Incari's CPS (features/cps) for the Rust build (ADR 0068, 0069). Hooks by name only
# (native-hooks.json). Its settings and HUD element are the client's (rust/mods/incari): the module
# menu shows them and the HUD editor places it.
[mod]
id = "incari_cps"
version = "0.1.0"
priority = 100
[[module]]
id = "runtime"
file = "crates/horizon-client/src/game.rs"
name = "incari_cps"
source = "runtime.rs"
[[injection]]
id = "hud"
hook = "hud"
hook_version = 1
kind = "HEAD"
helper = "hud.rs"
bindings = [
{ name = "game", ty = "&mut crate::game::Game<'_>", value = "&mut *self" },
{ name = "batch", ty = "&mut horizon_client::hud::HudBatch", value = "&mut *batch" },
{ name = "corners", ty = "&mut horizon_client::extras_hud::Corners", value = "&mut *corners" },
]
+16
View File
@@ -0,0 +1,16 @@
// The count on the glass, where the player placed it.
fn incari_cps_hud(
game: &mut crate::game::Game<'_>,
batch: &mut horizon_client::hud::HudBatch,
corners: &mut horizon_client::extras_hud::Corners,
) {
use crate::game::{incari_client as c, incari_cps as m};
let _ = corners;
let (left, right) = game.native_clicks();
c::element(game, batch, m::ID, "cps", |canvas| {
let buttons = canvas.module.choice("buttons");
m::with_text(buttons, left, right, |text| {
Some(canvas.text_element(text, Some(m::widest(buttons)), incari_core::theme::Tone::Text))
})
});
}
@@ -0,0 +1,66 @@
// Incari's CPS for the Rust build (ADR 0068, 0069), as features/cps does it: clicks in the last
// second, left, right or both, "12 | 4 CPS". Its settings and HUD element are the module's in
// `incari_core::modules` (the Java ids), shown in the module menu and placed in the HUD editor.
// This file is both the module the bundle adds to the game and, through rust/lib.rs, the code its
// tests run: it uses no game types.
/// The module's id, as the Java client's profiles name it.
pub const ID: &str = "cps";
/// "12 | 4 CPS" for `buttons` (the `buttons` setting's key).
pub fn text(buttons: &str, left: u32, right: u32) -> String {
match buttons {
"left" => format!("{left} CPS"),
"right" => format!("{right} CPS"),
_ => format!("{left} | {right} CPS"),
}
}
/// The widest it says, so its width holds still as the counts change.
pub fn widest(buttons: &str) -> &'static str {
if buttons == "both" {
"00 | 00 CPS"
} else {
"00 CPS"
}
}
/// The last text made, and what it was made for.
type CachedText = (Option<(&'static str, u32, u32)>, String);
// Hot path, don't allocate: the text is made again only when a count changes.
thread_local! {
static TEXT: std::cell::RefCell<CachedText> = const { std::cell::RefCell::new((None, String::new())) };
}
/// Calls `f` with `text(buttons, left, right)`, made again only when one of them changed.
pub fn with_text<R>(buttons: &'static str, left: u32, right: u32, f: impl FnOnce(&str) -> R) -> R {
TEXT.with(|cell| {
let mut cached = cell.borrow_mut();
if cached.0 != Some((buttons, left, right)) {
*cached = (Some((buttons, left, right)), text(buttons, left, right));
}
f(&cached.1)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn says_what_the_java_module_says() {
assert_eq!(text("both", 12, 4), "12 | 4 CPS");
assert_eq!(text("left", 12, 4), "12 CPS");
assert_eq!(text("right", 12, 4), "4 CPS");
assert_eq!(widest("left"), "00 CPS");
}
#[test]
fn makes_the_text_again_only_when_a_count_changes() {
let first = with_text("both", 3, 1, |t| (t.to_owned(), t.as_ptr()));
assert_eq!(first.0, "3 | 1 CPS");
assert_eq!(with_text("both", 3, 1, |t| t.as_ptr()), first.1);
assert_eq!(with_text("left", 3, 1, str::to_owned), "3 CPS");
}
}
@@ -0,0 +1,41 @@
# Incari's Custom Scoreboard (features/customscoreboard) for the Rust build (ADR 0068, 0069). Hooks by name where Horizon
# has stamped the hook point (native-hooks.json), by function where it's still pending. Its
# settings and HUD element are the client's (rust/mods/incari): the module menu shows them and the HUD editor places it.
[mod]
id = "incari_customscoreboard"
version = "0.1.0"
priority = 100
[[module]]
id = "runtime"
file = "crates/horizon-client/src/game.rs"
name = "incari_customscoreboard"
source = "runtime.rs"
[[injection]]
id = "place"
# Horizon's sidebar_place hook point is still a pending fragment
# (tools/native-hook-fragments/incari_client_hooks.json), so this targets its function. Make it
# `hook = "sidebar_place"` and `hook_version = 1` once Horizon stamps it.
target = "horizon_client::game::native_hooks::Game<'_>::native_sidebar_place"
kind = "HEAD"
helper = "place.rs"
bindings = [
{ name = "game", ty = "&crate::game::Game<'_>", value = "self" },
{ name = "screen", ty = "[f32; 2]", value = "screen" },
{ name = "bounds", ty = "[f32; 4]", value = "bounds" },
{ name = "offset", ty = "&mut [f32; 2]", value = "&mut *offset" },
{ name = "scale", ty = "&mut f32", value = "&mut *scale" },
]
[[injection]]
id = "hud"
hook = "hud"
hook_version = 1
kind = "HEAD"
helper = "hud.rs"
bindings = [
{ name = "game", ty = "&mut crate::game::Game<'_>", value = "&mut *self" },
{ name = "batch", ty = "&mut horizon_client::hud::HudBatch", value = "&mut *batch" },
{ name = "corners", ty = "&mut horizon_client::extras_hud::Corners", value = "&mut *corners" },
]
@@ -0,0 +1,41 @@
// The sidebar's element: placed by the sidebar's size, which Horizon then draws there
// (`place.rs`). In the HUD editor with no sidebar, a sample (GameParts.sample).
fn incari_customscoreboard_hud(
game: &mut crate::game::Game<'_>,
batch: &mut horizon_client::hud::HudBatch,
corners: &mut horizon_client::extras_hud::Corners,
) {
use crate::game::{incari_client as c, incari_customscoreboard as m};
use incari_core::framework::hud::Anchor;
use incari_core::theme::Tone;
let _ = corners;
let drawn = m::frame();
c::element(game, batch, m::ID, m::ELEMENT, |canvas| {
let size = match drawn {
Some(size) => size,
None if canvas.editing => {
let [w, h] = m::SAMPLE;
canvas.fill(0.0, 0.0, w, h, Tone::Background);
let tw = canvas.text_width(m::SAMPLE_TITLE);
canvas.text(m::SAMPLE_TITLE, ((w - tw) / 2.0).floor(), 1.0, Tone::Text);
for (i, (name, score)) in m::SAMPLE_LINES.iter().enumerate() {
let y = 10.0 + 9.0 * i as f32;
canvas.text(name, 2.0, y, Tone::Muted);
let sw = canvas.text_width(score);
canvas.text_argb(score, w - 2.0 - sw, y, 0xFFFF_5555);
}
return Some(m::SAMPLE);
}
None => return None,
};
// Where the client puts it (HudElement::bounds), for the game to draw it there.
let e = canvas.element;
let s = e.float("scale");
let anchor = Anchor::from_index(e.get("anchor").map_or(0, |a| a.as_choice()));
let (w, h) = ((size[0] * s).round() as i32, (size[1] * s).round() as i32);
let (sw, sh) = (canvas.screen[0] as i32, canvas.screen[1] as i32);
let at = [anchor.x(e.int("x"), w, sw) as f32, anchor.y(e.int("y"), h, sh) as f32];
m::place(at, s);
Some(size)
});
}
@@ -0,0 +1,15 @@
// The sidebar moved and scaled to the element.
fn incari_customscoreboard_place(
game: &crate::game::Game<'_>,
screen: [f32; 2],
bounds: [f32; 4],
offset: &mut [f32; 2],
scale: &mut f32,
) {
use crate::game::incari_customscoreboard as m;
let _ = (game, screen);
if let Some((o, s)) = m::drawing(bounds) {
*offset = o;
*scale = s;
}
}
@@ -0,0 +1,115 @@
// Incari's Custom Scoreboard for the Rust build (ADR 0068, 0069), as features/customscoreboard does
// it: the server's scoreboard sidebar wherever the player puts it in the HUD editor, at the scale
// they choose. Horizon still draws the sidebar; its `sidebar_place` hook moves and scales it to
// the module's `sidebar` element, which the `hud` hook places by the sidebar's size. No game
// types: rust/lib.rs tests it.
use std::cell::Cell;
/// The module's id, as the Java client's profiles name it.
pub const ID: &str = "customscoreboard";
/// Its HUD element, named after the part of the game's HUD it takes over.
pub const ELEMENT: &str = "sidebar";
/// The editor's sample while the server sends no sidebar: its size (Java's `GameParts.measure`),
/// title and lines.
pub const SAMPLE: [f32; 2] = [80.0, 36.0];
pub const SAMPLE_TITLE: &str = "Scoreboard";
pub const SAMPLE_LINES: [(&str, &str); 3] = [("Kills", "12"), ("Deaths", "3"), ("Coins", "250")];
/// The offset that puts a sidebar the game would draw at `bounds` (`[x, y, w, h]`), scaled `s`
/// about its top right as Horizon scales it, with its top left at `at`.
pub fn offset(bounds: [f32; 4], at: [f32; 2], s: f32) -> [f32; 2] {
let [x, y, w, _] = bounds;
[at[0] - (x + w - w * s), at[1] - y]
}
/// The sidebar as Horizon last placed it, and where the element wants it.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct Sidebar {
/// The game's own place for it, as last drawn.
bounds: Option<[f32; 4]>,
/// Drawn since the HUD last asked.
drawn: bool,
/// The element's top left and scale, this frame; none while the module is off.
target: Option<([f32; 2], f32)>,
}
// The window's thread only: the HUD and the sidebar are drawn there.
thread_local! {
static SIDEBAR: Cell<Sidebar> = const {
Cell::new(Sidebar { bounds: None, drawn: false, target: None })
};
}
fn with<R>(f: impl FnOnce(&mut Sidebar) -> R) -> R {
SIDEBAR.with(|c| {
let mut s = c.get();
let r = f(&mut s);
c.set(s);
r
})
}
/// The game is drawing a sidebar at `bounds`: the offset and scale that move it to the element,
/// or none to leave it be.
pub fn drawing(bounds: [f32; 4]) -> Option<([f32; 2], f32)> {
with(|s| {
s.bounds = Some(bounds);
s.drawn = true;
s.target
.map(|(at, scale)| (offset(bounds, at, scale), scale))
})
}
/// Once a HUD frame, before the element draws: the sidebar's unscaled size when one was drawn
/// since the last frame. Forgets the last target, so the sidebar goes back to the game's place if
/// the element doesn't draw.
pub fn frame() -> Option<[f32; 2]> {
with(|s| {
s.target = None;
let drawn = std::mem::take(&mut s.drawn);
s.bounds.filter(|_| drawn).map(|b| [b[2], b[3]])
})
}
/// Where the element is this frame: its top left and scale.
pub fn place(at: [f32; 2], scale: f32) {
with(|s| s.target = Some((at, scale)));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn moves_the_scaled_box_to_the_element() {
let b = [250.0, 100.0, 69.0, 40.0];
assert_eq!(offset(b, [250.0, 100.0], 1.0), [0.0, 0.0]);
assert_eq!(offset(b, [2.0, 2.0], 1.0), [-248.0, -98.0]);
// Twice the size about its top right: its left edge is 69 further left.
assert_eq!(offset(b, [181.0, 100.0], 2.0), [0.0, 0.0]);
}
#[test]
fn follows_the_element_only_while_it_draws() {
assert_eq!(frame(), None);
assert_eq!(
drawing([250.0, 100.0, 69.0, 40.0]),
None,
"nothing placed yet"
);
assert_eq!(frame(), Some([69.0, 40.0]));
place([2.0, 2.0], 1.0);
assert_eq!(
drawing([250.0, 100.0, 69.0, 40.0]),
Some(([-248.0, -98.0], 1.0))
);
assert_eq!(frame(), Some([69.0, 40.0]));
assert_eq!(frame(), None, "no sidebar since");
assert_eq!(
drawing([250.0, 100.0, 69.0, 40.0]),
None,
"the element didn't draw"
);
}
}
@@ -0,0 +1,62 @@
// Each frame: the layers read and their textures loaded while the module is on, freed when off
// (Java's ModuleSkyLayers.extract: a pack's large sky costs nothing until it's wanted).
fn incari_customsky_frame(game: &mut crate::game::Game<'_>) {
use crate::game::{incari_client as c, incari_customsky as m};
let brightness = c::settings(m::ID, |s| m::level(s.int("brightness"))).unwrap_or(0.0);
// Read in a world, as the sky is drawn (the title keeps what's loaded).
if brightness > 0.0 && game.native_player().is_none() {
return;
}
match m::step(brightness, |id| game.native_has_sky_texture(id)) {
m::Step::Keep => {}
m::Step::Release => {
for id in m::take_textures() {
game.native_drop_sky_texture(id);
}
}
m::Step::Load => {
for id in m::take_textures() {
game.native_drop_sky_texture(id);
}
// Every pack's layers in the first folder that has any, in their files' order; a
// texture two layers name is loaded once.
let mut layers = Vec::new();
let mut textures: Vec<(String, u64)> = Vec::new();
for folder in m::FOLDERS {
for file in m::layer_files(folder, &game.native_resource_files(folder)) {
let Some(bytes) = game.native_resource(&format!("assets/minecraft/{file}"))
else {
continue;
};
let Some(layer) = m::SkyLayer::parse(&String::from_utf8_lossy(&bytes), &file)
else {
log::warn!(
"Incari: custom sky {file}: can't be drawn (fade times or source)"
);
continue;
};
let texture = match textures.iter().find(|(s, _)| s == layer.source()) {
Some((_, id)) => Some(*id),
None => m::resource_path(layer.source())
.and_then(|path| game.native_resource(&path))
.and_then(|png| game.native_decode_png(&png))
.and_then(|(w, h, rgba)| game.native_sky_texture(w, h, &rgba)),
};
let Some(id) = texture else {
log::warn!("Incari: custom sky {file}: no texture {}", layer.source());
continue;
};
if !textures.iter().any(|(_, t)| *t == id) {
textures.push((layer.source().to_owned(), id));
}
layers.push((layer, id));
}
if !layers.is_empty() {
log::info!("Incari: custom sky: {} layers from {folder}", layers.len());
break;
}
}
m::finish_load(layers);
}
}
}
@@ -0,0 +1,50 @@
# Incari's Custom Sky (features/customsky) for the Rust build (ADR 0067, 0068, 0069). Hooks by name
# where Horizon has stamped the hook point (native-hooks.json), by function where it's still
# pending. Its setting is the client's (rust/mods/incari): the module menu shows it.
[mod]
id = "incari_customsky"
version = "0.1.0"
priority = 100
[[module]]
id = "runtime"
file = "crates/horizon-client/src/game.rs"
name = "incari_customsky"
source = "runtime.rs"
[[injection]]
id = "frame"
hook = "frame"
hook_version = 1
kind = "HEAD"
helper = "frame.rs"
bindings = [
{ name = "game", ty = "&mut crate::game::Game<'_>", value = "&mut *self" },
]
[[injection]]
id = "reloaded"
hook = "client_resources_reloaded"
hook_version = 1
kind = "HEAD"
helper = "reloaded.rs"
bindings = [
{ name = "game", ty = "&mut crate::game::Game<'_>", value = "&mut *self" },
]
[[injection]]
id = "sky_layers"
# Horizon's sky_layers hook point is still a pending fragment
# (tools/native-hook-fragments/incari_shell_hooks.json), so this targets its function. Make it
# `hook = "sky_layers"` and `hook_version = 1` once Horizon stamps it.
target = "horizon_client::game::native_hooks::Game<'_>::native_sky_layers"
kind = "HEAD"
helper = "sky.rs"
bindings = [
{ name = "game", ty = "&crate::game::Game<'_>", value = "self" },
{ name = "day_time", ty = "i64", value = "day_time" },
{ name = "rain", ty = "f32", value = "rain" },
{ name = "thunder", ty = "f32", value = "thunder" },
{ name = "sun_angle", ty = "f32", value = "sun_angle" },
{ name = "layers", ty = "&mut Vec<crate::game::native_hooks::NativeSkyLayer>", value = "&mut *layers" },
]
@@ -0,0 +1,5 @@
// A resource reload: the packs, and so the sky, may have changed (Java: a new SkyRenderer).
fn incari_customsky_reloaded(game: &mut crate::game::Game<'_>) {
let _ = game;
crate::game::incari_customsky::mark_stale();
}
@@ -0,0 +1,638 @@
// Incari's Custom Sky for the Rust build (ADR 0067, 0068, 0069), as features/customsky does it:
// the skies resource packs bring in OptiFine's format (`optifine/sky/world0/sky<N>.properties`,
// or MCPatcher's `mcpatcher/sky/world0`), drawn over the game's own sky in the Overworld. The
// parser is Java's `SkyLayer`; the loading and drawing are `ModuleSkyLayers`', with Horizon's
// renderer drawing the cubes (`native_sky_layers`). Its setting is the module's in
// `incari_core::modules` (the Java ids). No game types: rust/lib.rs tests it.
use std::cell::RefCell;
/// The module's id, as the Java client's profiles name it.
pub const ID: &str = "customsky";
/// Where the layers are looked for, in the resource root, the first folder with any winning.
pub const FOLDERS: [&str; 2] = [
"assets/minecraft/optifine/sky/world0",
"assets/minecraft/mcpatcher/sky/world0",
];
/// Ticks in a day; 0 is 6:00, as the game counts.
const DAY: i64 = 24000;
/// How a layer is mixed with what's behind it, OptiFine's names.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Blend {
Alpha,
Add,
Subtract,
Multiply,
Dodge,
Burn,
Screen,
Overlay,
Replace,
}
/// One layer of a resource pack's custom sky, in OptiFine's format: a `sky<N>.properties` naming
/// a texture that holds a cube's six faces in a 3 by 2 grid.
///
/// Understood: `source`, the four fade times, `blend`, `rotate`, `speed`, `axis` and `weather`.
/// Not yet: `biomes`, `heights`, `days` and `transition`; a layer that has them shows
/// everywhere, every day.
#[derive(Clone, Debug, PartialEq)]
pub struct SkyLayer {
source: String,
/// The fades in ticks from dawn; `start_fade_in` -1 for a layer always shown.
start_fade_in: i32,
end_fade_in: i32,
start_fade_out: i32,
end_fade_out: i32,
blend: Blend,
rotate: bool,
speed: f32,
axis: [f32; 3],
clear: bool,
rain: bool,
thunder: bool,
}
impl SkyLayer {
/// The layer `text` describes, or none if it can't be drawn (fade times missing or
/// unreadable, a source that isn't a path). `file` is where it was found,
/// `optifine/sky/world0/sky1.properties`: a source is relative to its folder, and its own
/// name with `.png` is the default source.
pub fn parse(text: &str, file: &str) -> Option<SkyLayer> {
let folder = file.rfind('/').map_or("", |i| &file[..i]);
let base = file.strip_suffix(".properties").unwrap_or(file);
let mut source_text: Option<&str> = None;
let mut fade_text: [Option<&str>; 4] = [None; 4];
let mut blend = Blend::Add;
let mut rotate = true;
let mut speed = 1.0;
let mut axis = [0.0, 0.0, 1.0];
let (mut clear, mut rain, mut thunder) = (true, false, false);
for raw in text.split('\n') {
let line = raw.trim();
if line.is_empty() || line.starts_with('#') || line.starts_with('!') {
continue;
}
let Some(split) = line.find('=').or_else(|| line.find(':')) else {
continue;
};
if split == 0 {
continue;
}
let key = line[..split].trim();
let value = line[split + 1..].trim();
match key {
"source" => source_text = Some(value),
"startFadeIn" => fade_text[0] = Some(value),
"endFadeIn" => fade_text[1] = Some(value),
"startFadeOut" => fade_text[2] = Some(value),
"endFadeOut" => fade_text[3] = Some(value),
"blend" => blend = parse_blend(value),
"rotate" => rotate = !value.eq_ignore_ascii_case("false"),
"speed" => speed = number(value).unwrap_or(1.0),
"axis" => axis = parse_axis(value),
"weather" => {
let has = |w: &str| value.split_whitespace().any(|v| v.eq_ignore_ascii_case(w));
(clear, rain, thunder) = (has("clear"), has("rain"), has("thunder"));
}
// Biomes, heights, days, transition: not yet; the layer shows regardless.
_ => {}
}
}
let fades = fades(fade_text)?;
let default_source = format!("{base}.png");
let source = resolve(source_text.unwrap_or(&default_source), folder)?;
Some(SkyLayer {
source,
start_fade_in: fades[0],
end_fade_in: fades[1],
start_fade_out: fades[2],
end_fade_out: fades[3],
blend,
rotate,
speed,
axis,
clear,
rain,
thunder,
})
}
/// The texture, `namespace:path`.
pub fn source(&self) -> &str {
&self.source
}
pub fn blend(&self) -> Blend {
self.blend
}
/// The axis the layer turns on, in the world's frame (x east, y up, z south), of length 1.
pub fn axis(&self) -> [f32; 3] {
self.axis
}
/// How far the layer is turned, in radians, with the sun at `sun_angle`.
pub fn angle(&self, sun_angle: f32) -> f32 {
if self.rotate {
sun_angle * self.speed
} else {
0.0
}
}
/// How strongly it shows, 0 to 1, at `time_of_day` ticks from dawn, with the rain and
/// thunder as shown (0 to 1 each).
pub fn brightness(&self, time_of_day: i64, rain: f32, thunder: f32) -> f32 {
let mut weather = 0.0;
if self.clear {
weather += 1.0 - rain;
}
if self.rain {
weather += (rain - thunder).max(0.0);
}
if self.thunder {
weather += thunder;
}
f32::clamp(weather, 0.0, 1.0) * self.fade(time_of_day)
}
fn fade(&self, time_of_day: i64) -> f32 {
if self.start_fade_in < 0 {
return 1.0;
}
// Every time from the start of the fade in, so a layer that shows over midnight wraps.
let start = i64::from(self.start_fade_in);
let full_in = wrap(i64::from(self.end_fade_in) - start);
let out = wrap(i64::from(self.start_fade_out) - start);
let gone = wrap(i64::from(self.end_fade_out) - start);
let now = wrap(time_of_day - start);
if now < full_in {
now as f32 / full_in as f32
} else if now < out {
1.0
} else if now < gone {
1.0 - (now - out) as f32 / (gone - out) as f32
} else {
0.0
}
}
}
/// The fades in ticks; -1 each for a layer always shown, none if they can't be read.
fn fades(text: [Option<&str>; 4]) -> Option<[i32; 4]> {
if text.iter().all(Option::is_none) {
return Some([-1; 4]);
}
let mut fades = [0; 4];
for i in 0..3 {
fades[i] = time(text[i]?);
if fades[i] < 0 {
return None;
}
}
// OptiFine's default: the fade out takes as long as the fade in.
fades[3] = match text[3] {
None => wrap(i64::from(fades[2]) + i64::from(fades[1]) - i64::from(fades[0])),
Some(t) => time(t),
};
(fades[3] >= 0).then_some(fades)
}
/// `hh:mm` as ticks from dawn (6:00 is 0), or -1.
pub fn time(text: &str) -> i32 {
let Some((hours, minutes)) = text.split_once(':') else {
return -1;
};
let (Ok(hours), Ok(minutes)) = (hours.trim().parse::<i32>(), minutes.trim().parse::<i32>())
else {
return -1;
};
if !(0..=24).contains(&hours) || !(0..=59).contains(&minutes) {
return -1;
}
wrap(i64::from(hours * 1000 + minutes * 1000 / 60 - 6000))
}
/// A source as OptiFine resolves it: `./` from the file's folder, `~/` from `optifine`,
/// `assets/<namespace>/` or a namespace for that namespace, a bare name in the file's folder,
/// and any other path from `assets/minecraft`. None if it isn't a path the game can name.
pub fn resolve(source: &str, folder: &str) -> Option<String> {
let mut path = source.trim().to_owned();
let mut namespace = "minecraft".to_owned();
if let Some(rest) = path.strip_prefix("./") {
path = format!("{folder}/{rest}");
} else if let Some(rest) = path.strip_prefix("~/") {
path = format!("optifine/{rest}");
} else {
if let Some(rest) = path.strip_prefix('/') {
path = rest.to_owned();
}
let assets = path
.strip_prefix("assets/")
.and_then(|rest| rest.split_once('/'))
.filter(|(ns, _)| !ns.is_empty())
.map(|(ns, p)| (ns.to_owned(), p.to_owned()));
match path.find(':') {
Some(colon) if colon > 0 => {
namespace = path[..colon].to_owned();
path = path[colon + 1..].to_owned();
}
_ => {
if let Some((ns, p)) = assets {
(namespace, path) = (ns, p);
} else if !path.contains('/') && !folder.is_empty() {
path = format!("{folder}/{path}");
}
}
}
}
valid_path(&namespace, &path).then(|| format!("{namespace}:{path}"))
}
/// What the game takes for a resource's namespace and path.
fn valid_path(namespace: &str, path: &str) -> bool {
let name = |c: char| c.is_ascii_lowercase() || c.is_ascii_digit() || "_-.".contains(c);
!namespace.is_empty()
&& !path.is_empty()
&& !path.contains("..")
&& namespace.chars().all(name)
&& path.chars().all(|c| c == '/' || name(c))
}
/// Where a resource `namespace:path` is in the resource root.
pub fn resource_path(id: &str) -> Option<String> {
let (namespace, path) = id.split_once(':')?;
valid_path(namespace, path).then(|| format!("assets/{namespace}/{path}"))
}
/// Where a file comes in its folder's order: the number in `sky12.properties`; a file without
/// one goes last.
pub fn order(file: &str) -> i32 {
let name = file.rfind('/').map_or(file, |i| &file[i + 1..]);
let end = name.find('.').unwrap_or(name.len());
let digits = name[..end]
.bytes()
.rev()
.take_while(u8::is_ascii_digit)
.count();
if digits == 0 || digits > 6 {
return i32::MAX;
}
name[end - digits..end].parse().unwrap_or(i32::MAX)
}
/// The layers' files among a folder's `names`, as their parser names them
/// (`optifine/sky/world0/sky1.properties`), in their order: `sun.properties` and
/// `moon_phases.properties` aren't layers.
pub fn layer_files(folder: &str, names: &[String]) -> Vec<String> {
let relative = folder.strip_prefix("assets/minecraft/").unwrap_or(folder);
let mut files: Vec<String> = names
.iter()
.filter(|n| n.ends_with(".properties") && order(n) != i32::MAX)
.map(|n| format!("{relative}/{n}"))
.collect();
files.sort_by(|a, b| order(a).cmp(&order(b)).then_with(|| a.cmp(b)));
files
}
fn parse_blend(text: &str) -> Blend {
match text.trim().to_ascii_lowercase().as_str() {
"alpha" => Blend::Alpha,
"subtract" => Blend::Subtract,
"multiply" => Blend::Multiply,
"dodge" => Blend::Dodge,
"burn" => Blend::Burn,
"screen" => Blend::Screen,
"overlay" => Blend::Overlay,
"replace" => Blend::Replace,
_ => Blend::Add,
}
}
fn number(text: &str) -> Option<f32> {
text.trim().parse::<f32>().ok().filter(|v| v.is_finite())
}
/// Three numbers, made length 1; the sun's axis if they aren't.
fn parse_axis(text: &str) -> [f32; 3] {
let parts: Vec<&str> = text.split_whitespace().collect();
if let [x, y, z] = parts[..]
&& let (Some(x), Some(y), Some(z)) = (number(x), number(y), number(z))
{
let length = (x * x + y * y + z * z).sqrt();
if length > 1.0e-4 {
return [x / length, y / length, z / length];
}
}
[0.0, 0.0, 1.0]
}
fn wrap(ticks: i64) -> i32 {
ticks.rem_euclid(DAY) as i32
}
/// The brightness setting (10 to 100%) as the layers' strength.
pub fn level(percent: i32) -> f32 {
(percent as f32 / 100.0).clamp(0.0, 1.0)
}
/// What the game side does this frame.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Step {
/// Nothing: the layers are as they should be.
Keep,
/// Off with textures kept: free them ([`take_textures`]).
Release,
/// On with the layers due (never read, a resource reload, a texture the renderer lost):
/// free the old ones ([`take_textures`]), read them, then [`finish_load`].
Load,
}
/// The layers read and their textures, the brightness asked for (0 while off), and whether the
/// layers must be read again. Window's thread only.
struct State {
layers: Vec<(SkyLayer, u64)>,
brightness: f32,
stale: bool,
}
thread_local! {
static STATE: RefCell<State> = const {
RefCell::new(State { layers: Vec::new(), brightness: 0.0, stale: true })
};
}
/// From the frame: the brightness asked for (0 while off), and which textures the renderer
/// still has. Allocation-free.
pub fn step(brightness: f32, alive: impl Fn(u64) -> bool) -> Step {
STATE.with_borrow_mut(|s| {
s.brightness = brightness.max(0.0);
if s.brightness <= 0.0 {
if s.layers.is_empty() {
return Step::Keep;
}
// Read again when next wanted: the packs may change while it's off.
s.stale = true;
return Step::Release;
}
if s.stale || s.layers.iter().any(|(_, id)| !alive(*id)) {
Step::Load
} else {
Step::Keep
}
})
}
/// A resource reload: the packs may have changed.
pub fn mark_stale() {
STATE.with_borrow_mut(|s| s.stale = true);
}
/// The kept textures, to free: the layers are gone until the next [`finish_load`].
pub fn take_textures() -> Vec<u64> {
STATE.with_borrow_mut(|s| {
s.stale = true;
s.layers.drain(..).map(|(_, id)| id).collect()
})
}
/// The layers just read, in order, with their textures.
pub fn finish_load(layers: Vec<(SkyLayer, u64)>) {
STATE.with_borrow_mut(|s| {
s.layers = layers;
s.stale = false;
});
}
/// Each layer that shows now, in order: its texture, blend, strength (the fades, the weather and
/// the brightness), angle and axis. `time_of_day`, `rain` and `thunder` as the player sees them,
/// `sun_angle` in radians. Allocation-free.
pub fn each_layer(
time_of_day: i64,
rain: f32,
thunder: f32,
sun_angle: f32,
mut f: impl FnMut(u64, Blend, f32, f32, [f32; 3]),
) {
STATE.with_borrow(|s| {
if s.brightness <= 0.0 {
return;
}
for (layer, texture) in &s.layers {
let alpha = layer.brightness(time_of_day, rain, thunder) * s.brightness;
if alpha > 1.0e-4 {
f(
*texture,
layer.blend(),
alpha,
layer.angle(sun_angle),
layer.axis(),
);
}
}
});
}
#[cfg(test)]
mod tests {
use super::*;
const FILE: &str = "optifine/sky/world0/sky1.properties";
fn close(a: f32, b: f32) -> bool {
(a - b).abs() < 0.01
}
fn at(text: &str) -> i64 {
i64::from(time(text))
}
#[test]
fn a_bare_file_is_its_own_texture_always_shown_added() {
let layer = SkyLayer::parse("", FILE).unwrap();
assert_eq!(layer.source(), "minecraft:optifine/sky/world0/sky1.png");
assert_eq!(layer.blend(), Blend::Add);
assert_eq!(layer.brightness(18000, 0.0, 0.0), 1.0);
assert_eq!(layer.angle(1.5), 1.5);
assert_eq!(layer.axis()[2], 1.0);
}
#[test]
fn reads_optifines_keys() {
let layer = SkyLayer::parse(
"# a night sky\nsource=./stars.png\nblend=alpha\nrotate=true\nspeed=2\naxis=0.0 2.0 0.0\n",
FILE,
)
.unwrap();
assert_eq!(layer.source(), "minecraft:optifine/sky/world0/stars.png");
assert_eq!(layer.blend(), Blend::Alpha);
assert_eq!(layer.angle(1.0), 2.0);
assert_eq!(layer.axis()[1], 1.0);
assert_eq!(
SkyLayer::parse("rotate=false", FILE).unwrap().angle(1.0),
0.0
);
// Windows line ends and a colon for the equals sign.
let layer = SkyLayer::parse("blend: screen\r\nspeed=x\r\n", FILE).unwrap();
assert_eq!(layer.blend(), Blend::Screen);
assert_eq!(layer.angle(1.0), 1.0);
}
#[test]
fn resolves_sources_as_optifine_does() {
let folder = "optifine/sky/world0";
let r = |s| resolve(s, folder);
assert_eq!(
r("sky2.png").as_deref(),
Some("minecraft:optifine/sky/world0/sky2.png")
);
assert_eq!(
r("~/sky/clouds.png").as_deref(),
Some("minecraft:optifine/sky/clouds.png")
);
assert_eq!(
r("/assets/minecraft/mcpatcher/sky/a.png").as_deref(),
Some("minecraft:mcpatcher/sky/a.png")
);
assert_eq!(
r("textures/sky/a.png").as_deref(),
Some("minecraft:textures/sky/a.png")
);
assert_eq!(r("pack:sky/a.png").as_deref(), Some("pack:sky/a.png"));
assert_eq!(r("Sky Night.png"), None);
assert_eq!(r("./../../secret.png"), None);
}
#[test]
fn fades_in_and_out_over_midnight() {
// Night stars: in from 18:00 to 19:00, out from 05:00 to 06:00.
let layer = SkyLayer::parse(
"startFadeIn=18:00\nendFadeIn=19:00\nstartFadeOut=5:00\nendFadeOut=6:00",
FILE,
)
.unwrap();
assert_eq!(layer.brightness(at("12:00"), 0.0, 0.0), 0.0);
assert!(close(layer.brightness(at("18:30"), 0.0, 0.0), 0.5));
assert_eq!(layer.brightness(at("0:00"), 0.0, 0.0), 1.0);
assert!(close(layer.brightness(at("5:30"), 0.0, 0.0), 0.5));
// A later day, and the game's total ticks.
assert_eq!(layer.brightness(at("0:00") + 24000 * 7, 0.0, 0.0), 1.0);
}
#[test]
fn an_end_fade_out_left_out_takes_as_long_as_the_fade_in() {
let layer = SkyLayer::parse(
"startFadeIn=18:00\nendFadeIn=20:00\nstartFadeOut=4:00",
FILE,
)
.unwrap();
assert!(close(layer.brightness(at("5:00"), 0.0, 0.0), 0.5));
assert_eq!(layer.brightness(at("6:30"), 0.0, 0.0), 0.0);
}
#[test]
fn half_the_fade_times_is_no_layer() {
assert_eq!(SkyLayer::parse("startFadeIn=18:00", FILE), None);
assert_eq!(
SkyLayer::parse("startFadeIn=dusk\nendFadeIn=19:00\nstartFadeOut=5:00", FILE),
None
);
}
#[test]
fn clear_skies_fade_with_the_rain() {
let clear = SkyLayer::parse("", FILE).unwrap();
assert_eq!(clear.brightness(0, 1.0, 0.0), 0.0);
assert_eq!(clear.brightness(0, 0.25, 0.0), 0.75);
let storm = SkyLayer::parse("weather=thunder", FILE).unwrap();
assert_eq!(storm.brightness(0, 0.0, 0.0), 0.0);
assert_eq!(storm.brightness(0, 1.0, 1.0), 1.0);
let wet = SkyLayer::parse("weather=rain thunder", FILE).unwrap();
assert_eq!(wet.brightness(0, 1.0, 0.0), 1.0);
assert_eq!(wet.brightness(0, 0.0, 0.0), 0.0);
}
#[test]
fn times_count_from_dawn() {
assert_eq!(time("6:00"), 0);
assert_eq!(time("12:00"), 6000);
assert_eq!(time("0:00"), 18000);
assert_eq!(time("6:30"), 500);
assert_eq!(time("noon"), -1);
assert_eq!(time("25:00"), -1);
}
#[test]
fn orders_files_by_their_number() {
assert!(
order("optifine/sky/world0/sky2.properties")
< order("optifine/sky/world0/sky10.properties")
);
assert_eq!(order("optifine/sky/world0/sun.properties"), i32::MAX);
let names = [
"sky10.properties",
"sun.properties",
"sky2.properties",
"sky2.png",
]
.map(String::from);
assert_eq!(
layer_files(FOLDERS[0], &names),
[
"optifine/sky/world0/sky2.properties",
"optifine/sky/world0/sky10.properties"
]
);
}
#[test]
fn sources_are_found_under_assets() {
assert_eq!(
resource_path("minecraft:optifine/sky/world0/sky1.png").as_deref(),
Some("assets/minecraft/optifine/sky/world0/sky1.png")
);
assert_eq!(resource_path("no-colon"), None);
}
#[test]
fn loads_when_on_releases_when_off() {
let alive = |_| true;
// Off with nothing kept.
assert_eq!(step(0.0, alive), Step::Keep);
// On: read them, then keep them.
assert_eq!(step(1.0, alive), Step::Load);
assert!(take_textures().is_empty());
finish_load(vec![(SkyLayer::parse("", FILE).unwrap(), 7)]);
assert_eq!(step(0.5, alive), Step::Keep);
let mut shown = Vec::new();
each_layer(0, 0.0, 0.0, 1.0, |t, b, a, angle, _| {
shown.push((t, b, a, angle))
});
assert_eq!(shown, [(7, Blend::Add, 0.5, 1.0)]);
// The renderer lost the texture (a new one): read again.
assert_eq!(step(0.5, |id| id != 7), Step::Load);
// A resource reload.
finish_load(vec![(SkyLayer::parse("", FILE).unwrap(), 8)]);
mark_stale();
assert_eq!(step(0.5, alive), Step::Load);
finish_load(vec![(SkyLayer::parse("", FILE).unwrap(), 9)]);
// Off: free them; nothing drawn.
assert_eq!(step(0.0, alive), Step::Release);
assert_eq!(take_textures(), [9]);
let mut any = false;
each_layer(0, 0.0, 0.0, 0.0, |_, _, _, _, _| any = true);
assert!(!any);
assert_eq!(step(0.0, alive), Step::Keep);
assert_eq!(step(1.0, alive), Step::Load);
}
#[test]
fn the_brightness_setting_is_a_share() {
assert_eq!(level(100), 1.0);
assert_eq!(level(40), 0.4);
}
}
@@ -0,0 +1,39 @@
// This frame's layers for Horizon to draw after the sunrise, before the sun, moon and stars.
fn incari_customsky_sky_layers(
game: &crate::game::Game<'_>,
day_time: i64,
rain: f32,
thunder: f32,
sun_angle: f32,
layers: &mut Vec<crate::game::native_hooks::NativeSkyLayer>,
) {
use crate::game::incari_customsky::{self as m, Blend};
use crate::game::native_hooks::{NativeSkyBlend as B, NativeSkyLayer};
let _ = game;
m::each_layer(
day_time,
rain,
thunder,
sun_angle,
|texture, blend, alpha, angle, axis| {
let blend = match blend {
Blend::Alpha => B::Alpha,
Blend::Add => B::Add,
Blend::Subtract => B::Subtract,
Blend::Multiply => B::Multiply,
Blend::Dodge => B::Dodge,
Blend::Burn => B::Burn,
Blend::Screen => B::Screen,
Blend::Overlay => B::Overlay,
Blend::Replace => B::Replace,
};
layers.push(NativeSkyLayer {
texture,
blend,
alpha,
angle,
axis,
});
},
);
}
@@ -0,0 +1,11 @@
// A hit on a server's object: a crystal it breaks is taken off this client at once.
fn incari_fastcrystal_attacked(game: &mut crate::game::Game<'_>, entity: u32) {
use crate::game::{incari_client as c, incari_fastcrystal as m};
// The server breaks it only if the hit does damage: weakness with a bare hand doesn't.
if c::settings(m::ID, |s| s.bool("crystals")) != Some(true) || !game.native_attack_hurts() {
return;
}
if game.native_take_crystal(entity) {
m::taken(entity, game.native_latency());
}
}
@@ -0,0 +1,51 @@
# Incari's Fast Crystal (features/fastcrystal) for the Rust build (ADR 0068, 0069, 0073). Hooks by
# name where Horizon has stamped the hook point (native-hooks.json), by function where it's still
# pending. Its settings are the client's (rust/mods/incari), shown in the module menu.
[mod]
id = "incari_fastcrystal"
version = "0.1.0"
priority = 100
[[module]]
id = "runtime"
file = "crates/horizon-client/src/game.rs"
name = "incari_fastcrystal"
source = "runtime.rs"
[[injection]]
id = "attacked"
# Horizon's object_attacked hook point is still a pending fragment
# (tools/native-hook-fragments/incari_fast_crystal.json), so this targets its function. Make it
# `hook = "object_attacked"` and `hook_version = 1` once Horizon stamps it.
target = "horizon_client::game::native_hooks::Game<'_>::native_object_attacked"
kind = "HEAD"
helper = "attacked.rs"
bindings = [
{ name = "game", ty = "&mut crate::game::Game<'_>", value = "&mut *self" },
{ name = "entity", ty = "u32", value = "entity" },
]
[[injection]]
id = "used"
# Horizon's block_used hook point is still a pending fragment
# (tools/native-hook-fragments/incari_fast_crystal.json), so this targets its function. Make it
# `hook = "block_used"` and `hook_version = 1` once Horizon stamps it.
target = "horizon_client::game::native_hooks::Game<'_>::native_block_used"
kind = "HEAD"
helper = "used.rs"
bindings = [
{ name = "game", ty = "&mut crate::game::Game<'_>", value = "&mut *self" },
{ name = "pos", ty = "[i32; 3]", value = "pos" },
{ name = "main_hand", ty = "bool", value = "main_hand" },
{ name = "sequence", ty = "i32", value = "sequence" },
]
[[injection]]
id = "tick"
hook = "tick"
hook_version = 1
kind = "HEAD"
helper = "tick.rs"
bindings = [
{ name = "game", ty = "&mut crate::game::Game<'_>", value = "&mut *self" },
]
@@ -0,0 +1,114 @@
// Incari's Fast Crystal for the Rust build (ADR 0068, 0069, 0073), as features/fastcrystal does
// it: a crystal the player hits, and a charged anchor they set off outside the Nether, gone on
// this client at once instead of a ping later. Prediction only: Horizon takes the crystal off
// (`native_take_crystal`) or shows the anchor as air under the use's sequence
// (`native_predict_air`); nothing more is sent. This keeps the crystals waiting for the server,
// and when each is due to come back. No game types: rust/lib.rs tests it.
use std::cell::RefCell;
/// The module's id, as the Java client's profiles name it.
pub const ID: &str = "fastcrystal";
/// The least and most a crystal waits for the server before coming back, in milliseconds.
const MIN_WAIT_MS: i64 = 600;
const MAX_WAIT_MS: i64 = 3000;
const TICK_MS: i64 = 50;
/// Ticks a crystal waits for the server: twice the ping and 0.3 s, from 0.6 s to 3 s, as Java.
pub fn wait_ticks(ping_ms: Option<i32>) -> u32 {
let ms = (2 * i64::from(ping_ms.unwrap_or(0).max(0)) + 300).clamp(MIN_WAIT_MS, MAX_WAIT_MS);
// Whole ticks, rounded up: never back sooner than the wait.
((ms + TICK_MS - 1) / TICK_MS) as u32
}
/// A crystal taken off this client: its entity id, and the ticks left before it's due back.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Waiting {
id: u32,
ticks: u32,
}
thread_local! {
/// Rarely more than a few: one per crystal hit in the last few seconds.
static WAITING: RefCell<Vec<Waiting>> = const { RefCell::new(Vec::new()) };
}
/// The crystal `id` was taken off this client; it waits `wait_ticks(ping_ms)` for the server.
pub fn taken(id: u32, ping_ms: Option<i32>) {
let ticks = wait_ticks(ping_ms);
WAITING.with(|w| {
let mut w = w.borrow_mut();
w.retain(|c| c.id != id);
w.push(Waiting { id, ticks });
});
}
/// One client tick: `back` gets each crystal whose wait ran out, to put back if the server kept
/// it (Horizon forgets the ones the server removed). Hot path: nothing allocated.
pub fn tick(mut back: impl FnMut(u32)) {
WAITING.with(|w| {
w.borrow_mut().retain_mut(|c| {
if c.ticks == 0 {
back(c.id);
false
} else {
c.ticks -= 1;
true
}
});
});
}
#[cfg(test)]
mod tests {
use super::*;
fn drain() {
while WAITING.with(|w| !w.borrow().is_empty()) {
tick(|_| {});
}
}
#[test]
fn the_wait_is_twice_the_ping_and_some_within_bounds() {
assert_eq!(wait_ticks(None), 12); // 0.6 s at least
assert_eq!(wait_ticks(Some(100)), 12); // 500 ms: still the least
assert_eq!(wait_ticks(Some(200)), 14); // 700 ms
assert_eq!(wait_ticks(Some(201)), 15); // 702 ms rounds up
assert_eq!(wait_ticks(Some(5000)), 60); // 3 s at most
assert_eq!(wait_ticks(Some(-7)), 12);
}
#[test]
fn a_crystal_comes_due_once_after_its_wait() {
drain();
taken(42, None);
let mut due = Vec::new();
for _ in 0..12 {
tick(|id| due.push(id));
}
assert!(due.is_empty());
tick(|id| due.push(id));
assert_eq!(due, [42]);
tick(|id| due.push(id));
assert_eq!(due, [42]);
}
#[test]
fn hitting_the_same_crystal_again_restarts_its_wait() {
drain();
taken(7, None);
for _ in 0..10 {
tick(|_| {});
}
taken(7, None);
let mut due = 0;
for _ in 0..12 {
tick(|_| due += 1);
}
assert_eq!(due, 0);
tick(|_| due += 1);
assert_eq!(due, 1);
}
}
@@ -0,0 +1,7 @@
// Crystals the server kept past their wait come back.
fn incari_fastcrystal_tick(game: &mut crate::game::Game<'_>) {
use crate::game::incari_fastcrystal as m;
m::tick(|id| {
game.native_return_crystal(id);
});
}
@@ -0,0 +1,11 @@
// A block used on a server: a charged anchor it sets off is shown as air until the server answers.
fn incari_fastcrystal_used(game: &mut crate::game::Game<'_>, pos: [i32; 3], main_hand: bool, sequence: i32) {
use crate::game::{incari_client as c, incari_fastcrystal as m};
if !main_hand
|| c::settings(m::ID, |s| s.bool("anchors")) != Some(true)
|| !game.native_anchor_set_off(pos)
{
return;
}
game.native_predict_air(pos, sequence);
}
@@ -0,0 +1,25 @@
# Incari's FPS Display (features/fpsdisplay) for the Rust build (ADR 0068, 0069). Hooks by name only
# (native-hooks.json). Its settings and HUD elements are the client's (rust/mods/incari): the module
# menu shows them and the HUD editor places them.
[mod]
id = "incari_fpsdisplay"
version = "0.1.0"
priority = 100
[[module]]
id = "runtime"
file = "crates/horizon-client/src/game.rs"
name = "incari_fpsdisplay"
source = "runtime.rs"
[[injection]]
id = "hud"
hook = "hud"
hook_version = 1
kind = "HEAD"
helper = "hud.rs"
bindings = [
{ name = "game", ty = "&mut crate::game::Game<'_>", value = "&mut *self" },
{ name = "batch", ty = "&mut horizon_client::hud::HudBatch", value = "&mut *batch" },
{ name = "corners", ty = "&mut horizon_client::extras_hud::Corners", value = "&mut *corners" },
]
@@ -0,0 +1,23 @@
// The frame rate on the glass, where the player placed it.
fn incari_fpsdisplay_hud(
game: &mut crate::game::Game<'_>,
batch: &mut horizon_client::hud::HudBatch,
corners: &mut horizon_client::extras_hud::Corners,
) {
use crate::game::{incari_client as c, incari_fpsdisplay as m};
use incari_core::theme::Tone;
let _ = corners;
let (fps, _, _) = game.native_frame_rate();
c::element(game, batch, m::ID, m::ELEMENT, |canvas| {
let format = canvas.module.choice("format");
let tone = match m::tone(canvas.module.bool("speed-colors"), fps) {
m::Tone::Text => Tone::Text,
m::Tone::Positive => Tone::Positive,
m::Tone::Warning => Tone::Warning,
m::Tone::Negative => Tone::Negative,
};
m::with_text(format, fps, |text| {
Some(canvas.text_element(text, Some(m::widest(format)), tone))
})
});
}
@@ -0,0 +1,92 @@
// Incari's FPS Display for the Rust build (ADR 0068, 0069), as features/fpsdisplay does it: frames
// drawn in the last second, "120 FPS", green from 60, amber from 30, red below. Its settings and HUD
// element are the module's in `incari_core::modules` (the Java ids), shown in the module menu and
// placed in the HUD editor. No game types: rust/lib.rs tests it.
/// The module's id, as the Java client's profiles name it.
pub const ID: &str = "fpsdisplay";
/// Its HUD element's id.
pub const ELEMENT: &str = "fps";
/// "120 FPS" in `format` (the `format` setting's key).
pub fn text(format: &str, fps: u32) -> String {
match format {
"before" => format!("FPS: {fps}"),
"number" => fps.to_string(),
_ => format!("{fps} FPS"),
}
}
/// The widest it says, so its width holds still as the count changes.
pub fn widest(format: &str) -> &'static str {
match format {
"before" => "FPS: 000",
"number" => "000",
_ => "000 FPS",
}
}
/// The text's tone (`incari_core::theme::Tone`'s of the same names).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Tone {
Text,
Positive,
Warning,
Negative,
}
/// The theme's text, or by speed when `by_speed`.
pub fn tone(by_speed: bool, fps: u32) -> Tone {
match fps {
_ if !by_speed => Tone::Text,
60.. => Tone::Positive,
30.. => Tone::Warning,
_ => Tone::Negative,
}
}
type CachedText = (Option<(&'static str, u32)>, String);
// Hot path, don't allocate: made again only when the count changes, about once a second.
thread_local! {
static TEXT: std::cell::RefCell<CachedText> = const { std::cell::RefCell::new((None, String::new())) };
}
/// Calls `f` with `text(format, fps)`, made again only when one of them changed.
pub fn with_text<R>(format: &'static str, fps: u32, f: impl FnOnce(&str) -> R) -> R {
TEXT.with(|cell| {
let mut cached = cell.borrow_mut();
if cached.0 != Some((format, fps)) {
*cached = (Some((format, fps)), text(format, fps));
}
f(&cached.1)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn says_what_the_java_module_says() {
assert_eq!(text("after", 120), "120 FPS");
assert_eq!(text("before", 120), "FPS: 120");
assert_eq!(text("number", 120), "120");
assert_eq!(widest("before"), "FPS: 000");
assert_eq!(with_text("after", 7, str::to_owned), "7 FPS");
}
#[test]
fn colours_by_speed_only_when_asked() {
assert_eq!(tone(false, 5), Tone::Text);
assert_eq!(
[
tone(true, 60),
tone(true, 59),
tone(true, 30),
tone(true, 29)
],
[Tone::Positive, Tone::Warning, Tone::Warning, Tone::Negative]
);
}
}
@@ -0,0 +1,4 @@
// The camera draws from the Freelook rotation while it's on.
fn incari_freelook_camera(yaw: &mut f32, pitch: &mut f32) {
crate::game::incari_freelook::with(|f| f.camera(yaw, pitch));
}
@@ -0,0 +1,63 @@
# Incari's Freelook (features/freelook) for the Rust build (ADR 0068, 0069). Hooks by name where
# Horizon has stamped the hook point (native-hooks.json), by function where it's still pending. Its
# settings are the client's (rust/mods/incari): the module menu shows them.
[mod]
id = "incari_freelook"
version = "0.1.0"
priority = 100
[[module]]
id = "runtime"
file = "crates/horizon-client/src/game.rs"
name = "incari_freelook"
source = "runtime.rs"
[[injection]]
id = "key"
hook = "key"
hook_version = 1
kind = "HEAD"
helper = "key.rs"
bindings = [
{ name = "game", ty = "&mut crate::game::Game<'_>", value = "&mut *self" },
{ name = "key", ty = "&str", value = "key" },
{ name = "pressed", ty = "bool", value = "pressed" },
]
[[injection]]
id = "tick"
hook = "tick"
hook_version = 1
kind = "HEAD"
helper = "tick.rs"
bindings = [
{ name = "game", ty = "&mut crate::game::Game<'_>", value = "&mut *self" },
]
[[injection]]
id = "turn"
# Horizon's turn hook point is still a pending fragment
# (tools/native-hook-fragments/incari_client_hooks.json), so this targets its function. Make it
# `hook = "turn"` and `hook_version = 1` once Horizon stamps it.
target = "horizon_client::game::native_hooks::Game<'_>::native_turn"
kind = "HEAD"
helper = "turn.rs"
bindings = [
{ name = "game", ty = "&mut crate::game::Game<'_>", value = "&mut *self" },
{ name = "dx", ty = "f64", value = "dx" },
{ name = "dy", ty = "f64", value = "dy" },
{ name = "claimed", ty = "&mut bool", value = "&mut *claimed" },
]
[[injection]]
id = "camera"
# Horizon's camera_rotation hook point is still a pending fragment
# (tools/native-hook-fragments/incari_client_hooks.json), so this targets its function. Make it
# `hook = "camera_rotation"` and `hook_version = 1` once Horizon stamps it.
target = "horizon_client::game::native_hooks::Game<'_>::native_camera_rotation"
kind = "HEAD"
helper = "camera.rs"
bindings = [
{ name = "yaw", ty = "&mut f32", value = "&mut *yaw" },
{ name = "pitch", ty = "&mut f32", value = "&mut *pitch" },
]
@@ -0,0 +1,10 @@
// The Freelook key (the module's `look` setting), held or pressed.
fn incari_freelook_key(game: &mut crate::game::Game<'_>, key: &str, pressed: bool) {
use crate::game::{incari_client as c, incari_freelook as m};
let bound = c::settings(m::ID, |s| s.key("look")).filter(|k| k.is_bound());
if bound != Some(incari_core::input::Key::from_name(key)) {
return;
}
let playing = game.native_playing();
m::with(|f| f.key(pressed, playing));
}
@@ -0,0 +1,202 @@
// Incari's Freelook for the Rust build (ADR 0068, 0069), as features/freelook does it: hold (or
// toggle) the key to look around without turning your player; letting go puts the view back.
// Horizon's camera hooks turn the view only: the server, movement and aiming keep the player's.
// Its settings are the module's in `incari_core::modules` (the Java ids), in the module menu.
// No game types: rust/lib.rs tests it.
/// The module's id, as the Java client's profiles name it.
pub const ID: &str = "freelook";
/// Horizon's view (`native_set_camera_type`: 0 first person, 1 behind, 2 in front) for the `view`
/// setting's key.
pub fn camera_type(view: &str) -> u8 {
match view {
"front" => 2,
"first" => 0,
_ => 1,
}
}
/// Degrees a mouse unit turns (`Entity.turn`).
pub const DEGREES: f64 = 0.15;
/// What a tick asks of the game.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Change {
None,
/// Freelook started: set the view to this (Horizon's camera type), if it isn't already.
Start(u8),
/// Freelook stopped: put the view back to this.
Stop(u8),
}
/// Freelook's state, as the Java module keeps it.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Freelook {
/// Flipped by each press (the key's `onPress`).
pub toggled: bool,
/// The key is held (it went down with no screen open and hasn't come up).
pub held: bool,
pub active: bool,
/// The camera's angles are still to be taken from the player's on the next frame.
pub fresh: bool,
pub yaw: f32,
pub pitch: f32,
/// The view to go back to.
pub before: u8,
}
impl Freelook {
pub const OFF: Self = Self {
toggled: false,
held: false,
active: false,
fresh: false,
yaw: 0.0,
pitch: 0.0,
before: 0,
};
/// The module's key went down (`pressed`) or up; `playing` with no screen open. Binds fire
/// only with no screen open, as the game's do.
pub fn key(&mut self, pressed: bool, playing: bool) {
if !pressed {
self.held = false;
} else if playing {
self.held = true;
self.toggled = !self.toggled;
}
}
/// Once a tick. `mode` is the `mode` setting's key, None while the module is off; `player`
/// whether there's a player; `view` the camera Freelook wants and `now` the camera now.
pub fn tick(
&mut self,
mode: Option<&str>,
playing: bool,
player: bool,
view: u8,
now: u8,
) -> Change {
let want = match mode {
None => false,
Some(mode) => {
player
&& if mode == "hold" {
self.held && playing
} else {
self.toggled
}
}
};
let change = if want == self.active {
Change::None
} else if want {
self.active = true;
self.fresh = true;
self.before = now;
if view == now {
Change::None
} else {
Change::Start(view)
}
} else {
self.active = false;
self.toggled = false;
if now == self.before {
Change::None
} else {
Change::Stop(self.before)
}
};
if mode.is_none() {
// Off: as the Java module's onDisable.
self.toggled = false;
}
change
}
/// The mouse turned `dx`, `dy` (positive right and down): true when Freelook took it.
pub fn turn(&mut self, dx: f64, dy: f64, invert: bool) -> bool {
if !self.active {
return false;
}
let dy = if invert { -dy } else { dy };
self.yaw += (dx * DEGREES) as f32;
self.pitch = (self.pitch + (dy * DEGREES) as f32).clamp(-90.0, 90.0);
true
}
/// The camera's rotation this frame, arriving as the player's.
pub fn camera(&mut self, yaw: &mut f32, pitch: &mut f32) {
if !self.active {
return;
}
if self.fresh {
(self.yaw, self.pitch) = (*yaw, *pitch);
self.fresh = false;
}
(*yaw, *pitch) = (self.yaw, self.pitch);
}
}
// The window's thread only: keys, ticks, the mouse and the camera all run there.
thread_local! {
static STATE: std::cell::Cell<Freelook> = const { std::cell::Cell::new(Freelook::OFF) };
}
/// Runs `f` on Freelook's state.
pub fn with<R>(f: impl FnOnce(&mut Freelook) -> R) -> R {
STATE.with(|cell| {
let mut state = cell.get();
let r = f(&mut state);
cell.set(state);
r
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn holds_the_key_to_look_from_behind_and_puts_the_view_back() {
let mut f = Freelook::OFF;
f.key(true, true);
assert_eq!(
f.tick(Some("hold"), true, true, camera_type("back"), 0),
Change::Start(1)
);
let (mut yaw, mut pitch) = (10.0, 80.0);
f.camera(&mut yaw, &mut pitch);
assert!(f.turn(100.0, 100.0, false));
f.camera(&mut yaw, &mut pitch);
assert_eq!((yaw, pitch), (25.0, 90.0));
assert!(f.turn(0.0, 100.0, true));
assert_eq!(f.pitch, 75.0);
f.key(false, true);
assert_eq!(f.tick(Some("hold"), true, true, 1, 1), Change::Stop(0));
assert!(!f.turn(1.0, 1.0, false));
}
#[test]
fn toggles_and_stops_when_turned_off() {
let mut f = Freelook::OFF;
f.key(true, false);
assert!(!f.toggled, "a press on a screen does nothing");
f.key(true, true);
f.key(false, true);
assert_eq!(f.tick(Some("toggle"), true, true, 0, 0), Change::None);
assert!(f.active);
assert_eq!(f.tick(None, true, true, 0, 0), Change::None);
assert!(!f.active && !f.toggled);
assert_eq!(camera_type("front"), 2);
}
#[test]
fn keeps_its_state() {
with(|f| f.held = true);
assert!(with(|f| f.held));
with(|f| *f = Freelook::OFF);
}
}
@@ -0,0 +1,28 @@
// Once a tick: Freelook starts or stops as the key says, and the view changes with it.
fn incari_freelook_tick(game: &mut crate::game::Game<'_>) {
use crate::game::{incari_client as c, incari_freelook as m};
if !game.native_window() {
return;
}
let mode = c::settings(m::ID, |s| {
(s.choice("mode"), m::camera_type(s.choice("view")))
});
let (playing, player, now) = (
game.native_playing(),
game.native_player().is_some(),
game.native_camera_type(),
);
let change = m::with(|f| {
f.tick(
mode.map(|x| x.0),
playing,
player,
mode.map_or(now, |x| x.1),
now,
)
});
match change {
m::Change::Start(view) | m::Change::Stop(view) => game.native_set_camera_type(view),
m::Change::None => {}
}
}
@@ -0,0 +1,9 @@
// The mouse turns the Freelook camera, not the player, while it's on.
fn incari_freelook_turn(game: &mut crate::game::Game<'_>, dx: f64, dy: f64, claimed: &mut bool) {
use crate::game::{incari_client as c, incari_freelook as m};
let _ = game;
let invert = c::settings(m::ID, |s| s.bool("invert")).unwrap_or(false);
if m::with(|f| f.turn(dx, dy, invert)) {
*claimed = true;
}
}
@@ -0,0 +1,6 @@
// Each frame: the world lit fully while on, and Horizon's own Fullbright extra's choice once off.
fn incari_fullbright_frame(game: &mut crate::game::Game<'_>) {
use crate::game::{incari_client as c, incari_fullbright as m};
let on = c::settings(m::ID, |s| m::lit(s.int("level"))).unwrap_or(false);
game.native_set_fullbright(on);
}
@@ -0,0 +1,22 @@
# Incari's Fullbright (features/fullbright) for the Rust build (ADR 0068, 0069). Hooks by name only
# (native-hooks.json). Its settings are the client's (rust/mods/incari), shown in the module menu.
[mod]
id = "incari_fullbright"
version = "0.1.0"
priority = 100
[[module]]
id = "runtime"
file = "crates/horizon-client/src/game.rs"
name = "incari_fullbright"
source = "runtime.rs"
[[injection]]
id = "frame"
hook = "frame"
hook_version = 1
kind = "HEAD"
helper = "frame.rs"
bindings = [
{ name = "game", ty = "&mut crate::game::Game<'_>", value = "&mut *self" },
]
@@ -0,0 +1,23 @@
// Incari's Fullbright for the Rust build (ADR 0068, 0069), as features/fullbright does it: caves
// and nights as light as day, for you only, with the Brightness option untouched. Its settings are
// the module's in `incari_core::modules`. Horizon lights the world fully or not at all (its own
// Fullbright extra), so any Brightness lights it fully. No game types: rust/lib.rs tests it.
/// The module's id, as the Java client's profiles name it.
pub const ID: &str = "fullbright";
/// Whether to light the world fully at Brightness `level` (percent): Horizon has no half way.
pub fn lit(level: i32) -> bool {
level > 0
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lights_at_every_brightness_the_menu_offers() {
assert!(lit(100) && lit(10));
assert!(!lit(0));
}
}
@@ -0,0 +1,8 @@
// The glint in the mod's colour.
fn incari_glintcolor_color(game: &crate::game::Game<'_>, tint: &mut [f32; 3]) {
use crate::game::{incari_client as c, incari_glintcolor as m};
let _ = game;
if let Some(t) = c::settings(m::ID, |s| m::tint(s.color("color"))) {
*tint = t;
}
}
@@ -0,0 +1,26 @@
# Incari's Enchant Glint (features/glintcolor) for the Rust build (ADR 0068, 0069). Hooks by name
# where Horizon has stamped the hook point (native-hooks.json), by function where it's still
# pending. Its settings are the client's (rust/mods/incari), shown in the module menu.
[mod]
id = "incari_glintcolor"
version = "0.1.0"
priority = 100
[[module]]
id = "runtime"
file = "crates/horizon-client/src/game.rs"
name = "incari_glintcolor"
source = "runtime.rs"
[[injection]]
id = "color"
# Horizon's glint_color hook point is still a pending fragment
# (tools/native-hook-fragments/incari_client_hooks.json), so this targets its function. Make it
# `hook = "glint_color"` and `hook_version = 1` once Horizon stamps it.
target = "horizon_client::game::native_hooks::Game<'_>::native_glint_color"
kind = "HEAD"
helper = "color.rs"
bindings = [
{ name = "game", ty = "&crate::game::Game<'_>", value = "self" },
{ name = "tint", ty = "&mut [f32; 3]", value = "&mut *tint" },
]
@@ -0,0 +1,26 @@
// Incari's Enchant Glint for the Rust build (ADR 0068, 0069), as features/glintcolor does it: the
// enchantment shimmer on items and armour in your colour; its speed and strength stay the game's
// options. Only you see it. Its settings are the module's in `incari_core::modules`. Horizon tints
// the game's purple glint by the colour (white is the game's own), where the Java module repaints
// the glint's brightness in it, so a colour shows a little purpler here. No game types:
// rust/lib.rs tests it.
/// The module's id, as the Java client's profiles name it.
pub const ID: &str = "glintcolor";
/// `[r, g, b]`, each 0 to 1, from the "color" setting.
pub fn tint(rgb: u32) -> [f32; 3] {
let [_, r, g, b] = rgb.to_be_bytes();
[r, g, b].map(|c| f32::from(c) / 255.0)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tints_in_the_chosen_color() {
assert_eq!(tint(0xFF7F_C8FF), [127.0 / 255.0, 200.0 / 255.0, 1.0]);
assert_eq!(tint(0xFFFF_FFFF), [1.0; 3]);
}
}
@@ -0,0 +1,27 @@
# Incari's Hitboxes (features/hitboxes) for the Rust build (ADR 0068, 0069). Hooks by name where
# Horizon has stamped the hook point (native-hooks.json), by function where it's still pending. Its
# settings are the client's (rust/mods/incari), shown in the module menu.
[mod]
id = "incari_hitboxes"
version = "0.1.0"
priority = 100
[[module]]
id = "runtime"
file = "crates/horizon-client/src/game.rs"
name = "incari_hitboxes"
source = "runtime.rs"
[[injection]]
id = "lines"
# Horizon's lines hook point is still a pending fragment
# (tools/native-hook-fragments/incari_client_hooks.json), so this targets its function. Make it
# `hook = "lines"` and `hook_version = 1` once Horizon stamps it.
target = "horizon_client::game::native_hooks::Game<'_>::native_lines"
kind = "HEAD"
helper = "lines.rs"
bindings = [
{ name = "game", ty = "&crate::game::Game<'_>", value = "self" },
{ name = "partial", ty = "f32", value = "partial" },
{ name = "lines", ty = "&mut Vec<crate::game::native_hooks::NativeLine>", value = "&mut *lines" },
]
@@ -0,0 +1,81 @@
// Every shown box's lines, near the player.
fn incari_hitboxes_lines(
game: &crate::game::Game<'_>,
partial: f32,
lines: &mut Vec<crate::game::native_hooks::NativeLine>,
) {
use crate::game::native_hooks::NativeLine;
use crate::game::{incari_client as c, incari_hitboxes as m};
let Some((color, target_color, width, show, eye, look)) = c::settings(m::ID, |s| {
let color = m::argb(s.color("color"), s.int("opacity"));
let target = if s.bool("target-colored") {
m::argb(s.color("target-color"), s.int("opacity"))
} else {
color
};
(
color,
target,
m::width(s.float("width")),
s.choice("show"),
s.bool("eye-line"),
s.bool("look-line"),
)
}) else {
return;
};
let Some(p) = game.native_player() else {
return;
};
let target = (target_color != color)
.then(|| game.native_targeted_entity())
.flatten();
let (eye_argb, look_argb) = (
m::with_alpha_of(color, m::EYE),
m::with_alpha_of(color, m::LOOK),
);
let line = |(start, end): ([f64; 3], [f64; 3]), argb| NativeLine {
start,
end,
argb,
width,
};
for n in 0..game.native_entity_count() {
let Some(e) = game.native_entity_at(n, partial) else {
continue;
};
let near = (e.min[0] - p.x).powi(2) + (e.min[1] - p.y).powi(2) + (e.min[2] - p.z).powi(2);
if !m::shown(show, e.player) || near > m::RANGE * m::RANGE {
continue;
}
let argb = if target == Some(e.id) {
target_color
} else {
color
};
lines.extend(
m::edges(e.min, e.max)
.into_iter()
.map(|edge| line(edge, argb)),
);
if eye {
lines.extend(
m::eye_edges(e.min, e.max, e.eye_y)
.into_iter()
.map(|edge| line(edge, eye_argb)),
);
}
if look {
let from = [
(e.min[0] + e.max[0]) / 2.0,
e.eye_y,
(e.min[2] + e.max[2]) / 2.0,
];
lines.extend(
m::look_arrow(from, e.yaw, e.pitch)
.into_iter()
.map(|edge| line(edge, look_argb)),
);
}
}
}
@@ -0,0 +1,131 @@
// Incari's Hitboxes for the Rust build (ADR 0068, 0069), as features/hitboxes does it: the box each
// player or mob is hit by, as F3+B draws it, in your colour, opacity and width; the one your
// crosshair is on in its own colour; the eye height and an arrow the way each looks. Only you see
// them. Its settings are the module's in `incari_core::modules`. Horizon's lines are 0.5 to 4
// pixels wide, within 128 blocks, at most 1024; its entity list is mobs and players only (no
// items or arrows), and doesn't hold your own. No game types: rust/lib.rs tests it.
/// The module's id, as the Java client's profiles name it.
pub const ID: &str = "hitboxes";
/// F3+B's eye line and look arrow: red, and blue 2 blocks out, at the boxes' opacity.
pub const EYE: u32 = 0xFF_0000;
pub const LOOK: u32 = 0x00_00FF;
pub const LOOK_LENGTH: f64 = 2.0;
/// The arrow head's sides, in blocks.
pub const HEAD: f64 = 0.25;
/// Horizon keeps lines within 128 blocks.
pub const RANGE: f64 = 128.0;
/// The widest line Horizon draws.
pub const MAX_WIDTH: f32 = 4.0;
/// `rgb` at `percent` opacity, as the Java module's `withOpacity`.
pub fn argb(rgb: u32, percent: i32) -> u32 {
((percent.clamp(0, 100) as f32 * 255.0 / 100.0).round() as u32) << 24 | (rgb & 0xFF_FFFF)
}
/// `rgb` at `color`'s opacity: the eye line and look arrow.
pub fn with_alpha_of(color: u32, rgb: u32) -> u32 {
color & 0xFF00_0000 | rgb
}
/// The lines' width in pixels: the "width" setting, as far as Horizon goes.
pub fn width(setting: f32) -> f32 {
setting.clamp(0.5, MAX_WIDTH)
}
/// Whether an entity gets a box under the "show" setting: "players" only, or every one Horizon
/// lists ("living", "all": its list has mobs and players only).
pub fn shown(show: &str, player: bool) -> bool {
show != "players" || player
}
/// A box's twelve edges.
pub fn edges(min: [f64; 3], max: [f64; 3]) -> [([f64; 3], [f64; 3]); 12] {
let c = |x: bool, y: bool, z: bool| {
[
if x { max[0] } else { min[0] },
if y { max[1] } else { min[1] },
if z { max[2] } else { min[2] },
]
};
let mut out = [([0.0; 3], [0.0; 3]); 12];
let mut n = 0;
for a in [false, true] {
for b in [false, true] {
out[n] = (c(false, a, b), c(true, a, b));
out[n + 1] = (c(a, false, b), c(a, true, b));
out[n + 2] = (c(a, b, false), c(a, b, true));
n += 3;
}
}
out
}
/// The eye height's rectangle: four edges round the box at `eye_y`.
pub fn eye_edges(min: [f64; 3], max: [f64; 3], eye_y: f64) -> [([f64; 3], [f64; 3]); 4] {
let p = |x: f64, z: f64| [x, eye_y, z];
[
(p(min[0], min[2]), p(max[0], min[2])),
(p(max[0], min[2]), p(max[0], max[2])),
(p(max[0], max[2]), p(min[0], max[2])),
(p(min[0], max[2]), p(min[0], min[2])),
]
}
/// The look arrow from `from`, by Minecraft's yaw and pitch: its shaft and the two sides of its
/// head, swept back from the tip across the way it looks.
pub fn look_arrow(from: [f64; 3], yaw: f32, pitch: f32) -> [([f64; 3], [f64; 3]); 3] {
let (yaw, pitch) = (f64::from(yaw).to_radians(), f64::from(pitch).to_radians());
let dir = [
-yaw.sin() * pitch.cos(),
-pitch.sin(),
yaw.cos() * pitch.cos(),
];
let tip: [f64; 3] = std::array::from_fn(|i| from[i] + dir[i] * LOOK_LENGTH);
// Across the look, level: to the look's right.
let side = [-yaw.cos(), 0.0, -yaw.sin()];
let head = |sign: f64| -> [f64; 3] {
std::array::from_fn(|i| tip[i] - dir[i] * HEAD + side[i] * HEAD * 0.5 * sign)
};
[(from, tip), (tip, head(1.0)), (tip, head(-1.0))]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn draws_every_edge_once() {
let e = edges([0.0; 3], [1.0; 3]);
for (a, b) in e {
let diff = (0..3).filter(|&i| a[i] != b[i]).count();
assert_eq!(diff, 1, "{a:?} {b:?}");
}
let mut sorted: Vec<_> = e.iter().map(|(a, b)| format!("{a:?}{b:?}")).collect();
sorted.sort();
sorted.dedup();
assert_eq!(sorted.len(), 12);
assert_eq!(
eye_edges([0.0; 3], [1.0; 3], 0.5)[0],
([0.0, 0.5, 0.0], [1.0, 0.5, 0.0])
);
}
#[test]
fn looks_south_at_yaw_zero() {
let [shaft, left, right] = look_arrow([0.0; 3], 0.0, 0.0);
assert!((shaft.1[2] - 2.0).abs() < 1e-9 && shaft.1[0].abs() < 1e-9);
assert!(left.1[2] < 2.0 && right.1[2] < 2.0 && (left.1[0] + right.1[0]).abs() < 1e-9);
}
#[test]
fn colors_as_the_java_module_does() {
assert_eq!(argb(0xFFFF_FFFF, 100), 0xFFFF_FFFF);
assert_eq!(argb(0xFFFF_5555, 50), 0x80FF_5555);
assert_eq!(with_alpha_of(0x80FF_FFFF, EYE), 0x80FF_0000);
assert_eq!(width(2.0), 2.0);
assert_eq!(width(6.0), MAX_WIDTH);
assert!(shown("living", false) && shown("all", false) && !shown("players", false));
}
}
@@ -0,0 +1,8 @@
// The hurt flash in the mod's colour.
fn incari_hitcolor_color(game: &crate::game::Game<'_>, color: &mut [f32; 4]) {
use crate::game::{incari_client as c, incari_hitcolor as m};
let _ = game;
if let Some(t) = c::settings(m::ID, |s| m::tint(s.color("color"), s.int("strength"))) {
*color = t;
}
}
@@ -0,0 +1,26 @@
# Incari's Hit Color (features/hitcolor) for the Rust build (ADR 0068, 0069). Hooks by name where
# Horizon has stamped the hook point (native-hooks.json), by function where it's still pending. Its
# settings are the client's (rust/mods/incari), shown in the module menu.
[mod]
id = "incari_hitcolor"
version = "0.1.0"
priority = 100
[[module]]
id = "runtime"
file = "crates/horizon-client/src/game.rs"
name = "incari_hitcolor"
source = "runtime.rs"
[[injection]]
id = "color"
# Horizon's hit_color hook point is still a pending fragment
# (tools/native-hook-fragments/incari_client_hooks.json), so this targets its function. Make it
# `hook = "hit_color"` and `hook_version = 1` once Horizon stamps it.
target = "horizon_client::game::native_hooks::Game<'_>::native_hit_color"
kind = "HEAD"
helper = "color.rs"
bindings = [
{ name = "game", ty = "&crate::game::Game<'_>", value = "self" },
{ name = "color", ty = "&mut [f32; 4]", value = "&mut *color" },
]
@@ -0,0 +1,31 @@
// Incari's Hit Color for the Rust build (ADR 0068, 0069), as features/hitcolor does it: hurt mobs
// and players flash in your colour, not red, at your strength (the game's red is 30%). Only you see
// it. Its settings are the module's in `incari_core::modules`. No game types: rust/lib.rs tests it.
/// The module's id, as the Java client's profiles name it.
pub const ID: &str = "hitcolor";
/// `[r, g, b, strength]`, each 0 to 1, from the "color" and "strength" (percent) settings.
pub fn tint(rgb: u32, strength: i32) -> [f32; 4] {
let [_, r, g, b] = rgb.to_be_bytes();
[
f32::from(r) / 255.0,
f32::from(g) / 255.0,
f32::from(b) / 255.0,
strength.clamp(0, 100) as f32 / 100.0,
]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn flashes_blue_at_the_games_strength_by_default() {
assert_eq!(
tint(0xFF5A_B8FF, 30),
[90.0 / 255.0, 184.0 / 255.0, 1.0, 0.3]
);
assert_eq!(tint(0xFF00_0000, 150)[3], 1.0);
}
}
@@ -0,0 +1,23 @@
// A hit: remembered for its kill, and its particles.
fn incari_hiteffects_attacked(game: &mut crate::game::Game<'_>, entity: u32, pos: [f64; 3]) {
use crate::game::{incari_client as c, incari_hiteffects as m};
let Some((on, key, count)) = c::settings(m::ID, |s| {
(s.bool("on-hit"), s.choice("hit"), s.int("hit-count"))
}) else {
return;
};
// Its size, from Horizon's list (a hit is rare: walking it is fine).
let size = (0..game.native_entity_count())
.filter_map(|n| game.native_entity_at(n, 1.0))
.find(|e| e.id == entity)
.map_or(m::SIZE, |e| [e.max[0] - e.min[0], e.max[1] - e.min[1]]);
m::with(|s| s.hit(entity, size));
if !on {
return;
}
let (particle, speed, _) = m::effect(key);
for _ in 0..count.max(0) {
let (at, velocity) = m::with(|s| s.spray(pos, size, speed));
game.native_spawn_particle(particle, at, velocity);
}
}
@@ -0,0 +1,29 @@
// A death soon after the player's hit: the kill burst and its sound.
fn incari_hiteffects_died(game: &mut crate::game::Game<'_>, entity: u32, pos: [f64; 3]) {
use crate::game::{incari_client as c, incari_hiteffects as m};
let Some((on, key, count, sound)) = c::settings(m::ID, |s| {
(
s.bool("on-kill"),
s.choice("kill"),
s.int("kill-count"),
s.bool("kill-sound"),
)
}) else {
return;
};
let Some(size) = m::with(|s| s.killed(entity).then(|| s.size())) else {
return;
};
if !on {
return;
}
let (particle, speed, event) = m::effect(key);
for _ in 0..count.max(0) {
let (at, velocity) = m::with(|s| s.spray(pos, size, speed));
game.native_spawn_particle(particle, at, velocity);
}
if sound {
let at = [pos[0], pos[1] + size[1] / 2.0, pos[2]];
game.native_play_local_sound(event, at, m::VOLUME, m::PITCH, 0);
}
}
@@ -0,0 +1,4 @@
// Ages the remembered hit.
fn incari_hiteffects_frame(elapsed: std::time::Duration) {
crate::game::incari_hiteffects::with(|s| s.advance(elapsed.as_secs_f32()));
}
@@ -0,0 +1,51 @@
# Incari's Hit & Kill Effects (features/hiteffects) for the Rust build (ADR 0068, 0069). Hooks by
# name where Horizon has stamped the hook point (native-hooks.json), by function where it's still
# pending. Its settings are the client's (rust/mods/incari), shown in the module menu.
[mod]
id = "incari_hiteffects"
version = "0.1.0"
priority = 100
[[module]]
id = "runtime"
file = "crates/horizon-client/src/game.rs"
name = "incari_hiteffects"
source = "runtime.rs"
[[injection]]
id = "attacked"
# Horizon's player_attacked hook point is still a pending fragment
# (tools/native-hook-fragments/incari_client_hooks.json), so this targets its function. Make it
# `hook = "player_attacked"` and `hook_version = 1` once Horizon stamps it.
target = "horizon_client::game::native_hooks::Game<'_>::native_player_attacked"
kind = "HEAD"
helper = "attacked.rs"
bindings = [
{ name = "game", ty = "&mut crate::game::Game<'_>", value = "&mut *self" },
{ name = "entity", ty = "u32", value = "entity" },
{ name = "pos", ty = "[f64; 3]", value = "pos" },
]
[[injection]]
id = "died"
# Horizon's mob_died hook point is still a pending fragment
# (tools/native-hook-fragments/incari_client_hooks.json), so this targets its function. Make it
# `hook = "mob_died"` and `hook_version = 1` once Horizon stamps it.
target = "horizon_client::game::native_hooks::Game<'_>::native_mob_died"
kind = "HEAD"
helper = "died.rs"
bindings = [
{ name = "game", ty = "&mut crate::game::Game<'_>", value = "&mut *self" },
{ name = "entity", ty = "u32", value = "entity" },
{ name = "pos", ty = "[f64; 3]", value = "pos" },
]
[[injection]]
id = "frame"
hook = "frame"
hook_version = 1
kind = "HEAD"
helper = "frame.rs"
bindings = [
{ name = "elapsed", ty = "std::time::Duration", value = "elapsed" },
]
@@ -0,0 +1,194 @@
// Incari's Hit & Kill Effects for the Rust build (ADR 0068, 0069), as features/hiteffects and the
// Java client's ModuleEffects do it: particles on whatever you hit, and a bigger burst with the
// effect's sound when it dies within 3 seconds of your last hit. Only you see them. Its settings
// are the module's in `incari_core::modules` (the effect keys of `modules::EFFECTS`). No game
// types: rust/lib.rs tests it.
/// The module's id, as the Java client's profiles name it.
pub const ID: &str = "hiteffects";
/// A death counts as your kill this long after your hit on it (the Java client's 60 ticks).
pub const KILL_WINDOW: f32 = 3.0;
/// The kill sound's volume and pitch.
pub const VOLUME: f32 = 0.6;
pub const PITCH: f32 = 1.0;
/// A mob's size when Horizon doesn't list it: a player's.
pub const SIZE: [f64; 2] = [0.6, 1.8];
/// An effect key's particle, how fast its particles fly apart, and its sound.
pub fn effect(key: &str) -> (&'static str, f64, &'static str) {
match key {
"crits" => ("minecraft:crit", 0.3, "minecraft:entity.player.attack.crit"),
"sparks" => (
"minecraft:electric_spark",
0.3,
"minecraft:block.amethyst_block.chime",
),
"hearts" => (
"minecraft:heart",
0.05,
"minecraft:entity.experience_orb.pickup",
),
"flames" => ("minecraft:flame", 0.3, "minecraft:item.firecharge.use"),
"snow" => (
"minecraft:snowflake",
0.3,
"minecraft:block.powder_snow.break",
),
"firework" => (
"minecraft:firework",
0.5,
"minecraft:entity.firework_rocket.blast",
),
"souls" => ("minecraft:soul", 0.05, "minecraft:particle.soul_escape"),
"smoke" => ("minecraft:poof", 0.1, "minecraft:block.fire.extinguish"),
"totem" => (
"minecraft:totem_of_undying",
0.5,
"minecraft:item.totem.use",
),
_ => (
"minecraft:enchanted_hit",
0.3,
"minecraft:block.enchantment_table.use",
),
}
}
/// What the player hit last, how long ago, its size, and a little random state.
#[derive(Clone, Copy, Debug)]
pub struct State {
target: Option<u32>,
since: f32,
size: [f64; 2],
seed: u64,
}
impl State {
pub const fn new() -> Self {
Self {
target: None,
since: 0.0,
size: SIZE,
seed: 0x9E37_79B9_7F4A_7C15,
}
}
/// The player hit `entity`, `size` (width, height) big.
pub fn hit(&mut self, entity: u32, size: [f64; 2]) {
self.target = Some(entity);
self.since = 0.0;
self.size = size;
}
pub fn advance(&mut self, seconds: f32) {
self.since += seconds;
if self.since > KILL_WINDOW {
self.target = None;
}
}
/// Whether `entity` dying is the player's kill, forgetting it.
pub fn killed(&mut self, entity: u32) -> bool {
if self.target != Some(entity) {
return false;
}
self.target = None;
true
}
/// The last hit's size.
pub fn size(&self) -> [f64; 2] {
self.size
}
/// A number from 0 to 1 (xorshift).
pub fn random(&mut self) -> f64 {
self.seed ^= self.seed << 13;
self.seed ^= self.seed >> 7;
self.seed ^= self.seed << 17;
(self.seed >> 11) as f64 / (1u64 << 53) as f64
}
/// A particle's start in the box of a mob `size` big standing at `at`, and its velocity, as
/// the Java client sprays them.
pub fn spray(&mut self, at: [f64; 3], size: [f64; 2], speed: f64) -> ([f64; 3], [f64; 3]) {
let [w, h] = size;
let start = [
at[0] - w / 2.0 + self.random() * w,
at[1] + h * (0.2 + self.random() * 0.7),
at[2] - w / 2.0 + self.random() * w,
];
let velocity = [
(self.random() - 0.5) * speed,
self.random() * speed * 0.6,
(self.random() - 0.5) * speed,
];
(start, velocity)
}
}
impl Default for State {
fn default() -> Self {
Self::new()
}
}
// The window's thread only: attacks, deaths and frames all run there.
thread_local! {
static STATE: std::cell::RefCell<State> = const { std::cell::RefCell::new(State::new()) };
}
pub fn with<R>(f: impl FnOnce(&mut State) -> R) -> R {
STATE.with(|s| f(&mut s.borrow_mut()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn counts_a_death_as_a_kill_only_soon_after_a_hit() {
let mut s = State::new();
s.hit(7, [1.0, 2.0]);
s.advance(1.0);
assert!(s.killed(7));
assert!(!s.killed(7));
s.hit(8, SIZE);
s.advance(KILL_WINDOW + 0.1);
assert!(!s.killed(8));
s.hit(8, SIZE);
s.hit(9, SIZE);
assert!(!s.killed(8) && s.killed(9));
}
#[test]
fn sprays_in_the_body() {
let mut s = State::new();
for _ in 0..100 {
let r = s.random();
assert!((0.0..1.0).contains(&r));
let (start, v) = s.spray([0.0; 3], [0.6, 1.8], 0.3);
assert!(start[1] >= 0.36 && start[1] <= 1.62 && start[0].abs() <= 0.3);
assert!(v[1] >= 0.0 && v[0].abs() <= 0.15);
}
}
#[test]
fn knows_every_effect() {
assert_eq!(effect("magic").0, "minecraft:enchanted_hit");
assert_eq!(
effect("firework"),
(
"minecraft:firework",
0.5,
"minecraft:entity.firework_rocket.blast"
)
);
for key in [
"crits", "sparks", "hearts", "flames", "snow", "souls", "smoke", "totem",
] {
assert_ne!(effect(key).0, "minecraft:enchanted_hit", "{key}");
}
}
}
@@ -0,0 +1,4 @@
// The menus' photo, under the title screen and the screens over it.
fn incari_client_backdrop(game: &crate::game::Game<'_>, batch: &mut horizon_client::hud::HudBatch) {
crate::game::incari_client::backdrop(game, batch);
}
@@ -0,0 +1,4 @@
// The menus' photo in place of the panorama.
fn incari_client_backdrop_claim(claimed: &mut bool) {
*claimed = true;
}
@@ -0,0 +1,7 @@
// Incari draws the title screen, the pause menu and its own screens in a world itself.
fn incari_client_claim(game: &crate::game::Game<'_>, screen: &str, claimed: &mut bool) {
let _ = game;
if crate::game::incari_client::claims(screen) {
*claimed = true;
}
}
@@ -0,0 +1,17 @@
# Incari Client on Horizon (ADR 0068, 0069): the client's look, screens, module framework and
# profiles, with no game types. The bundle's helpers (rust/mods/incari/*.rs) are its game side.
[package]
name = "incari-core"
version = "0.1.0"
edition = "2024"
license = "GPL-3.0-or-later"
publish = false
[lib]
name = "incari_core"
path = "src/lib.rs"
[dependencies]
ab_glyph = "0.2"
png = "0.18"
serde_json = "1"
@@ -0,0 +1,326 @@
//! The images Incari paints itself (UiAtlas.java): corners, icons, the mark, the backdrop, the
//! wordmark's letters. Painted once at the size they're shown at in screen pixels, packed in
//! shelves into Horizon's mod canvas (`horizon/mod-canvas`, 2048 by 1024), and uploaded by the game
//! side. A new atlas (a resource reload) or a full canvas starts over: everything is painted again
//! as it's next drawn.
use std::collections::HashMap;
/// The mod canvas's size in pixels (Horizon's `MOD_CANVAS_SIZE`).
pub const WIDTH: u32 = 2048;
pub const HEIGHT: u32 = 1024;
/// White pixels with coverage in alpha, or colour: unpremultiplied RGBA, row by row.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Image {
pub width: u32,
pub height: u32,
pub rgba: Vec<u8>,
}
impl Image {
pub fn new(width: u32, height: u32) -> Self {
Self {
width,
height,
rgba: vec![0; (width * height * 4) as usize],
}
}
/// White at coverage `a` (0 to 255) at (`x`, `y`).
pub fn set_alpha(&mut self, x: u32, y: u32, a: u8) {
let i = ((y * self.width + x) * 4) as usize;
self.rgba[i..i + 4].copy_from_slice(&[255, 255, 255, a]);
}
pub fn set_argb(&mut self, x: u32, y: u32, argb: u32) {
let i = ((y * self.width + x) * 4) as usize;
let [a, r, g, b] = argb.to_be_bytes();
self.rgba[i..i + 4].copy_from_slice(&[r, g, b, a]);
}
pub fn argb(&self, x: u32, y: u32) -> u32 {
let i = ((y * self.width + x) * 4) as usize;
let p = &self.rgba[i..i + 4];
u32::from_be_bytes([p[3], p[0], p[1], p[2]])
}
/// A white image of `width` by `height` with each pixel's coverage from `coverage`.
pub fn mask(width: u32, height: u32, coverage: impl Fn(u32, u32) -> f32) -> Self {
let mut image = Self::new(width, height);
for y in 0..height {
for x in 0..width {
let a = (coverage(x, y).clamp(0.0, 1.0) * 255.0).round() as u8;
image.set_alpha(x, y, a);
}
}
image
}
/// A PNG as an image.
pub fn decode_png(bytes: &[u8]) -> Option<Self> {
let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes));
decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
let mut reader = decoder.read_info().ok()?;
let mut buf = vec![0; reader.output_buffer_size()?];
let info = reader.next_frame(&mut buf).ok()?;
let (w, h) = (info.width, info.height);
let mut image = Self::new(w, h);
let channels = info.color_type.samples();
for i in 0..(w * h) as usize {
let p = &buf[i * channels..i * channels + channels];
let px = match channels {
1 => [p[0], p[0], p[0], 255],
2 => [p[0], p[0], p[0], p[1]],
3 => [p[0], p[1], p[2], 255],
_ => [p[0], p[1], p[2], p[3]],
};
image.rgba[i * 4..i * 4 + 4].copy_from_slice(&px);
}
Some(image)
}
/// This image scaled to `width` by `height`, each pixel the average of what it covers.
pub fn scaled(&self, width: u32, height: u32) -> Self {
let mut out = Self::new(width, height);
let (sx, sy) = (
self.width as f32 / width as f32,
self.height as f32 / height as f32,
);
for y in 0..height {
for x in 0..width {
let (x0, y0) = ((x as f32 * sx) as u32, (y as f32 * sy) as u32);
let x1 = (((x + 1) as f32 * sx).ceil() as u32).clamp(x0 + 1, self.width);
let y1 = (((y + 1) as f32 * sy).ceil() as u32).clamp(y0 + 1, self.height);
// Premultiplied while averaged, so transparent pixels don't darken the edges.
let mut sum = [0f32; 4];
for py in y0..y1 {
for px in x0..x1 {
let i = ((py * self.width + px) * 4) as usize;
let a = self.rgba[i + 3] as f32 / 255.0;
sum[0] += self.rgba[i] as f32 * a;
sum[1] += self.rgba[i + 1] as f32 * a;
sum[2] += self.rgba[i + 2] as f32 * a;
sum[3] += a;
}
}
let n = ((x1 - x0) * (y1 - y0)) as f32;
let a = sum[3] / n;
let i = ((y * width + x) * 4) as usize;
if a > 0.0 {
for c in 0..3 {
out.rgba[i + c] = (sum[c] / sum[3]).round().clamp(0.0, 255.0) as u8;
}
}
out.rgba[i + 3] = (a * 255.0).round() as u8;
}
}
out
}
}
/// What an image on the canvas is, so it's painted once a size.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Key {
/// A white pixel square, for fills.
White,
/// A rounded square's corner image: filled, its one-pixel ring, or its soft shadow (radius
/// and blur), in screen pixels.
Fill(u16),
Ring(u16),
Shadow(u16, u16),
/// A vertical band of light, brightest in its middle (a hovered button's sweep).
Band,
/// Opaque at the left, fading out smoothly to the right.
Fade,
/// Opaque at the top, fading out smoothly to the bottom.
FadeDown,
/// A soft round dot (snowflakes).
Dot,
/// A ring at a size in pixels, its hole's radius in thousandths of its own.
Ring2(u16, u16),
/// A line icon at a size in pixels.
Icon(crate::icons::Icon, u16),
/// Incari's mark at a size in pixels.
Logo(u16),
/// The title's backdrop photo.
Backdrop,
/// The player's skin.
Skin,
/// A picture painted at run time (a screenshot), its id and width in pixels.
Picture(u32, u16),
/// A letter of the wordmark at a height in pixels.
Wordmark(char, u16),
/// A shape (Shapes.java) at a size in pixels.
Shape(crate::paint::Shape, u16),
}
/// Where an image is on the canvas, in pixels (its transparent border not included).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Region {
pub x: u32,
pub y: u32,
pub w: u32,
pub h: u32,
}
impl Region {
/// The whole image, as a draw command's `src`.
pub fn src(&self) -> [f32; 4] {
[self.x as f32, self.y as f32, self.w as f32, self.h as f32]
}
/// Part of it, `[x, y, w, h]` in its own pixels.
pub fn part(&self, x: f32, y: f32, w: f32, h: f32) -> [f32; 4] {
[self.x as f32 + x, self.y as f32 + y, w, h]
}
}
/// Pixels to copy into the canvas before the next frame draws.
#[derive(Clone, Debug)]
pub struct Upload {
pub at: [u32; 2],
pub image: Image,
}
#[derive(Clone, Copy, Debug)]
struct Shelf {
y: u32,
height: u32,
x: u32,
}
/// The canvas as Incari has packed it.
#[derive(Default)]
pub struct Canvas {
regions: HashMap<Key, Region>,
shelves: Vec<Shelf>,
uploads: Vec<Upload>,
/// Bumped each time the canvas starts over.
pub generation: u32,
}
/// A transparent pixel around each image, so sampling at its edge never reaches its neighbour.
const PAD: u32 = 1;
impl Canvas {
/// Starts over: a new atlas, a full canvas, or a new GUI scale.
pub fn reset(&mut self) {
self.regions.clear();
self.shelves.clear();
self.uploads.clear();
self.generation = self.generation.wrapping_add(1);
}
/// Where `key` is, painting it with `make` the first time. None if it can't fit even on an
/// empty canvas.
pub fn get(&mut self, key: Key, make: impl FnOnce() -> Image) -> Option<Region> {
if let Some(r) = self.regions.get(&key) {
return Some(*r);
}
let image = make();
let (w, h) = (image.width, image.height);
if w == 0 || h == 0 || w + 2 * PAD > WIDTH || h + 2 * PAD > HEIGHT {
return None;
}
let at = match self.place(w + 2 * PAD, h + 2 * PAD) {
Some(at) => at,
None => {
// Full: start over with only what's drawn from now on.
let generation = self.generation;
self.reset();
self.generation = generation.wrapping_add(1);
self.place(w + 2 * PAD, h + 2 * PAD)?
}
};
let region = Region {
x: at[0] + PAD,
y: at[1] + PAD,
w,
h,
};
self.uploads.push(Upload {
at: [region.x, region.y],
image,
});
self.regions.insert(key, region);
Some(region)
}
/// Forgets `key`, so it's painted again (its old pixels stay unused until the canvas
/// starts over).
pub fn forget(&mut self, key: Key) {
self.regions.remove(&key);
}
/// Whether `key` has been painted.
pub fn has(&self, key: Key) -> bool {
self.regions.contains_key(&key)
}
/// The pixels painted since the last call, for the game side to upload.
pub fn take_uploads(&mut self) -> Vec<Upload> {
std::mem::take(&mut self.uploads)
}
/// A spot `w` by `h` on a shelf of about that height, or a new shelf.
fn place(&mut self, w: u32, h: u32) -> Option<[u32; 2]> {
// A shelf no more than a third taller than the image, so small corners don't waste the
// backdrop's rows.
for shelf in &mut self.shelves {
if h <= shelf.height && shelf.height <= h + h / 3 + 2 && shelf.x + w <= WIDTH {
let at = [shelf.x, shelf.y];
shelf.x += w;
return Some(at);
}
}
let y = self.shelves.last().map_or(0, |s| s.y + s.height);
if y + h > HEIGHT {
return None;
}
self.shelves.push(Shelf { y, height: h, x: w });
Some([0, y])
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn paints_each_image_once_and_uploads_it() {
let mut canvas = Canvas::default();
let a = canvas.get(Key::Fill(3), || Image::new(7, 7)).unwrap();
let again = canvas
.get(Key::Fill(3), || panic!("painted twice"))
.unwrap();
assert_eq!(a, again);
assert_eq!((a.x, a.y), (1, 1));
let b = canvas.get(Key::Ring(3), || Image::new(7, 7)).unwrap();
assert_eq!((b.x, b.y), (10, 1));
assert_eq!(canvas.take_uploads().len(), 2);
assert!(canvas.take_uploads().is_empty());
}
#[test]
fn starts_over_when_full() {
let mut canvas = Canvas::default();
let generation = canvas.generation;
for i in 0..3 {
canvas
.get(Key::Shadow(i, 0), || Image::new(1500, 400))
.unwrap();
}
assert_ne!(canvas.generation, generation);
assert!(canvas.has(Key::Shadow(2, 0)));
assert!(!canvas.has(Key::Shadow(0, 0)));
}
#[test]
fn scales_down_by_averaging() {
let mut image = Image::new(2, 2);
image.set_argb(0, 0, 0xFFFF_0000);
image.set_argb(1, 0, 0xFFFF_0000);
let small = image.scaled(1, 1);
assert_eq!(small.argb(0, 0), 0x80FF_0000);
}
}
@@ -0,0 +1,754 @@
//! The client: everything Incari keeps between frames, and what the game side calls each frame.
//! The game side draws the list a call leaves in `Client::list`, uploads the canvas's new pixels
//! and does what the call asked of the game through `Host`.
use crate::canvas::{Canvas, Upload};
use crate::draw::DrawList;
use crate::framework::system::{ModuleSystem, Storage};
use crate::input::{Input, Key, keys};
use crate::motion::Motion;
use crate::paint::{Assets, Measure, Painter};
use crate::screen::{Cx, Go, Host, Prefs, Screen};
use crate::skin::Skin;
use crate::theme::{Palette, Theme};
use crate::ui::Ui;
/// The module menu's key (IncariKeys): Right Shift.
pub const MENU_KEY: Key = Key::Keyboard(keys::RIGHT_SHIFT);
/// What the game showed when the client last looked.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Root {
/// The title screen's main page: Incari's title.
Title,
/// The pause menu: Incari's.
Pause,
/// Incari's own screen in a world (Horizon's mod screen).
World,
/// Anything else: the game's own screen, or playing.
Game,
}
pub struct Client {
pub canvas: Canvas,
pub motion: Motion,
pub assets: Assets,
pub ui: Ui,
pub list: DrawList,
pub modules: ModuleSystem,
pub prefs: Prefs,
pub theme: Theme,
skin: Skin,
/// Incari's screens over the root, last on top.
stack: Vec<Box<dyn Screen>>,
/// The screen at the root, when the game shows one Incari draws (title, pause).
root: Option<(Root, Box<dyn Screen>)>,
/// Screen pixels per GUI unit at the last frame.
scale: f32,
/// Whether the world is held for Incari's screens (Horizon's mod screen open).
holding_world: bool,
/// Whether a world was open at the last frame.
in_world: bool,
/// The modules' revision the theme was made at.
theme_revision: u64,
/// The crosshair is on a mob or player in reach (Crosshair Editor's colour on target).
pub on_target: bool,
}
/// Incari's files under the game folder's `incari/`, through the host.
pub struct HostFiles<'a>(pub &'a mut dyn Host);
impl Storage for HostFiles<'_> {
fn read(&self, path: &str) -> Option<String> {
self.0
.read(&format!("modules/{path}"))
.and_then(|b| String::from_utf8(b).ok())
}
fn write(&mut self, path: &str, text: &str) {
self.0.write(&format!("modules/{path}"), text.as_bytes());
}
fn delete(&mut self, path: &str) {
self.0.delete(&format!("modules/{path}"));
}
}
impl Client {
pub fn new(assets: Assets) -> Self {
Self {
canvas: Canvas::default(),
motion: Motion::default(),
assets,
ui: Ui::default(),
list: DrawList::default(),
modules: ModuleSystem::new(crate::modules::all()),
prefs: Prefs::default(),
theme: Theme::default(),
skin: Skin::default(),
stack: Vec::new(),
root: None,
scale: 0.0,
holding_world: false,
in_world: false,
theme_revision: 0,
on_target: false,
}
}
/// Whether a text field is focused, so the game side should read the clipboard for it.
pub fn wants_clipboard(&self) -> bool {
self.ui.focus.is_some()
}
/// Reads the profiles and the client's settings: once, at start.
pub fn load(&mut self, host: &mut dyn Host) {
let text =
|host: &dyn Host, path: &str| host.read(path).and_then(|b| String::from_utf8(b).ok());
self.prefs = Prefs::read(
text(host, "look.txt").as_deref(),
text(host, "settings.txt").as_deref(),
);
self.modules.load(&HostFiles(host));
self.refresh_skin(host);
self.refresh_theme();
}
/// Reads the player's skin again (the title shows, a profile was edited).
pub fn refresh_skin(&mut self, host: &dyn Host) {
self.assets.skin = host.own_skin().map(|(rgba, slim)| {
(
crate::canvas::Image {
width: 64,
height: 64,
rgba,
},
slim,
)
});
self.canvas.forget(crate::canvas::Key::Skin);
}
/// The theme from the Theme module's settings and the GUI preset.
pub fn refresh_theme(&mut self) {
let palette = self
.modules
.module("theme")
.map_or(crate::theme::FROST_PALETTE, |m| {
let s = &m.settings;
if s.get("accent").is_none() {
return crate::theme::FROST_PALETTE;
}
Palette {
accent: s.color("accent") & 0xFF_FFFF,
text: s.color("text") & 0xFF_FFFF,
muted: s.color("muted") & 0xFF_FFFF,
panel: s.color("panel") & 0xFF_FFFF,
panel_opacity: s.int("panel-opacity"),
hud_opacity: s.int("hud-opacity"),
radius: s.int("radius"),
}
});
self.theme = Theme::from_palette(palette, self.prefs.preset);
self.motion.on = self.theme.normal();
}
/// The root the game's screen calls for.
fn root_for(screen: &str, holding: bool) -> Root {
match screen {
"title" => Root::Title,
"paused" => Root::Pause,
"mod" if holding => Root::World,
_ => Root::Game,
}
}
/// Whether Incari draws the game's screen `screen` itself (`native_screen_claim`).
pub fn claims(&self, screen: &str) -> bool {
match screen {
"title" | "paused" => true,
"mod" => self.holding_world,
_ => false,
}
}
/// Whether anything of Incari's is showing, so input is Incari's.
pub fn showing(&self, screen: &str) -> bool {
self.claims(screen)
|| !self.stack.is_empty() && Self::root_for(screen, self.holding_world) != Root::Game
}
/// A frame: Incari's screens over the game's (`native_overlay`). Leaves what to draw in
/// `self.list`.
pub fn frame(
&mut self,
host: &mut dyn Host,
measure: &dyn Measure,
size: [f32; 2],
scale: f32,
) {
self.list.clear();
self.begin(host, scale);
let screen = host.screen().to_owned();
let root = Self::root_for(&screen, self.holding_world);
self.in_world = !screen.starts_with("title") && screen != "options" && screen != "loading";
// The root follows the game: a world opened, the pause menu closed.
let current = self.root.as_ref().map(|r| r.0);
if current != Some(root) {
self.root = match root {
Root::Title => {
self.refresh_skin(host);
Some((
Root::Title,
Box::new(crate::screens::title::Title::new(host.now_ms())),
))
}
Root::Pause => Some((
Root::Pause,
Box::new(crate::screens::pause::Pause::default()),
)),
Root::World | Root::Game => None,
};
if root == Root::Game {
// The game's own screen took over (a world loaded, the menu closed elsewhere).
self.stack.clear();
self.ui.reset();
}
}
if root == Root::Game {
self.draw_recording(host, measure, scale);
self.ui.end_frame();
return;
}
let top_is_stack = !self.stack.is_empty();
let mut screen_box = if top_is_stack {
self.stack.pop()
} else {
self.root.take().map(|r| r.1)
};
let Some(screen) = screen_box.as_mut() else {
self.ui.end_frame();
return;
};
let go = {
let mut p = Painter {
list: &mut self.list,
canvas: &mut self.canvas,
assets: &self.assets,
motion: &mut self.motion,
measure,
theme: self.theme,
scale,
fade: 1.0,
origin: [0.0, 0.0],
zoom: 1.0,
};
let in_world = self.in_world;
// The photo itself is under everything already on the title (`backdrop`).
if screen.backdrop() && !(root == Root::Title && !top_is_stack) {
crate::panels::backdrop(&mut p, size[0], size[1], false);
}
let mut cx = Cx {
p: &mut p,
ui: &mut self.ui,
modules: &mut self.modules,
host,
prefs: &mut self.prefs,
size,
in_world,
go: None,
};
if cx.ui.key(keys::ESCAPE) {
screen.escape(&mut cx);
}
screen.draw(&mut cx);
cx.ui.draw_tooltip(cx.p, size);
cx.go.take()
};
// Put it back where it came from, then do what it asked.
let screen_box = screen_box.take().expect("drawn");
if top_is_stack {
self.stack.push(screen_box);
} else {
self.root = Some((root, screen_box));
}
if let Some(go) = go {
self.navigate(go, host, measure, size, scale);
}
// Action settings pressed in a module's page: what each opens.
for (module, setting) in std::mem::take(&mut self.modules.actions) {
let screen = crate::screens::waypoint_list::for_action(module, setting)
.or_else(|| crate::screens::file_chooser::for_action(module, setting));
if let Some(screen) = screen {
self.ui.reset();
self.hold(host, true);
self.stack.push(screen);
} else {
crate::schematic::session::button(module, setting);
}
}
self.draw_recording(host, measure, scale);
self.ui.end_frame();
self.after(host);
}
/// While recording: REC and the time, over everything.
fn draw_recording(&mut self, host: &dyn Host, measure: &dyn Measure, scale: f32) {
let recorder = host.recorder();
if recorder.state() != crate::recorder::State::Recording {
return;
}
let mut p = Painter {
list: &mut self.list,
canvas: &mut self.canvas,
assets: &self.assets,
motion: &mut self.motion,
measure,
theme: self.theme,
scale,
fade: 1.0,
origin: [0.0, 0.0],
zoom: 1.0,
};
crate::recorder::draw_indicator(&mut p, recorder.as_ref());
}
/// The frame's start: the clock, a new GUI scale, the clipboard for a focused field.
fn begin(&mut self, host: &dyn Host, scale: f32) {
self.motion.now = host.now_ms();
if self.modules.revision != self.theme_revision {
// The Theme module's colours may have changed.
self.theme_revision = self.modules.revision;
self.refresh_theme();
}
if scale != self.scale {
// Every shape is painted for the new scale's pixels.
self.scale = scale;
self.canvas.reset();
}
if self.ui.focus.is_some() && self.ui.clipboard.is_none() {
self.ui.clipboard = Some(host.clipboard());
}
}
/// After a frame or input: copies, saved settings.
fn after(&mut self, host: &mut dyn Host) {
if let Some(text) = self.ui.copy.take() {
host.set_clipboard(&text);
}
if self.ui.focus.is_none() {
self.ui.clipboard = None;
}
if self.prefs.dirty {
self.prefs.dirty = false;
host.write("look.txt", self.prefs.look_text().as_bytes());
host.write("settings.txt", self.prefs.settings_text().as_bytes());
self.refresh_theme();
}
}
fn navigate(
&mut self,
go: Go,
host: &mut dyn Host,
measure: &dyn Measure,
size: [f32; 2],
scale: f32,
) {
self.ui.reset();
match go {
Go::Open(screen) => {
self.hold(host, true);
self.stack.push(screen);
}
Go::Replace(screen) => {
self.close_top(host, measure, size, scale);
self.stack.push(screen);
}
Go::Back => {
self.close_top(host, measure, size, scale);
if self.stack.is_empty() {
self.hold(host, false);
}
}
Go::CloseAll => {
while !self.stack.is_empty() {
self.close_top(host, measure, size, scale);
}
self.hold(host, false);
}
Go::Game(what) => {
while !self.stack.is_empty() {
self.close_top(host, measure, size, scale);
}
self.hold(host, false);
host.open(what);
}
Go::GameOver(what) => {
host.open(what);
}
Go::Connect(address) => {
self.stack.clear();
host.connect(&address);
}
}
self.modules.flush(&mut HostFiles(host));
}
/// Closes the top screen (the root's, when there's none of Incari's over it).
fn close_top(
&mut self,
host: &mut dyn Host,
measure: &dyn Measure,
size: [f32; 2],
scale: f32,
) {
let Some(mut screen) = self.stack.pop() else {
// Back from the root: the pause menu resumes; the title stays.
if self.root.as_ref().is_some_and(|r| r.0 == Root::Pause) {
host.open("resume");
}
return;
};
let mut p = Painter {
list: &mut self.list,
canvas: &mut self.canvas,
assets: &self.assets,
motion: &mut self.motion,
measure,
theme: self.theme,
scale,
fade: 1.0,
origin: [0.0, 0.0],
zoom: 1.0,
};
let mut cx = Cx {
p: &mut p,
ui: &mut self.ui,
modules: &mut self.modules,
host,
prefs: &mut self.prefs,
size,
in_world: self.in_world,
go: None,
};
screen.closed(&mut cx);
}
/// In a world with no game screen of Incari's root under it (playing), Incari's screens take
/// the pointer through Horizon's mod screen.
fn hold(&mut self, host: &mut dyn Host, held: bool) {
let in_world_playing = matches!(host.screen(), "playing" | "mod");
if held && !self.holding_world && in_world_playing {
self.holding_world = true;
host.hold_world(true);
} else if !held && self.holding_world {
self.holding_world = false;
host.hold_world(false);
}
}
/// Input before the game hears it (`native_overlay_input`): true when Incari took it.
pub fn input(&mut self, host: &mut dyn Host, event: &Input) -> bool {
let screen = host.screen().to_owned();
if self.holding_world && screen != "mod" {
// Escape or another screen closed Horizon's mod screen under Incari's.
self.holding_world = false;
self.stack.clear();
}
if self.showing(&screen) {
// The game keeps its fullscreen and screenshot keys.
if let Input::Key {
key: Key::Keyboard(code),
..
} = event
&& matches!(*code, keys::F11 | keys::F2)
{
return false;
}
self.ui.input(event);
// Horizon sends a key's text only when nobody took the key, so a key that types
// into the focused field goes on (its text then comes as `Input::Text`).
if self.ui.focus.is_some()
&& let Input::Key {
name,
pressed: true,
modifiers,
..
} = event
&& modifiers & (crate::input::CONTROL | crate::input::SUPER) == 0
&& types_text(name)
{
return false;
}
return !matches!(
event,
Input::Move { .. } | Input::Key { pressed: false, .. }
);
}
// Playing, or a screen of the game's: only Incari's keys.
if let Input::Key {
key: Key::Keyboard(crate::recorder::KEY),
pressed: true,
repeat: false,
..
} = event
&& self.ui.focus.is_none()
{
let text = host
.read("settings.txt")
.and_then(|b| String::from_utf8(b).ok())
.unwrap_or_default();
let settings = crate::recorder::Settings::read(&text);
let local = (host.local_time())();
crate::recorder::toggle(host.recorder().as_mut(), &settings, local);
return true;
}
if let Input::Key {
key,
pressed: true,
repeat: false,
..
} = event
{
if *key == MENU_KEY && screen == "playing" {
self.open_in_world(
host,
Box::new(crate::screens::modules::ModuleList::default()),
);
return true;
}
if screen == "playing" && self.modules.key_pressed(*key, &mut HostFiles(host)) {
return false;
}
}
if let Input::Move { at } = event {
self.ui.mouse = *at;
}
false
}
/// Opens an Incari screen over the world being played.
pub fn open_in_world(&mut self, host: &mut dyn Host, screen: Box<dyn Screen>) {
self.ui.reset();
self.hold(host, true);
self.stack.push(screen);
}
/// Once a game tick: saving settled changes.
pub fn tick(&mut self, host: &mut dyn Host) {
self.modules.tick(&mut HostFiles(host));
}
/// A sprite the game draws by name, in Frost: true when the skin drew it into `self.list`.
pub fn skin(
&mut self,
measure: &dyn Measure,
scale: f32,
name: &str,
rect: [f32; 4],
color: u32,
) -> bool {
self.list.clear();
if scale != self.scale {
self.scale = scale;
self.canvas.reset();
}
let mut p = Painter {
list: &mut self.list,
canvas: &mut self.canvas,
assets: &self.assets,
motion: &mut self.motion,
measure,
theme: self.theme,
scale,
fade: 1.0,
origin: [0.0, 0.0],
zoom: 1.0,
};
if name == "gui/sprites/hud/crosshair"
&& let Some(m) = self
.modules
.modules
.iter()
.find(|m| m.id == "crosshair" && m.enabled)
{
crate::crosshair::draw(
&mut p,
&m.settings,
self.on_target,
rect[0] + rect[2] / 2.0,
rect[1] + rect[3] / 2.0,
);
return true;
}
self.skin.sprite(&mut p, name, rect, color)
}
/// The backdrop behind the title screen and the screens over it (`native_backdrop`).
pub fn backdrop(&mut self, measure: &dyn Measure, size: [f32; 2], scale: f32) {
self.list.clear();
if scale != self.scale {
self.scale = scale;
self.canvas.reset();
}
let mut p = Painter {
list: &mut self.list,
canvas: &mut self.canvas,
assets: &self.assets,
motion: &mut self.motion,
measure,
theme: self.theme,
scale,
fade: 1.0,
origin: [0.0, 0.0],
zoom: 1.0,
};
p.backdrop([0.0, 0.0, size[0], size[1]], 0xFFFF_FFFF);
}
/// Whether module `id` is on.
pub fn on(&self, id: &str) -> bool {
self.modules.on(id)
}
/// Module `id`'s settings, while it's on.
pub fn settings(&self, id: &str) -> Option<&crate::framework::setting::Settings> {
self.modules
.module(id)
.filter(|m| m.enabled)
.map(|m| &m.settings)
}
/// Whether the HUD editor is open (elements with nothing to say show a sample).
pub fn editing_hud(&self) -> bool {
self.stack.last().is_some_and(|s| s.see_through())
}
/// HUD element `element` of module `module`, drawn by `draw` at its own origin (it returns
/// its size at scale 1, or None to draw nothing), then put where the player placed it.
/// Leaves what to draw in `self.list`; false when the module is off.
pub fn hud_element(
&mut self,
module: &str,
element: &str,
measure: &dyn Measure,
scale: f32,
screen: [f32; 2],
draw: impl FnOnce(&mut crate::hud::HudCanvas) -> Option<[f32; 2]>,
) -> bool {
self.list.clear();
if scale != self.scale {
self.scale = scale;
self.canvas.reset();
}
let editing = self.editing_hud();
let Some(m) = self
.modules
.modules
.iter()
.find(|m| m.id == module && m.enabled)
else {
return false;
};
let Some(e) = m.hud.iter().find(|e| e.id == element) else {
return false;
};
let (mid, eid) = (m.id, e.id);
let zoom = e.scale();
let mut p = Painter {
list: &mut self.list,
canvas: &mut self.canvas,
assets: &self.assets,
motion: &mut self.motion,
measure,
theme: self.theme,
scale,
fade: 1.0,
origin: [0.0, 0.0],
zoom,
};
let mut canvas = crate::hud::HudCanvas {
p: &mut p,
element: &e.settings,
module: &m.settings,
editing,
screen,
};
let Some(size) = draw(&mut canvas) else {
self.list.clear();
return false;
};
let [x, y, _, _] = e.bounds(size, screen);
self.list.translate_since(0, x, y);
self.modules.sizes.insert((mid, eid), size);
true
}
/// Draws `draw` over the HUD at the screen's origin, in GUI units (the Waypoints mod's
/// markers). Leaves what to draw in `self.list`.
pub fn overlay(
&mut self,
measure: &dyn Measure,
scale: f32,
screen: [f32; 2],
draw: impl FnOnce(&mut Painter<'_>, [f32; 2]),
) {
self.list.clear();
if scale != self.scale {
self.scale = scale;
self.canvas.reset();
}
let mut p = Painter {
list: &mut self.list,
canvas: &mut self.canvas,
assets: &self.assets,
motion: &mut self.motion,
measure,
theme: self.theme,
scale,
fade: 1.0,
origin: [0.0, 0.0],
zoom: 1.0,
};
draw(&mut p, screen);
}
/// The canvas's new pixels, for the game side to upload.
pub fn take_uploads(&mut self) -> Vec<Upload> {
self.canvas.take_uploads()
}
/// A new atlas: the canvas is blank, so everything is painted again as it's next drawn.
pub fn atlas_replaced(&mut self) {
self.canvas.reset();
}
}
/// Whether the key named `name` (`key.keyboard.a`) can type a character.
fn types_text(name: &str) -> bool {
let Some(key) = name.strip_prefix("key.keyboard.") else {
return false;
};
let keypad = key.strip_prefix("keypad.").unwrap_or(key);
keypad.chars().count() == 1
|| matches!(
keypad,
"space"
| "apostrophe"
| "comma"
| "minus"
| "period"
| "slash"
| "semicolon"
| "equal"
| "left.bracket"
| "right.bracket"
| "backslash"
| "grave.accent"
| "world.1"
| "world.2"
| "add"
| "subtract"
| "multiply"
| "divide"
| "decimal"
)
}
@@ -0,0 +1,91 @@
//! Colour arithmetic the look's parts share (`Panels.alpha`, `Panels.mix`, `ARGB.multiplyAlpha`):
//! colours are `0xAARRGGBB`, as the Java client's are.
/// `argb` with its alpha scaled by `fade` (0 to 1).
pub fn alpha(argb: u32, fade: f32) -> u32 {
if fade >= 1.0 {
return argb;
}
let a = ((argb >> 24) as f32 * fade.max(0.0)).round() as u32;
a << 24 | (argb & 0xFF_FFFF)
}
/// The colour `t` of the way from `from` to `to`, each channel.
pub fn mix(from: u32, to: u32, t: f32) -> u32 {
if t <= 0.0 {
return from;
}
if t >= 1.0 {
return to;
}
let channel = |shift: u32| {
let (a, b) = ((from >> shift & 0xFF) as f32, (to >> shift & 0xFF) as f32);
((a + (b - a) * t).round() as u32) << shift
};
channel(24) | channel(16) | channel(8) | channel(0)
}
/// `rgb` with each channel scaled by `keep` (Theme.darken).
pub fn darken(rgb: u32, keep: f32) -> u32 {
let c = |shift: u32| (((rgb >> shift & 0xFF) as f32 * keep).round() as u32).min(255) << shift;
c(16) | c(8) | c(0)
}
/// `rgb` moved `by` (0 to 1) of the way to white (Theme.lighten).
pub fn lighten(rgb: u32, by: f32) -> u32 {
let c = |shift: u32| {
let v = rgb >> shift & 0xFF;
(v + ((255 - v) as f32 * by).round() as u32) << shift
};
c(16) | c(8) | c(0)
}
/// How light `rgb` looks, 0 to 1 (Theme.luminance).
pub fn luminance(rgb: u32) -> f32 {
(0.2126 * (rgb >> 16 & 0xFF) as f32
+ 0.7152 * (rgb >> 8 & 0xFF) as f32
+ 0.0722 * (rgb & 0xFF) as f32)
/ 255.0
}
/// An alpha byte from a 0 to 100 opacity, in place for `<< 24`.
pub fn opacity(percent: i32) -> u32 {
((percent.clamp(0, 100) as f32 * 2.55).round() as u32) << 24
}
/// `#AARRGGBB` (or `#RRGGBB`, opaque) as the Java client writes colours.
pub fn parse_hex(text: &str) -> Option<u32> {
let hex = text.strip_prefix('#')?;
let value = u32::from_str_radix(hex, 16).ok()?;
match hex.len() {
6 => Some(0xFF00_0000 | value),
8 => Some(value),
_ => None,
}
}
/// `argb` as `#AARRGGBB`.
pub fn hex(argb: u32) -> String {
format!("#{argb:08X}")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fades_and_mixes_as_the_java_panels_do() {
assert_eq!(alpha(0xFF12_3456, 0.5), 0x8012_3456);
assert_eq!(alpha(0x2EFF_FFFF, 1.0), 0x2EFF_FFFF);
assert_eq!(mix(0x0000_0000, 0xFFFF_FFFF, 0.5), 0x8080_8080);
assert_eq!(mix(0x1F00_0000, 0x4700_0000, 1.0), 0x4700_0000);
}
#[test]
fn reads_and_writes_the_profiles_colours() {
assert_eq!(parse_hex("#FFA9DCFF"), Some(0xFFA9_DCFF));
assert_eq!(parse_hex("#A9DCFF"), Some(0xFFA9_DCFF));
assert_eq!(parse_hex("A9DCFF"), None);
assert_eq!(hex(0xFFA9_DCFF), "#FFA9DCFF");
}
}
@@ -0,0 +1,569 @@
//! The cosmetics' pictures, painted in code (ADR 0061; `CosmeticArt.java`): Incari's own art, so
//! nothing is shipped as an image and nothing is Mojang's. Capes are painted into the game's 64x32
//! cape layout (the outer side, the inner side, the edges and an elytra), some again and again as
//! time passes; the wardrobe's cards get small icons. Pixels are ARGB. Pure functions.
pub const CAPE_WIDTH: usize = 64;
pub const CAPE_HEIGHT: usize = 32;
/// A wardrobe card's icon, square.
pub const ICON: usize = 24;
/// Whether the cape `id` moves: it's painted again as time passes.
pub fn animated(id: &str) -> bool {
matches!(
id,
"cape.aurora" | "cape.midnight" | "cape.ember" | "cape.tide"
)
}
fn round(v: f32) -> i32 {
(v + 0.5).floor() as i32
}
// -------------------------------------------------------------------------------------------------
// Capes
// -------------------------------------------------------------------------------------------------
/// Paints the cape `id` at time `t` (seconds) into `out` (64x32): the outer side at (1, 1), 10x16,
/// as the game's cape model reads it; the inner side darker; the edges; and the elytra's wing at
/// (22, 0), so an elytra worn with it matches.
pub fn cape(id: &str, t: f32, out: &mut [u32]) {
out.fill(0);
let w = CAPE_WIDTH;
for py in 0..16 {
for px in 0..10 {
let color = design(id, px as f32 + 0.5, py as f32 + 0.5, t);
out[(py + 1) * w + px + 1] = color;
// The inner side faces the player: the same, mirrored and in shade.
out[(py + 1) * w + 12 + (9 - px)] = shade(color, 0.55);
}
}
let edge = shade(design(id, 5.0, 8.0, t), 0.7);
for py in 1..=16 {
out[py * w] = edge;
out[py * w + 11] = edge;
}
out[1..=20].fill(edge);
for y in 0..22 {
for x in 22..46 {
out[y * w + x] = design(
id,
(x as f32 - 22.0 + 0.5) * 10.0 / 24.0,
(y as f32 + 0.5) * 16.0 / 22.0,
t,
);
}
}
}
/// The cape's outer side alone, 10x16 (a wardrobe card's picture, the preview's cape).
pub fn cape_face(id: &str, t: f32, out: &mut [u32]) {
for py in 0..16 {
for px in 0..10 {
out[py * 10 + px] = design(id, px as f32 + 0.5, py as f32 + 0.5, t);
}
}
}
/// One cape's picture at (`px`, `py`) in its 10x16 face, at time `t`: opaque.
pub fn design(id: &str, px: f32, py: f32, t: f32) -> u32 {
let v = py / 16.0;
0xFF00_0000
| match id {
"cape.frost" => frost(px, py, v),
"cape.aurora" => aurora(px, py, v, t),
"cape.midnight" => midnight(px, py, v, t),
"cape.ember" => ember(px, py, v, t),
"cape.sakura" => sakura(px, py, v),
"cape.tide" => tide(px, py, v, t),
"cape.mono" => mono(px, py),
_ => 0x80_8080,
}
}
fn frost(px: f32, py: f32, v: f32) -> u32 {
let mut color = mix(0x9FD3F5, 0x1E3F66, v);
if !(1.0..=9.0).contains(&px) || !(1.0..=15.0).contains(&py) {
color = mix(color, 0xFFFFFF, 0.35);
}
// A snowflake in the middle: three strokes and a branch at each arm's end.
let dx = px - 5.0;
let dy = py - 6.5;
let flake = (dx.abs() < 0.6 && dy.abs() < 3.4)
|| (dy.abs() < 0.6 && dx.abs() < 3.4)
|| ((dx - dy).abs() < 0.75 && dx.abs() < 2.4)
|| ((dx + dy).abs() < 0.75 && dx.abs() < 2.4);
if flake {
return 0xF4FBFF;
}
// Frost glinting further down.
if py > 11.0 && hash(px as i32, py as i32, 3) < 0.12 {
return mix(color, 0xFFFFFF, 0.6);
}
color
}
fn aurora(px: f32, py: f32, v: f32, t: f32) -> u32 {
let mut color = mix(0x0E1B33, 0x050A15, v);
let bands = [0x3CF2A0, 0x3CC8F2, 0xA05CF2];
for (k, band) in bands.iter().enumerate() {
let k = k as f32;
let centre = 3.5 + k * 4.2 + 1.6 * (px * 0.7 + t * 1.3 + k * 2.1).sin();
let d = (py - centre) / 1.7;
let glow = (-d * d).exp() * (0.65 + 0.35 * (t * 0.9 + px * 0.5 + k).sin());
color = add(color, *band, glow * 0.85);
}
if hash(px as i32, py as i32, 11) < 0.05 {
color = mix(color, 0xFFFFFF, 0.5 + 0.5 * (t * 4.0 + px).sin());
}
color
}
fn midnight(px: f32, py: f32, v: f32, t: f32) -> u32 {
let color = mix(0x1F2A5C, 0x05081A, v);
// A crescent moon in the top right.
let (mx, my) = (px - 7.0, py - 3.2);
let (ox, oy) = (px - 7.9, py - 2.5);
if mx * mx + my * my < 4.4 && ox * ox + oy * oy > 3.0 {
return 0xF2EFD0;
}
if hash(px as i32, py as i32, 7) < 0.1 {
// Java's 6.283, not quite TAU: the stars twinkle as they do there.
#[allow(clippy::approx_constant)]
let phase = hash(px as i32, py as i32, 13) * 6.283;
let twinkle = 0.5 + 0.5 * (t * 2.6 + phase).sin();
return mix(color, 0xFFFFFF, 0.35 + 0.65 * twinkle);
}
color
}
fn ember(px: f32, py: f32, v: f32, t: f32) -> u32 {
let flame = noise(px * 0.55, py * 0.45 + t * 2.2);
let heat = clamp(v * 1.25 + (flame - 0.5) * 0.9 - 0.2);
let color = if heat < 0.33 {
mix(0x140806, 0x7A1708, heat / 0.33)
} else if heat < 0.66 {
mix(0x7A1708, 0xE5481A, (heat - 0.33) / 0.33)
} else {
mix(0xE5481A, 0xFFC94A, (heat - 0.66) / 0.34)
};
// Sparks rising.
let cell = (py + t * 5.0).floor() as i32;
if hash(px as i32, cell, 5) < 0.045 {
return 0xFFE38A;
}
color
}
fn sakura(px: f32, py: f32, v: f32) -> u32 {
let mut color = mix(0xFCDCE8, 0xE597B6, v);
// A branch across, from the bottom left to the top right.
let branch = ((py - 12.5) + px * 0.8).abs() / 1.28;
if branch < 0.55 && px < 9.5 {
color = 0x5E3B3B;
}
let blossoms = [
[2.0, 10.5],
[5.0, 8.0],
[8.0, 5.5],
[3.0, 4.0],
[7.5, 12.5],
[1.5, 1.8],
];
for [bx, by] in blossoms {
let (dx, dy) = (px - bx, py - by);
let d = dx * dx + dy * dy;
if d < 0.5 {
return 0xFFE9A8;
}
if d < 2.1 {
return 0xF4F0F2;
}
}
color
}
fn tide(px: f32, py: f32, v: f32, t: f32) -> u32 {
let color = mix(0x3D9FE0, 0x0A2552, v);
for k in 0..5 {
let k = k as f32;
let crest = 2.5 + k * 3.0 + 0.9 * (px * 0.9 + t * 2.0 + k * 1.7).sin();
if (py - crest).abs() < 0.55 {
return mix(color, 0xD8F1FF, 0.75);
}
}
if hash(px as i32, (py + t).floor() as i32, 9) < 0.04 {
return mix(color, 0xFFFFFF, 0.5);
}
color
}
fn mono(px: f32, py: f32) -> u32 {
if !(1.0..=9.0).contains(&px) || !(1.0..=15.0).contains(&py) || (px > 4.0 && px < 6.0) {
return 0xEDEDED;
}
0x151515
}
// -------------------------------------------------------------------------------------------------
// Wings
// -------------------------------------------------------------------------------------------------
/// A wing at (`sx`, `sy`) on its panel: `sx` from the root (0) to the tip (1), `sy` from the top
/// (0) to the bottom (1). Transparent outside the wing.
pub fn wing(id: &str, sx: f32, sy: f32) -> u32 {
match id {
"back.bat_wings" => bat_wing(sx, sy),
"back.frost_wings" => frost_wing(sx, sy),
_ => angel_wing(sx, sy),
}
}
fn wing_top(sx: f32) -> f32 {
0.34 - 0.3 * (sx * std::f32::consts::PI * 0.5).sin()
}
fn feather_bottom(sx: f32) -> f32 {
let scallop = 0.06 * (sx * std::f32::consts::PI * 5.0).sin().abs();
0.97 - 0.62 * sx.powf(1.15) - scallop
}
fn angel_wing(sx: f32, sy: f32) -> u32 {
let (top, bottom) = (wing_top(sx), feather_bottom(sx));
if sy < top || sy > bottom {
return 0;
}
let mut color = mix(
0xFFFFFF,
0xDCE3EC,
clamp((sy - top) / (bottom - top).max(0.05)) * 0.6,
);
// Rows of feathers: lines across, and their tips toward the bottom.
let row = (sy - top) / (bottom - top).max(0.05) * 4.0;
if row - row.floor() < 0.12 && row > 0.8 {
color = 0xC9D3E0;
}
if sx < 0.12 {
color = mix(color, 0xB8C3D2, 0.5);
}
0xFF00_0000 | color
}
fn frost_wing(sx: f32, sy: f32) -> u32 {
let (top, bottom) = (wing_top(sx), feather_bottom(sx));
if sy < top || sy > bottom {
return 0;
}
let facet = sx * 4.0 + sy * 2.5;
let edge = facet - facet.floor() < 0.09 || sy - top < 0.03 || bottom - sy < 0.03;
if edge {
return 0xF0F4_FBFF;
}
0xA800_0000 | mix(0xCDEBFF, 0x7FB8E8, clamp(sy))
}
fn bat_wing(sx: f32, sy: f32) -> u32 {
// The arm along the top, the fingers fanning down from the wrist, the skin scalloped between.
let top = 0.12 + 0.12 * sx;
let fingers = sx * 3.0;
let between = fingers - fingers.floor();
let bottom = 0.9 - 0.5 * sx - 0.22 * (between * std::f32::consts::PI).sin();
if sy < top || sy > bottom {
return 0;
}
if sy - top < 0.07 {
return 0xFF3A_2A40;
}
for finger in 1..=3 {
let end_x = finger as f32 / 3.0;
let end_y = 0.9 - 0.5 * end_x;
let along = sx / end_x;
if along <= 1.0 && (sy - (top + (end_y - top) * along)).abs() < 0.035 {
return 0xFF22_182A;
}
}
0xFF00_0000 | mix(0x62486E, 0x3E2D47, clamp(sy))
}
// -------------------------------------------------------------------------------------------------
// Icons
// -------------------------------------------------------------------------------------------------
/// The wardrobe card's icon for a hat or a back cosmetic, `ICON` square, into `out`.
pub fn icon(id: &str, out: &mut [u32]) {
for y in 0..ICON {
for x in 0..ICON {
out[y * ICON + x] = icon_pixel(id, x as f32 + 0.5, y as f32 + 0.5);
}
}
}
fn icon_pixel(id: &str, x: f32, y: f32) -> u32 {
match id {
"hat.crown" => crown_icon(x, y),
"hat.halo" => halo_icon(x, y),
"hat.top_hat" => top_hat_icon(x, y),
"hat.beanie" => beanie_icon(x, y),
"hat.horns" => horns_icon(x, y),
"hat.cat_ears" => ears_icon(x, y),
"back.backpack" => backpack_icon(x, y),
"back.angel_wings" | "back.frost_wings" | "back.bat_wings" => wings_icon(id, x, y),
_ => 0,
}
}
fn crown_icon(x: f32, y: f32) -> u32 {
let band = (13.0..19.0).contains(&y) && (4.0..20.0).contains(&x);
let points = [5.0f32, 12.0, 19.0].iter().any(|peak| {
let dx = (x - peak).abs();
y < 13.0 && y >= 6.0 + dx * 2.2 && dx < 3.0
});
if (x - 12.0).abs() < 1.6 && (y - 16.0).abs() < 1.6 {
return 0xFFE0_344B;
}
if band || points {
return 0xFF00_0000 | mix(0xFFE58A, 0xD69A1E, (y - 6.0) / 13.0);
}
0
}
fn halo_icon(x: f32, y: f32) -> u32 {
let (dx, dy) = ((x - 12.0) / 9.0, (y - 12.0) / 4.0);
let d = dx * dx + dy * dy;
if d < 1.0 && d > 0.45 {
return 0xFFFF_F0B0;
}
if d < 1.4 && d > 0.3 {
return 0x60FF_E68A;
}
0
}
fn top_hat_icon(x: f32, y: f32) -> u32 {
if (17.0..19.0).contains(&y) && (2.0..22.0).contains(&x) {
return 0xFF1C_1C22;
}
if (4.0..17.0).contains(&y) && (6.0..18.0).contains(&x) {
return if y >= 13.0 { 0xFFC0_263A } else { 0xFF26_262E };
}
0
}
fn beanie_icon(x: f32, y: f32) -> u32 {
let (dx, dy) = ((x - 12.0) / 9.0, (y - 17.0) / 11.0);
if y < 17.0 && dx * dx + dy * dy < 1.0 {
let row = (y / 2.5) as i32;
return if row & 1 == 0 {
0xFF7F_C3F2
} else {
0xFFEA_F6FF
};
}
if (17.0..20.0).contains(&y) && (3.0..21.0).contains(&x) {
return 0xFF4F_8FC7;
}
let (px, py) = (x - 12.0, y - 5.0);
if px * px + py * py < 6.0 {
return 0xFFFF_FFFF;
}
0
}
fn horns_icon(x: f32, y: f32) -> u32 {
for side in [-1.0f32, 1.0] {
let base_x = 12.0 + side * 5.0;
let t = (20.0 - y) / 15.0;
if !(0.0..=1.0).contains(&t) {
continue;
}
let centre = base_x + side * 5.0 * t * t;
let half = 2.6 * (1.0 - t) + 0.4;
if (x - centre).abs() < half {
return 0xFF00_0000 | mix(0xF2E6CC, 0x9C8A6A, t);
}
}
0
}
fn ears_icon(x: f32, y: f32) -> u32 {
for side in [-1.0f32, 1.0] {
let cx = 12.0 + side * 6.0;
let t = (19.0 - y) / 13.0;
if !(0.0..=1.0).contains(&t) {
continue;
}
let half = 4.5 * (1.0 - t);
let d = (x - cx).abs();
if d < half {
if d < half - 1.6 && t < 0.7 {
return 0xFFF2_A6BC;
}
// A light rim, so dark ears read on a dark card.
return if d > half - 0.8 || t > 0.92 {
0xFF9A_9AAE
} else {
0xFF4A_4A58
};
}
}
0
}
fn backpack_icon(x: f32, y: f32) -> u32 {
if (6.0..18.0).contains(&x) && (4.0..21.0).contains(&y) {
if y < 9.0 {
return 0xFF7F_C3F2;
}
if (8.0..16.0).contains(&x) && (12.0..18.0).contains(&y) {
return if x < 8.8 || x > 15.2 || y < 12.8 || y > 17.2 {
0xFFA9_DCFF
} else {
0xFF2C_4A72
};
}
return 0xFF22_385A;
}
0
}
fn wings_icon(id: &str, x: f32, y: f32) -> u32 {
// Both wings, spread from the middle.
let sx = (x - 12.0).abs() / 11.0;
let sy = (y - 2.0) / 20.0;
if (x - 12.0).abs() < 1.0 || !(0.0..=1.0).contains(&sy) || sx > 1.0 {
return 0;
}
let color = wing(id, sx, sy);
if color >> 24 == 0 {
0
} else {
0xFF00_0000 | color
}
}
// -------------------------------------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------------------------------------
/// A colour between `a` and `b` (RGB), `t` of the way.
pub fn mix(a: u32, b: u32, t: f32) -> u32 {
let k = clamp(t);
let ch = |shift: u32| {
let (x, y) = (((a >> shift) & 255) as f32, ((b >> shift) & 255) as f32);
round(x + (y - x) * k) as u32
};
ch(16) << 16 | ch(8) << 8 | ch(0)
}
fn add(base: u32, light: u32, amount: f32) -> u32 {
let ch = |shift: u32| {
(((base >> shift) & 255) as i32 + round(((light >> shift) & 255) as f32 * amount)).min(255)
as u32
};
ch(16) << 16 | ch(8) << 8 | ch(0)
}
/// `argb` darker by `factor`, alpha kept.
pub fn shade(argb: u32, factor: f32) -> u32 {
let ch = |shift: u32| round(((argb >> shift) & 255) as f32 * factor) as u32;
(argb & 0xFF00_0000) | ch(16) << 16 | ch(8) << 8 | ch(0)
}
pub fn clamp(value: f32) -> f32 {
value.clamp(0.0, 1.0)
}
/// A number in [0, 1) for a cell: the same for the same cell and salt (Java's int arithmetic).
pub fn hash(x: i32, y: i32, salt: i32) -> f32 {
let mut h = x
.wrapping_mul(374_761_393)
.wrapping_add(y.wrapping_mul(668_265_263))
.wrapping_add(salt.wrapping_mul(1_274_126_177));
h = (h ^ ((h as u32) >> 13) as i32).wrapping_mul(1_274_126_177);
h ^= ((h as u32) >> 16) as i32;
(h & 0xFF_FFFF) as f32 / 0x100_0000 as f32
}
/// Smooth value noise in [0, 1).
fn noise(x: f32, y: f32) -> f32 {
let (ix, iy) = (x.floor() as i32, y.floor() as i32);
let (fx, fy) = (x - ix as f32, y - iy as f32);
let sx = fx * fx * (3.0 - 2.0 * fx);
let sy = fy * fy * (3.0 - 2.0 * fy);
let a = hash(ix, iy, 1);
let b = hash(ix + 1, iy, 1);
let c = hash(ix, iy + 1, 1);
let d = hash(ix + 1, iy + 1, 1);
a + (b - a) * sx + (c - a) * sy + (a - b - c + d) * sx * sy
}
/// ARGB pixels as the canvas's RGBA bytes.
pub fn rgba(pixels: &[u32]) -> Vec<u8> {
let mut out = Vec::with_capacity(pixels.len() * 4);
for p in pixels {
let [a, r, g, b] = p.to_be_bytes();
out.extend_from_slice(&[r, g, b, a]);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cosmetics::catalog::{self, Slot};
#[test]
fn hash_matches_javas_ints() {
// CosmeticArt.hash(1, 2, 3) and (-5, 7, 11), from the Java client.
let java = |x: i32, y: i32, salt: i32| {
let mut h: i32 = x
.wrapping_mul(374761393)
.wrapping_add(y.wrapping_mul(668265263))
.wrapping_add(salt.wrapping_mul(1274126177));
h = (h ^ ((h as u32 >> 13) as i32)).wrapping_mul(1274126177);
h ^= (h as u32 >> 16) as i32;
(h & 0xFFFFFF) as f32 / 16777216.0
};
for (x, y, s) in [(1, 2, 3), (-5, 7, 11), (9, 15, 13)] {
assert_eq!(hash(x, y, s), java(x, y, s));
assert!((0.0..1.0).contains(&hash(x, y, s)));
}
}
#[test]
fn every_cape_and_icon_paints() {
let mut cape_px = vec![0u32; CAPE_WIDTH * CAPE_HEIGHT];
for c in catalog::in_slot(Slot::Cape) {
cape(c.id, 1.5, &mut cape_px);
assert_eq!(
cape_px[CAPE_WIDTH + 1] >> 24,
0xFF,
"{}: the outer side is opaque",
c.id
);
assert_eq!(
cape_px[CAPE_WIDTH * 31 + 63],
0,
"outside the layout stays clear"
);
}
let mut icon_px = vec![0u32; ICON * ICON];
for c in catalog::in_slot(Slot::Hat).chain(catalog::in_slot(Slot::Back)) {
icon(c.id, &mut icon_px);
assert!(icon_px.iter().any(|p| p >> 24 != 0), "{} has an icon", c.id);
}
assert_eq!(mix(0x000000, 0xFFFFFF, 0.5), 0x808080);
assert_eq!(shade(0xFF80_8080, 0.5), 0xFF40_4040);
}
#[test]
fn moving_capes_change_with_time() {
let (mut a, mut b) = (vec![0u32; 2048], vec![0u32; 2048]);
cape("cape.ember", 0.0, &mut a);
cape("cape.ember", 0.7, &mut b);
assert_ne!(a, b);
cape("cape.frost", 0.0, &mut a);
cape("cape.frost", 0.7, &mut b);
assert_eq!(a, b);
}
}
@@ -0,0 +1,141 @@
//! Incari's badge beside an Incari player's name tag, their name in the tab list and their name in
//! chat (ADR 0062; `Badges.java`), so Incari players know each other without asking. The badge is
//! one glyph of Incari's pack's `incari:badge` font (the mark, white so it keeps its own colours),
//! so the game's own text drawing carries it.
/// The badge's character in `incari:badge` (the pack's `font/badge.json`).
pub const GLYPH: &str = "\u{E100}";
/// Its font.
pub const FONT: &str = "incari:badge";
/// Its colour: white, so the glyph keeps its own.
pub const COLOR: u32 = 0xFFFFFF;
fn is_name_char(c: char) -> bool {
c.is_ascii_alphanumeric() || c == '_'
}
/// Where a badge goes in chat's `text` (character offsets): before the first mention of each name
/// `badged` takes. Names are runs of name characters up to 16 long; legacy `§` codes (1.8
/// servers' chat) are skipped over.
pub fn chat_positions(text: &str, badged: impl Fn(&str) -> bool) -> Vec<usize> {
let chars: Vec<char> = text.chars().collect();
let mut at = Vec::new();
let mut seen = std::collections::HashSet::new();
let mut i = 0;
while i < chars.len() {
let c = chars[i];
if c == '§' {
i += 2;
} else if !is_name_char(c) {
i += 1;
} else {
let start = i;
while i < chars.len() && is_name_char(chars[i]) {
i += 1;
}
let name: String = chars[start..i].iter().collect();
if i - start <= 16 && seen.insert(name.clone()) && badged(&name) {
at.push(start);
}
}
}
at
}
/// The `§` codes in `text`, in order: what a later cut of the same text must repeat.
pub fn legacy_codes(text: &str) -> String {
let chars: Vec<char> = text.chars().collect();
let mut out = String::new();
let mut i = 0;
while i + 1 < chars.len() {
if chars[i] == '§' {
out.push(chars[i]);
out.push(chars[i + 1]);
i += 2;
} else {
i += 1;
}
}
out
}
/// A piece of a badged chat line.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Piece {
/// Text in the style of the message's span `span`.
Text(usize, String),
/// The badge, then a space.
Badge,
}
/// The message whose spans' texts are `spans`, rebuilt piece by piece with a badge at each of
/// `positions` (from `chat_positions` on the spans' text joined). A span cut by a badge repeats
/// the `§` codes before the cut after it, so a coloured name keeps its colour.
pub fn badged_pieces(spans: &[&str], positions: &[usize]) -> Vec<Piece> {
let mut out = Vec::new();
let mut offset = 0;
let mut next = 0;
for (index, piece) in spans.iter().enumerate() {
let chars: Vec<char> = piece.chars().collect();
let end = offset + chars.len();
let mut from = 0;
let mut carried = String::new();
while next < positions.len() && positions[next] < end {
let cut = positions[next].saturating_sub(offset).max(from);
next += 1;
let before: String = chars[from..cut].iter().collect();
if !before.is_empty() {
out.push(Piece::Text(index, format!("{carried}{before}")));
}
carried.push_str(&legacy_codes(&before));
out.push(Piece::Badge);
from = cut;
}
let rest: String = chars[from..].iter().collect();
if !rest.is_empty() || !carried.is_empty() {
out.push(Piece::Text(index, format!("{carried}{rest}")));
}
offset = end;
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn badges_go_before_each_names_first_mention() {
let text = "<Steve> hi Alex, Steve here";
let at = chat_positions(text, |n| n == "Steve" || n == "Alex");
assert_eq!(at, [1, 11]);
let pieces = badged_pieces(&["<", "Steve> hi Alex, Steve here"], &at);
assert_eq!(
pieces,
[
Piece::Text(0, "<".into()),
Piece::Badge,
Piece::Text(1, "Steve> hi ".into()),
Piece::Badge,
Piece::Text(1, "Alex, Steve here".into()),
]
);
}
#[test]
fn legacy_codes_are_skipped_and_carried() {
let text = "§6[VIP] §eSteve: yo";
let at = chat_positions(text, |n| n == "Steve");
assert_eq!(at, [10]);
let pieces = badged_pieces(&[text], &at);
assert_eq!(
pieces,
[
Piece::Text(0, "§6[VIP] §e".into()),
Piece::Badge,
Piece::Text(0, "§6§eSteve: yo".into())
]
);
assert!(chat_positions("a_name_far_too_long_for_minecraft", |_| true).is_empty());
}
}
@@ -0,0 +1,175 @@
//! Every cosmetic this client can draw (ADR 0061; `:online`'s `Catalog` and `Cosmetic`), in the
//! wardrobe's order. The service keeps the same ids (`docs/online-protocol.md`); an id it sends
//! that isn't here (a newer client's) is left out, so a newer catalog never breaks this one.
/// Where a cosmetic is worn. An account wears at most one per slot; emotes are played, not worn.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Slot {
Cape,
Hat,
Back,
Nametag,
Trail,
Emote,
}
impl Slot {
pub const ALL: [Slot; 6] = [
Slot::Cape,
Slot::Hat,
Slot::Back,
Slot::Nametag,
Slot::Trail,
Slot::Emote,
];
/// The ids' prefix: `cape` in `cape.frost`.
pub fn prefix(self) -> &'static str {
match self {
Slot::Cape => "cape",
Slot::Hat => "hat",
Slot::Back => "back",
Slot::Nametag => "nametag",
Slot::Trail => "trail",
Slot::Emote => "emote",
}
}
/// What the wardrobe's tab says.
pub fn label(self) -> &'static str {
match self {
Slot::Cape => "Capes",
Slot::Hat => "Hats",
Slot::Back => "Wings & Back",
Slot::Nametag => "Name Tags",
Slot::Trail => "Trails",
Slot::Emote => "Emotes",
}
}
/// Whether a cosmetic in this slot is worn (and sent with `equip`); emotes aren't.
pub fn worn(self) -> bool {
self != Slot::Emote
}
/// Its place in `ALL`.
pub fn index(self) -> usize {
self as usize
}
}
/// One cosmetic: something an account wears that other Incari players see, or an emote it plays.
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct Cosmetic {
/// `<slot>.<name>`; never changes.
pub id: &'static str,
pub slot: Slot,
/// What the wardrobe calls it.
pub name: &'static str,
/// Whether every account owns it.
pub free: bool,
}
const fn free(id: &'static str, slot: Slot, name: &'static str) -> Cosmetic {
Cosmetic {
id,
slot,
name,
free: true,
}
}
use Slot::*;
/// Every cosmetic, in the wardrobe's order.
pub static ALL: [Cosmetic; 37] = [
// Capes: the client's own art (`art::cape`), some of it moving.
free("cape.frost", Cape, "Frost"),
free("cape.aurora", Cape, "Aurora"),
free("cape.midnight", Cape, "Midnight"),
free("cape.ember", Cape, "Ember"),
free("cape.sakura", Cape, "Sakura"),
free("cape.tide", Cape, "Tide"),
free("cape.mono", Cape, "Mono"),
// Hats: small models on the head, hidden under a helmet.
free("hat.crown", Hat, "Crown"),
free("hat.halo", Hat, "Halo"),
free("hat.top_hat", Hat, "Top Hat"),
free("hat.beanie", Hat, "Beanie"),
free("hat.horns", Hat, "Horns"),
free("hat.cat_ears", Hat, "Cat Ears"),
// On the back: hidden while an elytra is worn.
free("back.angel_wings", Back, "Angel Wings"),
free("back.frost_wings", Back, "Frost Wings"),
free("back.bat_wings", Back, "Bat Wings"),
free("back.backpack", Back, "Backpack"),
// Name tags: the name's colour over the head.
free("nametag.ice", Nametag, "Ice"),
free("nametag.gold", Nametag, "Gold"),
free("nametag.mint", Nametag, "Mint"),
free("nametag.rose", Nametag, "Rose"),
free("nametag.violet", Nametag, "Violet"),
free("nametag.frost", Nametag, "Frost Fade"),
free("nametag.sunset", Nametag, "Sunset Fade"),
free("nametag.aurora", Nametag, "Aurora Fade"),
// Trails: a few particles behind the player as they move.
free("trail.snow", Trail, "Snowflakes"),
free("trail.hearts", Trail, "Hearts"),
free("trail.sparkles", Trail, "Sparkles"),
free("trail.notes", Trail, "Notes"),
// Emotes: played from the emote wheel, seen by Incari players nearby.
free("emote.wave", Emote, "Wave"),
free("emote.clap", Emote, "Clap"),
free("emote.cheer", Emote, "Cheer"),
free("emote.salute", Emote, "Salute"),
free("emote.facepalm", Emote, "Facepalm"),
free("emote.shrug", Emote, "Shrug"),
free("emote.dab", Emote, "Dab"),
free("emote.bow", Emote, "Bow"),
];
/// Every cosmetic, in the wardrobe's order.
pub fn all() -> &'static [Cosmetic] {
&ALL
}
/// The cosmetic with this id, or None if this client has none by it.
pub fn by_id(id: &str) -> Option<&'static Cosmetic> {
ALL.iter().find(|c| c.id == id)
}
/// The cosmetics in `slot`, in the wardrobe's order.
pub fn in_slot(slot: Slot) -> impl Iterator<Item = &'static Cosmetic> {
ALL.iter().filter(move |c| c.slot == slot)
}
/// Its place in `ALL`: a small number for a cosmetic's textures and caches.
pub fn index(cosmetic: &Cosmetic) -> usize {
ALL.iter().position(|c| c.id == cosmetic.id).unwrap_or(0)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ids_are_unique_and_in_their_slot() {
for (i, c) in ALL.iter().enumerate() {
assert!(
c.id.starts_with(&format!("{}.", c.slot.prefix())),
"{}",
c.id
);
assert!(
ALL[..i].iter().all(|o| o.id != c.id),
"two cosmetics are {}",
c.id
);
assert_eq!(index(c), i);
}
let counts: Vec<usize> = Slot::ALL.iter().map(|s| in_slot(*s).count()).collect();
assert_eq!(counts, [7, 6, 4, 8, 4, 8], "ADR 0061's 37");
assert_eq!(by_id("hat.halo").map(|c| c.name), Some("Halo"));
assert!(by_id("hat.unknown").is_none());
}
}
@@ -0,0 +1,119 @@
//! Emotes as the player model plays them (ADR 0061; `Emotes.java`): each a pose for the arms and
//! head, eased in and out, some moving as they go (a wave, a clap). Laid over the game's own pose
//! after it's set up, so the legs still walk if the player does, and sleeves, hats and capes follow
//! the parts they hang from. Pure, and nothing allocates: it runs while the model is posed.
/// Ticks an emote takes to ease in, and out.
const EASE: f32 = 4.0;
/// How long `emote` plays, in ticks.
pub fn duration(emote: &str) -> u32 {
match emote {
"emote.wave" | "emote.clap" | "emote.facepalm" => 50,
"emote.cheer" => 45,
"emote.salute" | "emote.bow" => 40,
"emote.shrug" => 35,
"emote.dab" => 30,
_ => 40,
}
}
/// What an emote turns, `weight` of the way from the game's pose (0 to 1): each part's x, y and z
/// rotation in radians, as the game's model parts take them. None leaves a part as it was.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Pose {
pub weight: f32,
pub head: Option<[f32; 3]>,
pub right_arm: Option<[f32; 3]>,
pub left_arm: Option<[f32; 3]>,
}
impl Pose {
/// `part`'s rotation `from`, moved toward this pose (`Mth.lerp` per angle).
pub fn blend(weight: f32, from: [f32; 3], to: Option<[f32; 3]>) -> [f32; 3] {
match to {
Some(to) => [0, 1, 2].map(|i| from[i] + (to[i] - from[i]) * weight),
None => from,
}
}
}
/// `emote`'s pose `elapsed` ticks after it started, or None once it's over (or before it began).
pub fn pose(emote: &str, elapsed: f32) -> Option<Pose> {
let duration = duration(emote) as f32;
if !(0.0..duration).contains(&elapsed) {
return None;
}
let weight = (elapsed / EASE).min((duration - elapsed) / EASE).min(1.0);
let e = elapsed;
let mut p = Pose {
weight,
..Pose::default()
};
match emote {
"emote.wave" => p.right_arm = Some([0.0, 0.0, 2.6 + 0.35 * (e * 0.6).sin()]),
"emote.clap" => {
let swing = 0.25 + 0.3 * (0.5 + 0.5 * (e * 0.9).sin());
p.right_arm = Some([-1.35, -swing, 0.0]);
p.left_arm = Some([-1.35, swing, 0.0]);
}
"emote.cheer" => {
let bounce = 0.15 * (e * 0.5).sin();
p.right_arm = Some([-2.9 + bounce, 0.0, 0.35]);
p.left_arm = Some([-2.9 - bounce, 0.0, -0.35]);
p.head = Some([-0.25, 0.0, 0.0]);
}
"emote.salute" => {
p.right_arm = Some([-2.3, -0.55, 0.1]);
p.head = Some([-0.05, 0.0, 0.0]);
}
"emote.facepalm" => {
p.right_arm = Some([-2.1, -0.75, 0.0]);
p.head = Some([0.35, 0.0, 0.0]);
}
"emote.shrug" => {
let lift = 0.1 * (e * 0.4).sin();
p.right_arm = Some([-0.45, 0.0, 0.75 + lift]);
p.left_arm = Some([-0.45, 0.0, -0.75 - lift]);
p.head = Some([-0.1, 0.0, 0.12 * (e * 0.3).sin()]);
}
"emote.dab" => {
p.right_arm = Some([-1.6, -1.0, 0.0]);
p.left_arm = Some([-0.4, 0.0, -2.3]);
p.head = Some([0.55, 0.6, 0.0]);
}
"emote.bow" => {
p.right_arm = Some([-0.9, -0.6, 0.0]);
p.left_arm = Some([0.3, 0.0, 0.0]);
p.head = Some([0.75, 0.0, 0.0]);
}
_ => {}
}
Some(p)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cosmetics::catalog::{self, Slot};
#[test]
fn emotes_ease_in_and_out_and_end() {
for e in catalog::in_slot(Slot::Emote) {
let d = duration(e.id) as f32;
assert_eq!(pose(e.id, 0.0).unwrap().weight, 0.0, "{}", e.id);
assert_eq!(pose(e.id, d / 2.0).unwrap().weight, 1.0);
assert!(pose(e.id, d).is_none() && pose(e.id, -1.0).is_none());
let p = pose(e.id, d / 2.0).unwrap();
assert!(
p.right_arm.is_some() || p.head.is_some(),
"{} turns something",
e.id
);
}
assert_eq!(
Pose::blend(0.5, [0.0, 2.0, 0.0], Some([1.0, 0.0, 0.0])),
[0.5, 1.0, 0.0]
);
}
}
@@ -0,0 +1,122 @@
//! What a player wears (ADR 0061; `:online`'s `Loadout`): at most one cosmetic in each worn slot.
//! Read from the ids the service sends, forgivingly: an id this client doesn't know, an emote, or a
//! second cosmetic for a slot is left out. Small and `Copy`: comparing two costs nothing.
use super::catalog::{self, Cosmetic, Slot};
/// The worn slots, in `Slot`'s order.
const WORN: usize = 5;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Loadout {
by_slot: [Option<&'static Cosmetic>; WORN],
}
impl Loadout {
/// Nothing worn.
pub const EMPTY: Loadout = Loadout {
by_slot: [None; WORN],
};
/// The loadout these ids describe, leaving out what this client can't draw.
pub fn of<S: AsRef<str>>(ids: &[S]) -> Self {
let mut out = Self::EMPTY;
for id in ids {
if let Some(c) = catalog::by_id(id.as_ref())
&& c.slot.worn()
&& out.by_slot[c.slot.index()].is_none()
{
out.by_slot[c.slot.index()] = Some(c);
}
}
out
}
/// What's worn in `slot`.
pub fn in_slot(&self, slot: Slot) -> Option<&'static Cosmetic> {
if slot.worn() {
self.by_slot[slot.index()]
} else {
None
}
}
/// Whether `cosmetic` is worn.
pub fn wears(&self, cosmetic: &Cosmetic) -> bool {
self.in_slot(cosmetic.slot)
.is_some_and(|c| c.id == cosmetic.id)
}
/// This loadout with `cosmetic` in its slot, in place of what was there; itself for an emote.
pub fn with(mut self, cosmetic: &'static Cosmetic) -> Self {
if cosmetic.slot.worn() {
self.by_slot[cosmetic.slot.index()] = Some(cosmetic);
}
self
}
/// This loadout with nothing in `slot`.
pub fn without(mut self, slot: Slot) -> Self {
if slot.worn() {
self.by_slot[slot.index()] = None;
}
self
}
/// This loadout with only what `owns` allows.
pub fn owned_by(mut self, owns: impl Fn(&Cosmetic) -> bool) -> Self {
for slot in &mut self.by_slot {
if slot.is_some_and(|c| !owns(c)) {
*slot = None;
}
}
self
}
/// What's worn, in slot order.
pub fn worn(&self) -> impl Iterator<Item = &'static Cosmetic> + '_ {
self.by_slot.iter().flatten().copied()
}
/// The ids worn, in slot order: what `equip` sends.
pub fn ids(&self) -> Vec<String> {
self.worn().map(|c| c.id.to_owned()).collect()
}
pub fn is_empty(&self) -> bool {
self.by_slot.iter().all(Option::is_none)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_forgivingly_and_keeps_one_a_slot() {
let l = Loadout::of(&[
"hat.crown",
"hat.halo",
"emote.wave",
"cape.unknown",
"cape.tide",
]);
assert_eq!(
l.ids(),
["cape.tide", "hat.crown"],
"slot order, the first of a slot, no emotes"
);
let crown = catalog::by_id("hat.crown").unwrap();
assert!(l.wears(crown));
let halo = catalog::by_id("hat.halo").unwrap();
let l2 = l.with(halo);
assert!(l2.wears(halo) && !l2.wears(crown));
assert_eq!(l2.without(Slot::Hat).without(Slot::Cape), Loadout::EMPTY);
assert!(Loadout::of::<&str>(&[]).is_empty());
assert_eq!(
l.with(catalog::by_id("emote.bow").unwrap()),
l,
"emotes aren't worn"
);
assert_eq!(l.owned_by(|c| c.slot != Slot::Hat).ids(), ["cape.tide"]);
}
}
@@ -0,0 +1,20 @@
//! Cosmetics (ADR 0061): the catalog, what's worn, the device's wardrobe and its sync with the
//! service, the cosmetics' own art and models (painted in code), name tag styles, emotes, Incari's
//! badge, and what the world shows of them, with no game types. The Wardrobe and the emote wheel
//! are `screens::wardrobe` and `screens::emote_wheel`; the game side (`rust/mods/cosmetics`) draws
//! what's worn on players through the fork's player hooks.
pub mod art;
pub mod badges;
pub mod catalog;
pub mod emotes;
pub mod loadout;
pub mod models;
pub mod nametags;
pub mod preview;
pub mod textures;
pub mod wardrobe;
pub mod world;
pub use catalog::{Cosmetic, Slot};
pub use loadout::Loadout;
pub use world::Worn;
@@ -0,0 +1,803 @@
//! The hats and back cosmetics as models (ADR 0061; `CosmeticModels.java`): each a few boxes,
//! described here, with a 64x64 texture painted from the same description, so the boxes and
//! their pictures never disagree. Coordinates are the player model's, in pixels with +y down: a
//! hat's from the head's pivot (the head's box is -4..4 across, -8..0 up), a back cosmetic's from
//! the body's (the body's back is at z = 2).
//!
//! `mesh` lays a model out as quads in its anchor part's frame (the game side divides by 16 and
//! draws them under the head or body, `native_draw_quad`; the Wardrobe's preview projects them).
//! Pure: the same model and state always give the same quads.
use super::art;
/// The texture's side.
pub const TEXTURE: usize = 64;
/// Where a cosmetic sits on the player.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Anchor {
Head,
Body,
}
/// How a cosmetic is drawn.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Look {
/// Opaque, with see-through pixels cut out.
Cutout,
/// Partly see-through.
Translucent,
/// Glowing: lit by itself, at full brightness.
Glow,
}
/// What a box is painted with.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Material {
Gold,
GoldGem,
Halo,
Felt,
FeltBand,
Knit,
Pom,
Bone,
Ear,
Pack,
Pocket,
Wing,
}
impl Material {
/// The length of the Java enum constant's name: its grain's salt.
fn salt_len(self) -> i32 {
match self {
Material::Gold
| Material::Halo
| Material::Felt
| Material::Knit
| Material::Bone
| Material::Pack
| Material::Wing => 4,
Material::GoldGem => 8,
Material::Pocket => 6,
Material::FeltBand => 9,
Material::Pom | Material::Ear => 3,
}
}
}
/// A box: where, how big, how much bigger than that, what it's painted with; mirrored.
#[derive(Clone, Copy, Debug)]
struct Box3 {
at: [f32; 3],
size: [i32; 3],
grow: f32,
material: Material,
mirror: bool,
}
/// A part: its name, where it turns about, how it's turned (x, y, z radians), its boxes.
#[derive(Clone, Debug)]
struct Part {
name: &'static str,
offset: [f32; 3],
rotation: [f32; 3],
boxes: Vec<Box3>,
}
/// A cosmetic's model as described.
#[derive(Clone, Debug)]
pub struct Spec {
pub anchor: Anchor,
pub look: Look,
parts: Vec<Part>,
}
fn bx(x: f32, y: f32, z: f32, w: i32, h: i32, d: i32, grow: f32, material: Material) -> Box3 {
Box3 {
at: [x, y, z],
size: [w, h, d],
grow,
material,
mirror: false,
}
}
fn part(name: &'static str, offset: [f32; 3], rotation: [f32; 3], boxes: Vec<Box3>) -> Part {
Part {
name,
offset,
rotation,
boxes,
}
}
/// How far back the wings are swept at rest, in radians.
const WING_SWEEP: f32 = 0.28;
/// The model of cosmetic `id`, or None for one that isn't a model (capes, name tags...).
pub fn spec(id: &str) -> Option<Spec> {
use Material::*;
let zero = [0.0; 3];
let one = |anchor, look, p: Part| Spec {
anchor,
look,
parts: vec![p],
};
Some(match id {
"hat.crown" => {
// A band round the top of the head, outside the skin's hat layer, its top velvet.
let mut boxes = vec![bx(-4.0, -10.0, -4.0, 8, 2, 8, 0.6, GoldGem)];
for [x, z] in [
[-4.6, -4.6],
[3.6, -4.6],
[-4.6, 3.6],
[3.6, 3.6],
[-0.5, -4.6],
[-0.5, 3.6],
[-4.6, -0.5],
[3.6, -0.5],
] {
boxes.push(bx(x, -12.6, z, 1, 2, 1, 0.05, Gold));
}
one(Anchor::Head, Look::Cutout, part("crown", zero, zero, boxes))
}
"hat.halo" => one(
Anchor::Head,
Look::Glow,
part(
"ring",
[0.0, -12.5, 0.0],
zero,
vec![
bx(-3.0, -0.5, -3.5, 6, 1, 1, 0.0, Halo),
bx(-3.0, -0.5, 2.5, 6, 1, 1, 0.0, Halo),
bx(-3.5, -0.5, -3.0, 1, 1, 6, 0.0, Halo),
bx(2.5, -0.5, -3.0, 1, 1, 6, 0.0, Halo),
],
),
),
"hat.top_hat" => one(
Anchor::Head,
Look::Cutout,
part(
"hat",
zero,
zero,
vec![
bx(-5.0, -9.0, -5.0, 10, 1, 10, 0.1, Felt),
bx(-4.0, -15.0, -4.0, 8, 6, 8, -0.5, FeltBand),
],
),
),
"hat.beanie" => one(
Anchor::Head,
Look::Cutout,
part(
"beanie",
zero,
zero,
vec![
bx(-4.0, -9.0, -4.0, 8, 3, 8, 0.7, Knit),
bx(-1.0, -12.0, -1.0, 2, 2, 2, 0.3, Pom),
],
),
),
"hat.horns" => Spec {
anchor: Anchor::Head,
look: Look::Cutout,
parts: vec![horn("left", 1.0), horn("right", -1.0)],
},
"hat.cat_ears" => Spec {
anchor: Anchor::Head,
look: Look::Cutout,
parts: vec![ear("left", 1.0), ear("right", -1.0)],
},
"back.angel_wings" | "back.bat_wings" => wings(Look::Cutout),
"back.frost_wings" => wings(Look::Translucent),
"back.backpack" => one(
Anchor::Body,
Look::Cutout,
part(
"pack",
zero,
zero,
vec![
bx(-4.0, 1.0, 2.0, 8, 10, 4, 0.0, Pack),
bx(-3.0, 5.0, 6.0, 6, 4, 1, 0.0, Pocket),
],
),
),
_ => return None,
})
}
fn horn(name: &'static str, side: f32) -> Part {
part(
name,
[side * 2.5, -8.0, -1.0],
[-0.2, 0.0, side * 0.45],
vec![
bx(-1.0, -3.0, -1.0, 2, 3, 2, 0.0, Material::Bone),
bx(-0.5 + side * 0.4, -5.5, -0.5, 1, 3, 1, 0.0, Material::Bone),
],
)
}
fn ear(name: &'static str, side: f32) -> Part {
part(
name,
[side * 2.6, -8.2, -0.5],
[0.0, 0.0, side * 0.28],
vec![
bx(-1.5, -3.0, -0.5, 3, 3, 1, 0.0, Material::Ear),
bx(-0.5, -4.0, -0.5, 1, 1, 1, 0.0, Material::Ear),
],
)
}
/// Two wings, panels with nothing but a front and a back, from the shoulder blades, out past the
/// shoulders and up past them, swept back a little.
fn wings(look: Look) -> Spec {
let wing = |mirror: bool| Box3 {
at: [if mirror { -16.0 } else { 0.0 }, -9.0, 0.0],
size: [16, 16, 0],
grow: 0.0,
material: Material::Wing,
mirror,
};
Spec {
anchor: Anchor::Body,
look,
parts: vec![
part(
"left_wing",
[1.0, 3.0, 2.4],
[0.0, -WING_SWEEP, -0.12],
vec![wing(false)],
),
part(
"right_wing",
[-1.0, 3.0, 2.4],
[0.0, WING_SWEEP, 0.12],
vec![wing(true)],
),
],
}
}
// -------------------------------------------------------------------------------------------------
// The texture
// -------------------------------------------------------------------------------------------------
/// Where each box's faces start on the texture, in the order the boxes are described: packed on
/// shelves, as the Java client lays them out.
fn tex_offsets(spec: &Spec) -> Vec<[i32; 2]> {
let (mut sx, mut sy, mut sh) = (0, 0, 0);
let mut out = Vec::new();
for p in &spec.parts {
for b in &p.boxes {
let [w, h, d] = b.size;
let (width, height) = (2 * d + 2 * w, d + h);
if sx + width > TEXTURE as i32 {
sx = 0;
sy += sh;
sh = 0;
}
out.push([sx, sy]);
sx += width;
sh = sh.max(height);
}
}
out
}
/// Paints the model's 64x64 texture (ARGB) for cosmetic `id`.
pub fn texture(id: &str, spec: &Spec, out: &mut [u32]) {
out.fill(0);
let boxes = spec.parts.iter().flat_map(|p| p.boxes.iter());
for (b, [u, v]) in boxes.zip(tex_offsets(spec)) {
let [w, h, d] = b.size;
let faces = [
(u + d, v, w, d),
(u + d + w, v, w, d),
(u, v + d, d, h),
(u + d, v + d, w, h),
(u + d + w, v + d, d, h),
(u + 2 * d + w, v + d, w, h),
];
for (face, (x0, y0, fw, fh)) in faces.into_iter().enumerate() {
for y in 0..fh {
for x in 0..fw {
let (px, py) = (x0 + x, y0 + y);
if (px as usize) < TEXTURE && (py as usize) < TEXTURE {
out[py as usize * TEXTURE + px as usize] =
color(id, b.material, face, x, y, fw, fh);
}
}
}
}
}
}
/// A face's pixel: face 0 and 1 the bottom and top, 3 the front, 5 the back.
fn color(
id: &str,
material: Material,
face: usize,
x: i32,
y: i32,
width: i32,
height: i32,
) -> u32 {
use Material::*;
let flat = face <= 1;
let row = if height <= 1 {
0.0
} else {
y as f32 / (height - 1) as f32
};
let grain = art::hash(x, y, face as i32 + material.salt_len() * 7);
let opaque = |rgb: u32| 0xFF00_0000 | rgb;
match material {
Gold | GoldGem => {
if material == GoldGem && flat {
return opaque(art::mix(0x8E1B2E, 0x6A1222, grain));
}
if material == GoldGem
&& face == 3
&& (x as f32 - (width - 1) as f32 / 2.0).abs() < 1.0
&& y == 0
{
return 0xFFE0_344B;
}
let gold = art::mix(0xFFE58A, 0xD69A1E, if flat { 0.1 } else { row });
opaque(if grain < 0.08 {
art::mix(gold, 0xFFFFFF, 0.6)
} else {
gold
})
}
Halo => opaque(art::mix(0xFFF6D2, 0xFFDB7A, grain * 0.6)),
Felt => opaque(art::mix(0x2A2A33, 0x1A1A20, grain)),
FeltBand => {
if !flat && y >= height - 2 {
0xFFC0_263A
} else {
opaque(art::mix(0x2A2A33, 0x1A1A20, grain))
}
}
Knit => {
if !flat && y == height - 1 {
return 0xFF4F_8FC7;
}
let stripe = if flat { (x + y) / 2 } else { y };
if stripe & 1 == 0 {
0xFF7F_C3F2
} else {
0xFFEA_F6FF
}
}
Pom => opaque(art::mix(0xFFFFFF, 0xDDE8F2, grain)),
Bone => opaque(art::mix(
0xF2E6CC,
0x9C8A6A,
if flat { 0.3 } else { 1.0 - row },
)),
Ear => {
if face == 3 && x > 0 && x < width - 1 && y > 0 {
0xFFF2_A6BC
} else {
0xFF4A_4A58
}
}
Pack => {
if face == 1 {
return 0xFF7F_C3F2;
}
let seam = x == 0 || y == 0 || x == width - 1 || y == height - 1;
if seam {
0xFF3B_5B8A
} else {
opaque(art::mix(0x22385A, 0x1B2D49, grain))
}
}
Pocket => {
if x == 0 || y == 0 || x == width - 1 || y == height - 1 {
0xFFA9_DCFF
} else {
0xFF2C_4A72
}
}
Wing => {
// The back (south) face has the root on its left; the front shows it mirrored, so
// the two sides of the panel line up.
let sx = (x as f32 + 0.5) / width as f32;
let sy = (y as f32 + 0.5) / height as f32;
art::wing(id, if face == 5 { sx } else { 1.0 - sx }, sy)
}
}
}
// -------------------------------------------------------------------------------------------------
// The mesh
// -------------------------------------------------------------------------------------------------
/// What a model is posed from: the wearer's frame, as `CosmeticModel.setupAnim` and
/// `CosmeticsLayer` read it.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct State {
/// `ageInTicks`.
pub age: f32,
pub crouching: bool,
pub fall_flying: bool,
/// A chestplate (or other chest armour) is worn: a back cosmetic stands a pixel out.
pub chest_armor: bool,
/// A cape hangs from the shoulders, turned back this far (radians, `6 + capeLean / 2 +
/// capeFlap` degrees): a back cosmetic hangs behind it and swings with it.
pub cape_swing: Option<f32>,
}
/// A face to draw: its corners in the anchor part's frame (pixels, +y down) in the game's polygon
/// order, each with its texture position (pixels of the 64x64 texture).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Quad {
pub pos: [[f32; 3]; 4],
pub uv: [[f32; 2]; 4],
}
/// An affine transform, rows of a 3x4 matrix.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Affine(pub [[f32; 4]; 3]);
impl Affine {
pub const IDENTITY: Affine = Affine([
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
]);
pub fn translation(t: [f32; 3]) -> Self {
let mut m = Self::IDENTITY;
for (row, v) in m.0.iter_mut().zip(t) {
row[3] = v;
}
m
}
/// `Quaternionf.rotationZYX(z, y, x)`: x first, then y, then z.
pub fn rotation_zyx(x: f32, y: f32, z: f32) -> Self {
Self::rotation_z(z)
.then(&Self::rotation_y(y))
.then(&Self::rotation_x(x))
}
pub fn rotation_x(a: f32) -> Self {
let (s, c) = a.sin_cos();
Affine([[1.0, 0.0, 0.0, 0.0], [0.0, c, -s, 0.0], [0.0, s, c, 0.0]])
}
pub fn rotation_y(a: f32) -> Self {
let (s, c) = a.sin_cos();
Affine([[c, 0.0, s, 0.0], [0.0, 1.0, 0.0, 0.0], [-s, 0.0, c, 0.0]])
}
pub fn rotation_z(a: f32) -> Self {
let (s, c) = a.sin_cos();
Affine([[c, -s, 0.0, 0.0], [s, c, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]])
}
pub fn scale(s: [f32; 3]) -> Self {
Affine([
[s[0], 0.0, 0.0, 0.0],
[0.0, s[1], 0.0, 0.0],
[0.0, 0.0, s[2], 0.0],
])
}
/// `self * other`: `other` applied first (a pose stack's next transform).
pub fn then(&self, other: &Affine) -> Affine {
let (a, b) = (&self.0, &other.0);
let mut out = [[0.0; 4]; 3];
for (i, row) in out.iter_mut().enumerate() {
for (j, cell) in row.iter_mut().enumerate() {
*cell = a[i][0] * b[0][j]
+ a[i][1] * b[1][j]
+ a[i][2] * b[2][j]
+ if j == 3 { a[i][3] } else { 0.0 };
}
}
Affine(out)
}
pub fn apply(&self, p: [f32; 3]) -> [f32; 3] {
let m = &self.0;
[0, 1, 2].map(|i| m[i][0] * p[0] + m[i][1] * p[1] + m[i][2] * p[2] + m[i][3])
}
}
/// Lays `spec` out as quads in its anchor's frame, posed for `state`, into `out` (cleared first).
/// Per player per frame: nothing is made but what `out` grows to once.
pub fn mesh(id: &str, spec: &Spec, state: &State, out: &mut Vec<Quad>) {
out.clear();
let mut anchor = Affine::IDENTITY;
if spec.anchor == Anchor::Body {
if state.chest_armor {
// A chestplate stands a pixel out from the body.
anchor = anchor.then(&Affine::translation([0.0, 0.0, 1.0]));
}
if let Some(swing) = state.cape_swing
&& id != "back.backpack"
{
// Behind the cape, about its top edge at the body's back (z = 2), a pixel and a gap out.
anchor = anchor
.then(&Affine::translation([0.0, 0.0, 2.0]))
.then(&Affine::rotation_x(swing))
.then(&Affine::translation([0.0, 0.0, -2.0 + 1.0]));
}
}
let offsets = tex_offsets(spec);
let mut boxes = offsets.iter();
for p in &spec.parts {
let (mut offset, mut rotation) = (p.offset, p.rotation);
pose_part(p.name, state, &mut offset, &mut rotation);
let m = anchor
.then(&Affine::translation(offset))
.then(&Affine::rotation_zyx(rotation[0], rotation[1], rotation[2]));
for b in &p.boxes {
let Some(&tex) = boxes.next() else { break };
cube(b, tex, &m, out);
}
}
}
/// `CosmeticModel.setupAnim`: the halo turns and bobs; wings beat at rest, fold back while
/// sneaking and spread while gliding, never swept forward far enough to reach the arms.
fn pose_part(name: &str, state: &State, offset: &mut [f32; 3], rotation: &mut [f32; 3]) {
let age = state.age;
match name {
"ring" => {
rotation[1] = age * 0.04;
offset[1] += (age * 0.08).sin() * 0.4;
}
"left_wing" | "right_wing" => {
let beat = (age * 0.12).sin() * 0.08 + 0.08;
let fold = if state.crouching { 0.25 } else { 0.0 };
let spread = if state.fall_flying { 0.2 } else { 0.0 };
let sweep = (beat + fold - spread).max(-WING_SWEEP + 0.1);
if name == "left_wing" {
rotation[1] -= sweep;
} else {
rotation[1] += sweep;
}
}
_ => {}
}
}
/// A cosmetic's box as the game's `ModelPart.Cube` makes it.
fn cube(b: &Box3, tex: [i32; 2], m: &Affine, out: &mut Vec<Quad>) {
let g = if b.size[2] == 0 { 0.0 } else { b.grow };
box_quads(b.at, b.size, g, tex, b.mirror, m, out);
}
/// The game's `ModelPart.Cube` of `size` pixels from `at`, grown by `grow`, its faces from texture
/// position `tex`, under `m`: its polygons (a panel with no depth has only its front and back),
/// each vertex with its texture position, as the game lays them out. The player's own boxes in
/// the Wardrobe's preview are made the same way.
pub fn box_quads(
at: [f32; 3],
size: [i32; 3],
g: f32,
[u, v]: [i32; 2],
mirror: bool,
m: &Affine,
out: &mut Vec<Quad>,
) {
let [w, h, d] = size;
let (mut x0, y0, z0) = (at[0] - g, at[1] - g, at[2] - g);
let (mut x1, y1, z1) = (
at[0] + w as f32 + g,
at[1] + h as f32 + g,
at[2] + d as f32 + g,
);
if mirror {
std::mem::swap(&mut x0, &mut x1);
}
let v7 = [x0, y0, z0];
let v0 = [x1, y0, z0];
let v1 = [x1, y1, z0];
let v2 = [x0, y1, z0];
let v3 = [x0, y0, z1];
let v4 = [x1, y0, z1];
let v5 = [x1, y1, z1];
let v6 = [x0, y1, z1];
let (u, v, w, h, d) = (u as f32, v as f32, w as f32, h as f32, d as f32);
let (f4, f5, f6, f7, f8, f9) = (
u,
u + d,
u + d + w,
u + d + w + w,
u + d + w + d,
u + d + w + d + w,
);
let (f10, f11, f12) = (v, v + d, v + d + h);
let panel = size[2] == 0;
let faces: [([[f32; 3]; 4], [f32; 4], bool); 6] = [
([v4, v3, v7, v0], [f5, f10, f6, f11], !panel),
([v1, v2, v6, v5], [f6, f11, f7, f10], !panel),
([v7, v3, v6, v2], [f4, f11, f5, f12], !panel),
([v0, v7, v2, v1], [f5, f11, f6, f12], true),
([v4, v0, v1, v5], [f6, f11, f8, f12], !panel),
([v3, v4, v5, v6], [f8, f11, f9, f12], true),
];
for (corners, [u1, v1, u2, v2], shown) in faces {
if !shown {
continue;
}
let mut pos = corners.map(|c| m.apply(c));
let mut uv = [[u2, v1], [u1, v1], [u1, v2], [u2, v2]];
if mirror {
pos.reverse();
uv.reverse();
}
out.push(Quad { pos, uv });
}
}
/// Cosmetic `cosmetic`'s place among those that are models (the hats, then the back cosmetics,
/// in the catalog's order): where the game side keeps its texture.
pub fn number(cosmetic: &super::catalog::Cosmetic) -> Option<usize> {
use super::catalog::{self, Slot};
catalog::all()
.iter()
.filter(|c| matches!(c.slot, Slot::Hat | Slot::Back))
.position(|c| c.id == cosmetic.id)
}
/// Each cosmetic's model by catalog place (None: not made yet), and the last mesh's quads.
type Made = (Vec<Option<Option<Spec>>>, Vec<Quad>);
thread_local! {
/// Each cosmetic's model as described, made the first time it's drawn, and the quads of the
/// last mesh: drawing a player's hat each frame makes nothing.
static MADE: std::cell::RefCell<Made> = const { std::cell::RefCell::new((Vec::new(), Vec::new())) };
}
/// Runs `f` with `cosmetic`'s model and its quads posed for `state` (`mesh`), from a cache the
/// window's thread keeps; None for a cosmetic that isn't a model. Per player per frame.
pub fn with_mesh<R>(
cosmetic: &super::catalog::Cosmetic,
state: &State,
f: impl FnOnce(&Spec, &[Quad]) -> R,
) -> Option<R> {
let index = super::catalog::index(cosmetic);
MADE.with(|made| {
let mut made = made.borrow_mut();
let (specs, quads) = &mut *made;
if specs.len() <= index {
specs.resize_with(index + 1, || None);
}
let spec = specs[index]
.get_or_insert_with(|| spec(cosmetic.id))
.as_ref()?;
mesh(cosmetic.id, spec, state, quads);
Some(f(spec, quads))
})
}
/// A quad as `native_draw_quad` takes one: corners in its order (texture top left, bottom left,
/// bottom right, top right) and its texture rectangle `[u0, v0, u1, v1]`, by turning the quad's
/// corners round (never reversing them, so it faces the same way).
pub fn quad_for_rect(q: &Quad) -> ([[f32; 3]; 4], [f32; 4]) {
for k in 0..4 {
let at = |i: usize| q.uv[(k + i) % 4];
let (a, b, c, d) = (at(0), at(1), at(2), at(3));
if a[0] == b[0] && b[1] == c[1] && c[0] == d[0] && d[1] == a[1] {
let pos = [0, 1, 2, 3].map(|i| q.pos[(k + i) % 4]);
return (pos, [a[0], a[1], c[0], c[1]]);
}
}
(q.pos, [q.uv[1][0], q.uv[1][1], q.uv[3][0], q.uv[3][1]])
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cosmetics::catalog::{self, Slot};
#[test]
fn every_hat_and_back_cosmetic_is_a_model_on_its_texture() {
let mut quads = Vec::new();
let mut tex = vec![0u32; TEXTURE * TEXTURE];
for c in catalog::in_slot(Slot::Hat).chain(catalog::in_slot(Slot::Back)) {
let spec = spec(c.id).expect(c.id);
assert_eq!(spec.anchor == Anchor::Head, c.slot == Slot::Hat);
mesh(c.id, &spec, &State::default(), &mut quads);
assert!(!quads.is_empty());
texture(c.id, &spec, &mut tex);
for q in &quads {
for [u, v] in q.uv {
assert!(
(0.0..=TEXTURE as f32).contains(&u) && (0.0..=TEXTURE as f32).contains(&v),
"{}",
c.id
);
}
}
// Something painted under every face's middle (wings may be clear at their edges).
if spec.parts[0].boxes[0].material != Material::Wing {
for q in &quads {
let u = (q.uv[0][0] + q.uv[2][0]) / 2.0;
let v = (q.uv[0][1] + q.uv[2][1]) / 2.0;
assert_ne!(tex[v as usize * TEXTURE + u as usize] >> 24, 0, "{}", c.id);
}
}
}
assert!(spec("cape.frost").is_none());
assert_eq!(number(catalog::by_id("hat.crown").unwrap()), Some(0));
assert_eq!(number(catalog::by_id("back.backpack").unwrap()), Some(9));
assert_eq!(number(catalog::by_id("cape.frost").unwrap()), None);
}
#[test]
fn boxes_have_six_faces_and_panels_two() {
let mut quads = Vec::new();
mesh(
"hat.beanie",
&spec("hat.beanie").unwrap(),
&State::default(),
&mut quads,
);
assert_eq!(quads.len(), 12);
mesh(
"back.bat_wings",
&spec("back.bat_wings").unwrap(),
&State::default(),
&mut quads,
);
assert_eq!(quads.len(), 4);
}
#[test]
fn a_cape_or_chestplate_moves_a_back_cosmetic_out() {
let spec = spec("back.angel_wings").unwrap();
let (mut plain, mut moved) = (Vec::new(), Vec::new());
mesh("back.angel_wings", &spec, &State::default(), &mut plain);
mesh(
"back.angel_wings",
&spec,
&State {
chest_armor: true,
..State::default()
},
&mut moved,
);
assert!((moved[0].pos[0][2] - plain[0].pos[0][2] - 1.0).abs() < 1e-5);
}
#[test]
fn rect_quads_keep_their_corners_turning() {
let spec = spec("hat.crown").unwrap();
let mut quads = Vec::new();
mesh("hat.crown", &spec, &State::default(), &mut quads);
for q in &quads {
let (pos, [u0, v0, u1, v1]) = quad_for_rect(q);
let uv = [[u0, v0], [u0, v1], [u1, v1], [u1, v0]];
// Each corner keeps its own texture position.
for (p, t) in pos.iter().zip(uv) {
let i = q.pos.iter().position(|o| o == p).unwrap();
assert_eq!(q.uv[i], t);
}
}
}
#[test]
fn affine_matches_the_rotation_order() {
let m = Affine::rotation_zyx(0.0, std::f32::consts::FRAC_PI_2, 0.0);
let p = m.apply([1.0, 0.0, 0.0]);
assert!((p[2] + 1.0).abs() < 1e-5, "y turns +x to -z: {p:?}");
let t = Affine::translation([1.0, 2.0, 3.0]).then(&Affine::scale([2.0; 3]));
assert_eq!(t.apply([1.0, 1.0, 1.0]), [3.0, 4.0, 5.0]);
}
}
@@ -0,0 +1,58 @@
//! Name tag cosmetics (ADR 0061; `NameTags.java`): the name over a player's head in a colour, or
//! fading from one colour to another across it. Only where the server leaves the name uncoloured:
//! a team's or a rank's colour means something in the game, and wins.
use super::art;
use super::catalog::Cosmetic;
/// The colours (RGB) of `style`: one for a plain colour, two for a fade.
pub fn colors(style: &Cosmetic) -> &'static [u32] {
match style.id {
"nametag.ice" => &[0xA9DCFF],
"nametag.gold" => &[0xFFD36A],
"nametag.mint" => &[0x8FE3B0],
"nametag.rose" => &[0xFF9BB8],
"nametag.violet" => &[0xC6A2FF],
"nametag.frost" => &[0xFFFFFF, 0x7FC8FF],
"nametag.sunset" => &[0xFFB36A, 0xFF6FA8],
"nametag.aurora" => &[0x6AF2B0, 0xA06CFF],
_ => &[0xFFFFFF],
}
}
/// The colour (RGB) of each character of `name` in `style`, in order. One run for a plain colour.
pub fn styled(name: &str, style: &Cosmetic) -> Vec<(String, u32)> {
let colors = colors(style);
let count = name.chars().count();
if colors.len() == 1 || count < 2 {
return vec![(name.to_owned(), colors[0])];
}
let last = (count - 1) as f32;
name.chars()
.enumerate()
.map(|(i, c)| {
(
c.to_string(),
art::mix(colors[0], colors[1], i as f32 / last),
)
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cosmetics::catalog::by_id;
#[test]
fn fades_run_from_the_first_colour_to_the_second() {
let fade = styled("Steve", by_id("nametag.sunset").unwrap());
assert_eq!(fade.len(), 5);
assert_eq!(fade[0], ("S".into(), 0xFFB36A));
assert_eq!(fade[4], ("e".into(), 0xFF6FA8));
assert_eq!(
styled("Steve", by_id("nametag.gold").unwrap()),
[("Steve".to_owned(), 0xFFD36A)]
);
assert_eq!(styled("A", by_id("nametag.aurora").unwrap()).len(), 1);
}
}
@@ -0,0 +1,564 @@
//! The player in 3D wearing a loadout (ADR 0061; `PlayerPreview.java`): the Wardrobe's preview,
//! and the title card's player while they wear something. The Java client draws it with the
//! game's player renderer; here it's drawn on the canvas as `player.rs` draws the title's player:
//! the skin on the model's boxes, the cape, the hat and back models (`models`), faces lit, sorted
//! back to front and projected. Dragged to turn; left alone, it turns to show what was picked last
//! (the back for a cape or wings, the front otherwise). Emotes play on it.
use super::catalog::{Cosmetic, Slot};
use super::loadout::Loadout;
use super::models::{self, Affine, Anchor, Look, Quad};
use super::{emotes, textures};
use crate::canvas::{Key, Region};
use crate::paint::Painter;
use crate::ui::Ui;
/// Blocks of height the preview's height holds: a player is 1.8, a halo or wings stand above.
const BLOCKS: f32 = 2.6;
/// Turned to show the front, a little from the side (degrees).
pub const FRONT: f32 = -28.0;
/// Turned to show the back: a cape, wings.
pub const BACK: f32 = 152.0;
/// The middle of what's shown, from the feet to a halo's top: 1.12 blocks up, in model pixels
/// (the feet are at y = 24, +y down).
const MIDDLE_Y: f32 = 24.0 - 1.12 * 16.0;
/// Looking down at the model a little (radians).
const TILT: f32 = 0.12;
/// After a drag, how long the preview stays where it was left before turning back.
const DRAG_HOLD_MS: f64 = 4_000.0;
/// A box of the player's skin: its part, corner, size, growth and texture position.
type SkinBox<'a> = (&'a Affine, [f32; 3], [i32; 3], f32, [i32; 2]);
/// What a face is painted from.
#[derive(Clone, Copy)]
enum Source {
Skin,
/// A cape's outer side (10x16), times a shade.
Cape(f32),
/// A hat's or back cosmetic's 64x64 texture; glowing.
Model(bool),
}
/// One face to draw: its corners on screen, its picture and how near it is.
struct Face {
corners: [[f32; 2]; 4],
src: [f32; 4],
depth: f32,
argb: u32,
}
/// A part's frame and the parts' poses, as the game's player model sets them up.
struct Rig {
head: Affine,
body: Affine,
right_arm: Affine,
left_arm: Affine,
right_leg: Affine,
left_leg: Affine,
}
pub struct PlayerPreview {
yaw: f32,
target: f32,
dragged_at: Option<f64>,
dragging: Option<f32>,
emote: Option<(&'static Cosmetic, f64)>,
quads: Vec<Quad>,
faces: Vec<Face>,
}
impl Default for PlayerPreview {
fn default() -> Self {
Self {
yaw: FRONT,
target: FRONT,
dragged_at: None,
dragging: None,
emote: None,
quads: Vec::new(),
faces: Vec::new(),
}
}
}
impl PlayerPreview {
/// Turns to show `slot` best: capes and wings from behind, the rest from the front.
pub fn show(&mut self, slot: Slot) {
self.target = if matches!(slot, Slot::Cape | Slot::Back) {
BACK
} else {
FRONT
};
self.dragged_at = None;
}
/// Stands turned as `show` would, without turning there.
pub fn face(&mut self, slot: Slot) {
self.show(slot);
self.yaw = self.target;
}
/// Plays `emote` now (`now_ms`, the painter's clock), from the front.
pub fn play(&mut self, emote: &'static Cosmetic, now_ms: f64) {
self.emote = Some((emote, now_ms));
self.target = FRONT;
self.dragged_at = None;
}
/// The emote playing, if any.
pub fn playing(&self) -> Option<&'static Cosmetic> {
self.emote.map(|e| e.0)
}
/// Draws the player wearing `loadout` in `rect`, turned by a drag inside it.
pub fn draw(&mut self, p: &mut Painter, ui: &mut Ui, rect: [f32; 4], loadout: Loadout) {
let now = p.motion.now;
if self.dragging.is_none() && ui.clicked(rect) {
self.dragging = Some(ui.mouse[0]);
self.dragged_at = Some(now);
}
if let Some(last) = self.dragging {
if ui.down {
self.yaw -= (ui.mouse[0] - last) * 2.5;
self.target = self.yaw;
self.dragging = Some(ui.mouse[0]);
self.dragged_at = Some(now);
} else {
self.dragging = None;
}
}
if self.dragged_at.is_none_or(|at| now - at > DRAG_HOLD_MS) {
self.yaw += (self.target - self.yaw) * 0.12;
}
let age = (now / 50.0) as f32;
let pose = match self.emote {
Some((e, start)) => {
let pose = emotes::pose(e.id, ((now - start) / 50.0) as f32);
if pose.is_none() {
self.emote = None;
}
pose
}
None => None,
};
self.render(p, rect, loadout, age, self.yaw.to_radians(), TILT, pose);
}
/// Draws the player standing still in `rect`, turned `yaw` degrees (the title card's: facing
/// the pointer as `player.rs` does).
pub fn draw_still(
&mut self,
p: &mut Painter,
rect: [f32; 4],
loadout: Loadout,
yaw: f32,
pitch: f32,
) {
let age = (p.motion.now / 50.0) as f32;
self.render(p, rect, loadout, age, yaw.to_radians(), pitch, None);
}
#[allow(clippy::too_many_arguments)]
fn render(
&mut self,
p: &mut Painter,
rect: [f32; 4],
loadout: Loadout,
age: f32,
yaw: f32,
tilt: f32,
pose: Option<emotes::Pose>,
) {
let Some((skin, slim)) = p.assets.skin.as_ref() else {
return;
};
let slim = *slim;
let Some(skin_region) = p.canvas.get(Key::Skin, || skin.clone()) else {
return;
};
let [x, y, w, h] = rect;
let unit = (h / (BLOCKS * 16.0)).min(w / (BLOCKS * 8.0));
let (cx, cy) = (x + w / 2.0, y + h / 2.0);
let view = Affine::rotation_x(tilt)
.then(&Affine::rotation_y(yaw))
.then(&Affine::translation([0.0, -MIDDLE_Y, 0.0]));
let rig = rig(age, slim, pose);
self.faces.clear();
let mut quads = std::mem::take(&mut self.quads);
// The player's own boxes, inner layers then outer.
let arm = if slim { 3 } else { 4 };
let right_x = if slim { -2.0 } else { -3.0 };
let boxes: [SkinBox; 12] = [
(&rig.head, [-4.0, -8.0, -4.0], [8, 8, 8], 0.0, [0, 0]),
(&rig.body, [-4.0, 0.0, -2.0], [8, 12, 4], 0.0, [16, 16]),
(
&rig.right_arm,
[right_x, -2.0, -2.0],
[arm, 12, 4],
0.0,
[40, 16],
),
(
&rig.left_arm,
[-1.0, -2.0, -2.0],
[arm, 12, 4],
0.0,
[32, 48],
),
(&rig.right_leg, [-2.0, 0.0, -2.0], [4, 12, 4], 0.0, [0, 16]),
(&rig.left_leg, [-2.0, 0.0, -2.0], [4, 12, 4], 0.0, [16, 48]),
(&rig.head, [-4.0, -8.0, -4.0], [8, 8, 8], 0.5, [32, 0]),
(&rig.body, [-4.0, 0.0, -2.0], [8, 12, 4], 0.25, [16, 32]),
(
&rig.right_arm,
[right_x, -2.0, -2.0],
[arm, 12, 4],
0.25,
[40, 32],
),
(
&rig.left_arm,
[-1.0, -2.0, -2.0],
[arm, 12, 4],
0.25,
[48, 48],
),
(&rig.right_leg, [-2.0, 0.0, -2.0], [4, 12, 4], 0.25, [0, 32]),
(&rig.left_leg, [-2.0, 0.0, -2.0], [4, 12, 4], 0.25, [0, 48]),
];
for (part, at, size, grow, tex) in boxes {
quads.clear();
models::box_quads(at, size, grow, tex, false, &view.then(part), &mut quads);
for q in &quads {
self.push(q, skin_region, Source::Skin, [cx, cy], unit, grow);
}
}
let backpack = loadout
.in_slot(Slot::Back)
.is_some_and(|b| b.id == "back.backpack");
// The cape hangs from the body's back, swung out a little (the preview's lean is 6).
let swing = (6.0f32 + 6.0 / 2.0).to_radians();
if let Some(cape) = loadout.in_slot(Slot::Cape).filter(|_| !backpack)
&& let Some(face) = textures::cape_face(p, cape)
{
let m = view
.then(&rig.body)
.then(&Affine::translation([0.0, 0.0, 2.0]))
.then(&Affine::rotation_x(swing));
for (q, shade) in cape_quads(&m) {
self.push(&q, face, Source::Cape(shade), [cx, cy], unit, 0.1);
}
}
let state = models::State {
age,
cape_swing: loadout
.in_slot(Slot::Cape)
.filter(|_| !backpack)
.map(|_| swing),
..models::State::default()
};
for cosmetic in [loadout.in_slot(Slot::Hat), loadout.in_slot(Slot::Back)]
.into_iter()
.flatten()
{
let (Some(spec), Some(region)) =
(models::spec(cosmetic.id), textures::model(p, cosmetic))
else {
continue;
};
models::mesh(cosmetic.id, &spec, &state, &mut quads);
let anchor = if spec.anchor == Anchor::Head {
&rig.head
} else {
&rig.body
};
let m = view.then(anchor);
let glow = spec.look == Look::Glow;
for q in &quads {
let q = Quad {
pos: q.pos.map(|c| m.apply(c)),
uv: q.uv,
};
self.push(&q, region, Source::Model(glow), [cx, cy], unit, 0.2);
}
}
self.quads = quads;
self.faces.sort_by(|a, b| b.depth.total_cmp(&a.depth));
for f in &self.faces {
let argb = p.faded(f.argb);
p.list.quad(
f.src,
f.corners.map(|c| {
let [gx, gy, _, _] = p.place(c[0], c[1], 0.0, 0.0);
[gx, gy]
}),
argb,
);
}
}
/// Projects a quad (view space, model pixels) and keeps it when it faces the viewer.
fn push(
&mut self,
q: &Quad,
region: Region,
source: Source,
[cx, cy]: [f32; 2],
unit: f32,
bias: f32,
) {
let [a, b, c] = [q.pos[0], q.pos[1], q.pos[2]];
let e1 = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
let e2 = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
let mut n = [
e1[1] * e2[2] - e1[2] * e2[1],
e1[2] * e2[0] - e1[0] * e2[2],
e1[0] * e2[1] - e1[1] * e2[0],
];
let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
if len < 1e-6 {
// A corner doubled: the other three.
return;
}
n = n.map(|v| v / len);
// The viewer is at -z: a face turned away isn't drawn.
if n[2] >= 0.0 {
return;
}
// Lit from above and in front, as the game's entity light falls.
let light = [0.3f32, -0.8, -0.6];
let lit = (n[0] * light[0] + n[1] * light[1] + n[2] * light[2]).max(0.0) / 1.044;
let (shade, glow) = match source {
Source::Skin => (1.0, false),
Source::Cape(s) => (s, false),
Source::Model(g) => (1.0, g),
};
let bright = if glow {
1.0
} else {
(0.55 + 0.45 * lit) * shade
};
let v = (bright.clamp(0.0, 1.0) * 255.0).round() as u32;
let argb = 0xFF00_0000 | v << 16 | v << 8 | v;
let (umin, umax) = (
q.uv.iter().map(|t| t[0]).fold(f32::MAX, f32::min),
q.uv.iter().map(|t| t[0]).fold(f32::MIN, f32::max),
);
let (vmin, vmax) = (
q.uv.iter().map(|t| t[1]).fold(f32::MAX, f32::min),
q.uv.iter().map(|t| t[1]).fold(f32::MIN, f32::max),
);
let project = |p: [f32; 3]| [cx + p[0] * unit, cy + p[1] * unit];
let mut corners = [[0.0; 2]; 4];
if umax - umin < 1e-4 || vmax - vmin < 1e-4 {
// A solid colour: one texel over the whole face, corners as they come.
for (i, p) in q.pos.iter().enumerate() {
corners[i] = project(*p);
}
} else {
// The canvas draws a rectangle of its pixels onto four corners: top left, top right,
// bottom right, bottom left of the rectangle, whichever corners of the quad they are.
for (p, t) in q.pos.iter().zip(q.uv) {
let right = (t[0] - umax).abs() < (t[0] - umin).abs();
let bottom = (t[1] - vmax).abs() < (t[1] - vmin).abs();
let i = match (right, bottom) {
(false, false) => 0,
(true, false) => 1,
(true, true) => 2,
(false, true) => 3,
};
corners[i] = project(*p);
}
}
let depth = q.pos.iter().map(|p| p[2]).sum::<f32>() / 4.0 - bias;
let src = region.part(umin, vmin, (umax - umin).max(1.0), (vmax - vmin).max(1.0));
self.faces.push(Face {
corners,
src,
depth,
argb,
});
}
}
thread_local! {
/// The title card's player while they wear something.
static TITLE: std::cell::RefCell<PlayerPreview> = std::cell::RefCell::new(PlayerPreview::default());
}
/// The title card's player in `rect` (`TitleProfile.playerView`): wearing what the player wears
/// while they wear anything (`Cosmetics.wearsAny`), else `player::draw`'s. Turned toward the
/// pointer as the inventory's player is.
pub fn draw_title(cx: &mut crate::screen::Cx, rect: [f32; 4]) {
super::wardrobe::load_and_save(cx.host);
let worn = super::wardrobe::with(|w| w.worn());
let mouse = cx.ui.mouse;
if worn.is_empty() {
crate::player::draw(cx.p, rect, mouse);
return;
}
let [x, y, w, h] = rect;
let ax = ((x + w / 2.0 - mouse[0]) / 40.0).atan();
let ay = ((y + h * 0.15 - mouse[1]) / 40.0).atan();
// The model's 2.6 blocks hold a halo and wings: a little larger box than `player::draw`'s.
let grown = [x - w * 0.2, y - h * 0.22, w * 1.4, h * 1.3];
TITLE.with(|t| {
t.borrow_mut()
.draw_still(cx.p, grown, worn, -ax * 20.0, TILT + ay * 0.2)
});
}
/// The game's player model posed standing at `age` (`AnimationUtils.bobArms`), with an emote's
/// pose over it. Model pixels, +y down, the feet at y = 24.
fn rig(age: f32, slim: bool, pose: Option<emotes::Pose>) -> Rig {
let part = |at: [f32; 3], r: [f32; 3]| {
Affine::translation(at).then(&Affine::rotation_zyx(r[0], r[1], r[2]))
};
let bob_z = (age * 0.09).cos() * 0.05 + 0.05;
let bob_x = (age * 0.067).sin() * 0.05;
let (w, head, right, left) = match pose {
Some(p) => (p.weight, p.head, p.right_arm, p.left_arm),
None => (0.0, None, None, None),
};
let head = emotes::Pose::blend(w, [0.0; 3], head);
let right = emotes::Pose::blend(w, [bob_x, 0.0, bob_z], right);
let left = emotes::Pose::blend(w, [-bob_x, 0.0, -bob_z], left);
let arm_y = if slim { 2.5 } else { 2.0 };
Rig {
head: part([0.0; 3], head),
body: Affine::IDENTITY,
right_arm: part([-5.0, arm_y, 0.0], right),
left_arm: part([5.0, arm_y, 0.0], left),
right_leg: part([-1.9, 12.0, 0.0], [0.0; 3]),
left_leg: part([1.9, 12.0, 0.0], [0.0; 3]),
}
}
/// The cape as a box from its top edge (10 across, 16 down, 1 thick) under `m`: its outer side
/// from the cape's face, the inner side the same in shade, the edges the face's middle colour.
fn cape_quads(m: &Affine) -> Vec<(Quad, f32)> {
let p = |x: f32, y: f32, z: f32| m.apply([x, y, z]);
let face = |a, b, c, d, uv: [[f32; 2]; 4], shade: f32| {
(
Quad {
pos: [a, b, c, d],
uv,
},
shade,
)
};
// Both sides show the design's left at the player's left (+x), as the game's cape does.
let middle = [[5.0, 8.0]; 4];
vec![
// Outer, facing away from the player (+z).
face(
p(-5.0, 0.0, 1.0),
p(5.0, 0.0, 1.0),
p(5.0, 16.0, 1.0),
p(-5.0, 16.0, 1.0),
[[10.0, 0.0], [0.0, 0.0], [0.0, 16.0], [10.0, 16.0]],
1.0,
),
// Inner, facing the player's back.
face(
p(5.0, 0.0, 0.0),
p(-5.0, 0.0, 0.0),
p(-5.0, 16.0, 0.0),
p(5.0, 16.0, 0.0),
[[0.0, 0.0], [10.0, 0.0], [10.0, 16.0], [0.0, 16.0]],
0.55,
),
// The edges: the sides, the bottom and the top.
face(
p(5.0, 0.0, 0.0),
p(5.0, 16.0, 0.0),
p(5.0, 16.0, 1.0),
p(5.0, 0.0, 1.0),
middle,
0.7,
),
face(
p(-5.0, 0.0, 0.0),
p(-5.0, 0.0, 1.0),
p(-5.0, 16.0, 1.0),
p(-5.0, 16.0, 0.0),
middle,
0.7,
),
face(
p(-5.0, 16.0, 0.0),
p(-5.0, 16.0, 1.0),
p(5.0, 16.0, 1.0),
p(5.0, 16.0, 0.0),
middle,
0.7,
),
face(
p(-5.0, 0.0, 0.0),
p(5.0, 0.0, 0.0),
p(5.0, 0.0, 1.0),
p(-5.0, 0.0, 1.0),
middle,
0.7,
),
]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn showing_a_cape_turns_to_the_back() {
let mut preview = PlayerPreview::default();
preview.face(Slot::Cape);
assert_eq!(preview.yaw, BACK);
preview.show(Slot::Hat);
assert_eq!(preview.target, FRONT);
assert_eq!(preview.yaw, BACK, "turns there as it's drawn");
}
#[test]
fn the_capes_faces_turn_outward() {
for (q, _) in cape_quads(&Affine::IDENTITY) {
let [a, b, c] = [q.pos[0], q.pos[1], q.pos[2]];
let e1 = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
let e2 = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
let n = [
e1[1] * e2[2] - e1[2] * e2[1],
e1[2] * e2[0] - e1[0] * e2[2],
e1[0] * e2[1] - e1[1] * e2[0],
];
let centre = q.pos.iter().fold([0.0f32; 3], |s, p| {
[s[0] + p[0] / 4.0, s[1] + p[1] / 4.0, s[2] + p[2] / 4.0]
});
let out = [centre[0], centre[1] - 8.0, centre[2] - 0.5];
assert!(
n[0] * out[0] + n[1] * out[1] + n[2] * out[2] > 0.0,
"{:?}",
q.pos
);
}
}
#[test]
fn the_players_boxes_face_out() {
// The head's front (the game's north face) faces the viewer at -z.
let mut quads = Vec::new();
models::box_quads(
[-4.0, -8.0, -4.0],
[8, 8, 8],
0.0,
[0, 0],
false,
&Affine::IDENTITY,
&mut quads,
);
let front = &quads[3];
assert!(front.pos.iter().all(|p| p[2] == -4.0));
assert_eq!(front.uv[1], [8.0, 8.0], "the face's texture");
}
}
@@ -0,0 +1,126 @@
//! The cosmetics' pictures on the client's canvas (`CosmeticTextures.java`'s GUI half): a cape's
//! outer side, a hat's or back cosmetic's card icon, and a model's texture for the Wardrobe's
//! preview, painted by `art` and `models` the first time each is drawn. A moving cape is painted
//! again ten times a second while it's drawn, and costs nothing once it isn't.
//!
//! The world's textures are the game side's (`rust/mods/cosmetics`): painted from the same
//! functions into the fork's entity canvas.
use super::catalog::{self, Cosmetic};
use super::{art, models};
use crate::canvas::{Image, Key, Region};
use crate::paint::Painter;
use std::cell::RefCell;
/// Canvas picture ids of the cosmetics' images, clear of the screenshots' (counted from 1).
const CAPE_FACE: u32 = 0xC05_0000;
const ICON: u32 = 0xC05_1000;
const MODEL: u32 = 0xC05_2000;
/// A moving cape's frames a second.
pub const CAPE_FPS: f64 = 10.0;
thread_local! {
/// Each moving cape's frame on the canvas, so the one before is let go.
static FRAMES: RefCell<Vec<(usize, u16)>> = const { RefCell::new(Vec::new()) };
}
fn image(width: usize, height: usize, pixels: &[u32]) -> Image {
Image {
width: width as u32,
height: height as u32,
rgba: art::rgba(pixels),
}
}
/// The frame a moving cape shows at `now_ms`; 0 for one that doesn't move.
pub fn cape_frame(cape: &Cosmetic, now_ms: f64) -> u16 {
if art::animated(cape.id) {
// 1 up: frame 0 is a still cape's.
((now_ms / 1000.0 * CAPE_FPS) as u64 % u64::from(u16::MAX - 1)) as u16 + 1
} else {
0
}
}
/// Where the cape's outer side (10x16) is on the canvas, painted for `p`'s clock.
pub fn cape_face(p: &mut Painter, cape: &Cosmetic) -> Option<Region> {
let index = catalog::index(cape);
let frame = cape_frame(cape, p.motion.now);
let key = Key::Picture(CAPE_FACE + index as u32, frame);
if frame != 0 && !p.canvas.has(key) {
// The last frame's pixels are let go (they stay unused until the canvas starts over).
FRAMES.with(|f| {
let mut f = f.borrow_mut();
match f.iter_mut().find(|(i, _)| *i == index) {
Some((_, last)) => {
p.canvas
.forget(Key::Picture(CAPE_FACE + index as u32, *last));
*last = frame;
}
None => f.push((index, frame)),
}
});
}
let t = (p.motion.now / 1000.0) as f32;
p.canvas.get(key, || {
let mut px = [0u32; 160];
art::cape_face(cape.id, t, &mut px);
image(10, 16, &px)
})
}
/// Where a hat's or back cosmetic's card icon (24 square) is on the canvas.
pub fn icon(p: &mut Painter, cosmetic: &Cosmetic) -> Option<Region> {
let key = Key::Picture(ICON + catalog::index(cosmetic) as u32, art::ICON as u16);
p.canvas.get(key, || {
let mut px = vec![0u32; art::ICON * art::ICON];
art::icon(cosmetic.id, &mut px);
image(art::ICON, art::ICON, &px)
})
}
/// Where a model's 64x64 texture is on the canvas (a hat or back cosmetic; None for the rest).
pub fn model(p: &mut Painter, cosmetic: &Cosmetic) -> Option<Region> {
let spec = models::spec(cosmetic.id)?;
let key = Key::Picture(
MODEL + catalog::index(cosmetic) as u32,
models::TEXTURE as u16,
);
p.canvas.get(key, || {
let mut px = vec![0u32; models::TEXTURE * models::TEXTURE];
models::texture(cosmetic.id, &spec, &mut px);
image(models::TEXTURE, models::TEXTURE, &px)
})
}
/// Draws the cape's outer side as it hangs over `[x, y, w, h]`.
pub fn draw_cape(p: &mut Painter, cape: &Cosmetic, rect: [f32; 4]) {
if let Some(r) = cape_face(p, cape) {
let argb = p.faded(0xFFFF_FFFF);
let dst = p.place(rect[0], rect[1], rect[2], rect[3]);
p.list.image(r.src(), dst, argb);
}
}
/// Draws a hat's or back cosmetic's icon over `[x, y, size, size]`.
pub fn draw_icon(p: &mut Painter, cosmetic: &Cosmetic, x: f32, y: f32, size: f32) {
if let Some(r) = icon(p, cosmetic) {
let argb = p.faded(0xFFFF_FFFF);
let dst = p.place(x, y, size, size);
p.list.image(r.src(), dst, argb);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn still_capes_keep_one_frame_and_moving_ones_ten_a_second() {
let frost = catalog::by_id("cape.frost").unwrap();
let tide = catalog::by_id("cape.tide").unwrap();
assert_eq!(cape_frame(frost, 12_345.0), 0);
assert_ne!(cape_frame(tide, 0.0), cape_frame(tide, 100.0));
assert_eq!(cape_frame(tide, 0.0), cape_frame(tide, 99.0));
}
}
@@ -0,0 +1,601 @@
//! The player's own cosmetics (ADR 0061; `:online`'s `Wardrobe`): what they wear, what they own,
//! their saved outfits, and whether they see other players' cosmetics. Kept on this device in
//! `online/wardrobe.json` under `incari/` (the Java client's file, same keys), so what's worn
//! shows at once and without an account; while signed in, the account's wardrobe on the service
//! is the truth and this follows it.
//!
//! Changes apply here at once, so the Wardrobe never waits on the service; `sync`, once a frame,
//! sends `equip` at most once a second (the Java `OnlineService` tick's part).
//!
//! No files here: `load` takes the file's text and `take_unsaved` hands the text to write.
use super::catalog::{self, Cosmetic, Slot};
use super::loadout::Loadout;
use crate::online::{Failure, Online, Outcome, Status, Ticket};
use serde_json::{Value, json};
use std::cell::RefCell;
use std::collections::HashSet;
/// The file, under the game folder's `incari/`.
pub const FILE: &str = "online/wardrobe.json";
/// The most outfits kept.
pub const MAX_OUTFITS: usize = 12;
/// The longest outfit name.
pub const MAX_OUTFIT_NAME: usize = 24;
/// At least this long between two `equip`s: the wardrobe's clicks are gathered into one.
pub const EQUIP_INTERVAL_MILLIS: f64 = 1_000.0;
/// A loadout the player saved under a name, to put on again in one click.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Outfit {
pub name: String,
pub loadout: Loadout,
}
/// What `sync` needs of the online service (`Online`; a stand-in in the tests).
pub trait Service {
fn status(&self) -> Status;
fn greeted(&self) -> bool;
/// The account's name, kept while reconnecting; None once signed out.
fn account_name(&self) -> Option<&str>;
/// (owned, equipped) as the service last said.
fn wardrobe(&self) -> Option<&(Vec<String>, Vec<String>)>;
fn wardrobe_serial(&self) -> u64;
fn equip(&mut self, ids: &[String]) -> Ticket;
fn take_result(&mut self, ticket: Ticket) -> Option<Outcome>;
}
impl Service for Online {
fn status(&self) -> Status {
Online::status(self)
}
fn greeted(&self) -> bool {
Online::greeted(self)
}
fn account_name(&self) -> Option<&str> {
Online::account_name(self)
}
fn wardrobe(&self) -> Option<&(Vec<String>, Vec<String>)> {
Online::wardrobe(self)
}
fn wardrobe_serial(&self) -> u64 {
Online::wardrobe_serial(self)
}
fn equip(&mut self, ids: &[String]) -> Ticket {
Online::equip(self, ids)
}
fn take_result(&mut self, ticket: Ticket) -> Option<Outcome> {
Online::take_result(self, ticket)
}
}
#[derive(Debug)]
pub struct Wardrobe {
loaded: bool,
worn: Loadout,
/// The non-free cosmetics the account owns, as the service last said.
owned: HashSet<String>,
outfits: Vec<Outfit>,
show_others: bool,
/// The account's wardrobe arrived on this connection: what's worn is then the account's.
synced: bool,
/// It arrived at all since signing in (a reconnect keeps changes made while away).
account_seen: bool,
/// What's worn changed here and the service hasn't heard yet.
unsent: bool,
revision: u64,
/// Changed since the file was last handed out.
dirty: bool,
// The service's side.
serial: u64,
last_status: Status,
equipping: Option<(Ticket, Loadout)>,
next_equip: f64,
}
impl Default for Wardrobe {
fn default() -> Self {
Self {
loaded: false,
worn: Loadout::EMPTY,
owned: HashSet::new(),
outfits: Vec::new(),
show_others: true,
synced: false,
account_seen: false,
unsent: false,
revision: 0,
dirty: false,
serial: 0,
last_status: Status::Off,
equipping: None,
next_equip: 0.0,
}
}
}
impl Wardrobe {
// ---------------------------------------------------------------------------------------------
// What the screens read
// ---------------------------------------------------------------------------------------------
/// What the player wears now.
pub fn worn(&self) -> Loadout {
self.worn
}
/// Whether the player may wear (or play) `cosmetic`.
pub fn owns(&self, cosmetic: &Cosmetic) -> bool {
cosmetic.free || self.owned.contains(cosmetic.id)
}
/// The emotes the player owns, in the catalog's order: the emote wheel's.
pub fn emotes(&self) -> Vec<&'static Cosmetic> {
catalog::in_slot(Slot::Emote)
.filter(|c| self.owns(c))
.collect()
}
/// The saved outfits, oldest first.
pub fn outfits(&self) -> &[Outfit] {
&self.outfits
}
/// Whether other players' cosmetics are drawn (the player may find them distracting).
pub fn show_others(&self) -> bool {
self.show_others
}
/// Whether other Incari players see what's worn: signed in, with the account's wardrobe here.
pub fn shared(&self) -> bool {
self.synced
}
/// Goes up whenever anything here changes.
pub fn revision(&self) -> u64 {
self.revision
}
// ---------------------------------------------------------------------------------------------
// What the screens change
// ---------------------------------------------------------------------------------------------
/// Puts `cosmetic` on, in place of what was in its slot. Ignored for one not owned.
pub fn wear(&mut self, cosmetic: &'static Cosmetic) {
if self.owns(cosmetic) && cosmetic.slot.worn() {
self.change(self.worn.with(cosmetic));
}
}
/// Takes off what's worn in `slot`.
pub fn take_off(&mut self, slot: Slot) {
self.change(self.worn.without(slot));
}
/// Puts on `loadout` whole (an outfit, or nothing), leaving out what isn't owned.
pub fn wear_all(&mut self, loadout: Loadout) {
let owned = self.owned_filter(loadout);
self.change(owned);
}
/// Saves what's worn as an outfit called `name` (cut to `MAX_OUTFIT_NAME`), replacing one of
/// the same name. False if there's no room for another.
pub fn save_outfit(&mut self, name: &str) -> bool {
let mut trimmed: String = name.trim().chars().take(MAX_OUTFIT_NAME).collect();
if trimmed.is_empty() {
trimmed = format!("Outfit {}", self.outfits.len() + 1);
}
let worn = self.worn;
if let Some(o) = self
.outfits
.iter_mut()
.find(|o| o.name.to_lowercase() == trimmed.to_lowercase())
{
*o = Outfit {
name: trimmed,
loadout: worn,
};
self.saved();
return true;
}
if self.outfits.len() >= MAX_OUTFITS {
return false;
}
self.outfits.push(Outfit {
name: trimmed,
loadout: worn,
});
self.saved();
true
}
/// Forgets the outfit at `index`.
pub fn delete_outfit(&mut self, index: usize) {
if index < self.outfits.len() {
self.outfits.remove(index);
self.saved();
}
}
/// Draws other players' cosmetics, or not.
pub fn set_show_others(&mut self, show: bool) {
if show != self.show_others {
self.show_others = show;
self.saved();
}
}
fn owned_filter(&self, loadout: Loadout) -> Loadout {
loadout.owned_by(|c| c.free || self.owned.contains(c.id))
}
fn change(&mut self, next: Loadout) {
if next == self.worn {
return;
}
self.worn = next;
self.unsent = true;
self.saved();
}
// ---------------------------------------------------------------------------------------------
// The service's side
// ---------------------------------------------------------------------------------------------
/// The account's wardrobe arrived. On signing in, what the account wears replaces what's worn
/// here, unless the account wears nothing yet and this device does: then the device's is kept
/// and sent, so what a player picked before making an account carries over. Later (a
/// reconnect, or another session's change), a change made here and not yet sent wins. True
/// when what's worn here should be sent.
pub fn from_account(&mut self, owned: &[String], equipped: Loadout) -> bool {
self.owned = owned.iter().cloned().collect();
let keep = if self.account_seen {
self.unsent
} else {
equipped.is_empty() && !self.worn.is_empty()
};
self.synced = true;
self.account_seen = true;
self.worn = if keep {
self.owned_filter(self.worn)
} else {
self.owned_filter(equipped)
};
self.unsent = keep;
self.saved();
self.unsent
}
/// The service took what was sent; `equipped` is what it keeps.
pub fn sent(&mut self, sent: Loadout, equipped: Loadout) {
if self.worn == sent {
self.unsent = false;
if equipped != self.worn {
self.worn = self.owned_filter(equipped);
self.saved();
}
}
}
/// What's worn here, if the service hasn't heard of it yet and is to.
pub fn unsent(&self) -> Option<Loadout> {
(self.synced && self.unsent).then_some(self.worn)
}
/// Signed out: the device keeps what was worn, less what only the account owned.
pub fn signed_out(&mut self) {
self.synced = false;
self.account_seen = false;
self.unsent = false;
self.owned.clear();
self.worn = self.owned_filter(self.worn);
self.saved();
}
/// The connection dropped: the account's wardrobe is asked for again when it's back.
pub fn disconnected(&mut self) {
if self.synced {
self.synced = false;
self.revision += 1;
}
}
/// Once a frame, after the service's tick: the account's wardrobe taken when it arrives,
/// sign-outs and dropped connections noticed, and what's worn sent (at most once a second).
pub fn sync(&mut self, service: &mut dyn Service, now: f64) {
let status = service.status();
if self.last_status == Status::SignedIn && status != Status::SignedIn {
if service.account_name().is_none() {
self.signed_out();
} else {
self.disconnected();
}
// An answer to an equip on the old connection is never coming.
self.equipping = None;
}
self.last_status = status;
if let Some((ticket, loadout)) = self.equipping
&& let Some(outcome) = service.take_result(ticket)
{
self.equipping = None;
match outcome {
Ok(_) => {
let equipped = service.wardrobe().map_or(loadout, |w| Loadout::of(&w.1));
self.sent(loadout, equipped);
}
// The service and this client disagree on what's owned: it sends its wardrobe again.
Err(Failure::Rejected) => self.sent(loadout, loadout),
// Offline or limited: still unsent, so it goes again later.
Err(_) => {}
}
}
let serial = service.wardrobe_serial();
if serial != self.serial {
self.serial = serial;
if status == Status::SignedIn
&& let Some((owned, equipped)) = service.wardrobe().cloned()
{
self.from_account(&owned, Loadout::of(&equipped));
}
}
if status == Status::SignedIn
&& service.greeted()
&& self.equipping.is_none()
&& now >= self.next_equip
&& let Some(loadout) = self.unsent()
{
self.next_equip = now + EQUIP_INTERVAL_MILLIS;
let ticket = service.equip(&loadout.ids());
self.equipping = Some((ticket, loadout));
}
}
// ---------------------------------------------------------------------------------------------
// The file
// ---------------------------------------------------------------------------------------------
/// Whether `load` was called.
pub fn loaded(&self) -> bool {
self.loaded
}
/// Reads `wardrobe.json`'s text (None: no file). A broken file costs the player their
/// outfits, not their game.
pub fn load(&mut self, text: Option<&str>) {
self.loaded = true;
let Some(json) = text.and_then(|t| serde_json::from_str::<Value>(t).ok()) else {
return;
};
let strings = |v: &Value, key: &str| -> Vec<String> {
v.get(key)
.and_then(Value::as_array)
.map(|a| {
a.iter()
.filter_map(|e| match e {
Value::String(s) => Some(s.clone()),
Value::Number(n) => Some(n.to_string()),
Value::Bool(b) => Some(b.to_string()),
_ => None,
})
.collect()
})
.unwrap_or_default()
};
self.owned = strings(&json, "owned").into_iter().collect();
self.worn = self.owned_filter(Loadout::of(&strings(&json, "worn")));
if let Some(list) = json.get("outfits").and_then(Value::as_array) {
for each in list {
if self.outfits.len() >= MAX_OUTFITS {
break;
}
if let Some(name) = each.get("name").and_then(Value::as_str) {
self.outfits.push(Outfit {
name: name.to_owned(),
loadout: Loadout::of(&strings(each, "worn")),
});
}
}
}
if let Some(show) = json.get("showOthers").and_then(Value::as_bool) {
self.show_others = show;
}
self.revision += 1;
}
/// The file's text as Java writes it.
pub fn file_text(&self) -> String {
let mut owned: Vec<&String> = self.owned.iter().collect();
owned.sort();
let outfits: Vec<Value> = self
.outfits
.iter()
.map(|o| json!({"name": o.name, "worn": o.loadout.ids()}))
.collect();
json!({"worn": self.worn.ids(), "owned": owned, "outfits": outfits, "showOthers": self.show_others})
.to_string()
}
/// The file's text, when it changed since the last call: the caller writes it to `FILE`.
pub fn take_unsaved(&mut self) -> Option<String> {
std::mem::take(&mut self.dirty).then(|| self.file_text())
}
fn saved(&mut self) {
self.revision += 1;
self.dirty = true;
}
}
thread_local! {
// The window's thread only, as the online service.
static WARDROBE: RefCell<Wardrobe> = RefCell::new(Wardrobe::default());
}
/// Runs `f` with the player's wardrobe (one for the window's thread, as `online::with`).
pub fn with<R>(f: impl FnOnce(&mut Wardrobe) -> R) -> R {
WARDROBE.with(|w| f(&mut w.borrow_mut()))
}
/// Reads the file through `read` the first time: whoever draws first (a screen with its `Host`,
/// or the game side) loads it.
pub fn ensure_loaded(read: impl FnOnce() -> Option<Vec<u8>>) {
with(|w| {
if !w.loaded() {
let text = read().and_then(|b| String::from_utf8(b).ok());
w.load(text.as_deref());
}
});
}
/// For a screen: the file read once through `host`, and written when it changed.
pub fn load_and_save(host: &mut dyn crate::screen::Host) {
ensure_loaded(|| host.read(FILE));
if let Some(text) = with(Wardrobe::take_unsaved) {
host.write(FILE, text.as_bytes());
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::online::Answer;
fn c(id: &str) -> &'static Cosmetic {
catalog::by_id(id).unwrap()
}
#[test]
fn the_file_reads_back_as_written() {
let mut w = Wardrobe::default();
w.load(None);
w.wear(c("cape.ember"));
w.wear(c("hat.halo"));
assert!(w.save_outfit(" Party "));
w.set_show_others(false);
let text = w.take_unsaved().expect("changed");
assert!(w.take_unsaved().is_none());
let mut back = Wardrobe::default();
back.load(Some(&text));
assert_eq!(back.worn(), w.worn());
assert_eq!(back.outfits(), w.outfits());
assert_eq!(back.outfits()[0].name, "Party");
assert!(!back.show_others());
let mut broken = Wardrobe::default();
broken.load(Some("{not json"));
assert!(broken.worn().is_empty() && broken.show_others());
}
#[test]
fn outfits_replace_by_name_and_stop_at_twelve() {
let mut w = Wardrobe::default();
for i in 0..MAX_OUTFITS {
assert!(w.save_outfit(&format!("o{i}")));
}
assert!(!w.save_outfit("more"));
w.wear(c("cape.mono"));
assert!(w.save_outfit("O3"), "same name, any case: replaced");
assert_eq!(w.outfits()[3].loadout.ids(), ["cape.mono"]);
w.delete_outfit(0);
assert!(w.save_outfit(""));
assert_eq!(w.outfits().last().unwrap().name, "Outfit 12");
assert!(!w.save_outfit(&"x".repeat(40)), "full again");
w.delete_outfit(0);
assert!(w.save_outfit(&"x".repeat(40)));
assert_eq!(w.outfits().last().unwrap().name.len(), MAX_OUTFIT_NAME);
}
#[test]
fn the_account_wins_unless_it_wears_nothing() {
let mut w = Wardrobe::default();
w.wear(c("cape.frost"));
assert!(
w.from_account(&[], Loadout::EMPTY),
"the device's carries over"
);
assert_eq!(w.unsent(), Some(w.worn()));
w.sent(w.worn(), w.worn());
assert_eq!(w.unsent(), None);
w.signed_out();
assert!(
!w.from_account(&[], Loadout::of(&["hat.crown"])),
"a new sign-in: the account's"
);
assert_eq!(w.worn().ids(), ["hat.crown"]);
// A reconnect: a change made while away wins.
w.disconnected();
w.wear(c("hat.beanie"));
assert!(w.from_account(&[], Loadout::of(&["hat.crown"])));
assert_eq!(w.worn().ids(), ["hat.beanie"]);
}
/// A service that answers what the test says.
#[derive(Default)]
struct Stub {
status: Option<Status>,
name: Option<String>,
wardrobe: Option<(Vec<String>, Vec<String>)>,
serial: u64,
sent: Vec<Vec<String>>,
results: Vec<(Ticket, Outcome)>,
}
impl Service for Stub {
fn status(&self) -> Status {
self.status.unwrap_or(Status::SignedOut)
}
fn greeted(&self) -> bool {
true
}
fn account_name(&self) -> Option<&str> {
self.name.as_deref()
}
fn wardrobe(&self) -> Option<&(Vec<String>, Vec<String>)> {
self.wardrobe.as_ref()
}
fn wardrobe_serial(&self) -> u64 {
self.serial
}
fn equip(&mut self, ids: &[String]) -> Ticket {
self.sent.push(ids.to_vec());
self.sent.len() as Ticket
}
fn take_result(&mut self, ticket: Ticket) -> Option<Outcome> {
let i = self.results.iter().position(|r| r.0 == ticket)?;
Some(self.results.remove(i).1)
}
}
#[test]
fn sync_sends_once_a_second_and_follows_sign_outs() {
let mut w = Wardrobe::default();
let mut s = Stub {
status: Some(Status::SignedIn),
name: Some("me".into()),
..Default::default()
};
w.wear(c("cape.tide"));
s.wardrobe = Some((vec![], vec![]));
s.serial = 1;
w.sync(&mut s, 0.0);
assert!(w.shared());
assert_eq!(
s.sent,
[vec!["cape.tide".to_owned()]],
"the device's carried over"
);
w.wear(c("cape.mono"));
w.sync(&mut s, 100.0);
assert_eq!(s.sent.len(), 1, "one at a time");
s.wardrobe = Some((vec![], vec!["cape.tide".into()]));
s.results.push((1, Ok(Answer::Done)));
w.sync(&mut s, 500.0);
assert_eq!(s.sent.len(), 1, "a second apart");
w.sync(&mut s, 1_000.0);
assert_eq!(s.sent.last().unwrap(), &vec!["cape.mono".to_owned()]);
// Signed out elsewhere: device-only again, what's worn kept.
s.status = Some(Status::SignedOut);
s.name = None;
w.sync(&mut s, 2_000.0);
assert!(!w.shared());
assert_eq!(w.worn().ids(), ["cape.mono"]);
}
}
@@ -0,0 +1,414 @@
//! Cosmetics in the world (ADR 0061; `Cosmetics.java`), with no game types: what each player
//! shows (their `Worn`), the emotes playing and when they end, the camera turned for the player's
//! own emote, and the trails' particles. The game side asks once a frame per player drawn
//! (`worn_by`), once a tick (`tick`), and plays the wheel's emote (`play_own`).
//!
//! Others' cosmetics show only for Incari players the service named, and only while the Wardrobe's
//! "Show others' cosmetics" is on. Window's thread; per player per frame nothing is made unless
//! what someone wears changed.
use super::catalog::{self, Cosmetic};
use super::emotes;
use super::loadout::Loadout;
use std::cell::RefCell;
use std::collections::HashMap;
/// Trails are left only by players this near (blocks).
pub const TRAIL_DISTANCE: f64 = 32.0;
/// At most this many trail particles a tick, however many players are about.
pub const TRAIL_BUDGET: u32 = 12;
/// Past this, worn models aren't drawn (blocks): a hat is a pixel or two.
pub const MAX_DISTANCE: f64 = 48.0;
/// Another player walking faster than this (`walkAnimation.speed`) cuts their emote short.
pub const WALK_ENDS_EMOTE: f32 = 0.35;
/// The camera views (`native_camera_type`): first person, behind, in front.
pub const FIRST_PERSON: u8 = 0;
pub const THIRD_PERSON_FRONT: u8 = 2;
/// What one player shows: what they wear, and the emote they're playing.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Worn {
pub loadout: Loadout,
pub emote: Option<&'static Cosmetic>,
/// When the emote started, in client ticks (`World::now`'s clock).
pub emote_start: f32,
}
impl Worn {
pub const NONE: Worn = Worn {
loadout: Loadout::EMPTY,
emote: None,
emote_start: 0.0,
};
pub fn is_empty(&self) -> bool {
self.loadout.is_empty() && self.emote.is_none()
}
/// The emote's pose at client time `now` (ticks, the partial tick added).
pub fn pose(&self, now: f32) -> Option<emotes::Pose> {
emotes::pose(self.emote?.id, now - self.emote_start)
}
}
/// An emote playing: which, and the client ticks it started and ends on.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Play {
emote: &'static Cosmetic,
start: u64,
ends_at: u64,
}
/// A trail particle: its type, where from the player's feet, and its speed.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Particle {
pub kind: &'static str,
pub offset: [f64; 3],
pub velocity: [f64; 3],
}
#[derive(Default)]
pub struct World {
ticks: u64,
plays: HashMap<u128, Play>,
/// Others' cosmetic ids as last seen, what they came to, and the tick they were last drawn.
others: HashMap<u128, (Vec<String>, Loadout, u64)>,
/// The camera to go back to once the player's own emote ends.
camera_before: Option<u8>,
own: Option<u128>,
trails_left: u32,
random: u64,
/// The emote the wheel chose, for the game side to play on its next tick.
pending_own: Option<&'static Cosmetic>,
}
impl World {
/// Client ticks since the game started.
pub fn ticks(&self) -> u64 {
self.ticks
}
/// The clock emotes are timed by: client ticks, the frame's partial tick added.
pub fn now(&self, partial: f32) -> f32 {
self.ticks as f32 + partial
}
/// What player `id` shows. `local`: the window's own player, who wears `own`. `incari`: the ids
/// the service says they wear, when they're an Incari player.
pub fn worn_by(
&mut self,
id: u128,
local: bool,
own: Loadout,
incari: Option<&[String]>,
show_others: bool,
) -> Worn {
let play = self.plays.get(&id).copied();
let worn = |loadout: Loadout| Worn {
loadout,
emote: play.map(|p| p.emote),
emote_start: play.map_or(0.0, |p| p.start as f32),
};
if local {
self.own = Some(id);
return worn(own);
}
if !show_others || (incari.is_none() && play.is_none()) {
return Worn::NONE;
}
let source = incari.unwrap_or(&[]);
let ticks = self.ticks;
let loadout = match self.others.get_mut(&id) {
Some((seen, loadout, drawn)) if seen.as_slice() == source => {
*drawn = ticks;
*loadout
}
_ => {
if self.others.len() > 512 {
self.others.clear();
}
let loadout = Loadout::of(source);
self.others.insert(id, (source.to_vec(), loadout, ticks));
loadout
}
};
worn(loadout)
}
/// Another player `id` was seen walking at `speed` (`walkAnimation.speed`): moving cuts their
/// emote short.
pub fn walking(&mut self, id: u128, speed: f32) {
if speed > WALK_ENDS_EMOTE && Some(id) != self.own {
self.plays.remove(&id);
}
}
/// The player `own` plays `emote` (the emote wheel, after the service took it): the camera
/// turns to face them while it plays. Returns the view to set, if it changes (`camera` is the
/// view now).
pub fn play_own(&mut self, own: u128, emote: &'static Cosmetic, camera: u8) -> Option<u8> {
self.own = Some(own);
self.start(own, emote);
if camera == FIRST_PERSON {
self.camera_before = Some(FIRST_PERSON);
return Some(THIRD_PERSON_FRONT);
}
None
}
/// The emote wheel chose `emote` (the service took it): the game side plays it on its next
/// tick (`take_own`, then `play_own`), where it knows the player and the camera.
pub fn play_own_later(&mut self, emote: &'static Cosmetic) {
self.pending_own = Some(emote);
}
/// The emote the wheel chose since the last call.
pub fn take_own(&mut self) -> Option<&'static Cosmetic> {
self.pending_own.take()
}
fn start(&mut self, id: u128, emote: &'static Cosmetic) {
let ends_at = self.ticks + u64::from(emotes::duration(emote.id));
self.plays.insert(
id,
Play {
emote,
start: self.ticks,
ends_at,
},
);
}
/// Once a client tick. `in_world`: a world is open. `played`: the emotes Incari players played
/// since the last tick (`Online::take_emotes`: UUID and id). `own_moving`: the player's keys
/// move them, they jump or swing. `camera`: the view now. Returns the view to set when the
/// player's own emote ended and turned the camera.
pub fn tick(
&mut self,
in_world: bool,
show_others: bool,
played: &[(u128, String)],
own_moving: bool,
camera: u8,
) -> Option<u8> {
self.ticks += 1;
self.trails_left = TRAIL_BUDGET;
if !in_world {
self.plays.clear();
self.others.clear();
self.own = None;
// Left the world mid-emote: the camera goes back now, not with the next world.
return self.emote_ended(camera);
}
if show_others {
for (id, emote) in played {
if let Some(e) = catalog::by_id(emote).filter(|e| e.slot == catalog::Slot::Emote) {
self.start(*id, e);
}
}
}
let (ticks, own) = (self.ticks, self.own);
let mut mine_ended = false;
self.plays.retain(|id, play| {
let mine = Some(*id) == own;
let over = ticks >= play.ends_at || (!mine && !show_others) || (mine && own_moving);
mine_ended |= over && mine;
!over
});
let mine_playing = own.is_some_and(|o| self.plays.contains_key(&o));
if mine_ended || (self.camera_before.is_some() && !mine_playing) {
return self.emote_ended(camera);
}
if ticks % 200 == 0 {
// Players who left (not drawn for ten seconds), forgotten now and then.
self.others.retain(|_, (_, _, drawn)| ticks - *drawn < 200);
}
None
}
fn emote_ended(&mut self, camera: u8) -> Option<u8> {
let before = self.camera_before.take()?;
// Unless the player moved the camera themselves meanwhile.
(camera == THIRD_PERSON_FRONT).then_some(before)
}
/// Whether any emote plays (the game side poses players for it).
pub fn any_playing(&self) -> bool {
!self.plays.is_empty()
}
/// Whether the player's own emote plays: the camera faces them.
pub fn own_playing(&self) -> bool {
self.own.is_some_and(|o| self.plays.contains_key(&o))
}
/// The trail particle player `entity` (the game's entity id) leaves this tick wearing `trail`,
/// `distance_sq` blocks² from the player and having moved `moved_sq` blocks² since the last
/// tick; None when there's none to leave (every other tick, at most `TRAIL_BUDGET` a tick).
pub fn trail(
&mut self,
trail: &Cosmetic,
entity: u32,
distance_sq: f64,
moved_sq: f64,
) -> Option<Particle> {
if self.ticks & 1 != 0 || self.trails_left == 0 {
return None;
}
if distance_sq > TRAIL_DISTANCE * TRAIL_DISTANCE || moved_sq < 0.0004 {
return None;
}
// Hearts are big: fewer of them.
if trail.id == "trail.hearts" && !(self.ticks / 2 + u64::from(entity)).is_multiple_of(3) {
return None;
}
self.trails_left -= 1;
let mut r = || self.next_random();
let (x, y, z) = ((r() - 0.5) * 0.5, 0.1 + r() * 0.2, (r() - 0.5) * 0.5);
Some(match trail.id {
"trail.hearts" => Particle {
kind: "minecraft:heart",
offset: [x, y + 0.3, z],
velocity: [0.0; 3],
},
"trail.sparkles" => Particle {
kind: "minecraft:end_rod",
offset: [x, y + 0.2, z],
velocity: [(r() - 0.5) * 0.02, 0.02, (r() - 0.5) * 0.02],
},
// A note's colour is its first speed (a pitch, 0 to 1).
"trail.notes" => Particle {
kind: "minecraft:note",
offset: [x, y + 0.4, z],
velocity: [r(), 0.0, 0.0],
},
_ => Particle {
kind: "minecraft:snowflake",
offset: [x, y, z],
velocity: [0.0, 0.02, 0.0],
},
})
}
/// A number in [0, 1).
fn next_random(&mut self) -> f64 {
// xorshift64*: the trails only need to look scattered.
let mut x = self.random.wrapping_add(0x9E37_79B9_7F4A_7C15) | 1;
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
self.random = x;
(x.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 11) as f64 / (1u64 << 53) as f64
}
}
thread_local! {
static WORLD: RefCell<World> = RefCell::new(World::default());
}
/// Runs `f` with the world's cosmetics (the window's thread).
pub fn with<R>(f: impl FnOnce(&mut World) -> R) -> R {
WORLD.with(|w| f(&mut w.borrow_mut()))
}
#[cfg(test)]
mod tests {
use super::*;
fn c(id: &str) -> &'static Cosmetic {
catalog::by_id(id).unwrap()
}
#[test]
fn others_show_only_as_incari_players_and_while_shown() {
let mut w = World::default();
let ids = vec!["hat.halo".to_owned()];
assert_eq!(w.worn_by(7, false, Loadout::EMPTY, None, true), Worn::NONE);
assert_eq!(
w.worn_by(7, false, Loadout::EMPTY, Some(&ids), true)
.loadout
.ids(),
["hat.halo"]
);
assert_eq!(
w.worn_by(7, false, Loadout::EMPTY, Some(&ids), false),
Worn::NONE
);
let own = Loadout::of(&["cape.tide"]);
assert_eq!(
w.worn_by(1, true, own, None, false).loadout,
own,
"your own always show"
);
}
#[test]
fn your_emote_turns_the_camera_and_moving_ends_it() {
let mut w = World::default();
assert_eq!(
w.play_own(1, c("emote.wave"), FIRST_PERSON),
Some(THIRD_PERSON_FRONT)
);
assert!(w.own_playing());
let worn = w.worn_by(1, true, Loadout::EMPTY, None, true);
assert!(worn.pose(w.now(0.5) + 10.0).is_some());
assert_eq!(w.tick(true, true, &[], false, THIRD_PERSON_FRONT), None);
assert_eq!(
w.tick(true, true, &[], true, THIRD_PERSON_FRONT),
Some(FIRST_PERSON),
"moved: back to first person"
);
assert!(!w.own_playing());
// Played out, with the camera moved by hand meanwhile: left where the player put it.
w.play_own(1, c("emote.dab"), FIRST_PERSON);
for _ in 0..emotes::duration("emote.dab") - 1 {
assert_eq!(w.tick(true, true, &[], false, 1), None);
}
assert_eq!(w.tick(true, true, &[], false, 1), None);
assert!(!w.own_playing());
}
#[test]
fn others_emotes_play_until_they_walk() {
let mut w = World::default();
w.tick(
true,
true,
&[(9, "emote.bow".into()), (8, "emote.nope".into())],
false,
0,
);
assert!(
w.worn_by(9, false, Loadout::EMPTY, None, true)
.emote
.is_some(),
"an emote shows on anyone named"
);
assert_eq!(w.worn_by(8, false, Loadout::EMPTY, None, true), Worn::NONE);
w.walking(9, 0.5);
assert!(
w.worn_by(9, false, Loadout::EMPTY, None, true)
.emote
.is_none()
);
}
#[test]
fn trails_keep_to_their_budget() {
let mut w = World::default();
w.tick(true, true, &[], false, 0);
w.tick(true, true, &[], false, 0);
let snow = c("trail.snow");
let left = (0..20)
.filter(|_| w.trail(snow, 1, 4.0, 1.0).is_some())
.count();
assert_eq!(left as u32, TRAIL_BUDGET);
w.tick(true, true, &[], false, 0);
assert!(w.trail(snow, 1, 4.0, 1.0).is_none(), "every other tick");
w.tick(true, true, &[], false, 0);
assert!(w.trail(snow, 1, 40.0 * 40.0, 1.0).is_none(), "too far");
assert!(w.trail(snow, 1, 4.0, 0.0).is_none(), "standing still");
let p = w.trail(snow, 1, 4.0, 1.0).unwrap();
assert!(p.offset[0].abs() <= 0.25 && p.kind == "minecraft:snowflake");
}
}
@@ -0,0 +1,167 @@
//! What the credits screen lists (Credits.java): Incari and the third-party software the Rust
//! build adds, each under its own license, with where its source and license are. Horizon's own
//! dependencies are Horizon's to credit (its `THIRD_PARTY_NOTICES.md`), as the game's own
//! libraries are Mojang's in the Java build.
use crate::release::BuildInfo;
/// One entry: a piece of software in this build, under its own license.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Credit {
pub name: &'static str,
/// The version in this build, shown after the name; None when it isn't known here.
pub version: Option<String>,
/// Who holds its copyright.
pub authors: &'static str,
/// The license's short name, as SPDX names it where it can.
pub license: &'static str,
/// Where the license's full text is.
pub license_text: String,
/// Where its source code is.
pub source: String,
}
impl Credit {
/// The name with the version after it, if there is one.
pub fn title(&self) -> String {
match &self.version {
Some(v) => format!("{} {v}", self.name),
None => self.name.to_owned(),
}
}
}
pub const GPL_3: &str = "https://www.gnu.org/licenses/gpl-3.0.html";
pub const APACHE_2: &str = "https://www.apache.org/licenses/LICENSE-2.0";
pub const MIT: &str = "https://opensource.org/license/mit";
pub const OFL_1_1: &str = "https://openfontlicense.org/open-font-license-official-text/";
/// The pause menu's Report Bugs: a new issue on the repository, from its bug template.
pub fn report_bugs(build: &BuildInfo) -> String {
format!("{}/issues/new?template=bug_report.yml", build.repository)
}
/// The pause menu's Give Feedback: a new discussion in the repository's Feedback category.
pub fn feedback(build: &BuildInfo) -> String {
format!("{}/discussions/new?category=feedback", build.repository)
}
/// Everything this build credits: Incari first, then the game it runs on, then what Incari's
/// client compiles in, then the look's fonts.
pub fn all(build: &BuildInfo) -> Vec<Credit> {
let c = |name, authors, license, license_text: &str, source: &str| Credit {
name,
version: None,
authors,
license,
license_text: license_text.to_owned(),
source: source.to_owned(),
};
let repo = build.repository.as_str();
let mut all = vec![
c(
"Incari Client",
"The Incari Client contributors",
"GPL-3.0-or-later, with an exception for Minecraft",
&format!("{repo}/blob/main/LICENSE-EXCEPTION.txt"),
repo,
),
c(
"Horizon",
"The Horizon contributors",
"MIT",
&build.horizon_page("LICENSE"),
&build.horizon_page(""),
),
c(
"horizon-mixins",
"The Horizon contributors",
"MIT",
&build.mixins_page("LICENSE"),
&build.mixins_page(""),
),
// incari_core's own dependencies: PNGs, the wordmark's font, profiles' JSON.
c(
"png",
"The image-rs Developers",
"MIT OR Apache-2.0",
APACHE_2,
"https://github.com/image-rs/image-png",
),
c(
"ab_glyph",
"Alex Butler",
"Apache-2.0",
APACHE_2,
"https://github.com/alexheretic/ab-glyph",
),
c(
"serde_json",
"Erick Tryzelaar, David Tolnay",
"MIT OR Apache-2.0",
MIT,
"https://github.com/serde-rs/json",
),
];
// The look's fonts, in Incari's pack with their licences beside them.
for (name, authors, source) in [
(
"Red Hat Display",
"The Red Hat Project Authors",
"https://github.com/RedHatOfficial/RedHatFont",
),
(
"Michroma",
"The Michroma Project Authors",
"https://github.com/googlefonts/Michroma-font",
),
(
"Inter",
"The Inter Project Authors",
"https://github.com/rsms/inter",
),
(
"Nunito",
"The Nunito Project Authors",
"https://github.com/googlefonts/nunito",
),
(
"Poppins",
"The Poppins Project Authors",
"https://github.com/itfoundry/Poppins",
),
(
"JetBrains Mono",
"The JetBrains Mono Project Authors",
"https://github.com/JetBrains/JetBrainsMono",
),
] {
all.push(c(name, authors, "OFL-1.1", OFL_1_1, source));
}
all
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn incari_comes_first_with_its_source_offer() {
let build = BuildInfo {
repository: "https://github.com/incari-client/incari-client".into(),
horizon_repository: "https://github.com/x/horizon-web.git".into(),
horizon_revision: "abc".into(),
mixins_repository: "https://github.com/x/horizon-mixins".into(),
mixins_revision: "def".into(),
..BuildInfo::default()
};
let all = all(&build);
assert_eq!(all[0].title(), "Incari Client");
assert_eq!(all[0].source, build.repository);
assert_eq!(all[1].source, "https://github.com/x/horizon-web");
assert!(all.iter().all(|c| c.license_text.starts_with("https://")));
assert_eq!(
report_bugs(&build),
"https://github.com/incari-client/incari-client/issues/new?template=bug_report.yml"
);
}
}
@@ -0,0 +1,181 @@
//! Crosshair Editor (features/crosshair): a crosshair of the player's own, drawn in place of the
//! game's (its `hud/crosshair` sprite): a cross, T, circle or dot from sliders, or a 15 by 15 grid.
use crate::framework::setting::{Settings, Val};
use crate::paint::Painter;
const GRID: usize = 15;
/// The presets: style, length, gap, thickness, dot, outline.
const PRESETS: &[(&str, &str, i32, i32, i32, bool, bool)] = &[
("classic", "cross", 9, 0, 2, false, false),
("competitive", "cross", 6, 3, 2, false, true),
("small", "cross", 4, 2, 1, false, true),
("dot", "dot", 0, 0, 4, true, true),
("circle", "circle", 0, 8, 2, true, true),
("t_shape", "t", 7, 3, 2, false, true),
];
/// After setting `id` changed: a preset picked loads its values; a slider moved away from the
/// preset makes it Custom, so picking the preset again loads it.
pub fn changed(s: &mut Settings, id: &str) {
let chosen = s.choice("preset");
let preset = PRESETS.iter().find(|p| p.0 == chosen);
if id == "preset" {
if let Some(&(_, style, length, gap, thickness, dot, outline)) = preset {
set_choice(s, "style", style);
set(s, "length", Val::Int(length.max(1)));
set(s, "gap", Val::Int(gap));
set(s, "thickness", Val::Int(thickness));
set(s, "dot", Val::Bool(dot));
set(s, "outline", Val::Bool(outline));
}
return;
}
if let Some(&(_, style, length, gap, thickness, dot, outline)) = preset {
let shows = s.choice("style") == style
&& s.int("length") == length.max(1)
&& s.int("gap") == gap
&& s.int("thickness") == thickness
&& s.bool("dot") == dot
&& s.bool("outline") == outline;
if !shows {
set_choice(s, "preset", "custom");
}
}
}
fn set(s: &mut Settings, id: &str, v: Val) {
if let Some(x) = s.get_mut(id) {
x.set(v);
}
}
fn set_choice(s: &mut Settings, id: &str, key: &str) {
if let Some(x) = s.get_mut(id)
&& let crate::framework::setting::Kind::Choice { choices, .. } = x.kind
&& let Some(i) = choices.iter().position(|c| c.0 == key)
{
x.set(Val::Choice(i));
}
}
/// The crosshair centred on (`cx`, `cy`) in GUI units.
pub fn draw(p: &mut Painter, s: &Settings, on_target: bool, cx: f32, cy: f32) {
let alpha = ((s.int("opacity") as f32 * 2.55).round() as u32) << 24;
let rgb = if s.bool("target-color") && on_target {
s.color("on-target-color")
} else {
s.color("color")
} & 0xFF_FFFF;
let (argb, shade) = (alpha | rgb, alpha);
if s.choice("style") == "grid" {
// In GUI units, as the game's own crosshair is drawn.
let rows: Vec<u64> = match s.get("grid").map(|g| g.value.clone()) {
Some(Val::Grid(rows)) => rows,
_ => return,
};
let (ox, oy) = (cx - GRID as f32 / 2.0, cy - GRID as f32 / 2.0);
let row = |y: i32| {
if y < 0 || y >= GRID as i32 {
0
} else {
rows[y as usize] << 1
}
};
if s.bool("outline") {
for y in -1..=GRID as i32 {
let around = row(y - 1) | row(y + 1) | row(y) << 1 | row(y) >> 1;
runs(p, around, ox, oy, y, -1.0, shade);
}
}
for (y, r) in rows.iter().enumerate() {
runs(p, *r, ox, oy, y as i32, 0.0, argb);
}
return;
}
// In screen pixels, around the middle.
let px = 1.0 / p.scale;
p.push(
(cx * p.scale).round() * px,
(cy * p.scale).round() * px,
px,
|p| {
if s.bool("outline") {
shapes(p, s, shade, 1.0);
}
shapes(p, s, argb, 0.0);
},
);
}
fn shapes(p: &mut Painter, s: &Settings, argb: u32, grow: f32) {
let t = s.int("thickness") as f32;
let half = (t / 2.0).floor();
let g = s.int("gap") as f32;
let l = s.int("length") as f32;
let style = s.choice("style");
let mut rect = |x: f32, y: f32, w: f32, h: f32| {
p.fill(x - grow, y - grow, w + grow * 2.0, h + grow * 2.0, argb)
};
match style {
"cross" | "t" => {
rect(-g - l, -half, l, t);
rect(g + (t - half * 2.0), -half, l, t);
rect(-half, g + (t - half * 2.0), t, l);
if style == "cross" {
rect(-half, -g - l, t, l);
}
}
_ => {}
}
if style == "circle" {
let r = g + t + grow;
p.ring(0.0, 0.0, r, t + grow * 2.0, argb);
}
if s.bool("dot") || style == "dot" {
p.fill(
-half - grow,
-half - grow,
t + grow * 2.0,
t + grow * 2.0,
argb,
);
}
}
/// A row's lit cells as runs of quads.
fn runs(p: &mut Painter, row: u64, ox: f32, oy: f32, y: i32, first: f32, argb: u32) {
let mut i = 0;
while i < 64 {
if row >> i & 1 != 0 {
let mut run = 1;
while i + run < 64 && row >> (i + run) & 1 != 0 {
run += 1;
}
p.fill(ox + i as f32 + first, oy + y as f32, run as f32, 1.0, argb);
i += run;
} else {
i += 1;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn presets_load_and_a_moved_slider_makes_custom() {
let mut m = crate::modules::all()
.into_iter()
.find(|m| m.id == "crosshair")
.unwrap();
set_choice(&mut m.settings, "preset", "competitive");
changed(&mut m.settings, "preset");
assert_eq!((m.settings.int("length"), m.settings.int("gap")), (6, 3));
assert!(m.settings.bool("outline"));
set(&mut m.settings, "gap", Val::Int(5));
changed(&mut m.settings, "gap");
assert_eq!(m.settings.choice("preset"), "custom");
}
}
@@ -0,0 +1,244 @@
//! What Incari draws in a frame, as a list the game side replays through Horizon's `native_*`
//! helpers: fills, parts of the canvas (shapes, icons, the backdrop), the game's text, items and
//! clipping. Kept between frames and cleared, so a frame allocates nothing once warm.
use std::ops::Range;
/// `[x, y, w, h]` in GUI units.
pub type Rect = [f32; 4];
/// Whether `p` is inside `r`.
pub fn contains(r: Rect, p: [f32; 2]) -> bool {
p[0] >= r[0] && p[1] >= r[1] && p[0] < r[0] + r[2] && p[1] < r[1] + r[3]
}
/// `r` with `by` taken off each side.
pub fn inset(r: Rect, by: f32) -> Rect {
[
r[0] + by,
r[1] + by,
(r[2] - 2.0 * by).max(0.0),
(r[3] - 2.0 * by).max(0.0),
]
}
/// The part of `a` inside `b`.
pub fn intersect(a: Rect, b: Rect) -> Rect {
let x0 = a[0].max(b[0]);
let y0 = a[1].max(b[1]);
let x1 = (a[0] + a[2]).min(b[0] + b[2]);
let y1 = (a[1] + a[3]).min(b[1] + b[3]);
[x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0)]
}
/// One thing to draw.
#[derive(Clone, Debug, PartialEq)]
pub enum Cmd {
/// A plain rectangle.
Fill {
rect: Rect,
argb: u32,
},
/// Part `src` (canvas pixels) of the canvas over `dst`, multiplied by `argb`.
Image {
src: Rect,
dst: Rect,
argb: u32,
},
/// Part `src` (canvas pixels) of the canvas over any four-cornered shape (`corners` match
/// `src`'s top left, top right, bottom right, bottom left).
Quad {
src: Rect,
corners: [[f32; 2]; 4],
argb: u32,
},
/// A sprite of the game's atlas by name (`gui/sprites/...`), part `src` of it over `dst`;
/// a `src` of no size is the whole sprite (`WHOLE`), whatever size the pack made it.
Sprite {
name: Range<u32>,
src: Rect,
dst: Rect,
argb: u32,
},
/// A line of the game's text, `scale` times its size from its top left.
Text {
text: Range<u32>,
at: [f32; 2],
argb: u32,
shadow: bool,
scale: f32,
},
/// An item's icon, `size` square.
Item {
id: Range<u32>,
at: [f32; 2],
size: f32,
},
/// Only what's drawn until the matching `ClipEnd` and inside `rect` shows.
ClipStart {
rect: Rect,
},
ClipEnd,
}
/// A frame's commands and the text they name.
#[derive(Default, Debug)]
pub struct DrawList {
pub cmds: Vec<Cmd>,
pub text: String,
clips: Vec<Rect>,
}
impl DrawList {
pub fn clear(&mut self) {
self.cmds.clear();
self.text.clear();
self.clips.clear();
}
/// The text of a command's range.
pub fn str(&self, range: &Range<u32>) -> &str {
&self.text[range.start as usize..range.end as usize]
}
fn intern(&mut self, s: &str) -> Range<u32> {
let start = self.text.len() as u32;
self.text.push_str(s);
start..self.text.len() as u32
}
/// The clip in effect, if any.
pub fn clip(&self) -> Option<Rect> {
self.clips.last().copied()
}
pub fn fill(&mut self, rect: Rect, argb: u32) {
if argb >> 24 == 0 || rect[2] <= 0.0 || rect[3] <= 0.0 {
return;
}
self.cmds.push(Cmd::Fill { rect, argb });
}
pub fn image(&mut self, src: Rect, dst: Rect, argb: u32) {
if argb >> 24 == 0 || dst[2] <= 0.0 || dst[3] <= 0.0 {
return;
}
self.cmds.push(Cmd::Image { src, dst, argb });
}
pub fn quad(&mut self, src: Rect, corners: [[f32; 2]; 4], argb: u32) {
if argb >> 24 != 0 {
self.cmds.push(Cmd::Quad { src, corners, argb });
}
}
/// A `src` meaning the whole sprite.
pub const WHOLE: Rect = [0.0; 4];
pub fn sprite(&mut self, name: &str, src: Rect, dst: Rect, argb: u32) {
if argb >> 24 == 0 {
return;
}
let name = self.intern(name);
self.cmds.push(Cmd::Sprite {
name,
src,
dst,
argb,
});
}
pub fn text(&mut self, text: &str, at: [f32; 2], argb: u32, shadow: bool, scale: f32) {
if text.is_empty() || argb >> 24 < 4 {
return;
}
let text = self.intern(text);
self.cmds.push(Cmd::Text {
text,
at,
argb,
shadow,
scale,
});
}
pub fn item(&mut self, id: &str, at: [f32; 2], size: f32) {
let id = self.intern(id);
self.cmds.push(Cmd::Item { id, at, size });
}
/// Moves what was drawn since command `start` by (`dx`, `dy`): an element drawn at its own
/// origin, put where it goes once its size is known.
pub fn translate_since(&mut self, start: usize, dx: f32, dy: f32) {
for cmd in &mut self.cmds[start..] {
match cmd {
Cmd::Fill { rect, .. } | Cmd::ClipStart { rect } => {
rect[0] += dx;
rect[1] += dy;
}
Cmd::Image { dst, .. } | Cmd::Sprite { dst, .. } => {
dst[0] += dx;
dst[1] += dy;
}
Cmd::Text { at, .. } | Cmd::Item { at, .. } => {
at[0] += dx;
at[1] += dy;
}
Cmd::Quad { corners, .. } => {
for c in corners {
c[0] += dx;
c[1] += dy;
}
}
Cmd::ClipEnd => {}
}
}
}
/// Clips what follows to `rect` (inside any clip already in effect) until `clip_end`.
pub fn clip_start(&mut self, rect: Rect) {
let rect = match self.clip() {
Some(outer) => intersect(rect, outer),
None => rect,
};
self.clips.push(rect);
self.cmds.push(Cmd::ClipStart { rect });
}
pub fn clip_end(&mut self) {
if self.clips.pop().is_some() {
self.cmds.push(Cmd::ClipEnd);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn keeps_text_in_one_buffer_and_skips_what_wouldnt_show() {
let mut list = DrawList::default();
list.text("Singleplayer", [1.0, 2.0], 0xFFFF_FFFF, false, 1.0);
list.fill([0.0, 0.0, 10.0, 10.0], 0x00FF_FFFF);
list.text("", [0.0, 0.0], 0xFFFF_FFFF, false, 1.0);
assert_eq!(list.cmds.len(), 1);
let Cmd::Text { text, .. } = &list.cmds[0] else {
panic!()
};
assert_eq!(list.str(text), "Singleplayer");
list.clear();
assert!(list.cmds.is_empty() && list.text.is_empty());
}
#[test]
fn nested_clips_stay_inside_each_other() {
let mut list = DrawList::default();
list.clip_start([0.0, 0.0, 100.0, 100.0]);
list.clip_start([50.0, 50.0, 100.0, 100.0]);
assert_eq!(list.clip(), Some([50.0, 50.0, 50.0, 50.0]));
list.clip_end();
list.clip_end();
list.clip_end();
assert_eq!(list.cmds.len(), 4);
}
}

Some files were not shown because too many files have changed in this diff Show More