[PR #5647] [MERGED] OptiFine entity models: compile animation expressions once, evaluate them without allocating #6413

Closed
opened 2026-11-03 06:20:11 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/horizon-rust/horizon/pull/5647
Author: @some-du6e
Created: 11/1/2026
Status: ✅ Merged
Merged: 11/1/2026
Merged by: @ludovic111

Base: main ← Head: optifine/emf-expr


📝 Commits (10+)

  • b2a09a2 OptiFine CEM: read .jem and .jpm entity models into vanilla-frame geometry
  • 02a522b OptiFine CEM: compile animation expressions once, evaluate them without allocating
  • d8c627e Merge main into optifine/emf-jem
  • 9469537 OptiFine CEM: read .jem files the way OptiFine does, and keep packs inside the root
  • af00d7a CLAUDE.md: list horizon-optifine among the crates
  • 5eeb2cd OptiFine reader: paths with a backslash are refused too
  • d037799 OptiFine CEM: inheriting shares instead of copying, every entry and bone counts
  • a52700e OptiFine CEM: third review round of the .jem reader
  • c0be27a OptiFine CEM: first review round of the expression compiler
  • 25023c2 Merge optifine/emf-jem into optifine/emf-expr

📊 Changes

11 files changed (+2885 additions, -4 deletions)

View changed files

📝 AGENTS.md (+1 -0)
📝 Cargo.lock (+1 -0)
📝 crates/horizon-optifine/Cargo.toml (+5 -1)
➕ crates/horizon-optifine/examples/cem_expr_bench.rs (+136 -0)
➕ crates/horizon-optifine/src/cem/curves.rs (+157 -0)
➕ crates/horizon-optifine/src/cem/expr.rs (+996 -0)
➕ crates/horizon-optifine/src/cem/json.rs (+340 -0)
➕ crates/horizon-optifine/src/cem/mod.rs (+9 -0)
➕ crates/horizon-optifine/src/cem/model.rs (+1234 -0)
📝 crates/horizon-optifine/src/lib.rs (+1 -0)
📝 crates/horizon-optifine/src/paths.rs (+5 -3)

📄 Description

Animation packs (Fresh Animations and friends) drive entity models with OptiFine's CEM expression language: "left_leg.rx": "sin(limb_swing * 0.6662) * limb_speed * 1.4", evaluated for every entity every frame. Hundreds of entities times dozens of expressions means parsing or allocating per frame is out. This is the second PR of the custom entity models stack, and still only a library: players see no change yet.

horizon_optifine::cem::expr::compile parses an expression once (at resource load) into a tree, folds its constant parts (torad(45), if(true, a, b), false branches), then emits a flat stack program. Variables are slots the caller resolves when compiling (limb_swing, head.rx, var.x...), so the animation PR can lay out entity parameters, part transforms and var.* in one array.

Expr::eval(&[f32]) runs it with no allocation and no string work. Programs that need up to 64 values run on a fixed stack array; deeper ones, such as long keyframe tracks, run on a per-thread buffer that grows once and is reused.

&&, || and ! are lowered to if/comparisons, so if, ifb, && and || jump past the branches they don't take. Booleans are 1/0; any value but 0 is true, NaN included.

Coverage:

  • OptiFine's operators, with C-like precedence (all binary operators left-associative), and unary -, + and !.
  • OptiFine's constants: pi, true, false.
  • OptiFine's functions: sin cos asin acos tan atan atan2 torad todeg min max clamp abs floor ceil exp frac log pow random round signum sqrt fmod lerp if ifb print printb between equals in.
    • Float behaviour follows Java's where Rust's differs:
      • min and max return NaN if an argument is NaN.
      • clamp is x < lo ? lo : Math.min(x, hi), so a NaN x or hi gives NaN.
      • pow gives NaN for a NaN exponent and for ±1 to an infinite power.
      • round is Math.round(float): halves up, NaN to 0, saturating at the int range.
    • print(id, n, x) and printb return x and print nothing.
    • random(seed) repeats per seed; random() draws a new value each call from a per-thread state seeded at first use.
    • ifb returns 1/0.
  • EMF's documented additions:
    • constants e and nan
    • wrapdeg wraprad degdiff raddiff randomb
    • catch(x, c[, id]): c only when x is NaN; infinities pass
    • keyframe and keyframeloop: past the end, keyframe gives the last frame, including for infinite k
    • catmullrom hermite cubicbezier quadbezier
    • every ease* curve, from easings.net's formulas: each curve's ease-in, with ease-out as 1 - in(1 - t) and in-out derived the same way, except back and elastic, which keep their own constants
    • nbt(...), whose arguments are skipped unparsed (so nbt(SaddleItem, exists:false) compiles) and which gives 0: the client model has no entity NBT
  • Limits, so a pack can't crash the game: 64 levels of nesting ("expression too deep") and 1024 nodes ("expression too long"). Those also bound the recursion in folding, emitting and dropping. Compile errors for unknown names, wrong arity and unbalanced parentheses carry the offset.

Files:

  • cem/expr.rs: parser, folding, bytecode, functions
  • cem/curves.rs: easings, splines, keyframes
  • examples/cem_expr_bench.rs, with a horizon-bench dev-dependency for its CPU-time helper. It's dev only, and pulls in horizon-telemetry without its network features.

horizon-shaders/src/custom.rs also parses an OptiFine expression language, but it's the shader packs' custom-uniform one: f64 and vector values, name lookups on every evaluation, and a Vec result. Sharing it would cost the per-frame budget this needs, so I wrote a separate compiler.

Speed: cargo run --release -p horizon-optifine --example cem_expr_bench times an animation pack's frame of 20 expressions: walk cycle, breathing, head tracking, a water counter, keyframes, easing, and nested ifs on is_* flags. Before the review rounds it measured about 35 ns of CPU per expression, ~0.7 µs per entity frame (/usr/bin/time user time). The example now prints CPU time itself (horizon_bench::cpu_seconds). I haven't re-run it since the review changes, because builds aren't allowed on this shared machine.

Size:

  • expr.rs is ~980 lines, about 240 of them tests.
  • curves.rs is ~160.
  • the benchmark is ~135.

That's over the ~500 guideline. The parser, folding, bytecode and functions don't make sense apart, and the curves are already split out.

Unsure (docs are thin):

  • catmullrom(k, x, y, z, w) follows Mth.catmullrom (from the second to the third value), while EMF's doc phrases it as "between x and y with control points z and w".
  • hermite takes z and w as tangents.
  • The bezier functions take z (and w) as control points.
  • keyframe uses |k|.
  • nbt(...) is always 0, even for an exists:false test.

Docs I wrote it from (no mod source read):

  • OptiFine's cem_animation.txt (github.com/sp614x/optifine, OptiFineDoc/doc)
  • OptiDocs' CEM animation page (optifine.readthedocs.io, CC0)
  • EMF's FEATURES.md and .github/emf_animation.txt
  • easings.net

Depends on #5622 (the .jem reader). It isn't merged yet; its branch is merged into this one, so until it lands the diff shows its commits too. #5574, the shared crate, is on main.

Checks:

  • cargo fmt -p horizon-optifine: clean
  • cargo test -p horizon-optifine cem:: (run locally, the one test run allowed on this machine): 31 passed, 7 of them the expression tests. Hand-computed cases cover:
    • precedence
    • real laziness: untaken if/&&/|| branches don't advance a replayed random() sequence, and the values come out right
    • per-thread seeding
    • mid-curve easings through slots
    • the runtime evaluator: negation, !, lowered &&, atan2, pow/sqrt/ceil/log
    • NaN min/max/clamp, and Java's pow special cases
    • round edges, including NaN and inf
    • ifb, nbt, catch on inf and NaN
    • a 300-frame keyframe track (deep stack, more than 255 arguments)
    • the node cap's boundary: a 512-term sum works, 513 terms is "too long"
    • the nesting and length caps, with offsets
  • clippy and the full suite, via fork CI (this machine is too loaded to build): https://github.com/some-du6e/horizon/actions/runs/41275087197 (verify passed on the previous heads)
  • review loop: three rounds, each fixed (c0be27ae1, 883cf5b01, a0144420a). Round 3 found only Java float edge cases and test gaps; round 4 is next. The live game test is skipped: there's no .local/ vanilla data here, and this PR has nothing in the game to run.

Note

Filed by Opus 5.5 using Claude Code.


🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/horizon-rust/horizon/pull/5647 **Author:** [@some-du6e](https://github.com/some-du6e) **Created:** 11/1/2026 **Status:** ✅ Merged **Merged:** 11/1/2026 **Merged by:** [@ludovic111](https://github.com/ludovic111) **Base:** `main` ← **Head:** `optifine/emf-expr` --- ### 📝 Commits (10+) - [`b2a09a2`](https://github.com/horizon-rust/horizon/commit/b2a09a2118909ee17da22fb44c3006afbe650e11) OptiFine CEM: read .jem and .jpm entity models into vanilla-frame geometry - [`02a522b`](https://github.com/horizon-rust/horizon/commit/02a522b86833bc21acd215623ab3ed7977a4e225) OptiFine CEM: compile animation expressions once, evaluate them without allocating - [`d8c627e`](https://github.com/horizon-rust/horizon/commit/d8c627e75ed61b3fef2dea5fdb877e642701a744) Merge main into optifine/emf-jem - [`9469537`](https://github.com/horizon-rust/horizon/commit/9469537b1409349518e732bfefb5f5b7e60b6dee) OptiFine CEM: read .jem files the way OptiFine does, and keep packs inside the root - [`af00d7a`](https://github.com/horizon-rust/horizon/commit/af00d7af2b79b3642073319d3632a2bb2c7f057c) CLAUDE.md: list horizon-optifine among the crates - [`5eeb2cd`](https://github.com/horizon-rust/horizon/commit/5eeb2cdd7e039ffae4f10f7e47597b783b354504) OptiFine reader: paths with a backslash are refused too - [`d037799`](https://github.com/horizon-rust/horizon/commit/d0377992dba118264623c58fffed4d0a0e6c9b66) OptiFine CEM: inheriting shares instead of copying, every entry and bone counts - [`a52700e`](https://github.com/horizon-rust/horizon/commit/a52700ebae645f5f7c4c74964c6e614a43a4e6ee) OptiFine CEM: third review round of the .jem reader - [`c0be27a`](https://github.com/horizon-rust/horizon/commit/c0be27ae15b99fd7d93b6cd809dda63526cb207f) OptiFine CEM: first review round of the expression compiler - [`25023c2`](https://github.com/horizon-rust/horizon/commit/25023c28c9f0f1a97f2080f1912dcc90ac4ae4d8) Merge optifine/emf-jem into optifine/emf-expr ### 📊 Changes **11 files changed** (+2885 additions, -4 deletions) <details> <summary>View changed files</summary> 📝 `AGENTS.md` (+1 -0) 📝 `Cargo.lock` (+1 -0) 📝 `crates/horizon-optifine/Cargo.toml` (+5 -1) ➕ `crates/horizon-optifine/examples/cem_expr_bench.rs` (+136 -0) ➕ `crates/horizon-optifine/src/cem/curves.rs` (+157 -0) ➕ `crates/horizon-optifine/src/cem/expr.rs` (+996 -0) ➕ `crates/horizon-optifine/src/cem/json.rs` (+340 -0) ➕ `crates/horizon-optifine/src/cem/mod.rs` (+9 -0) ➕ `crates/horizon-optifine/src/cem/model.rs` (+1234 -0) 📝 `crates/horizon-optifine/src/lib.rs` (+1 -0) 📝 `crates/horizon-optifine/src/paths.rs` (+5 -3) </details> ### 📄 Description Animation packs (Fresh Animations and friends) drive entity models with OptiFine's CEM expression language: `"left_leg.rx": "sin(limb_swing * 0.6662) * limb_speed * 1.4"`, evaluated for every entity every frame. Hundreds of entities times dozens of expressions means parsing or allocating per frame is out. This is the second PR of the custom entity models stack, and still only a library: players see no change yet. `horizon_optifine::cem::expr::compile` parses an expression once (at resource load) into a tree, folds its constant parts (`torad(45)`, `if(true, a, b)`, false branches), then emits a flat stack program. Variables are slots the caller resolves when compiling (`limb_swing`, `head.rx`, `var.x`...), so the animation PR can lay out entity parameters, part transforms and `var.*` in one array. `Expr::eval(&[f32])` runs it with no allocation and no string work. Programs that need up to 64 values run on a fixed stack array; deeper ones, such as long keyframe tracks, run on a per-thread buffer that grows once and is reused. `&&`, `||` and `!` are lowered to `if`/comparisons, so `if`, `ifb`, `&&` and `||` jump past the branches they don't take. Booleans are 1/0; any value but 0 is true, NaN included. **Coverage:** - **OptiFine's operators**, with C-like precedence (all binary operators left-associative), and unary `-`, `+` and `!`. - **OptiFine's constants**: `pi`, `true`, `false`. - **OptiFine's functions**: `sin cos asin acos tan atan atan2 torad todeg min max clamp abs floor ceil exp frac log pow random round signum sqrt fmod lerp if ifb print printb between equals in`. - Float behaviour follows Java's where Rust's differs: - `min` and `max` return NaN if an argument is NaN. - `clamp` is `x < lo ? lo : Math.min(x, hi)`, so a NaN x or hi gives NaN. - `pow` gives NaN for a NaN exponent and for ±1 to an infinite power. - `round` is `Math.round(float)`: halves up, NaN to 0, saturating at the int range. - `print(id, n, x)` and `printb` return x and print nothing. - `random(seed)` repeats per seed; `random()` draws a new value each call from a per-thread state seeded at first use. - `ifb` returns 1/0. - **EMF's documented additions**: - constants `e` and `nan` - `wrapdeg wraprad degdiff raddiff randomb` - `catch(x, c[, id])`: c only when x is NaN; infinities pass - `keyframe` and `keyframeloop`: past the end, `keyframe` gives the last frame, including for infinite k - `catmullrom hermite cubicbezier quadbezier` - every `ease*` curve, from easings.net's formulas: each curve's ease-in, with ease-out as `1 - in(1 - t)` and in-out derived the same way, except back and elastic, which keep their own constants - `nbt(...)`, whose arguments are skipped unparsed (so `nbt(SaddleItem, exists:false)` compiles) and which gives 0: the client model has no entity NBT - **Limits, so a pack can't crash the game:** 64 levels of nesting ("expression too deep") and 1024 nodes ("expression too long"). Those also bound the recursion in folding, emitting and dropping. Compile errors for unknown names, wrong arity and unbalanced parentheses carry the offset. **Files:** - `cem/expr.rs`: parser, folding, bytecode, functions - `cem/curves.rs`: easings, splines, keyframes - `examples/cem_expr_bench.rs`, with a `horizon-bench` dev-dependency for its CPU-time helper. It's dev only, and pulls in `horizon-telemetry` without its network features. `horizon-shaders/src/custom.rs` also parses an OptiFine expression language, but it's the shader packs' custom-uniform one: f64 and vector values, name lookups on every evaluation, and a `Vec` result. Sharing it would cost the per-frame budget this needs, so I wrote a separate compiler. **Speed:** `cargo run --release -p horizon-optifine --example cem_expr_bench` times an animation pack's frame of 20 expressions: walk cycle, breathing, head tracking, a water counter, keyframes, easing, and nested `if`s on `is_*` flags. Before the review rounds it measured about 35 ns of CPU per expression, ~0.7 µs per entity frame (`/usr/bin/time` user time). The example now prints CPU time itself (`horizon_bench::cpu_seconds`). I haven't re-run it since the review changes, because builds aren't allowed on this shared machine. **Size:** - `expr.rs` is ~980 lines, about 240 of them tests. - `curves.rs` is ~160. - the benchmark is ~135. That's over the ~500 guideline. The parser, folding, bytecode and functions don't make sense apart, and the curves are already split out. **Unsure** (docs are thin): - `catmullrom(k, x, y, z, w)` follows `Mth.catmullrom` (from the second to the third value), while EMF's doc phrases it as "between x and y with control points z and w". - `hermite` takes z and w as tangents. - The bezier functions take z (and w) as control points. - `keyframe` uses `|k|`. - `nbt(...)` is always 0, even for an `exists:false` test. **Docs I wrote it from** (no mod source read): - OptiFine's `cem_animation.txt` (github.com/sp614x/optifine, OptiFineDoc/doc) - OptiDocs' CEM animation page (optifine.readthedocs.io, CC0) - EMF's `FEATURES.md` and `.github/emf_animation.txt` - easings.net **Depends on** #5622 (the `.jem` reader). It isn't merged yet; its branch is merged into this one, so until it lands the diff shows its commits too. #5574, the shared crate, is on main. **Checks:** - `cargo fmt -p horizon-optifine`: clean - `cargo test -p horizon-optifine cem::` (run locally, the one test run allowed on this machine): 31 passed, 7 of them the expression tests. Hand-computed cases cover: - precedence - real laziness: untaken `if`/`&&`/`||` branches don't advance a replayed `random()` sequence, and the values come out right - per-thread seeding - mid-curve easings through slots - the runtime evaluator: negation, `!`, lowered `&&`, `atan2`, `pow`/`sqrt`/`ceil`/`log` - NaN `min`/`max`/`clamp`, and Java's `pow` special cases - `round` edges, including NaN and inf - `ifb`, `nbt`, `catch` on inf and NaN - a 300-frame keyframe track (deep stack, more than 255 arguments) - the node cap's boundary: a 512-term sum works, 513 terms is "too long" - the nesting and length caps, with offsets - clippy and the full suite, via fork CI (this machine is too loaded to build): https://github.com/some-du6e/horizon/actions/runs/41275087197 (`verify` passed on the previous heads) - review loop: three rounds, each fixed (c0be27ae1, 883cf5b01, a0144420a). Round 3 found only Java float edge cases and test gaps; round 4 is next. The live game test is skipped: there's no `.local/` vanilla data here, and this PR has nothing in the game to run. > [!NOTE] > Filed by Opus 5.5 using Claude Code. --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-11-03 06:20:11 +07:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
horizon-rust/horizon#6413
No description provided.