Ship portable optimization packs with original frame and tick measurement

This commit is contained in:
Ludovic Marie
2026-10-03 20:06:01 +02:00
parent 32a4383459
commit 702e59372f
34 changed files with 1868 additions and 47 deletions
+28
View File
@@ -25,3 +25,31 @@ jobs:
cargo +stable clippy --workspace --all-targets -- -D warnings
- name: Test voxel kernel correctness
run: cargo +stable test --workspace
portable-mod:
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-26, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '25'
- name: Compile original mod and test metrics
run: python tools/build_mod.py
- name: Build pinned portable packs
run: python tools/build_pack.py
- name: Test pack integrity and comparisons
run: python -m unittest discover -s tests -v
- name: Upload original mod and pack manifests only
uses: actions/upload-artifact@v4
with:
name: horizon-${{ matrix.os }}
path: |
dist/*.mrpack
dist/horizon-lab-*.jar
+2
View File
@@ -13,3 +13,5 @@
/assets/
/run/
/logs/
/dist/
/mods/horizon-lab/build/
+65 -45
View File
@@ -1,14 +1,65 @@
# Minecraft Optimization Lab
# Minecraft Optimization Lab / Horizon Lab
A personal research workspace for understanding Minecraft Java Edition and testing original performance improvements, including Rust kernels. Not affiliated with Mojang or Microsoft.
Client-first performance research for Minecraft Java **26.3**, preserving vanilla gameplay rules. Any language or renderer may be used when measured gains justify it. Not affiliated with Mojang or Microsoft.
**Current scope:** complete local client/server decompilation for pinned Java Edition **26.3**, class inventories and output checks, and a tested Rust occupancy experiment. This is not a playable Rust port, a rebuilt Minecraft distribution, or proof of a game-level speedup.
**First playable release:** pinned Java performance packs, distant terrain, an original frame/tick recorder, and Mac/client/server starter downloads. The M2 Pro/16 GB Mac is the first testing target. A Rust rewrite or custom renderer has not been completed; no M2 FPS improvement has been measured yet.
The game JARs, libraries, decompiled Java, inventories, and logs live **inside this checkout** under **`.local/`**, which is gitignored. GitHub contains only our tooling, original Rust code, and research documentation. A fresh clone regenerates the local game workspace from official downloads.
## Play on your Mac
## Prepare and inspect the game
Download **horizon-mac-starter-0.2.0.zip** from [Releases](https://github.com/ludovic111/minecraft-optimization-lab/releases), extract it and open `Mac-Start.command`. It verifies and installs official universal Prism Launcher in `~/Applications` if needed, then opens the balanced pack import. Sign into Microsoft **inside Prism yourself**. This project needs no credentials.
Requires Python 3.11+, JDK 25+, and Git. No Microsoft account credentials are needed for these downloads or decompilation. Use your normal licensed launcher and sign-in when playing or collecting client performance measurements.
Use native **Java 25 ARM64**, maximum heap **6144 MiB**, minimum **512 MiB** on your 16 GB M2 Pro. Prism can download Java automatically. Start at 1280×800 or 1920×1200; full Retina resolution is a larger GPU workload. [START-HERE.txt](packs/START-HERE.txt) has details. The same `.mrpack` files import into Prism on Windows and Linux.
| Profile | Full-detail chunks | Distant LOD radius | Suggested maximum heap |
| --- | ---: | ---: | ---: |
| baseline | 12 | none | 6144 MiB |
| m2-balanced | 12 | 128 | 6144 MiB |
| low-memory | 8 | none | 3072 MiB |
| far-distance | 12 | 256 | 8192 MiB, with sufficient physical RAM |
| cinematic | 12 | 128 | 6144 MiB |
| vulkan | 12 | 128 | 6144 MiB |
Balanced combines [Sodium](https://modrinth.com/mod/sodium), [Lithium](https://modrinth.com/mod/lithium), [FerriteCore](https://modrinth.com/mod/ferrite-core), [ImmediatelyFast](https://modrinth.com/mod/immediatelyfast), [EntityCulling](https://modrinth.com/mod/entityculling), and [Distant Horizons](https://modrinth.com/mod/distanthorizons). Cinematic adds [Iris](https://modrinth.com/mod/iris) and [Complementary Reimagined](https://modrinth.com/shader/complementary-reimagined), initially disabled. Vulkan independently experiments with the game's own backend and fallback, without Iris.
Distant LOD is simplified terrain. Nearby blocks retain full detail. Initial generation costs CPU/disk/memory and needs warm-up. DH adjusts clouds, chunk fade and transparency to blend its renderer; assess appearance as well as speed. Shaders cost GPU time and have [Mac-specific limits](https://shaders.properties/current/reference/miscellaneous/macos/). Universal CPU/GPU support and exact vanilla equivalence remain validation goals. Simulation distance stays 12 in every profile; normal 20 TPS rules are retained.
## Measure on your hardware
Press **F8** during gameplay to start a 120-second recording, or again to stop early. Rebind in Controls if needed. This also works with restricted chat accounts. Alternatively: `/horizon bench <label> 120`, `/horizon stop`, `/horizon status`.
Use separate identical world copies and the same camera route, resolution, render/simulation distance, heap, VSync and FPS limit. Warm up, then alternate at least three baseline/optimized runs. Test fresh chunk exploration separately. For everyday play cap FPS or enable VSync to reduce power usage.
The instance's `horizon-benchmarks/` folder receives JSON/CSV frame and integrated-server tick timings: average FPS, slowest-1%-average FPS, p95/p99 durations, stalls, JVM heap/GC, GPU/backend/driver and render settings. Frames include presentation/limiting waits and exclude menus/pauses/unfocused time. Tick `meanRate` is execution capacity, **not TPS**; observed tick counts are separate. Heap is **not process RSS or unified GPU memory**.
```sh
python3 tools/compare_benchmarks.py baseline-frames.json optimized-frames.json --strict
```
The comparison flags captured setting differences, but cannot verify route, world, shader state or cache warm-up. See [validation evidence](docs/playable-validation.md). Software-renderer test FPS is not evidence of a Mac/GPU speedup.
## Build and run
Requires Python 3.10+ and JDK 25. No Gradle, Rust or native compilation is required for playable packs.
```sh
python3 tools/build_mod.py
python3 tools/build_release.py
```
Gitignored `dist/` contains six packs, our original instrumentation JAR, client/server starter ZIPs and SHA256SUMS. [mods.lock.json](packs/mods.lock.json) pins mod versions, exact dependency closure, SHA-1/SHA-512 and source/license; [fabric.lock.json](packs/fabric.lock.json) pins loader/library SHA-256. Packs use the [Modrinth format](https://support.modrinth.com/en/articles/8802351-modrinth-modpack-format-mrpack). They embed only original project code; third-party mods, game and assets download from their publishers.
The server starter uses Lithium/FerriteCore and `/horizonserver bench <label> <seconds>`. [Server instructions](docs/server-quickstart.txt) cover setup and a baseline. Files are prepared before you accept Minecraft's EULA locally. A 50-active-player workload remains to be measured.
Local smoke testing uses the game's built-in limited demo; normal play uses Prism's licensed account authentication:
```sh
python3 tools/build_pack.py --profile m2-balanced --instance .local/runtime/m2-balanced
vscreen run python3 tools/runtime.py demo --instance .local/runtime/m2-balanced
```
## Local game inspection
Game JARs, decompiled Java, libraries, inventories, worlds and logs live **inside this checkout** under gitignored **`.local/`**. No game code is in Git history or release downloads. Fresh clones regenerate the inspection workspace from official downloads; Microsoft credentials are not needed for this step.
```sh
git clone https://github.com/ludovic111/minecraft-optimization-lab.git
@@ -19,51 +70,24 @@ python3 tools/lab.py decompile
python3 tools/lab.py status
```
`research-lock.json` pins the version manifest and Vineflower 1.12.0 with checksums. Preparation verifies official artifact hashes, extracts the inner server game JAR from its launcher bundle, and supplies client/server libraries to the decompiler. No game process is launched, no game authentication is implemented, and no server `eula.txt` is written by the tooling.
`research-lock.json` pins the official manifest and Vineflower. The inner server JAR is extracted and checked; client/server libraries provide decompiler context. Output: `.local/minecraft/26.3/sources/{client,server}/` and coverage/inventory reports. Current inventories cover 11,383 client classes and 7,762 server classes, producing 7,301/5,037 Java files. See [decompilation status](docs/decompilation-status.md).
The default decompilation uses four threads and a 6 GiB Java heap, with one side processed at a time:
Class-file SourceFile metadata covers inner classes, which often share a source file. Coverage does not prove semantic equivalence or recompilability; original bytecode remains the reference. Completed source directories are not overwritten automatically. Older obfuscated releases require a separate remapping stage.
```sh
python3 tools/lab.py decompile --side client --threads 4 --heap 6G
python3 tools/lab.py decompile --side server --java /path/to/jdk-25/bin/java
```
Outputs:
```text
.local/minecraft/26.3/
jars/client.jar
jars/server.jar # Downloaded launcher bundle
jars/server-game.jar # Actual server bytecode
libraries/{client,server}/
sources/client/ # Decompiled client, including shared game logic
sources/server/ # Decompiled dedicated server
reports/*-inventory.json # Every class, SourceFile, method count, size
reports/*-coverage.json # Missing files and detected failure markers
reports/*-decompiler.log
```
Inner classes generally share a `.java` file with their enclosing class. Source coverage compares class-file `SourceFile` metadata with emitted Java, and scans Vineflower error markers. An exit code of 2 from `decompile` or `status` means coverage/failure markers need investigation. This does not establish semantic equivalence, preservation of every synthetic method, or recompilability; keep the original bytecode as the reference. Completed source directories are never overwritten automatically. Move a directory aside before repeating decompilation.
For older obfuscated versions, preparation deliberately stops: a version-specific remapping stage is needed. The tool does not silently present obfuscated output as readable source. The current pin can be updated by reviewing an official version manifest and its checksums.
## Run the original Rust experiment
Requires Rust 1.85+; there are no third-party crate dependencies.
## Original Rust research
```sh
cargo test --workspace
cargo run --release --bin voxel-bench -- 100 > .local/voxel-benchmark.csv
```
`voxel-kernels` compares a scalar reference with a row-bitset algorithm for counting exposed faces in synthetic 16×16×16 sections. It checks empty, full, flat, checkerboard, and seeded random occupancy at three densities. Each result is the median of 21 samples, with warm-up, alternating measurement order, and checks against the reference. The repeat count is configurable.
The dependency-free occupancy experiment compares scalar and bitset exposed-face counting for synthetic 16³ sections. It has no real mesh, material/AO/light work, neighboring-section context, JNI bridge or game integration. Speedups are kernel-only, not Minecraft FPS. [Research plan](docs/optimization-plan.md) describes profiling, improved Java baselines, native integration and behavior checks before expanding scope.
All cubes are treated as opaque/full, and external neighbors as air. There is no mesh output, texture lookup, AO, lighting, GPU work, cross-section neighborhood, JNI bridge, or Minecraft integration yet. A speedup here applies only to this kernel relative to our scalar reference, not to Minecraft's renderer or its frame rate. See [the optimization plan](docs/optimization-plan.md).
## Develop
## Validation and ownership
```sh
python3 -m unittest discover -s tests -v
python3 tools/build_mod.py --test-only
cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace
@@ -71,10 +95,6 @@ python3 tools/check_public_tree.py
python3 tools/check_public_tree.py --history
```
CI is offline with respect to Minecraft: it tests the original tooling and Rust kernels without downloading or publishing game files. The optional hooks and CI reject `.local/`, game/profiling binaries, and `.java` files even if force-added. Original Java mod sources would need an explicit reviewed exception before adding them. The path check is a guardrail, not a substitute for reviewing a public diff.
CI checks offline tools/Rust and compiles the original mod/builds packs on Linux, Windows and Apple Silicon macOS. Game dependencies download to ephemeral `.local/`; CI uploads only our original JAR and packs. Compilation is not Mac GPU gameplay testing. Publication checks allow Java only under our original `dev/horizonlab` namespace; review diffs as well.
## Ownership and references
The [MIT license](LICENSE) applies only to the original code and documentation tracked in this repository. It does not relicense downloaded game content, local decompiled Java, dependency JARs, or Vineflower. Their respective licenses still apply.
Mojang [announced removal of Java Edition obfuscation](https://www.minecraft.net/en-us/article/removing-obfuscation-in-java-edition) without changing the [Minecraft EULA](https://www.minecraft.net/en-us/eula). Keep game code and modified game builds local; publish original tools and independent optimization work. Decompiler behavior is documented by [Vineflower](https://vineflower.org/usage/).
[MIT](LICENSE) covers only our original tracked work. Dependencies retain their licenses. Mojang [removed obfuscation](https://www.minecraft.net/en-us/article/removing-obfuscation-in-java-edition) without changing [Minecraft's EULA](https://www.minecraft.net/en-us/eula). Decompiled game source remains local; published code implements independent tooling and instrumentation.
+3 -1
View File
@@ -2,9 +2,11 @@
## Starting point
The first playable Java foundation is in the root README. Client optimization has priority. Vanilla gameplay, world formats and multiplayer behavior must be preserved; existing modpack compatibility is not required. Any language, renderer or architecture is in scope when measured gains justify it. Windows/Linux and Apple Silicon/Intel macOS are targets, with the M2 Pro/16 GB Mac prioritized.
Inspect both pinned game JARs locally, retain bytecode as the reference, and measure actual Minecraft workloads before selecting a subsystem to replace. The Rust face-count experiment establishes a small correctness/benchmark workflow; it does not identify a Minecraft bottleneck.
Whole-game translation is a long-term research objective. Decompiled Java is an inspection artifact, not the original source tree: build configuration, comments, tooling history, and some source-level constructs cannot be recovered faithfully. A mechanically translated Rust game would also have to preserve behavior, data formats, networking, rendering, and mod compatibility. An isolated hot-path replacement is a useful first experiment.
Whole-game translation is a long-term research objective. Decompiled Java is an inspection artifact, not the original source tree: build configuration, comments, tooling history, and some source-level constructs cannot be recovered faithfully. A mechanically translated Rust game would also have to preserve behavior, data formats, networking and rendering. An isolated hot-path replacement is a useful first experiment.
## Local code map
+28
View File
@@ -0,0 +1,28 @@
# First playable release validation
Version 0.2.0 targets Minecraft 26.3 / Fabric 0.19.5 / Java 25. This is an initial playable Java optimization stack, not a completed renderer rewrite. Measurements here establish what was actually checked.
## Local checks
- Official client runs through a Wayland virtual screen in built-in limited demo mode, without Microsoft credentials. Normal Mac play uses licensed Prism sign-in.
- Balanced stack (Sodium, Lithium, FerriteCore, ImmediatelyFast, EntityCulling, Distant Horizons, Fabric API, Horizon Lab) reaches the menu, loads the demo world, logs in locally, renders terrain, and saves/quits.
- DH generates and accepts the current configuration schema: 128-chunk LOD radius, two background threads at 0.5 run-time ratio, priority 3. No old-version guessed config keys.
- A missing desktop AWT component in the local headless JRE initially caused a DH cloud-texture error. Installing the complete Java 25 runtime resolved it; this was an environment issue, not a packaged mod change.
- Native libraries are chosen by OS and architecture, including ARM64 selection when the official manifest has OS-only rules. Builds use portable `/` ZIP paths on Windows too.
- The official Prism 11.1.1 macOS ZIP was downloaded, SHA-256 verified, and its actual app layout checked. Its launcher executable is a universal Mach-O containing x86_64 and arm64. The starter does not redistribute it or disable macOS security checks.
- Dedicated-server optimized dependencies and original mod initialize with the real server game JAR; EULA-false startup exits as expected. No license acceptance is made on the user's behalf. Integrated-server gameplay is a separate client check.
- 17 offline Python tests cover corrupt/cached artifacts, server extraction/traversal rejection, decompilation inventory, publication exclusions, dependency closure, safe download paths, pack format, OS/ARM native selection, and comparison mismatches.
- Original Java metrics tests cover percentiles, the average of the slowest 1% (not the reciprocal of p99), stall boundaries, bounded samples/overflow, filename sanitization, exclusions and player counts.
- Existing three Rust differential tests, formatting and Clippy checks pass. Rust kernels remain unintegrated.
## Interpretation limits
The local Linux host uses **Mesa llvmpipe software rendering**. It is useful for mod/mixin/startup/report validation, not for predicting M2 Pro, Windows GPU or Linux discrete-GPU performance. Warm-up/world loading on this host is slow. Demo credentials produce expected unavailable account-properties/Realms logs, and chat restrictions prevent chat commands; the independent F8 measurement shortcut supports this case.
CI compiles/builds on Linux, Windows and Apple Silicon macOS. Successful compilation is not graphics, authentication, UI or Mac-driver runtime validation. macOS 27 and the user's actual M2 Pro have not been tested here. Optional cinematic shaders and Vulkan are experiments; the OpenGL balanced pack is the first manual test.
No numerical game speedup, least-memory claim, exhaustive vanilla equivalence, universal GPU support, or 50-active-player result is claimed. Worlds need copies, repeated matched routes and real hardware measurements before decisions about deeper replacements. New terrain generation and steady-state rendering are separate workloads.
## Release content
Packs embed only the original MIT Horizon Lab JAR and config. Mod/game/library downloads retain upstream licenses and are checked against pinned hashes. No game JAR, class, decompiled source, asset, world or credential is committed or uploaded in a starter. The narrow publication allowance is for original Java under `dev/horizonlab`, and the built JAR checks its emitted class namespace.
+42
View File
@@ -0,0 +1,42 @@
Horizon server 0.2.0 — Minecraft 26.3, Fabric 0.19.5, Java 25
Install Python 3.10+ and native Java 25. Extract this ZIP and open a terminal here.
python3 tools/server.py prepare
Read Minecraft's EULA at https://www.minecraft.net/eula. Create/edit
.local/server/optimized/eula.txt to contain eula=true if you agree, then:
python3 tools/server.py run --heap 4G
Windows: use python in place of python3 if needed. Server downloads and assets
stay in .local. No game code, third-party mod JARs or credentials are bundled.
Lithium and FerriteCore optimize the original simulation/storage; tick rate and
vanilla gameplay rules are retained. No Paper-style gameplay configuration.
From the server console:
horizonserver bench populated-50 120
horizonserver stop
From an operator's in-game chat, prefix each command with /. JSON/CSV reports
appear in the instance's horizon-benchmarks directory. They record actual peak
players, tick execution durations, observed tick count per elapsed second,
JVM heap/GC and platform metadata. meanRate is tick execution capacity, NOT TPS.
An idle server does not establish performance for 50 active players.
Baseline:
python3 tools/server.py prepare --baseline
python3 tools/server.py run --baseline --heap 4G
Use separate world copies with the same seed, settings, Java and maximum heap.
Only run one at a time unless you give them distinct ports/resources. When
benchmarking 50 players include normal exploration, entity farms, redstone and
chunk loading; repeat with 1, 10 and 100. Do not change simulation/view distance
between matched runs or turn off game logic to manufacture a speedup.
This first release has not been validated under a 50-player real workload.
Compare generated reports:
python3 tools/compare_benchmarks.py baseline-ticks.json optimized-ticks.json --strict
Baseline must be a separate instance: --baseline adds no optimizers but doesn't
delete mods from an existing optimized instance. Use clean directories.
@@ -0,0 +1,64 @@
package dev.horizonlab;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.arguments.StringArgumentType;
import dev.horizonlab.metrics.Recording;
import dev.horizonlab.metrics.Reports;
import java.nio.file.Path;
import java.util.Map;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.Component;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.permissions.Permissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class HorizonLab implements ModInitializer {
public static final Logger LOGGER = LoggerFactory.getLogger("horizonlab");
private static volatile Recording ticks;
@Override public void onInitialize() {
CommandRegistrationCallback.EVENT.register((dispatcher, context, selection) -> dispatcher.register(
Commands.literal("horizonserver")
.requires(source -> source.permissions().hasPermission(Permissions.COMMANDS_ADMIN))
.then(Commands.literal("bench")
.then(Commands.argument("label", StringArgumentType.word())
.then(Commands.argument("seconds", IntegerArgumentType.integer(10, 600))
.executes(command -> {
boolean started = startTicks(StringArgumentType.getString(command, "label"),
IntegerArgumentType.getInteger(command, "seconds"), Path.of("horizon-benchmarks"), "server");
command.getSource().sendSuccess(() -> Component.literal(started
? "Horizon: recording tick times; run the intended workload now."
: "Horizon: a tick recording is already active."), false);
return started ? 1 : 0;
}))))
.then(Commands.literal("stop").executes(command -> { finishTicks(); return 1; }))));
LOGGER.info("Horizon Lab ready. Simulation rules and tick rate are unchanged.");
}
public static synchronized boolean startTicks(String label, int seconds, Path output, String profile) {
if (ticks != null) return false;
ticks = new Recording(label, "ticks", output, seconds, Map.of("profile", profile, "minecraft", "26.3"));
return true;
}
public static void tick(long durationNs, MinecraftServer server) {
Recording recording = ticks;
if (recording == null) return;
recording.add(durationNs);
recording.players(server.getPlayerList().getPlayerCount());
if (System.nanoTime() >= recording.deadlineNs) finishTicks();
}
public static synchronized void finishTicks() {
Recording recording = ticks;
if (recording == null) return;
ticks = null;
Reports.write(recording.finish()).whenComplete((path, error) -> {
if (error != null) LOGGER.error("Tick report failed", error);
else LOGGER.info("Horizon tick benchmark saved to {}", path);
});
}
}
@@ -0,0 +1,130 @@
package dev.horizonlab.client;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.platform.InputConstants;
import dev.horizonlab.HorizonLab;
import dev.horizonlab.metrics.Recording;
import dev.horizonlab.metrics.Reports;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.Map;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback;
import net.fabricmc.fabric.api.client.keymapping.v1.KeyMappingHelper;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.client.Minecraft;
import net.minecraft.client.KeyMapping;
import net.minecraft.network.chat.Component;
import static net.fabricmc.fabric.api.client.command.v2.ClientCommands.argument;
import static net.fabricmc.fabric.api.client.command.v2.ClientCommands.literal;
public final class HorizonClient implements ClientModInitializer {
private static Recording frames;
private static long previousStart;
private static String profile = "custom";
@Override public void onInitializeClient() {
KeyMapping benchmarkKey = KeyMappingHelper.registerKeyMapping(new KeyMapping(
"key.horizonlab.benchmark", InputConstants.KEY_F8, KeyMapping.Category.MISC));
ClientTickEvents.END_CLIENT_TICK.register(client -> {
while (benchmarkKey.consumeClick()) {
if (client.level != null && client.gui.screen() == null) {
if (frames == null) start(profile, 120); else finish();
}
}
});
Path profileFile = FabricLoader.getInstance().getConfigDir().resolve("horizon-profile.txt");
try {
if (Files.exists(profileFile)) profile = Files.readString(profileFile).strip();
} catch (Exception error) { HorizonLab.LOGGER.warn("Profile label could not be read", error); }
ClientCommandRegistrationCallback.EVENT.register((dispatcher, context) -> dispatcher.register(
literal("horizon")
.then(literal("bench")
.executes(command -> start("benchmark", 120))
.then(argument("label", StringArgumentType.word())
.executes(command -> start(StringArgumentType.getString(command, "label"), 120))
.then(argument("seconds", IntegerArgumentType.integer(10, 600))
.executes(command -> start(StringArgumentType.getString(command, "label"),
IntegerArgumentType.getInteger(command, "seconds"))))))
.then(literal("stop").executes(command -> { finish(); return 1; }))
.then(literal("status").executes(command -> {
message("Profile: " + profile + "; recording: " + (frames != null)); return 1;
}))));
HorizonLab.LOGGER.info("Horizon client profile: {}. F8 or /horizon bench <label> [seconds]", profile);
}
private static int start(String label, int seconds) {
if (frames != null) { message("A benchmark is already recording; /horizon stop finishes it."); return 0; }
Minecraft client = Minecraft.getInstance();
Path output = client.gameDirectory.toPath().resolve("horizon-benchmarks");
Map<String, Object> context = new LinkedHashMap<>();
context.put("minecraft", "26.3");
context.put("profile", profile);
context.put("render_distance", client.options.renderDistance().get());
context.put("simulation_distance", client.options.simulationDistance().get());
context.put("vsync", client.options.enableVsync().get());
context.put("fps_limit", client.options.framerateLimit().get());
context.put("framebuffer_width", client.getWindow().getWidth());
context.put("framebuffer_height", client.getWindow().getHeight());
var device = RenderSystem.getDevice().getDeviceInfo();
context.put("gpu", device.name());
context.put("graphics_backend", device.backendName());
context.put("graphics_driver", device.driverInfo());
context.put("graphics_preset", client.options.graphicsPreset().get().toString());
context.put("ambient_occlusion", client.options.ambientOcclusion().get());
context.put("improved_transparency", client.options.improvedTransparency().get());
context.put("mipmap_levels", client.options.mipmapLevels().get());
context.put("entity_distance_scaling", client.options.entityDistanceScaling().get());
context.put("entity_shadows", client.options.entityShadows().get());
context.put("particles", client.options.particles().get().toString());
context.put("clouds", client.options.cloudStatus().get().toString());
context.put("cloud_range", client.options.cloudRange().get());
context.put("mods", FabricLoader.getInstance().getAllMods().stream()
.map(mod -> mod.getMetadata().getId() + "@" + mod.getMetadata().getVersion().getFriendlyString())
.sorted().toList());
frames = new Recording(label, "frames", output, seconds, context);
previousStart = 0;
if (client.getSingleplayerServer() != null) HorizonLab.startTicks(label, seconds, output, profile);
message("Recording " + seconds + " seconds. Close chat, keep the game focused, and run your route.");
return 1;
}
public static void frameStart() {
Recording recording = frames;
if (recording == null) return;
long now = System.nanoTime();
if (now >= recording.deadlineNs) { finish(); return; }
Minecraft client = Minecraft.getInstance();
if (client.level == null || client.isPaused() || !client.isWindowActive() || client.gui.screen() != null) {
recording.exclude();
previousStart = 0;
return;
}
if (previousStart != 0) recording.add(now - previousStart);
previousStart = now;
}
private static void finish() {
Recording recording = frames;
if (recording == null) return;
frames = null;
previousStart = 0;
HorizonLab.finishTicks();
Reports.write(recording.finish()).whenComplete((path, error) -> {
if (error != null) HorizonLab.LOGGER.error("Frame report failed", error);
else {
HorizonLab.LOGGER.info("Horizon frame benchmark saved to {}", path);
Minecraft.getInstance().execute(() -> message("Benchmark saved: " + path.getFileName()));
}
});
}
private static void message(String text) {
Minecraft client = Minecraft.getInstance();
if (client.gui != null) client.gui.hud.getChat().addClientSystemMessage(Component.literal("[Horizon] " + text));
}
}
@@ -0,0 +1,83 @@
package dev.horizonlab.metrics;
import java.lang.management.ManagementFactory;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
/** One preallocated bounded buffer per recording, no per-sample allocations or disk I/O. */
public final class Recording {
public static final int MAX_SAMPLES = 300_000;
public final String label;
public final String kind;
public final Path output;
public final long startedNs;
public final long deadlineNs;
public final Map<String, Object> context;
private final long[] samples = new long[MAX_SAMPLES];
private int count;
private int dropped;
private int excluded;
private int peakPlayers;
private final long initialGcCount;
private final long initialGcMs;
public Recording(String label, String kind, Path output, int seconds, Map<String, Object> context) {
if (seconds < 1 || seconds > 600) throw new IllegalArgumentException("Duration must be 1..600 seconds");
String safeLabel = label.replaceAll("[^A-Za-z0-9_-]", "_");
this.label = safeLabel.substring(0, Math.min(safeLabel.length(), 64));
this.kind = kind;
this.output = output;
this.context = new LinkedHashMap<>(context);
this.startedNs = System.nanoTime();
this.deadlineNs = startedNs + seconds * 1_000_000_000L;
this.initialGcCount = gcCount();
this.initialGcMs = gcMs();
}
public synchronized void add(long ns) {
if (ns <= 0) return;
if (count == samples.length) { dropped++; return; }
samples[count++] = ns;
}
public synchronized void exclude() { excluded++; }
public synchronized void players(int players) { peakPlayers = Math.max(players, peakPlayers); }
public synchronized Snapshot finish() {
Map<String, Object> metadata = new LinkedHashMap<>(context);
metadata.put("label", label);
metadata.put("kind", kind);
metadata.put("schema", 1);
double elapsed = (System.nanoTime() - startedNs) / 1e9;
metadata.put("elapsed_seconds", elapsed);
if (kind.equals("ticks")) metadata.put("observed_ticks_per_second", (count + (long) dropped) / elapsed);
metadata.put("dropped_samples", dropped);
metadata.put("excluded_frames", excluded);
metadata.put("peak_players", peakPlayers);
metadata.put("java_version", System.getProperty("java.version"));
metadata.put("os", System.getProperty("os.name"));
metadata.put("os_version", System.getProperty("os.version"));
metadata.put("architecture", System.getProperty("os.arch"));
metadata.put("logical_processors", Runtime.getRuntime().availableProcessors());
metadata.put("heap_used_end_bytes", ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed());
metadata.put("heap_committed_end_bytes", ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getCommitted());
metadata.put("heap_max_bytes", Runtime.getRuntime().maxMemory());
metadata.put("gc_collections", gcCount() - initialGcCount);
metadata.put("gc_time_ms", gcMs() - initialGcMs);
return new Snapshot(label, kind, output, Arrays.copyOf(samples, count), metadata);
}
private static long gcCount() {
return ManagementFactory.getGarbageCollectorMXBeans().stream()
.mapToLong(gc -> Math.max(0, gc.getCollectionCount())).sum();
}
private static long gcMs() {
return ManagementFactory.getGarbageCollectorMXBeans().stream()
.mapToLong(gc -> Math.max(0, gc.getCollectionTime())).sum();
}
public record Snapshot(String label, String kind, Path output, long[] samples, Map<String, Object> metadata) {}
}
@@ -0,0 +1,43 @@
package dev.horizonlab.metrics;
import com.google.gson.GsonBuilder;
import java.io.BufferedWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
public final class Reports {
private Reports() {}
public static CompletableFuture<Path> write(Recording.Snapshot snapshot) {
return CompletableFuture.supplyAsync(() -> {
try {
Files.createDirectories(snapshot.output());
String name = snapshot.label() + "-" + snapshot.kind() + "-" + Instant.now().toEpochMilli();
Path csv = snapshot.output().resolve(name + ".csv");
try (BufferedWriter writer = Files.newBufferedWriter(csv, StandardCharsets.UTF_8)) {
writer.write("sample,duration_ns\n");
for (int i = 0; i < snapshot.samples().length; i++) {
writer.write(i + "," + snapshot.samples()[i] + "\n");
}
}
SampleStats stats = SampleStats.of(snapshot.samples(), snapshot.samples().length);
Map<String, Object> report = new LinkedHashMap<>(snapshot.metadata());
report.put("stats", stats);
report.put("samples_file", csv.getFileName().toString());
report.put("note", snapshot.kind().equals("frames")
? "Frame start intervals include frame limiting and presentation waits; menus, pauses and unfocused frames are excluded. Not GPU timings or process RSS."
: "Tick execution durations exclude scheduler sleep. meanRate is execution capacity, not observed TPS.");
Path json = snapshot.output().resolve(name + ".json");
Files.writeString(json, new GsonBuilder().setPrettyPrinting().create().toJson(report) + "\n");
return json;
} catch (Exception exception) {
throw new IllegalStateException("Could not write Horizon benchmark", exception);
}
});
}
}
@@ -0,0 +1,36 @@
package dev.horizonlab.metrics;
import java.util.Arrays;
/** Original bounded measurement utilities; no Minecraft dependency. */
public record SampleStats(int count, double meanMs, double p50Ms, double p95Ms,
double p99Ms, double maxMs, double meanRate, double lowOnePercentRate,
int over16Ms, int over33Ms, int over50Ms, int over100Ms) {
public static SampleStats of(long[] samples, int count) {
if (count < 0 || count > samples.length) throw new IllegalArgumentException("Invalid sample count");
if (count == 0) return new SampleStats(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
long[] sorted = Arrays.copyOf(samples, count);
double sum = 0;
int over16 = 0, over33 = 0, over50 = 0, over100 = 0;
for (long ns : sorted) {
if (ns <= 0) throw new IllegalArgumentException("Sample duration must be positive");
sum += ns;
if (ns > 16_666_667L) over16++;
if (ns > 33_333_333L) over33++;
if (ns > 50_000_000L) over50++;
if (ns > 100_000_000L) over100++;
}
Arrays.sort(sorted);
int tail = Math.max(1, (int) Math.ceil(count * 0.01));
double tailSum = 0;
for (int i = count - tail; i < count; i++) tailSum += sorted[i];
return new SampleStats(count, sum / count / 1e6, quantile(sorted, 0.50) / 1e6,
quantile(sorted, 0.95) / 1e6, quantile(sorted, 0.99) / 1e6,
sorted[count - 1] / 1e6, 1e9 * count / sum, 1e9 * tail / tailSum,
over16, over33, over50, over100);
}
private static long quantile(long[] sorted, double fraction) {
return sorted[Math.max(0, (int) Math.ceil(sorted.length * fraction) - 1)];
}
}
@@ -0,0 +1,16 @@
package dev.horizonlab.mixin;
import dev.horizonlab.client.HorizonClient;
import net.minecraft.client.Minecraft;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(Minecraft.class)
public abstract class FrameMixin {
@Inject(method = "runTick", at = @At("HEAD"))
private void horizonFrame(boolean advanceGameTime, CallbackInfo callback) {
HorizonClient.frameStart();
}
}
@@ -0,0 +1,25 @@
package dev.horizonlab.mixin;
import dev.horizonlab.HorizonLab;
import java.util.function.BooleanSupplier;
import net.minecraft.server.MinecraftServer;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(MinecraftServer.class)
public abstract class ServerTickMixin {
@Unique private long horizonTickStart;
@Inject(method = "tickServer", at = @At("HEAD"))
private void horizonBegin(BooleanSupplier haveTime, CallbackInfo callback) {
horizonTickStart = System.nanoTime();
}
@Inject(method = "tickServer", at = @At("RETURN"))
private void horizonEnd(BooleanSupplier haveTime, CallbackInfo callback) {
HorizonLab.tick(System.nanoTime() - horizonTickStart, (MinecraftServer) (Object) this);
}
}
@@ -0,0 +1,3 @@
{
"key.horizonlab.benchmark": "Start / stop performance recording (120 seconds)"
}
@@ -0,0 +1,21 @@
{
"schemaVersion": 1,
"id": "horizonlab",
"version": "0.2.0",
"name": "Horizon Lab",
"description": "Client frame pacing and server tick measurements for reproducible optimization experiments.",
"authors": ["Ludovic"],
"license": "MIT",
"environment": "*",
"entrypoints": {
"main": ["dev.horizonlab.HorizonLab"],
"client": ["dev.horizonlab.client.HorizonClient"]
},
"mixins": ["horizonlab.mixins.json"],
"depends": {
"fabricloader": ">=0.19.5",
"fabric-api": "*",
"minecraft": "26.3",
"java": ">=25"
}
}
@@ -0,0 +1,8 @@
{
"required": true,
"package": "dev.horizonlab.mixin",
"compatibilityLevel": "JAVA_25",
"mixins": ["ServerTickMixin"],
"client": ["FrameMixin"],
"injectors": {"defaultRequire": 1}
}
@@ -0,0 +1,35 @@
package dev.horizonlab.metrics;
import java.nio.file.Path;
import java.util.Map;
public final class MetricsTest {
public static void main(String[] args) {
SampleStats empty = SampleStats.of(new long[0], 0);
check(empty.count() == 0 && empty.meanRate() == 0, "empty recording");
SampleStats fixed = SampleStats.of(new long[]{10_000_000, 10_000_000, 10_000_000}, 3);
check(fixed.meanRate() == 100 && fixed.lowOnePercentRate() == 100, "constant pacing");
long[] data = new long[100];
java.util.Arrays.fill(data, 10_000_000);
data[99] = 100_000_000;
SampleStats spike = SampleStats.of(data, 100);
check(spike.p99Ms() == 10 && spike.maxMs() == 100 && spike.lowOnePercentRate() == 10,
"nearest-rank percentiles and slowest-one-percent mean");
check(spike.over50Ms() == 1 && spike.over100Ms() == 0, "stall boundaries");
Recording recording = new Recording("../../recording label", "frames", Path.of("unused"), 120, Map.of());
for (int i = 0; i < Recording.MAX_SAMPLES + 2; i++) recording.add(10_000_000);
recording.exclude();
recording.players(50);
Recording.Snapshot snapshot = recording.finish();
check(snapshot.samples().length == Recording.MAX_SAMPLES, "bounded buffer");
check(snapshot.metadata().get("dropped_samples").equals(2), "overflow reported");
check(snapshot.metadata().get("excluded_frames").equals(1), "excluded frames reported");
check(snapshot.metadata().get("peak_players").equals(50), "workload size reported");
check(!snapshot.label().contains("/"), "safe report filename");
System.out.println("Metrics tests passed.");
}
private static void check(boolean condition, String name) {
if (!condition) throw new AssertionError(name);
}
}
+32
View File
@@ -0,0 +1,32 @@
#!/bin/bash
set -euo pipefail
cd "$(dirname "$0")"
PACK="$PWD/horizon-m2-balanced-0.2.0.mrpack"
if [[ ! -f "$PACK" ]]; then
printf 'Keep this script beside the .mrpack files from the extracted starter ZIP.\n'
exit 1
fi
APP=""
for candidate in "/Applications/Prism Launcher.app" "$HOME/Applications/Prism Launcher.app"; do
if [[ -d "$candidate" ]]; then APP="$candidate"; break; fi
done
if [[ -z "$APP" ]]; then
printf 'Installing official Prism Launcher 11.1.1 into ~/Applications...\n'
TEMP_DIR=$(mktemp -d)
trap 'rm -rf "$TEMP_DIR"' EXIT
curl --fail --location --retry 3 --output "$TEMP_DIR/prism.zip" \
'https://github.com/PrismLauncher/PrismLauncher/releases/download/11.1.1/PrismLauncher-macOS-11.1.1.zip'
printf '%s %s\n' '15126a7df57acb4f37fe581dad68cb03c7bb60b70eb82345f8bb3246235600c6' "$TEMP_DIR/prism.zip" | shasum -a 256 -c -
ditto -x -k "$TEMP_DIR/prism.zip" "$TEMP_DIR/unpacked"
mkdir -p "$HOME/Applications"
APP="$HOME/Applications/Prism Launcher.app"
if [[ ! -d "$TEMP_DIR/unpacked/Prism Launcher.app" ]]; then
printf 'Unexpected official launcher archive layout. Install Prism from https://prismlauncher.org/download/macOS/\n'
exit 1
fi
mv "$TEMP_DIR/unpacked/Prism Launcher.app" "$APP"
fi
printf '\nIn Prism: sign into Microsoft yourself, allow automatic Java 25 download, import the pack, and launch.\n'
printf 'For this 16 GB Mac set maximum memory to 6144 MiB; start at 1280x800 or 1920x1200.\n'
printf 'Read START-HERE.txt for the baseline comparison and graphics profiles.\n\n'
open -a "$APP" --args --import "$PACK"
+79
View File
@@ -0,0 +1,79 @@
HORIZON LAB 0.2.0 — first playable optimization release
YOUR MAC
1. Extract this ZIP. Double-click Mac-Start.command. If macOS asks, use Open
from the file's context menu. It installs the official Prism Launcher in
~/Applications if needed and opens the M2 balanced pack import.
Alternatively install Prism yourself: https://prismlauncher.org/download/macOS/
then Add Instance > Import > horizon-m2-balanced-0.2.0.mrpack.
2. Sign into your Microsoft account in Prism yourself. No credentials are
shared with this project. You need an owned Minecraft Java license.
3. Enable Prism automatic Java downloads, using Java 25 ARM64 on Apple Silicon.
Instance > Edit > Settings > Java: maximum memory 6144 MiB, minimum 512 MiB.
If auto Java fails, install a native ARM64 Java 25 JDK and select it there.
4. Launch. Start with a new test world or a COPY of a world from Minecraft 26.3.
This release is 26.3; do not load an older-version world for a fair comparison.
Choose 1280x800 or 1920x1200 before testing; the Retina screen's full native
resolution is a substantially larger GPU workload.
WINDOWS / LINUX
Install Prism from https://prismlauncher.org/download/ and import the same packs.
Use Java 25 matching your CPU architecture. No Rust compilation is required.
PROFILES
- m2-balanced: 12 chunks of full-detail terrain plus 128 chunks of distant LOD.
Sodium, Lithium, FerriteCore, ImmediatelyFast, EntityCulling, Distant Horizons.
Recommended first test for your 16 GB M2 Pro. OpenGL, shaders not installed.
- baseline: original game renderer and simulation with Fabric API and the same
Horizon timing instrument. 12 full-detail chunks, no performance mods or LOD.
Use the SAME 6144 MiB maximum heap as m2-balanced for a fair comparison.
- low-memory: 8 full-detail chunks, no LOD. Set maximum memory 3072 MiB.
For a matched comparison set both instances to the same render distance.
- far-distance: 12 full-detail plus 256 LOD chunks. Start with 8192 MiB ONLY on
machines with enough physical RAM; this is not the recommended 16 GB Mac pack.
- cinematic: M2 pack plus Iris and Complementary Reimagined. Shaders start OFF.
Video Settings > Shader Packs lets you enable them. They cost GPU time; Mac
driver limitations may cause visual issues. Try after the balanced pack works.
- vulkan: experimental Vulkan preference with the game's OpenGL fallback,
no Iris. Test independently against OpenGL; faster is hardware-dependent.
All profiles retain simulation distance 12 and normal 20 TPS. These are initial
budgets, not promises of identical speed on every CPU/GPU. More distant LOD uses
simplified geometry; blocks nearby retain full detail. Building a fresh LOD cache
costs CPU/disk/memory. Wait for it to settle before judging steady-state FPS.
Background distant generation does not replace your normal gameplay simulation.
MEASURE ON YOUR M2 PRO
1. Import baseline too. Close every other Minecraft instance. Plug in the Mac,
disable Low Power Mode, and use the same window size, FPS cap, VSync setting,
render distance, simulation distance, world COPY, and camera route in each.
2. Warm each world for 2–3 minutes; allow distant generation to settle. Test new
chunk exploration separately from already-generated terrain. Do not compare
baseline's warmed world against an optimized world's first-time generation.
3. Press F8 in gameplay to start a 120-second recording; press again to stop.
On Mac you may need Fn+F8 if media keys take priority. You can rebind it in
Controls. Alternatively run /horizon bench baseline 120, close chat and play
your route. In balanced use /horizon bench m2 120. /horizon stop ends early.
/horizon status shows the profile. F8 also works when chat is restricted.
4. Open Prism's instance Minecraft folder > horizon-benchmarks. Each run writes
frames JSON/CSV and integrated-server ticks JSON/CSV. They include average FPS,
slowest-1%-average FPS, p95/p99 frame durations, stalls and JVM heap/GC data.
Menus, pauses and unfocused frames are excluded. Tick execution time is not
the observed TPS. JVM heap is not whole-process memory or unified GPU memory.
5. Repeat at least three times, alternating baseline/optimized. For daily play
turn VSync back on or cap FPS to your display; uncapped FPS spends more power.
DH changes clouds, chunk fade and transparency to blend its distant renderer;
assess visual differences as well as speed. For collector experiments test
Java 25's -XX:+UseZGC against its default G1 in both profiles; ZGC trades some
CPU/memory for shorter pauses and is not an automatic win on a 16 GB machine.
This build is a playable Java optimization stack with original measurement code.
It is NOT a completed Rust rewrite, a new custom renderer, or a measured M2 speedup.
It has no gameplay feature additions and is intended to preserve vanilla rules;
exhaustive vanilla equivalence has not been proven. Start on world copies.
Only original project binaries are embedded. Mods, the game and assets download
from their publishers with pinned hashes. No decompiled Minecraft is distributed.
Source, build commands and measured validation:
https://github.com/ludovic111/minecraft-optimization-lab
+18
View File
@@ -0,0 +1,18 @@
# Only explicit overrides; DH fills in other defaults on first launch.
[common.multiThreading]
numberOfThreads = 2
threadRunTimeRatio = "0.5"
threadPriority = 3
[common.worldGenerator]
limitIfServerUnhealthy = true
pauseIfMovingQuickly = true
[client.advanced.graphics.quality]
lodChunkRenderDistanceRadius = 128
horizontalQuality = "MEDIUM"
verticalQuality = "MEDIUM"
[client.advanced.autoUpdater]
enableAutoUpdater = false
enableSilentUpdates = false
+17
View File
@@ -0,0 +1,17 @@
[common.multiThreading]
numberOfThreads = 4
threadRunTimeRatio = "0.5"
threadPriority = 3
[common.worldGenerator]
limitIfServerUnhealthy = true
pauseIfMovingQuickly = true
[client.advanced.graphics.quality]
lodChunkRenderDistanceRadius = 256
horizontalQuality = "MEDIUM"
verticalQuality = "MEDIUM"
[client.advanced.autoUpdater]
enableAutoUpdater = false
enableSilentUpdates = false
+18
View File
@@ -0,0 +1,18 @@
# Only explicit overrides; DH fills in other defaults on first launch.
[common.multiThreading]
numberOfThreads = 2
threadRunTimeRatio = "0.5"
threadPriority = 3
[common.worldGenerator]
limitIfServerUnhealthy = true
pauseIfMovingQuickly = true
[client.advanced.graphics.quality]
lodChunkRenderDistanceRadius = 128
horizontalQuality = "MEDIUM"
verticalQuality = "MEDIUM"
[client.advanced.autoUpdater]
enableAutoUpdater = false
enableSilentUpdates = false
+18
View File
@@ -0,0 +1,18 @@
# Only explicit overrides; DH fills in other defaults on first launch.
[common.multiThreading]
numberOfThreads = 2
threadRunTimeRatio = "0.5"
threadPriority = 3
[common.worldGenerator]
limitIfServerUnhealthy = true
pauseIfMovingQuickly = true
[client.advanced.graphics.quality]
lodChunkRenderDistanceRadius = 128
horizontalQuality = "MEDIUM"
verticalQuality = "MEDIUM"
[client.advanced.autoUpdater]
enableAutoUpdater = false
enableSilentUpdates = false
+75
View File
@@ -0,0 +1,75 @@
{
"id": "fabric-loader-0.19.5-26.3",
"inheritsFrom": "26.3",
"releaseTime": "2026-10-03T15:06:21+0000",
"time": "2026-10-03T15:06:21+0000",
"type": "release",
"mainClass": "net.fabricmc.loader.impl.launch.knot.KnotClient",
"arguments": {
"game": [],
"jvm": [
"-DFabricMcEmu= net.minecraft.client.main.Main "
]
},
"libraries": [
{
"name": "org.ow2.asm:asm:9.10.1",
"url": "https://maven.fabricmc.net/",
"md5": "9cb72080438acf27f2607002e1444a7b",
"sha1": "ada2141c0cc52ee8f5c48cd5fa4ce0e794f22236",
"sha256": "ed825d10ab1399c8c0cb669e688cf0c8c82629b4c8399b58352b68e92ca10fcb",
"sha512": "8db6efa37d4d569bf2b95d90931b8064f87ed928d20bbf8d8e7fa6182e9a11d32e6a2cc034a3d173a38ee70ce2ea9f20f52f9d8730d9401d2bc6060674c18928",
"size": 126151
},
{
"name": "org.ow2.asm:asm-analysis:9.10.1",
"url": "https://maven.fabricmc.net/",
"md5": "6dd9011ec87f65e4b2e14e938c4118e4",
"sha1": "8d49f14d51f632cb1d87c88d1ceaf50db0d8af1b",
"sha256": "dede75a21306b65974ecd8f87114ff6970f09fb794157a4ca09ab25c888c2bfc",
"sha512": "0542a90be38f81e39ef43a9253630a2d59f82c17c24492f005c67619561308afbbd23bf8504d3e83b1d4cebe5746126da76037473ddac3071b028c2ae279296b",
"size": 35140
},
{
"name": "org.ow2.asm:asm-commons:9.10.1",
"url": "https://maven.fabricmc.net/",
"md5": "8eee0b1bdd046baf472eb83dd5e6bb44",
"sha1": "4229e4c55fd8e01c23f9fe9884075cc628aacc50",
"sha256": "6d0abefb7cbf972ea16edb37ec14835372505063a45f976ab7ea889ed9497895",
"sha512": "8540a8f9a63b22bae54fc501f2da405c2c1c45fa13921a1193629cfbfbb716473f8a19984559af7b0b1ea3814d439ec445ea1cfeb159bf922bb7e60a40acf823",
"size": 74840
},
{
"name": "org.ow2.asm:asm-tree:9.10.1",
"url": "https://maven.fabricmc.net/",
"md5": "62541e1dc62331408ef31317555bf4fa",
"sha1": "e244332a17564c1d1572449399a842de35881be2",
"sha256": "3dfb0d5b6a106cd40b5b250e39935fbf2f927f4477546a5369a3ac609cf0506b",
"sha512": "2ffe5bbfac53bbacc1e4e474628b4247fb1c5f592017f393a327b3f2d2a72a338263f2f6549a42cea57a42f676b967153a10a22aae46affed83608f74daf3768",
"size": 51958
},
{
"name": "org.ow2.asm:asm-util:9.10.1",
"url": "https://maven.fabricmc.net/",
"md5": "d0892ecb209867805e7d2418e5dc6c42",
"sha1": "7bb9d450e8d4cbf9f9e04096c44bbfe7fba80b15",
"sha256": "1bb99d091fba2597dc6d51193e9bbcf0d8447e7ed96bd8f0198b18152f09655c",
"sha512": "7330ded981ddeb01b302cba12d56b419207b6b02ebfaf814cbbc3d2d2d1055e055294ce108ac9e4de9e1d0f3c4e0064f133e87e8085922241c1a2e5fa1fedd2c",
"size": 95628
},
{
"name": "net.fabricmc:sponge-mixin:0.17.4+mixin.0.8.7",
"url": "https://maven.fabricmc.net/",
"md5": "9e33b145b2a46fbc70daf532e3705066",
"sha1": "5f66cc9f59b8efaa942155a3d5a30599bf6640dd",
"sha256": "1f0ae44db7295f8626f33b1dc0ad7f043d8954a8d6847247875fcc5dfcecc934",
"sha512": "837b479c7e831463e074b56314259952f2f82c2ec8ddd71930514ca04f97bb488f43fdb2d4608e7f3fad334604a546053256844ea653542bae8d25bbdab66e21",
"size": 1539080
},
{
"name": "net.fabricmc:fabric-loader:0.19.5",
"url": "https://maven.fabricmc.net/",
"sha256": "93044e4dd46de5d8136701292f05e868da096d2c9fddb4793e4fdbcc63efc695"
}
]
}
+322
View File
@@ -0,0 +1,322 @@
{
"format": 1,
"minecraft": "26.3",
"java_major": 25,
"fabric_loader": "0.19.5",
"pack_version": "0.2.0",
"projects": {
"sodium": {
"slug": "sodium",
"project_id": "AANobbMI",
"version_id": "bAZQdGpg",
"version": "mc26.3-0.9.2-fabric",
"game_versions": [
"26.3"
],
"loaders": [
"fabric"
],
"license": "LicenseRef-Polyform-Shield-1.0.0",
"source": "https://github.com/CaffeineMC/sodium",
"url": "https://cdn.modrinth.com/data/AANobbMI/versions/bAZQdGpg/sodium-fabric-0.9.2%2Bmc26.3.jar",
"filename": "sodium-fabric-0.9.2+mc26.3.jar",
"size": 1908068,
"hashes": {
"sha1": "9acfe851e36f4fb27d7c5baa224e8bd4e0334283",
"sha512": "f3f260f204b8ce5e8777c2c73f537956755ec61f3817b0b78b5e5568e8aa40f14891f146475075109747665c7c88a45ca0ca9a8df3c68d79c58ecdaa8d8c4b93"
},
"dependencies": [],
"client_side": "required",
"server_side": "unsupported"
},
"lithium": {
"slug": "lithium",
"project_id": "gvQqBUqZ",
"version_id": "xS0Q8LSi",
"version": "mc26.3-0.26.2-fabric",
"game_versions": [
"26.3"
],
"loaders": [
"fabric",
"quilt"
],
"license": "LGPL-3.0-only",
"source": "https://github.com/caffeinemc/lithium-fabric",
"url": "https://cdn.modrinth.com/data/gvQqBUqZ/versions/xS0Q8LSi/lithium-fabric-0.26.2%2Bmc26.3.jar",
"filename": "lithium-fabric-0.26.2+mc26.3.jar",
"size": 914543,
"hashes": {
"sha512": "4d7fee66132eedc71feab9390b92c95d7058edbdad0fecfac1d836a2950b97a7ca463afbede61c7ef361ce65e1f927ab9e89dde5bf2e0e0ce486afb5c5dbee40",
"sha1": "dd5a4ec2c68d7601d8bce9076f789c55a5f8bef3"
},
"dependencies": [],
"client_side": "optional",
"server_side": "optional"
},
"iris": {
"slug": "iris",
"project_id": "YL57xq9U",
"version_id": "vTN4NRGW",
"version": "1.11.7+26.3-fabric",
"game_versions": [
"26.3"
],
"loaders": [
"fabric"
],
"license": "LGPL-3.0-only",
"source": "https://github.com/IrisShaders/Iris",
"url": "https://cdn.modrinth.com/data/YL57xq9U/versions/vTN4NRGW/iris-fabric-1.11.7%2Bmc26.3.jar",
"filename": "iris-fabric-1.11.7+mc26.3.jar",
"size": 2850938,
"hashes": {
"sha1": "fa03640ba1e4ef2f7ae3619c6373a06e46d0ba2c",
"sha512": "d8d3312f77fc52a48e4a6cd836fda33669bdebcb4de0b8c0d30adc808b287330a533e0baef355cc1ce6336a26851d9775369a802a4666b7b7a6266af20088f42"
},
"dependencies": [
{
"version_id": "bAZQdGpg",
"project_id": "AANobbMI",
"file_name": null,
"dependency_type": "required"
}
],
"client_side": "required",
"server_side": "unsupported"
},
"distanthorizons": {
"slug": "distanthorizons",
"project_id": "uCdwusMi",
"version_id": "TGgEbP9A",
"version": "3.3.4-26.3",
"game_versions": [
"26.3"
],
"loaders": [
"fabric",
"neoforge"
],
"license": "LGPL-3.0-only",
"source": "https://gitlab.com/distant-horizons-team/distant-horizons",
"url": "https://cdn.modrinth.com/data/uCdwusMi/versions/TGgEbP9A/DistantHorizons-3.3.4-26.3-fabric-neoforge.jar",
"filename": "DistantHorizons-3.3.4-26.3-fabric-neoforge.jar",
"size": 28476894,
"hashes": {
"sha512": "0b90b1b08d99974bfc3c8e86b2ceb252e2f91715ed66b925004c28335fb44e1bddbbb6b8043e4d4d53c87ed247789cd1788b1ba4e3f4394efe154e0c59cff236",
"sha1": "310c0363068dfae18e91f799ed671a591b6ad49a"
},
"dependencies": [],
"client_side": "optional",
"server_side": "optional"
},
"ferrite-core": {
"slug": "ferrite-core",
"project_id": "uXXizFIs",
"version_id": "d5ddUdiB",
"version": "9.0.0-fabric",
"game_versions": [
"26.1",
"26.1.1",
"26.1.2",
"26.2",
"26.3"
],
"loaders": [
"fabric"
],
"license": "MIT",
"source": "https://github.com/malte0811/FerriteCore",
"url": "https://cdn.modrinth.com/data/uXXizFIs/versions/d5ddUdiB/ferritecore-9.0.0-fabric.jar",
"filename": "ferritecore-9.0.0-fabric.jar",
"size": 72677,
"hashes": {
"sha1": "eac76ff0f3753422c61b2c44487d0d195d88d4bc",
"sha512": "d81fa97e11784c19d42f89c2f433831d007603dd7193cee45fa177e4a6a9c52b384b198586e04a0f7f63cd996fed713322578bde9a8db57e1188854ae5cbe584"
},
"dependencies": [],
"client_side": "optional",
"server_side": "optional"
},
"fabric-api": {
"slug": "fabric-api",
"project_id": "P7dR8mSH",
"version_id": "bNnaTiuM",
"version": "0.161.0+26.3",
"game_versions": [
"26.3"
],
"loaders": [
"fabric"
],
"license": "Apache-2.0",
"source": "https://github.com/FabricMC/fabric",
"url": "https://cdn.modrinth.com/data/P7dR8mSH/versions/bNnaTiuM/fabric-api-0.161.0%2B26.3.jar",
"filename": "fabric-api-0.161.0+26.3.jar",
"size": 2620967,
"hashes": {
"sha1": "53f9ee02c3702734d90520aa8c9719bf0e1c8d4f",
"sha512": "ed6b2586d6fde11fde8472f5a527c51e99b67026e46f94d4bfd85e7e28ce5ee299173ee16ad576ceb51f39f98d30a811086a6deb1a86a524859cc16e12da109d"
},
"dependencies": [],
"client_side": "optional",
"server_side": "optional"
},
"entityculling": {
"slug": "entityculling",
"project_id": "NNAgCjsB",
"version_id": "F4loCvYt",
"version": "1.11.2",
"game_versions": [
"26.3"
],
"loaders": [
"fabric"
],
"license": "LicenseRef-tr7zw-Protective-License",
"source": "https://github.com/tr7zw/EntityCulling",
"url": "https://cdn.modrinth.com/data/NNAgCjsB/versions/F4loCvYt/entityculling-fabric-1.11.2-mc26.3.jar",
"filename": "entityculling-fabric-1.11.2-mc26.3.jar",
"size": 1508273,
"hashes": {
"sha1": "f2196e803fe77cfbb62c4a2acb64803d98b4f61c",
"sha512": "c5d8947cb022f8baed4bf17e38ca598c56b8049871e7e47fb462bcecc9bc01e7eb75290494199fcb1aa73f5e37f93a296211ba78c9dd2a5bff30d5eed497ebcc"
},
"dependencies": [
{
"version_id": null,
"project_id": "P7dR8mSH",
"file_name": null,
"dependency_type": "required"
}
],
"client_side": "required",
"server_side": "unsupported"
},
"immediatelyfast": {
"slug": "immediatelyfast",
"project_id": "5ZwdcRci",
"version_id": "3MP9UR23",
"version": "1.17.1+26.3-fabric",
"game_versions": [
"26.3"
],
"loaders": [
"fabric",
"quilt"
],
"license": "LGPL-3.0-or-later",
"source": "https://github.com/RaphiMC/ImmediatelyFast",
"url": "https://cdn.modrinth.com/data/5ZwdcRci/versions/3MP9UR23/ImmediatelyFast-Fabric-1.17.1%2B26.3.jar",
"filename": "ImmediatelyFast-Fabric-1.17.1+26.3.jar",
"size": 99586,
"hashes": {
"sha512": "8e139589fd995bce3d485a34d92a07243964212f7ed2e4fc2f6de5b9a74d0f59b03252e7ce40c64e006cf3e21bed5de27b830d33ef048b286e041f6178ad8428",
"sha1": "f565bbeb201f2305e81761429d3f1f47e1c3a321"
},
"dependencies": [],
"client_side": "required",
"server_side": "unsupported"
},
"complementary-reimagined": {
"slug": "complementary-reimagined",
"project_id": "HVnmMxH1",
"version_id": "Bqen1mJX",
"version": "r5.9.3",
"game_versions": [
"1.7.10",
"1.8",
"1.8.1",
"1.8.2",
"1.8.3",
"1.8.4",
"1.8.5",
"1.8.6",
"1.8.7",
"1.8.8",
"1.8.9",
"1.9",
"1.9.1",
"1.9.2",
"1.9.3",
"1.9.4",
"1.10",
"1.10.1",
"1.10.2",
"1.11",
"1.11.1",
"1.11.2",
"1.12",
"1.12.1",
"1.12.2",
"1.13",
"1.13.1",
"1.13.2",
"1.14",
"1.14.1",
"1.14.2",
"1.14.3",
"1.14.4",
"1.15",
"1.15.1",
"1.15.2",
"1.16",
"1.16.1",
"1.16.2",
"1.16.3",
"1.16.4",
"1.16.5",
"1.17",
"1.17.1",
"1.18",
"1.18.1",
"1.18.2",
"1.19",
"1.19.1",
"1.19.2",
"1.19.3",
"1.19.4",
"1.20",
"1.20.1",
"1.20.2",
"1.20.3",
"1.20.4",
"1.20.5",
"1.20.6",
"1.21",
"1.21.1",
"1.21.2",
"1.21.3",
"1.21.4",
"1.21.5",
"1.21.6",
"1.21.7",
"1.21.8",
"1.21.9",
"1.21.10",
"1.21.11",
"26.1",
"26.1.1",
"26.1.2",
"26.2",
"26.3"
],
"loaders": [
"iris",
"optifine"
],
"license": "LicenseRef-Custom",
"source": "https://github.com/ComplementaryDevelopment/ComplementaryReimagined",
"url": "https://cdn.modrinth.com/data/HVnmMxH1/versions/Bqen1mJX/ComplementaryReimagined_r5.9.3.zip",
"filename": "ComplementaryReimagined_r5.9.3.zip",
"size": 553397,
"hashes": {
"sha1": "838139b54cddb56b2e83cd260d8efd960ac536d6",
"sha512": "45304b1d7862afdb2177b7e6226fc9c6737911d17a4ad46cc9c519ca4deb935f05072cd337cd8b19a15bb8062b57b54eceec7bdee4cd572d94858e2946d37d85"
},
"dependencies": [],
"client_side": "required",
"server_side": "unsupported"
}
}
}
+3 -1
View File
@@ -98,8 +98,10 @@ class PublicationTests(unittest.TestCase):
def test_private_paths_rejected(self):
for path in [".local/minecraft/source.java", "decompiled/Foo.txt", "game.JAR", "capture.jfr", "source/Foo.java"]:
self.assertTrue(check_public_tree.prohibited(path), path)
for path in ["tools/lab.py", "crates/voxel-kernels/src/lib.rs", "Cargo.lock", "docs/analysis.md"]:
for path in ["tools/lab.py", "crates/voxel-kernels/src/lib.rs", "Cargo.lock", "docs/analysis.md",
"mods/horizon-lab/src/main/java/dev/horizonlab/HorizonLab.java"]:
self.assertFalse(check_public_tree.prohibited(path), path)
self.assertTrue(check_public_tree.prohibited("mods/horizon-lab/src/main/java/net/minecraft/Client.java"))
def test_force_added_ignored_file_is_detected_in_index_and_history(self):
with tempfile.TemporaryDirectory() as temp:
+88
View File
@@ -0,0 +1,88 @@
import copy
import json
from pathlib import Path
import tempfile
import unittest
from unittest import mock
import zipfile
from tools import build_pack, compare_benchmarks, runtime
class PackTests(unittest.TestCase):
def test_every_profile_has_correct_game_and_exact_dependency_closure(self):
lock = build_pack.read_lock()
for profile in build_pack.PROFILES.values():
build_pack.validate_selection(lock, profile["mods"])
def test_missing_exact_iris_sodium_dependency_is_rejected(self):
with self.assertRaisesRegex(ValueError, "Missing pinned dependency"):
build_pack.validate_selection(build_pack.read_lock(), ["iris"])
def test_wrong_game_or_download_path_is_rejected(self):
for field, value in [("game_versions", ["1.21"]), ("filename", "../bad.jar"), ("url", "http://unsafe.invalid")]:
lock = copy.deepcopy(build_pack.read_lock())
lock["projects"]["sodium"][field] = value
with self.assertRaises(ValueError):
build_pack.validate_selection(lock, ["sodium"])
def test_portable_pack_contains_only_original_embedded_mod_and_download_references(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
(root / "packs").mkdir()
(root / "packs/mods.lock.json").write_text(json.dumps(build_pack.read_lock()))
(root / "packs/config").mkdir()
(root / "packs/config/m2-balanced.toml").write_text("[client.advanced.graphics.quality]\nlodChunkRenderDistanceRadius = 128\n")
original = root / "original.jar"
original.write_bytes(b"original fixture")
with mock.patch.object(build_pack, "ROOT", root):
pack = build_pack.build("m2-balanced", original)
with zipfile.ZipFile(pack) as archive:
names = archive.namelist()
self.assertEqual([n for n in names if n.endswith(".jar")], ["overrides/mods/horizon-lab-0.2.0.jar"])
index = json.loads(archive.read("modrinth.index.json"))
self.assertEqual(index["dependencies"]["minecraft"], "26.3")
for entry in index["files"]:
self.assertEqual(set(entry["hashes"]), {"sha1", "sha512"})
self.assertTrue(entry["downloads"][0].startswith("https://cdn.modrinth.com/"))
def test_native_library_rules_choose_only_matching_operating_system(self):
library = {"rules": [{"action": "allow", "os": {"name": "osx", "arch": "aarch64|arm64"}}]}
self.assertTrue(runtime.library_allowed(library, "osx", "aarch64"))
self.assertFalse(runtime.library_allowed(library, "linux", "aarch64"))
self.assertFalse(runtime.library_allowed(library, "osx", "x86_64"))
def test_native_architecture_is_selected_even_with_os_only_rules(self):
intel = {"name": "org.lwjgl:lwjgl:3.4.3:natives-macos"}
arm = {"name": "org.lwjgl:lwjgl:3.4.3:natives-macos-arm64"}
self.assertTrue(runtime.native_library_matches(arm, "aarch64"))
self.assertFalse(runtime.native_library_matches(intel, "aarch64"))
self.assertTrue(runtime.native_library_matches(intel, "x86_64"))
self.assertFalse(runtime.native_library_matches(arm, "AMD64"))
class ComparisonTests(unittest.TestCase):
def report(self, kind="frames"):
return {"schema": 1, "kind": kind, "elapsed_seconds": 120, "framebuffer_width": 1920,
"stats": {"count": 1000, "meanRate": 100, "lowOnePercentRate": 50,
"meanMs": 10, "p95Ms": 15, "p99Ms": 20, "maxMs": 30}}
def test_rate_improvement_and_setting_mismatch(self):
baseline = self.report()
candidate = copy.deepcopy(baseline)
candidate["stats"]["meanRate"] = 150
candidate["framebuffer_width"] = 1280
result = compare_benchmarks.compare(baseline, candidate)
self.assertEqual(result["metrics"][0]["change_percent"], 50)
self.assertIn("framebuffer_width", result["mismatches"][0])
def test_no_samples_and_mixed_kinds_are_rejected(self):
empty = self.report()
empty["stats"]["count"] = 0
for other in [empty, self.report("ticks")]:
with self.assertRaises(ValueError):
compare_benchmarks.compare(self.report(), other)
if __name__ == "__main__":
unittest.main()
+81
View File
@@ -0,0 +1,81 @@
#!/usr/bin/env python3
"""Compile only original unobfuscated-26.3 mod sources; never bundle game classes."""
import argparse
import json
import os
from pathlib import Path
import shutil
import subprocess
import zipfile
try:
from . import lab, runtime
except ImportError:
import lab
import runtime
ROOT = lab.ROOT
SOURCE = ROOT / "mods/horizon-lab/src"
BUILD = ROOT / ".local/mod-build"
def test_metrics():
destination = BUILD / "metric-tests"
destination.mkdir(parents=True, exist_ok=True)
sources = [SOURCE / "main/java/dev/horizonlab/metrics" / name
for name in ["SampleStats.java", "Recording.java"]]
sources.append(SOURCE / "test/java/dev/horizonlab/metrics/MetricsTest.java")
subprocess.run(["javac", "--release", "25", "-d", str(destination), *map(str, sources)], check=True)
subprocess.run(["java", "-cp", str(destination), "dev.horizonlab.metrics.MetricsTest"], check=True)
def build():
lock = json.loads((ROOT / "packs/mods.lock.json").read_text())
_, jars, _ = runtime.prepare_client(assets=False)
api = lock["projects"]["fabric-api"]
api_jar = runtime.fetch(api["url"], ROOT / ".local/pack-cache" / api["filename"],
api["hashes"]["sha512"], "sha512")
nested = BUILD / "fabric-api"
nested.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(api_jar) as archive:
for name in archive.namelist():
if name.startswith("META-INF/jars/") and name.endswith(".jar"):
destination = nested / Path(name).name
destination.write_bytes(archive.read(name))
jars.append(destination)
classes = BUILD / "classes"
if classes.exists():
shutil.rmtree(classes)
classes.mkdir(parents=True)
sources = sorted((SOURCE / "main/java").rglob("*.java"))
command = ["--release", "25", "-proc:none", "-encoding", "UTF-8", "-d", str(classes),
"-classpath", os.pathsep.join(map(str, jars)), *map(str, sources)]
argfile = BUILD / "javac.args"
argfile.write_text("\n".join(json.dumps(arg) for arg in command) + "\n")
subprocess.run(["javac", "@" + str(argfile)], cwd=ROOT, check=True)
output = ROOT / "dist" / f"horizon-lab-{lock['pack_version']}.jar"
output.parent.mkdir(exist_ok=True)
entries = {path.relative_to(classes).as_posix(): path.read_bytes() for path in classes.rglob("*.class")}
if any(not name.startswith("dev/horizonlab/") for name in entries):
raise ValueError("Only original Horizon Lab classes may be packaged")
resources = SOURCE / "main/resources"
entries.update({path.relative_to(resources).as_posix(): path.read_bytes() for path in resources.rglob("*") if path.is_file()})
entries["LICENSE"] = (ROOT / "LICENSE").read_bytes()
with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED) as archive:
for name in sorted(entries):
info = zipfile.ZipInfo(name, date_time=(2026, 1, 1, 0, 0, 0))
info.compress_type = zipfile.ZIP_DEFLATED
info.external_attr = 0o100644 << 16
archive.writestr(info, entries[name])
print(f"Built {output} ({output.stat().st_size} bytes, sha256 {lab.digest(output, 'sha256')})")
return output
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--test-only", action="store_true")
args = parser.parse_args()
test_metrics()
if not args.test_only:
build()
+153
View File
@@ -0,0 +1,153 @@
#!/usr/bin/env python3
"""Build portable pinned Modrinth packs; game code/assets remain launcher downloads."""
import argparse
import json
from pathlib import Path
import shutil
import zipfile
try:
from . import lab, runtime
except ImportError:
import lab
import runtime
ROOT = lab.ROOT
CORE = ["fabric-api", "sodium", "lithium", "ferrite-core", "immediatelyfast", "entityculling"]
PROFILES = {
"baseline": {"title": "Vanilla baseline", "mods": ["fabric-api"], "render": 12, "lod": 0, "heap": 6144},
"m2-balanced": {"title": "M2 Pro balanced", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 128, "heap": 6144},
"low-memory": {"title": "Low memory", "mods": CORE, "render": 8, "lod": 0, "heap": 3072},
"far-distance": {"title": "Far distance", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 256, "heap": 8192},
"cinematic": {"title": "Cinematic (optional)", "mods": CORE + ["distanthorizons", "iris", "complementary-reimagined"], "render": 12, "lod": 128, "heap": 6144},
"vulkan": {"title": "Vulkan experiment", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 128, "heap": 6144, "backend": "vulkan"},
}
def read_lock():
return json.loads((ROOT / "packs/mods.lock.json").read_text())
def validate_selection(lock, selection):
projects = lock["projects"]
selected_ids = {projects[name]["project_id"] for name in selection}
selected_versions = {projects[name]["version_id"] for name in selection}
for name in selection:
entry = projects[name]
if lock["minecraft"] not in entry["game_versions"]:
raise ValueError(f"Wrong game version: {name}")
if not entry["filename"].endswith(".zip") and "fabric" not in entry["loaders"]:
raise ValueError(f"Wrong loader: {name}")
if Path(entry["filename"]).name != entry["filename"] or "\\" in entry["filename"]:
raise ValueError(f"Unsafe filename: {name}")
if not entry["url"].startswith("https://cdn.modrinth.com/"):
raise ValueError(f"Unexpected download host: {name}")
for dependency in entry["dependencies"]:
if dependency["dependency_type"] != "required":
continue
if dependency.get("version_id"):
if dependency["version_id"] not in selected_versions:
raise ValueError(f"Missing pinned dependency for {name}: {dependency}")
elif dependency.get("project_id") not in selected_ids:
raise ValueError(f"Missing dependency for {name}: {dependency}")
def mod_path(entry):
return ("shaderpacks/" if entry["filename"].endswith(".zip") else "mods/") + entry["filename"]
def options(profile):
# Simulation distance stays at the vanilla default in every profile.
values = {"renderDistance": profile["render"], "simulationDistance": 12, "enableVsync": "false",
"maxFps": 260, "guiScale": 2, "onboardAccessibility": "false",
"preferredGraphicsBackend": json.dumps(profile.get("backend", "opengl"))}
return "".join(f"{key}:{value}\n" for key, value in values.items())
def overrides(profile_name, mod_bytes):
profile = PROFILES[profile_name]
files = {"mods/horizon-lab-0.2.0.jar": mod_bytes,
"config/horizon-profile.txt": (profile_name + "\n").encode(),
"options.txt": options(profile).encode()}
config = ROOT / "packs/config" / f"{profile_name}.toml"
if profile["lod"]:
if not config.exists():
raise FileNotFoundError(f"Missing verified DH profile config: {config}")
files["config/DistantHorizons.toml"] = config.read_bytes()
if profile_name == "cinematic":
# Start with shaders disabled: users explicitly select their visual/performance budget.
files["config/iris.properties"] = b"enableShaders=false\nshaderPack=ComplementaryReimagined_r5.9.3.zip\n"
return files
def write_zip(path, entries):
path.parent.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED) as archive:
for name in sorted(entries):
info = zipfile.ZipInfo(name, (2026, 1, 1, 0, 0, 0))
info.compress_type = zipfile.ZIP_DEFLATED
mode = 0o100755 if name.endswith(".command") else 0o100644
info.external_attr = mode << 16
archive.writestr(info, entries[name])
def build(profile_name, mod_jar):
lock = read_lock()
profile = PROFILES[profile_name]
validate_selection(lock, profile["mods"])
files = []
for name in profile["mods"]:
entry = lock["projects"][name]
files.append({"path": mod_path(entry), "hashes": entry["hashes"], "downloads": [entry["url"]],
"fileSize": entry["size"], "env": {"client": "required", "server": "unsupported"}})
index = {"formatVersion": 1, "game": "minecraft", "versionId": lock["pack_version"],
"name": "Horizon Lab — " + profile["title"],
"summary": "Vanilla mechanics, pinned performance mods, measured frame and tick timings.",
"files": files, "dependencies": {"minecraft": lock["minecraft"], "fabric-loader": lock["fabric_loader"]}}
entries = {"modrinth.index.json": json.dumps(index, indent=2).encode()}
entries.update({"overrides/" + name: data for name, data in overrides(profile_name, mod_jar.read_bytes()).items()})
output = ROOT / "dist" / f"horizon-{profile_name}-{lock['pack_version']}.mrpack"
write_zip(output, entries)
print(f"Built {output.name}: {len(files)} pinned downloads")
return output
def prepare_instance(profile_name, destination, mod_jar):
lock = read_lock()
profile = PROFILES[profile_name]
validate_selection(lock, profile["mods"])
destination.mkdir(parents=True, exist_ok=True)
for name in profile["mods"]:
entry = lock["projects"][name]
source = runtime.fetch(entry["url"], ROOT / ".local/pack-cache" / entry["filename"],
entry["hashes"]["sha512"], "sha512")
target = destination / mod_path(entry)
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source, target)
for name, data in overrides(profile_name, mod_jar.read_bytes()).items():
target = destination / name
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(data)
print(f"Prepared {profile_name} instance: {destination}")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--profile", choices=PROFILES)
parser.add_argument("--instance", type=Path, help="Local demo smoke-test directory (no normal account launch)")
parser.add_argument("--mod", type=Path, default=ROOT / "dist/horizon-lab-0.2.0.jar")
args = parser.parse_args()
if not args.mod.exists():
parser.error("Build the original mod first: python3 tools/build_mod.py")
if args.instance:
if not args.profile:
parser.error("--instance requires --profile")
prepare_instance(args.profile, args.instance.resolve(), args.mod)
else:
for profile in [args.profile] if args.profile else PROFILES:
build(profile, args.mod)
if __name__ == "__main__":
main()
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env python3
"""Create downloadable client/server starters and hashes from original project artifacts."""
import hashlib
from pathlib import Path
try:
from . import build_pack
except ImportError:
import build_pack
ROOT = build_pack.ROOT
def main():
lock = build_pack.read_lock()
version = lock["pack_version"]
mod = ROOT / "dist" / f"horizon-lab-{version}.jar"
if not mod.exists():
raise FileNotFoundError("Run tools/build_mod.py first")
packs = [build_pack.build(profile, mod) for profile in build_pack.PROFILES]
client = {pack.name: pack.read_bytes() for pack in packs}
client["START-HERE.txt"] = (ROOT / "packs/START-HERE.txt").read_bytes()
client["Mac-Start.command"] = (ROOT / "packs/Mac-Start.command").read_bytes()
client["LICENSE"] = (ROOT / "LICENSE").read_bytes()
build_pack.write_zip(ROOT / "dist" / f"horizon-mac-starter-{version}.zip", client)
server = {"LICENSE": client["LICENSE"], "dist/" + mod.name: mod.read_bytes(),
"START-HERE.txt": (ROOT / "docs/server-quickstart.txt").read_bytes(),
"research-lock.json": (ROOT / "research-lock.json").read_bytes()}
for name in ["lab.py", "runtime.py", "server.py", "compare_benchmarks.py"]:
server["tools/" + name] = (ROOT / "tools" / name).read_bytes()
for name in ["mods.lock.json", "fabric.lock.json"]:
server["packs/" + name] = (ROOT / "packs" / name).read_bytes()
build_pack.write_zip(ROOT / "dist" / f"horizon-server-starter-{version}.zip", server)
artifacts = sorted((ROOT / "dist").glob("*"))
checksums = []
for path in artifacts:
if path.suffix in [".jar", ".mrpack", ".zip"]:
checksums.append(hashlib.sha256(path.read_bytes()).hexdigest() + " " + path.name)
(ROOT / "dist/SHA256SUMS.txt").write_text("\n".join(checksums) + "\n")
print("Built client/server starters and SHA256SUMS.txt")
if __name__ == "__main__":
main()
+3
View File
@@ -12,6 +12,9 @@ PRIVATE_EXTENSIONS = {".jar", ".class", ".jfr", ".hprof", ".java"}
def prohibited(path):
parsed = PurePosixPath(path)
# Only original Horizon Lab sources may be tracked; recovered game Java stays private.
if parsed.suffix == ".java" and path.startswith("mods/horizon-lab/src/"):
return not ("/dev/horizonlab/" in path)
return bool(parsed.parts and parsed.parts[0] in PRIVATE_ROOTS) or parsed.suffix.lower() in PRIVATE_EXTENSIONS
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/env python3
"""Compare two real Horizon JSON reports and flag mismatched workloads."""
import argparse
import json
from pathlib import Path
MATCH_FIELDS = ("minecraft", "kind", "os", "architecture", "gpu", "graphics_backend", "graphics_driver",
"java_version", "heap_max_bytes", "framebuffer_width", "framebuffer_height", "render_distance",
"simulation_distance", "vsync", "fps_limit", "graphics_preset", "ambient_occlusion",
"improved_transparency", "mipmap_levels", "entity_distance_scaling", "entity_shadows", "particles",
"clouds", "cloud_range")
def compare(baseline, candidate):
for report in [baseline, candidate]:
if report.get("schema") != 1 or report.get("kind") not in ["frames", "ticks"]:
raise ValueError("Expected a schema-1 Horizon frame/tick report")
if report.get("stats", {}).get("count", 0) < 1:
raise ValueError("Report contains no samples")
if baseline["kind"] != candidate["kind"]:
raise ValueError("Compare frames with frames, or ticks with ticks")
mismatches = [f"{key}: {baseline.get(key)!r} vs {candidate.get(key)!r}" for key in MATCH_FIELDS
if baseline.get(key) != candidate.get(key)]
warnings = ["World, route, warm-up, shader state and LOD cache must also match; these are not verified by this tool."]
for name, report in [("baseline", baseline), ("candidate", candidate)]:
if report.get("dropped_samples", 0):
warnings.append(f"{name} exceeded the recording buffer: {report['dropped_samples']} dropped samples.")
if report.get("elapsed_seconds", 0) < 60:
warnings.append(f"{name} is shorter than 60 seconds; use longer repeated runs for decisions.")
if baseline["kind"] == "ticks" and baseline.get("peak_players") != candidate.get("peak_players"):
mismatches.append("Peak player count differs")
rows = []
keys = ["meanRate", "lowOnePercentRate", "p95Ms", "p99Ms", "maxMs"] if baseline["kind"] == "frames" else ["meanMs", "p95Ms", "p99Ms", "maxMs"]
for key in keys:
before, after = baseline["stats"][key], candidate["stats"][key]
rows.append({"metric": key, "baseline": before, "candidate": after,
"change_percent": 100 * (after / before - 1) if before else None})
for key in ["heap_used_end_bytes", "gc_time_ms", "observed_ticks_per_second"]:
if key in baseline and key in candidate:
before, after = baseline[key], candidate[key]
rows.append({"metric": key, "baseline": before, "candidate": after,
"change_percent": 100 * (after / before - 1) if before else None})
return {"kind": baseline["kind"], "mismatches": mismatches, "warnings": warnings, "metrics": rows}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("baseline", type=Path)
parser.add_argument("candidate", type=Path)
parser.add_argument("--json", action="store_true")
parser.add_argument("--strict", action="store_true", help="Exit nonzero on unmatched captured settings")
args = parser.parse_args()
result = compare(json.loads(args.baseline.read_text()), json.loads(args.candidate.read_text()))
if args.json:
print(json.dumps(result, indent=2))
else:
for row in result["metrics"]:
change = "n/a" if row["change_percent"] is None else f"{row['change_percent']:+.1f}%"
print(f"{row['metric']:25} {row['baseline']:12.3f} -> {row['candidate']:12.3f} ({change})")
for mismatch in result["mismatches"]:
print("UNMATCHED: " + mismatch)
for warning in result["warnings"]:
print("NOTE: " + warning)
return int(args.strict and bool(result["mismatches"]))
if __name__ == "__main__":
raise SystemExit(main())
+141
View File
@@ -0,0 +1,141 @@
#!/usr/bin/env python3
"""Prepare an isolated, authenticated-by-launcher game runtime; local smoke tests use demo mode."""
from concurrent.futures import ThreadPoolExecutor
import argparse
import json
import os
from pathlib import Path
import platform
import re
import subprocess
import sys
import time
import urllib.error
import zipfile
try:
from . import lab
except ImportError:
import lab
ROOT = lab.ROOT
CACHE = ROOT / ".local" / "runtime"
def fetch(url, path, checksum, algorithm="sha1"):
for attempt in range(3):
try:
return lab.download(url, path, checksum, algorithm)
except (OSError, urllib.error.URLError):
if attempt == 2:
raise
time.sleep(attempt + 1)
def fabric_libraries():
profile = json.loads((ROOT / "packs/fabric.lock.json").read_text())
jars = []
for library in profile["libraries"]:
group, artifact, version = library["name"].split(":")
relative = f"{group.replace('.', '/')}/{artifact}/{version}/{artifact}-{version}.jar"
jars.append(fetch(library["url"] + relative, CACHE / "fabric" / relative,
library["sha256"], "sha256"))
return jars
def library_allowed(library, system=None, architecture=None):
system = system or {"Darwin": "osx", "Linux": "linux", "Windows": "windows"}[platform.system()]
architecture = (architecture or platform.machine()).lower()
rules = library.get("rules", [])
allowed = not rules
for rule in rules:
operating_system = rule.get("os", {})
if operating_system.get("name", system) != system:
continue
if "arch" in operating_system and not re.fullmatch(operating_system["arch"], architecture):
continue
if "version" in operating_system and not re.search(operating_system["version"], platform.release()):
continue
if rule.get("features"):
continue
allowed = rule["action"] == "allow"
return allowed
def native_library_matches(library, architecture=None):
"""Modern manifests list both x64 and ARM natives with OS-only rules."""
architecture = (architecture or platform.machine()).lower()
name = library["name"]
if ":natives-" not in name:
return True
arm = architecture in {"arm64", "aarch64"}
if "-arm64" in name or "-aarch64" in name:
return arm
return not arm
def prepare_client(assets=True):
lock, directory = lab.config()
game = lock["minecraft"]
manifest_file = fetch(game["manifest_url"], directory / "manifest.json", game["manifest_sha1"])
manifest = json.loads(manifest_file.read_text())
if manifest["id"] != game["version"] or manifest["javaVersion"]["majorVersion"] != game["java_major"]:
raise ValueError("Game manifest does not match research lock")
artifact = manifest["downloads"]["client"]
jars = [fetch(artifact["url"], directory / "jars/client.jar", artifact["sha1"])]
natives = CACHE / "natives"
natives.mkdir(parents=True, exist_ok=True)
for library in manifest["libraries"]:
if not library_allowed(library) or not native_library_matches(library):
continue
artifact = library.get("downloads", {}).get("artifact")
if not artifact:
continue
jar = fetch(artifact["url"], directory / "libraries/client" / artifact["path"], artifact["sha1"])
jars.append(jar)
with zipfile.ZipFile(jar) as archive:
for name in archive.namelist():
if name.endswith((".so", ".dll", ".dylib", ".jnilib")):
(natives / Path(name).name).write_bytes(archive.read(name))
jars.extend(fabric_libraries())
if assets:
info = manifest["assetIndex"]
index = fetch(info["url"], CACHE / "assets/indexes" / f"{info['id']}.json", info["sha1"])
objects = json.loads(index.read_text())["objects"]
unique = {v["hash"] for v in objects.values()}
def asset(checksum):
return fetch(f"https://resources.download.minecraft.net/{checksum[:2]}/{checksum}",
CACHE / "assets/objects" / checksum[:2] / checksum, checksum)
print(f"Verifying/downloading {len(unique)} unique game assets...", flush=True)
with ThreadPoolExecutor(max_workers=12) as pool:
list(pool.map(asset, sorted(unique)))
return manifest, jars, natives
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("command", choices=["prepare", "demo"])
parser.add_argument("--instance", type=Path, default=CACHE / "demo")
parser.add_argument("--heap", default="4G")
args = parser.parse_args()
if not re.fullmatch(r"[1-9][0-9]*[MGmg]", args.heap):
parser.error("--heap must look like 4G")
manifest, jars, natives = prepare_client()
if args.command == "prepare":
return
instance = args.instance.resolve()
instance.mkdir(parents=True, exist_ok=True)
command = ["java", "-Xms512M", f"-Xmx{args.heap}", "--enable-native-access=ALL-UNNAMED",
f"-Djava.library.path={natives}", f"-Dorg.lwjgl.system.SharedLibraryExtractPath={natives}",
"-Dfabric.log.disableAnsi=true", "-cp", os.pathsep.join(map(str, jars)),
"net.fabricmc.loader.impl.launch.knot.KnotClient",
"--username", "HorizonDemo", "--version", manifest["id"], "--gameDir", str(instance),
"--assetsDir", str(CACHE / "assets"), "--assetIndex", manifest["assetIndex"]["id"],
"--accessToken", "0", "--uuid", "00000000000000000000000000000000", "--demo",
"--width", "1280", "--height", "800"]
subprocess.run(command, cwd=instance, check=True)
if __name__ == "__main__":
main()
+74
View File
@@ -0,0 +1,74 @@
#!/usr/bin/env python3
"""Prepare/run a vanilla-rules Fabric server with pinned memory and simulation optimizers."""
import argparse
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
try:
from . import lab, runtime
except ImportError:
import lab
import runtime
ROOT = lab.ROOT
def prepare(instance, baseline=False):
lock, directory = lab.config()
game = lock["minecraft"]
manifest_file = runtime.fetch(game["manifest_url"], directory / "manifest.json", game["manifest_sha1"])
manifest = json.loads(manifest_file.read_text())
artifact = manifest["downloads"]["server"]
launcher = runtime.fetch(artifact["url"], directory / "jars/server.jar", artifact["sha1"])
server, libraries = lab.unpack_server(launcher, directory, game["version"])
libraries = [server, *libraries, *runtime.fabric_libraries()]
mods = json.loads((ROOT / "packs/mods.lock.json").read_text())["projects"]
selection = ["fabric-api"] if baseline else ["fabric-api", "lithium", "ferrite-core"]
mod_dir = instance / "mods"
mod_dir.mkdir(parents=True, exist_ok=True)
for name in selection:
entry = mods[name]
source = runtime.fetch(entry["url"], ROOT / ".local/pack-cache" / entry["filename"],
entry["hashes"]["sha512"], "sha512")
shutil.copyfile(source, mod_dir / entry["filename"])
original = ROOT / "dist/horizon-lab-0.2.0.jar"
if not original.exists():
raise FileNotFoundError("Build the original mod first with tools/build_mod.py, or use the server starter ZIP")
shutil.copyfile(original, mod_dir / original.name)
return libraries
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("command", choices=["prepare", "run"])
parser.add_argument("--instance", type=Path, default=ROOT / ".local/server/optimized")
parser.add_argument("--heap", default="4G")
parser.add_argument("--baseline", action="store_true", help="Use a separate instance for the baseline")
args = parser.parse_args()
if not re.fullmatch(r"[1-9][0-9]*[MGmg]", args.heap):
parser.error("--heap must look like 4G")
instance = args.instance.resolve()
if args.baseline and args.instance == parser.get_default("instance"):
instance = ROOT / ".local/server/baseline"
libraries = prepare(instance, args.baseline)
if args.command == "prepare":
print(f"Prepared server at {instance}. Read https://www.minecraft.net/eula before setting eula=true locally.")
return
eula = instance / "eula.txt"
if not eula.exists() or not re.search(r"(?m)^\s*eula\s*=\s*true\s*$", eula.read_text()):
if not eula.exists():
eula.write_text("# Read https://www.minecraft.net/eula then change this value yourself.\neula=false\n")
print(f"Server prepared. Read Minecraft's EULA and set eula=true in {eula} before running.")
return
subprocess.run(["java", "-Xms512M", f"-Xmx{args.heap}", "--enable-native-access=ALL-UNNAMED",
"-cp", os.pathsep.join(map(str, libraries)), "net.fabricmc.loader.impl.launch.knot.KnotServer",
"--nogui"], cwd=instance, check=True)
if __name__ == "__main__":
main()