Archive incari-client (client, 26.3, clean)

This commit is contained in:
2026-11-28 00:54:38 -06:00
parent 7a6174687f
commit 12838e838c
2383 changed files with 280266 additions and 0 deletions
+18
View File
@@ -0,0 +1,18 @@
# client
- Game changes are patches: edit `work/client`, commit there (`<subsystem>: <summary>`), run
`./incari rebuild`. Never edit `patches/` by hand.
- A patch is a one- or two-line hook into Incari code, wrapped in `// Incari start: <reason>` and
`// Incari end`. Decompile fixes (`decompile:` subsystem) are the only unmarked patches.
- Incari code in `src/main/java` is adapters only: logic goes in a strict module. It may use game
types and `platform-api`, never LWJGL or TeaVM (`BoundaryTest`).
- Test: `./gradlew :client:check` (needs `./incari setup`).
- Incari's screens get their widgets from `incari.client.ui` (`Ui`, `Theme`, `ControlList`,
`ListScreen`), never by making the game's widgets themselves: the restyle changes that
package and the screens follow. Colors and sizes come from `Theme`, not literals.
- The game's own screens are changed with `ScreenEdits` (ADR 0047): `edit` to move, remove or add
widgets after each layout, `replace` to show an Incari screen instead. Prefer that to a new patch
per screen. How the GUI looks is a `GuiSkin` (`Skins.use`), never per-screen drawing code; skin
methods are hot paths.
- Feature logic lives in `features/*` (ADR 0046); `incari.client.modules` only adapts the game to
`:framework`.
+52
View File
@@ -0,0 +1,52 @@
# client: the game
## Purpose
Builds Minecraft from the patched vendor tree in `work/client`, together with the Incari code the
patches call. It's one compilation because the calls go both ways (ARCHITECTURE.md).
## Entry points
- The vendor tree: `work/client/src/main/java`, generated by `./incari setup`.
- Replacement classes: `src/main/java/com/mojang/...`, Incari's versions of the vendor classes
`patches/classes.txt` replaces (the window, event pump, audio...). They keep the game's API and
delegate to `platform-api`; the build compiles them instead of the vendor copies.
- Incari's code: `src/main/java/incari/client`, the adapters between the game, the platform and
Incari's strict modules. Each package's `package-info.java` says what it holds.
| Package | What it holds |
| --- | --- |
| `platform` | Hooks the patches call into the installed platform: window, input, lifecycle, graphics backends; `OnlineServices` turns Realms and Mojang's services off (ADR 0074); `PlatformNotices` shows the platform's notices (saves not kept) and, once, the browser's Ctrl+W hint |
| `net` | Joining servers: WebSocket addresses (ADR 0009), each join's pipeline and the server's version (`ServerConnections`, `VersionRetry`, `JoinFailures`; Via off unless turned on per server, on the edit-server screen or Direct Connect (`DirectJoinVia`), with `ViaHint` on a refusal (not for featured servers) and "Needs Via" in the list for an Eagler server known to run another version; ADR 0017, 0018, 0071), the packet handoff (ADR 0033), featured servers (ADR 0062), Reconnect and Auto Reconnect on the disconnection screen (`Reconnect`), and Connection Details there (`ConnectionDetailsScreen`, from `ConnectionReport`) |
| `eagler`, `skins` | Eagler servers' extras: passwords, cookies, redirects, voice chat (ADR 0019), Eagler skins (ADR 0016); `SkinDownloads` fetches profiles' skins, capes and custom heads through the platform; `ProfileTextures` reads them with Mojang's services off (ADR 0074) |
| `relay` | Worlds shared through Eagler relays, joined and hosted (ADR 0019, 0062) |
| `legacy` | Playing older servers as their clients did, 1.8 above all (ADR 0020) |
| `singleplayer` | Singleplayer's server in a Web Worker (ADR 0039 to 0043); it saves when the page is hidden or closed (`SAVE`, posted by the page itself) |
| `audio`, `resources` | Sounds through the platform's decoder (ADR 0013); resources fetched from the asset index (ADR 0037); `PackDownloads` fetches servers' resource packs in a page (hosts must allow CORS) |
| `render`, `gui`, `particle`, `world` | Performance work in the game's own paths (ADR 0022 to 0034) |
| `memory`, `datafix`, `startup`, `tier` | The memory diet (ADR 0025), start-up (ADR 0026), the device's quality tier |
| `profiler` | The F9 profiler overlay (ADR 0021) |
| `modules` | The game's side of the module framework (ADR 0046): events, keybinds, the HUD, the module menu |
| `ui`, `look` | Incari's UI kit, screen edits and skins (ADR 0047), and the Frost look (ADR 0048) |
| `online`, `cosmetics` | Account and chat screens (ADR 0058, 0059); cosmetics, the Wardrobe and emotes (ADR 0061) |
| `settings`, `recorder`, `credits`, `profile` | Incari Settings and the screen recorder (ADR 0062), the credits, Edit Profile (ADR 0029) |
| `account` | Microsoft sign-in (ADR 0070): the saved account, its screen, the handshake's session join, chat keys |
| `IncariKeys`, `IncariTicks`, `TickPacing` | Incari's key mappings, its once-a-tick work, catch-up ticks paced (ADR 0032) |
## Invariants
- **Incari code here is platform-neutral**: the `incari.client` packages and every replacement
class reach the machine only through `platform-api` (`BoundaryTest`), never LWJGL or TeaVM.
- **Replacements are written fresh**, never adapted from the decompiled class (`./incari copycheck`).
- **Vendor code is compiled as-is**: lint off, never edited to silence a warning. Incari's sources
are rechecked with the full gates by `strictCompile`.
- **Screens fit the smallest GUI the game allows, 320x240**, in Incari's font and the pixel font:
widgets trim their own text (`Ui.fit`), list rows narrow with the screen. `smokeLayout` checks.
- **The build needs `./incari setup` first**; it fails with that hint otherwise.
- **Output matches the jar**: every class Mojang ships is compiled from source (11,383 for 26.3).
## How to test
```sh
./gradlew :client:check # compiles ~11,000 classes, then strictCompile and the tests
```
+254
View File
@@ -0,0 +1,254 @@
import java.util.Properties
import net.ltgt.gradle.errorprone.errorprone
plugins {
`java-library`
}
// The game: the patched vendor tree in work/client (generated by `./incari setup`, never
// tracked) compiled together with the Incari code in src/main/java that vendor patches call.
// They are one compilation because the dependency runs both ways: patches call Incari hooks,
// and the hooks use game types.
val repoRoot = rootProject.layout.projectDirectory
val minecraftVersion: String = Properties().run {
repoRoot.file("incari.properties").asFile.reader().use { load(it) }
getProperty("minecraft.version")
}
val vendorSources = repoRoot.dir("work/client/src/main/java")
val vendorClasspathList = repoRoot.file("work/cache/versions/$minecraftVersion/classpath.txt")
/** Mojang's libraries for this version, as `incari fetch` downloaded and checked them. */
val vendorLibraries = run {
// A local, not the script property: a lambda capturing the script can't be cached.
val root = repoRoot.asFile
providers.fileContents(vendorClasspathList).asText.map { text ->
text.lines().filter { it.isNotBlank() }.map { root.resolve(it.trim()) }
}.orElse(emptyList())
}
val clientJar = repoRoot.file("work/cache/versions/$minecraftVersion/client.jar")
// The game's own resources (textures, models, data packs, version.json) from Mojang's jar, next
// to the classes compiled from source. Kept in build/, which is never tracked or published.
val gameResources = tasks.register<Sync>("gameResources") {
description = "Extracts the non-class files of Mojang's client jar."
from(zipTree(clientJar)) {
exclude("**/*.class")
// Mojang's signature covers Mojang's classes, not these; a partial signature breaks loading.
exclude("META-INF/**")
}
into(layout.buildDirectory.dir("game-resources"))
}
/**
* Vendor files that patches/classes.txt deletes or replaces. Replacements are Incari sources in
* this module's src/main/java (`./incari apply` also copies them into work/client, so the tree
* is complete on its own); the build compiles them from here and skips the vendor path.
*/
val manifestOwnedFiles: Set<String> = repoRoot.file("patches/classes.txt").asFile.readLines()
.map { it.substringBefore('#').trim() }
.filter { it.isNotEmpty() }
.map { it.split(Regex("\\s+"))[1].replace('.', '/') + ".java" }
.toSet()
// The online service's URL (ADR 0058), built in: `-Pincari.online.url=<wss://...>`, else
// incari.properties' `incari.online.url`; empty turns accounts off. A URL, never a key or secret:
// anything in a page can be read by whoever opens it. The page's ?online= and the desktop's
// -Dincari.online.url override it for testing against a local service.
val onlineUrl: String = providers.gradleProperty("incari.online.url").orNull ?: Properties().run {
repoRoot.file("incari.properties").asFile.reader().use { load(it) }
getProperty("incari.online.url", "")
}
val onlineUrlSource = tasks.register("onlineUrlSource") {
description = "Writes the online service's URL into a generated source."
val url = onlineUrl
val out = layout.buildDirectory.dir("generated/sources/online")
inputs.property("url", url)
outputs.dir(out)
doLast {
val file = out.get().file("incari/client/online/OnlineUrl.java").asFile
file.parentFile.mkdirs()
val quoted = url.replace("\\", "\\\\").replace("\"", "\\\"")
file.writeText(
"""
|package incari.client.online;
|
|/** Generated by :client's onlineUrlSource from incari.online.url. */
|final class OnlineUrl {
| static final String BUILT_IN = "$quoted";
|
| private OnlineUrl() {}
|}
|""".trimMargin())
}
}
// This build's Incari version, public repository and game version (incari.properties), and whether it's a release
// build (`-Pteavm.release`, as `./incari build` makes): only those show the title screen's update
// notice. Dev builds never do, except for tests (-Dincari.updates=on, the page's ?updates=on).
val incariProperties = Properties().apply {
repoRoot.file("incari.properties").asFile.reader().use { load(it) }
}
val buildInfoSource = tasks.register("buildInfoSource") {
description = "Writes this build's Incari version, repository, featured servers, game version and release flag into a generated source."
val version = incariProperties.getProperty("incari.version", "")
val minecraftVersion = incariProperties.getProperty("minecraft.version", "")
val repository = incariProperties.getProperty("incari.repository", "")
val featured = incariProperties.getProperty("incari.featured", "")
val release = providers.gradleProperty("teavm.release").isPresent
val out = layout.buildDirectory.dir("generated/sources/build-info")
inputs.property("version", version)
inputs.property("repository", repository)
inputs.property("featured", featured)
inputs.property("minecraftVersion", minecraftVersion)
inputs.property("release", release)
outputs.dir(out)
doLast {
val file = out.get().file("incari/client/IncariBuild.java").asFile
file.parentFile.mkdirs()
fun quoted(text: String) = "\"" + text.replace("\\", "\\\\").replace("\"", "\\\"") + "\""
file.writeText(
"""
|package incari.client;
|
|/** Generated by :client's buildInfoSource from incari.properties and -Pteavm.release. */
|public final class IncariBuild {
| /** This build's Incari Client version. */
| public static final String VERSION = ${quoted(version)};
| /** The public repository, where the update notice leads. */
| public static final String REPOSITORY = ${quoted(repository)};
| /** The featured servers built in, as "name|address" joined by ";" (ADR 0062). */
| public static final String FEATURED = ${quoted(featured)};
| /**
| * The Minecraft release this tree targets ("26.3"). For code that runs before the game's
| * own SharedConstants can be read, such as the page naming its cached client jar.
| */
| public static final String MINECRAFT_VERSION = ${quoted(minecraftVersion)};
| /** Whether this is a release build, the kind players are given. */
| public static final boolean RELEASE = $release;
|
| private IncariBuild() {}
|}
|""".trimMargin())
}
}
sourceSets.main {
java.srcDir(onlineUrlSource)
java.srcDir(buildInfoSource)
java.srcDir(vendorSources)
// Locals, not script properties: a lambda capturing the script can't be cached.
val vendorRoot = vendorSources.asFile
val ownedByManifest = manifestOwnedFiles
java.exclude { element -> element.file.startsWith(vendorRoot) && element.relativePath.pathString in ownedByManifest }
output.dir(mapOf("builtBy" to gameResources), layout.buildDirectory.dir("game-resources"))
}
dependencies {
api(project(":platform-api"))
api(project(":net"))
api(project(":via"))
// Incari's terrain mesher: the game's section compiles go to it through incari.client.render.mesher.
api(project(":mesher"))
// The module framework (ADR 0046): incari.client.modules adapts the game to it, and lists
// the features below.
api(project(":framework"))
// Incari accounts and the online service (ADR 0058): incari.client.online draws the account
// screens and feeds it the world.
api(project(":online"))
implementation(project(":features:togglesprint"))
implementation(project(":features:lowfire"))
implementation(project(":features:nohurtcam"))
implementation(project(":features:clearchat"))
implementation(project(":features:armorpotionview"))
implementation(project(":features:customscoreboard"))
implementation(project(":features:waypoints"))
implementation(project(":features:minimap"))
implementation(project(":features:fpsdisplay"))
implementation(project(":features:cps"))
implementation(project(":features:reachdisplay"))
implementation(project(":features:keystrokes"))
implementation(project(":features:coordinates"))
implementation(project(":features:shieldtotem"))
implementation(project(":features:cooldownindicator"))
implementation(project(":features:crosshair"))
implementation(project(":features:freelook"))
implementation(project(":features:zoom"))
implementation(project(":features:saturation"))
implementation(project(":features:weatherchanger"))
implementation(project(":features:lowshield"))
implementation(project(":features:shortitems"))
implementation(project(":features:oldtextures"))
implementation(project(":features:blockoutline"))
implementation(project(":features:hitcolor"))
implementation(project(":features:glintcolor"))
implementation(project(":features:hiteffects"))
implementation(project(":features:fullbright"))
implementation(project(":features:customsky"))
implementation(project(":features:hitboxes"))
implementation(project(":features:schematics"))
implementation(project(":features:norender"))
implementation(project(":features:fastcrystal"))
implementation(project(":features:oldanimations"))
implementation(project(":features:shulkertooltips"))
implementation(project(":features:theme"))
api(files(vendorLibraries))
// Annotations Mojang compiled against but doesn't ship in the game's libraries.
compileOnlyApi(libs.jetbrains.annotations)
compileOnlyApi(libs.jsr305)
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
testImplementation(libs.assertj)
testImplementation(libs.archunit)
testImplementation(testFixtures(project(":online")))
testRuntimeOnly(libs.junit.launcher)
}
tasks.compileJava {
val tree = vendorSources.asFile
val classpathList = vendorClasspathList.asFile
doFirst {
if (!tree.isDirectory || !classpathList.isFile) {
throw GradleException("The client tree isn't set up yet. Run: ./incari setup")
}
}
// Roughly 9,000 vendor files in one compilation.
options.isFork = true
options.forkOptions.memoryMaximumSize = "6g"
// Vendor code is compiled as-is and never edited to silence a warning, so this compilation
// allows warnings. Incari's sources get the strict treatment in strictCompile below.
options.compilerArgs.add("-Xlint:none")
options.errorprone {
// Error Prone and NullAway check Incari's code here, never Mojang's.
excludedPaths = ".*/work/client/.*"
}
}
// Recompiles only Incari's sources in this module, against the full build, with the flags every
// other Incari module uses: -Xlint:all -Werror plus Error Prone and NullAway. The output is
// thrown away; this is a check, and `check` runs it.
val strictCompile = tasks.register<JavaCompile>("strictCompile") {
group = "verification"
description = "Compiles Incari's own sources in :client with warnings as errors."
source = fileTree("src/main/java")
classpath = files(tasks.compileJava.flatMap { it.destinationDirectory }) + sourceSets.main.get().compileClasspath
destinationDirectory = layout.buildDirectory.dir("strict-compile")
javaCompiler = javaToolchains.compilerFor { languageVersion = JavaLanguageVersion.of(25) }
options.compilerArgs.addAll(listOf("-Xlint:all,-classfile", "-Werror"))
}
tasks.check {
dependsOn(strictCompile)
}
tasks.test {
// Game classes loaded by tests write logs/ into the working directory; keep that in build/.
val runDir = layout.buildDirectory.dir("test-run").get().asFile
workingDir = runDir
systemProperty("incari.repoRoot", rootDir.path)
// ArchUnit imports the whole game to check the replacement classes.
maxHeapSize = "3g"
doFirst { runDir.mkdirs() }
}
@@ -0,0 +1,54 @@
package com.mojang.blaze3d;
import incari.client.platform.ClientPlatform;
import incari.client.world.FolderDownloads;
import java.net.URI;
import java.nio.file.Path;
/** Incari's replacement for Mojang's {@code Blaze3D} helpers (patches/classes.txt), over the platform. */
public class Blaze3D {
private static final double NANOS_PER_SECOND = 1_000_000_000.0;
private Blaze3D() {}
/** The debug crash: kills the process the way a native bug would, to test crash handling. */
public static void youJustLostTheGame() {
ClientPlatform.get().crashNatively();
}
/** Seconds on the platform's monotonic clock. The game's frame timing is built on it. */
public static double getTime() {
return ClientPlatform.get().nanoTime() / NANOS_PER_SECOND;
}
/** Opens a link in the player's browser, without waiting for it. */
public static void openUri(final URI uri) {
ClientPlatform.get().shell().open(uri);
}
/**
* Opens a folder or file in the system's file manager. In the browser a file downloads, a
* folder the player adds files to (the pack folders) offers the file picker
* ({@code PlatformShell.openPath}), and any other folder (a world, the backups) downloads as a
* zip ({@link FolderDownloads}).
*/
public static void openPath(final Path path) {
Path absolute = path.toAbsolutePath().normalize();
if (FolderDownloads.shouldDownload(absolute)) {
FolderDownloads.download(absolute);
return;
}
ClientPlatform.get().shell().openPath(absolute.toString());
}
/**
* Opens a folder for the player to put files in: the system's file manager, or in the browser
* the file picker, whose files reach the game as a drop. Incari's own folders (skins, capes).
*/
public static void openFolderToAddFiles(final Path folder) {
ClientPlatform.get()
.shell()
.openPath(folder.toAbsolutePath().normalize().toString());
}
}
@@ -0,0 +1,50 @@
package com.mojang.blaze3d.audio;
import incari.platform.api.Platforms;
import incari.platform.api.audio.PlatformAudio;
/**
* Incari replacement: tracks device changes the platform announces, instead of polling. The
* platform's notice only raises a flag; the list itself is re-read on the game's next tick, as
* {@link AbstractDeviceTracker} does for every tracker.
*/
public class CallbackDeviceTracker extends AbstractDeviceTracker {
/** Written by the platform's notification thread, read and cleared by the game's tick. */
private volatile boolean updateRequested;
public CallbackDeviceTracker(final DeviceList deviceList) {
super(deviceList);
}
@Override
protected boolean isUpdateRequested() {
return updateRequested;
}
@Override
protected void discardUpdateRequest() {
updateRequested = false;
}
/** Whether the running platform announces device changes. */
public static boolean isSupported() {
return Platforms.current().audio().reportsDeviceChanges();
}
/** A tracker that the running platform's announcements flag for an update. */
public static CallbackDeviceTracker createAndInstall(final DeviceList deviceList) {
return createAndInstall(Platforms.current().audio(), deviceList);
}
static CallbackDeviceTracker createAndInstall(final PlatformAudio audio, final DeviceList deviceList) {
CallbackDeviceTracker tracker = new CallbackDeviceTracker(deviceList);
audio.setDeviceChangeListener(tracker::requestUpdate);
return tracker;
}
// Must not block or touch the game: it runs on the platform's notification thread.
private void requestUpdate() {
updateRequested = true;
}
}
@@ -0,0 +1,206 @@
package com.mojang.blaze3d.audio;
import com.mojang.logging.LogUtils;
import incari.client.audio.CompressedSoundStream;
import incari.platform.api.audio.AudioBuffer;
import incari.platform.api.audio.AudioDevice;
import incari.platform.api.audio.AudioException;
import incari.platform.api.audio.AudioSource;
import incari.platform.api.audio.PcmFormat;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.sound.sampled.AudioFormat;
import net.minecraft.client.sounds.AudioStream;
import net.minecraft.world.phys.Vec3;
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
/**
* Incari replacement: one playing sound, over a platform {@link AudioSource}.
*
* <p>It plays either a whole decoded {@link SoundBuffer} or an {@link AudioStream} (music, long
* records), which is decoded a second at a time into a short queue of buffers and topped up by
* {@link #updateStream} as they finish; or, on a device that streams compressed files itself (the
* browser's), is handed over whole. All calls come from the sound thread.
*/
public class Channel {
private static final Logger LOGGER = LogUtils.getLogger();
/** Buffers kept queued ahead while streaming: enough to ride out a slow sound-thread tick. */
private static final int STREAM_QUEUE_LENGTH = 4;
public static final int BUFFER_DURATION_SECONDS = 1;
private final AudioDevice device;
private final AudioSource source;
private final AtomicBoolean initialized = new AtomicBoolean(true);
private @Nullable AudioStream stream;
private @Nullable PcmFormat streamFormat;
private int streamChunkBytes;
/** A new channel on {@code device}, or null if it has no free source. */
static @Nullable Channel create(final AudioDevice device) {
AudioSource source = device.createSource();
return source == null ? null : new Channel(device, source);
}
private Channel(final AudioDevice device, final AudioSource source) {
this.device = device;
this.source = source;
}
/** Stops, closes the stream if any, and frees the source. Only the first call does anything. */
public void destroy() {
if (!initialized.compareAndSet(true, false)) {
return;
}
source.stop();
AudioStream current = stream;
if (current != null) {
try {
current.close();
} catch (IOException e) {
LOGGER.error("Failed to close audio stream", e);
}
stream = null;
}
// Frees the queued stream buffers too. A static buffer belongs to its SoundBuffer.
source.close();
}
public void play() {
if (initialized.get()) {
source.play();
}
}
private AudioSource.State state() {
return initialized.get() ? source.state() : AudioSource.State.STOPPED;
}
public void pause() {
if (state() == AudioSource.State.PLAYING) {
source.pause();
}
}
public void unpause() {
if (state() == AudioSource.State.PAUSED) {
source.play();
}
}
public void stop() {
if (initialized.get()) {
source.stop();
}
}
public boolean playing() {
return state() == AudioSource.State.PLAYING;
}
/**
* Whether it has finished (or was destroyed). A channel that was set up but never played is
* not stopped, so the game doesn't reclaim it before its first {@link #play}.
*/
public boolean stopped() {
return state() == AudioSource.State.STOPPED;
}
public void setSelfPosition(final Vec3 newPosition) {
source.setPosition(newPosition.x, newPosition.y, newPosition.z);
}
public void setPitch(final float pitch) {
source.setPitch(pitch);
}
public void setLooping(final boolean looping) {
source.setLooping(looping);
}
public void setVolume(final float volume) {
source.setGain(volume);
}
public void disableAttenuation() {
source.disableAttenuation();
}
public void linearAttenuation(final float maxDistance) {
source.setLinearAttenuation(maxDistance);
}
public void setRelative(final boolean relative) {
source.setRelative(relative);
}
public void attachStaticBuffer(final SoundBuffer buffer) {
AudioBuffer uploaded = buffer.bufferOn(device);
if (uploaded != null) {
source.setBuffer(uploaded);
}
}
public void attachBufferStream(final AudioStream stream) {
if (stream instanceof CompressedSoundStream compressed && device.streamsOggVorbis()) {
this.stream = stream;
try {
source.streamOggVorbis(compressed.file(), compressed.looping());
} catch (AudioException e) {
LOGGER.error("Can't stream audio: {}", e.getMessage());
}
return;
}
AudioFormat format = stream.getFormat();
this.stream = stream;
this.streamChunkBytes = bytesPerSeconds(format, BUFFER_DURATION_SECONDS);
try {
this.streamFormat = SoundBuffer.toPcmFormat(format);
} catch (IllegalArgumentException e) {
LOGGER.error("Can't stream audio: {}", e.getMessage());
this.streamFormat = null;
return;
}
queueChunks(STREAM_QUEUE_LENGTH);
}
/** How many bytes of {@code format} last {@code seconds}. */
static int bytesPerSeconds(final AudioFormat format, final int seconds) {
float bytesPerSample = format.getSampleSizeInBits() / 8.0F;
return (int) (seconds * format.getSampleRate() * format.getChannels() * bytesPerSample);
}
/** Refills the stream's queue with as many chunks as finished playing since the last call. */
public void updateStream() {
if (stream != null) {
queueChunks(source.releaseProcessedBuffers());
}
}
/** Decodes up to {@code count} more chunks of the stream and queues them. */
private void queueChunks(final int count) {
AudioStream current = stream;
PcmFormat format = streamFormat;
if (current == null || format == null) {
return;
}
try {
for (int i = 0; i < count; i++) {
ByteBuffer chunk = current.read(streamChunkBytes);
// The decoder hands back an empty buffer at the end; queueing nothing is fine.
if (!chunk.hasRemaining()) {
continue;
}
source.queue(device.createBuffer(chunk, format));
}
} catch (IOException e) {
LOGGER.error("Failed to read from audio stream", e);
} catch (AudioException e) {
LOGGER.error("Failed to queue audio stream data: {}", e.getMessage());
}
}
}
@@ -0,0 +1,25 @@
package com.mojang.blaze3d.audio;
import incari.platform.api.Platforms;
import incari.platform.api.audio.AudioDeviceList;
import java.util.List;
import org.jspecify.annotations.Nullable;
/**
* Incari replacement: the output devices the platform offers, in the game's own type. The options
* screen lists {@link #allDevices}; the sound engine compares snapshots to notice changes, which
* is why this stays a record (value equality).
*/
public record DeviceList(@Nullable String defaultDevice, List<String> allDevices) {
public static final DeviceList EMPTY = new DeviceList(null, List.of());
/** Asks the platform now. May be slow on the desktop (it probes the system), so the game calls it off the render thread. */
public static DeviceList query() {
return from(Platforms.current().audio().devices());
}
static DeviceList from(final AudioDeviceList devices) {
return new DeviceList(devices.defaultDevice(), devices.all());
}
}
@@ -0,0 +1,252 @@
package com.mojang.blaze3d.audio;
import com.mojang.logging.LogUtils;
import incari.platform.api.Platforms;
import incari.platform.api.audio.AudioDevice;
import incari.platform.api.audio.AudioException;
import incari.platform.api.audio.PlatformAudio;
import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import net.minecraft.SharedConstants;
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
/**
* Incari replacement: the sound engine's output, over the platform's {@link PlatformAudio}.
*
* <p>It owns the open device and hands out {@link Channel}s from two pools, so that a burst of
* short sounds can never take the sources music and records need: most sources go to
* {@link Pool#STATIC} sounds, and a few (about the square root of the total) are kept for
* {@link Pool#STREAMING} ones.
*/
public class Library {
private static final Logger LOGGER = LogUtils.getLogger();
/** What {@link #currentDeviceName} reports while nothing is open. */
private static final String NO_DEVICE_NAME = "(None)";
private static final int MIN_STREAMING = 2;
private static final int MAX_STREAMING = 8;
private static final int MIN_STATIC = 8;
private static final int MAX_STATIC = 255;
private @Nullable AudioDevice device;
private String currentDeviceName = NO_DEVICE_NAME;
private ChannelPool staticChannels = ChannelPool.NONE;
private ChannelPool streamingChannels = ChannelPool.NONE;
private final Listener listener = new Listener();
/**
* Opens a device: the player's choice, else the system default the game last saw, else
* whatever the platform picks.
*
* @param preferredDevice the device from the options, or null to use the default
* @param currentDevices the devices as the game last listed them
* @param useHrtf whether to spatialize with HRTF ("Directional Audio")
* @throws IllegalStateException if no device can be opened
*/
public void init(final @Nullable String preferredDevice, final DeviceList currentDevices, final boolean useHrtf) {
init(Platforms.current().audio(), preferredDevice, currentDevices, useHrtf);
}
void init(
final PlatformAudio audio,
final @Nullable String preferredDevice,
final DeviceList currentDevices,
final boolean useHrtf) {
currentDeviceName = NO_DEVICE_NAME;
AudioDevice opened = openWithFallback(audio, preferredDevice, currentDevices.defaultDevice(), useHrtf);
device = opened;
currentDeviceName = opened.name();
int total = opened.maxSources();
int streaming = streamingPoolSize(total);
staticChannels = new ChannelPool(opened, staticPoolSize(total, streaming));
streamingChannels = new ChannelPool(opened, streaming);
listener.attach(opened.listener());
LOGGER.info("Sound output opened on device {}", currentDeviceName);
}
/** Sources kept for streams: the square root of the total, between 2 and 8. */
static int streamingPoolSize(final int totalSources) {
int root = (int) Math.sqrt(totalSources);
return Math.clamp(root, MIN_STREAMING, MAX_STREAMING);
}
/**
* Sources for everything else: the rest, between 8 and 255. The floor can promise more than a
* tiny device has; then acquiring just fails early, as the device runs out.
*/
static int staticPoolSize(final int totalSources, final int streamingSources) {
return Math.clamp(totalSources - streamingSources, MIN_STATIC, MAX_STATIC);
}
/**
* Tries each candidate in turn, skipping repeats, and returns the first that opens. A failed
* one is only logged: an unplugged favourite shouldn't leave the game silent.
*/
static AudioDevice openWithFallback(
final PlatformAudio audio,
final @Nullable String preferredDevice,
final @Nullable String systemDefault,
final boolean useHrtf) {
List<@Nullable String> candidates = new ArrayList<>(3);
if (preferredDevice != null) {
candidates.add(preferredDevice);
}
if (systemDefault != null && !systemDefault.equals(preferredDevice)) {
candidates.add(systemDefault);
}
candidates.add(null); // The platform's own default.
@Nullable AudioException lastFailure = null;
for (String candidate : candidates) {
try {
return audio.open(candidate, useHrtf);
} catch (AudioException e) {
LOGGER.warn(
"Couldn't open sound device {}: {}",
candidate == null ? "(default)" : candidate,
e.getMessage());
lastFailure = e;
}
}
throw new IllegalStateException("Failed to open a sound device", lastFailure);
}
public @Nullable String currentDeviceName() {
return currentDeviceName;
}
/** Frees every channel and closes the device. Safe to call with nothing open. */
public void cleanup() {
staticChannels.cleanup();
streamingChannels.cleanup();
// Nothing more can be handed out until the next init: the device is going away.
staticChannels = ChannelPool.NONE;
streamingChannels = ChannelPool.NONE;
listener.attach(null);
AudioDevice open = device;
if (open != null) {
open.close();
}
device = null;
}
public Listener getListener() {
return listener;
}
/** A channel from {@code pool}, or null if the pool or the device is out of sources. */
public @Nullable Channel acquireChannel(final Pool pool) {
return (pool == Pool.STREAMING ? streamingChannels : staticChannels).acquire();
}
/**
* Destroys a channel and returns its slot to its pool.
*
* @throws IllegalStateException if it didn't come from this library's current pools
*/
public void releaseChannel(final Channel channel) {
if (!staticChannels.release(channel) && !streamingChannels.release(channel)) {
throw new IllegalStateException("Tried to release unknown channel");
}
}
/** The "Sounds:" line of the debug screen: used/size of the static then the streaming pool. */
public String getChannelDebugString() {
return String.format(
Locale.ROOT,
"Sounds: %d/%d + %d/%d",
staticChannels.usedCount(),
staticChannels.limit(),
streamingChannels.usedCount(),
streamingChannels.limit());
}
public boolean isCurrentDeviceDisconnected() {
AudioDevice open = device;
return open != null && open.isDisconnected();
}
/**
* A tracker for the device list: pushed changes when the platform announces them, polling
* otherwise.
*/
public static DeviceTracker createDeviceTracker() {
PlatformAudio audio = Platforms.current().audio();
DeviceList devices = DeviceList.from(audio.devices());
if (audio.reportsDeviceChanges()) {
LOGGER.debug("Tracking audio device changes through platform notifications");
return CallbackDeviceTracker.createAndInstall(audio, devices);
}
LOGGER.debug("Tracking audio device changes by polling");
return new PollingDeviceTracker(devices);
}
/** A capped set of live channels on one device. */
static final class ChannelPool {
/** Before the first device opens and after it closes: hands out nothing. */
static final ChannelPool NONE = new ChannelPool(null, 0);
private final @Nullable AudioDevice device;
private final int limit;
private final Set<Channel> active = Collections.newSetFromMap(new IdentityHashMap<>());
ChannelPool(final @Nullable AudioDevice device, final int limit) {
this.device = device;
this.limit = limit;
}
@Nullable
Channel acquire() {
AudioDevice target = device;
if (target == null) {
return null;
}
if (active.size() >= limit) {
if (SharedConstants.IS_RUNNING_IN_IDE) {
LOGGER.warn("Maximum sound pool size {} reached", limit);
}
return null;
}
Channel channel = Channel.create(target);
if (channel != null) {
active.add(channel);
}
return channel;
}
boolean release(final Channel channel) {
if (!active.remove(channel)) {
return false;
}
channel.destroy();
return true;
}
void cleanup() {
active.forEach(Channel::destroy);
active.clear();
}
int limit() {
return limit;
}
int usedCount() {
return active.size();
}
}
public enum Pool {
STATIC,
STREAMING
}
}
@@ -0,0 +1,49 @@
package com.mojang.blaze3d.audio;
import incari.platform.api.audio.AudioListener;
import net.minecraft.world.phys.Vec3;
import org.jspecify.annotations.Nullable;
/**
* Incari replacement: the player's ears, forwarded to the open device's {@link AudioListener}.
*
* <p>The game creates this once, before any device is open, and keeps it across device changes.
* So it remembers the transform itself, and {@link Library} points it at each new device's
* listener as it opens.
*/
public class Listener {
private ListenerTransform transform = ListenerTransform.INITIAL;
private @Nullable AudioListener target;
public void setTransform(final ListenerTransform transform) {
this.transform = transform;
push();
}
public void reset() {
setTransform(ListenerTransform.INITIAL);
}
public ListenerTransform getTransform() {
return transform;
}
/** Sends every later transform to {@code target}, starting with the current one; null for no device. */
void attach(final @Nullable AudioListener target) {
this.target = target;
push();
}
private void push() {
AudioListener out = target;
if (out == null) {
return; // No device open: the transform is kept for the next one.
}
Vec3 position = transform.position();
Vec3 forward = transform.forward();
Vec3 up = transform.up();
out.setPosition(position.x, position.y, position.z);
out.setOrientation(forward.x, forward.y, forward.z, up.x, up.y, up.z);
}
}
@@ -0,0 +1,128 @@
package com.mojang.blaze3d.audio;
import com.mojang.logging.LogUtils;
import incari.platform.api.audio.AudioBuffer;
import incari.platform.api.audio.AudioDevice;
import incari.platform.api.audio.AudioException;
import incari.platform.api.audio.DecodedAudio;
import incari.platform.api.audio.PcmFormat;
import java.nio.ByteBuffer;
import java.util.Objects;
import javax.sound.sampled.AudioFormat;
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
/**
* Incari replacement: a fully decoded sound, uploaded to the device the first time a channel
* plays it.
*
* <p>Decoding happens off the sound thread, before any device may be open, so the samples are
* held here until then: PCM from the game's decoder, or what the platform's own decoder produced
* (the browser's, ADR 0013). Once uploaded, the device copy is the only one: the samples are
* dropped to save memory, and {@link #discardAlBuffer} ends the buffer's life.
*/
public class SoundBuffer {
private static final Logger LOGGER = LogUtils.getLogger();
private @Nullable ByteBuffer data;
private @Nullable DecodedAudio decoded;
private final AudioFormat format;
private final int size;
private @Nullable AudioBuffer uploaded;
private @Nullable AudioDevice uploadedTo;
public SoundBuffer(final ByteBuffer data, final AudioFormat format) {
this.data = data;
this.format = format;
this.size = data.limit();
}
/** A sound the platform decoded: 32-bit float samples, as far as the game's statistics tell. */
public SoundBuffer(final DecodedAudio decoded) {
this.decoded = decoded;
int frameSize = decoded.channels() * Float.BYTES;
this.format = new AudioFormat(
AudioFormat.Encoding.PCM_FLOAT,
decoded.sampleRate(),
Float.SIZE,
decoded.channels(),
frameSize,
decoded.sampleRate(),
false);
this.size = decoded.sizeInBytes();
}
/**
* The device copy of these samples, uploading them on first use.
*
* @return null if the upload failed (logged, and retried next time), or if the samples went
* to another device and were dropped here, or after {@link #discardAlBuffer}
*/
@Nullable
AudioBuffer bufferOn(final AudioDevice device) {
AudioBuffer buffer = uploaded;
if (buffer != null) {
return device.equals(uploadedTo) ? buffer : null;
}
ByteBuffer samples = data;
DecodedAudio platformSamples = decoded;
if (samples == null && platformSamples == null) {
return null;
}
try {
buffer = samples != null
? device.createBuffer(samples, toPcmFormat(format))
: device.createBuffer(Objects.requireNonNull(platformSamples));
} catch (AudioException | IllegalArgumentException e) {
LOGGER.error("Couldn't upload a sound buffer: {}", e.getMessage());
return null;
}
uploaded = buffer;
uploadedTo = device;
data = null;
decoded = null;
return buffer;
}
/** Frees the device copy. The samples were dropped when it was made, so this buffer is spent. */
public void discardAlBuffer() {
AudioBuffer buffer = uploaded;
if (buffer != null) {
buffer.close();
}
uploaded = null;
uploadedTo = null;
}
public AudioFormat format() {
return format;
}
public int size() {
return size;
}
/** Whether it can still be played: the samples are held here or on a device. */
public boolean isValid() {
return data != null || decoded != null || uploaded != null;
}
/**
* The platform's description of {@code format}. Only uncompressed PCM, mono or stereo, 8 or
* 16 bits: what the game's Ogg decoder produces.
*
* @throws IllegalArgumentException for anything else
*/
static PcmFormat toPcmFormat(final AudioFormat format) {
AudioFormat.Encoding encoding = format.getEncoding();
if (!AudioFormat.Encoding.PCM_SIGNED.equals(encoding) && !AudioFormat.Encoding.PCM_UNSIGNED.equals(encoding)) {
throw new IllegalArgumentException("Not uncompressed PCM: " + format);
}
try {
return new PcmFormat((int) format.getSampleRate(), format.getChannels(), format.getSampleSizeInBits());
} catch (AudioException e) {
throw new IllegalArgumentException("Unsupported audio format: " + format, e);
}
}
}
@@ -0,0 +1,19 @@
package com.mojang.blaze3d.platform;
import incari.client.platform.ClientPlatform;
import net.minecraft.util.StringDecomposer;
/** Incari's replacement for Mojang's clipboard access (patches/classes.txt), over the platform shell. */
public class ClipboardManager {
/** The clipboard's text, or "" if it holds none or can't be read (the platform logs why). */
public String getClipboard() {
String text = ClientPlatform.get().shell().clipboardText();
// Other programs can put lone surrogates on the clipboard; the game's text code can't take them.
return text == null ? "" : StringDecomposer.filterBrokenSurrogates(text);
}
public void setClipboard(final String text) {
ClientPlatform.get().shell().setClipboardText(text);
}
}
@@ -0,0 +1,40 @@
package com.mojang.blaze3d.platform;
import incari.client.platform.ClientPlatform;
import incari.platform.api.window.PlatformWindow;
import incari.platform.api.window.SystemBehavior;
import net.minecraft.util.Util;
/**
* Incari's replacement for Mojang's macOS helpers (patches/classes.txt). The two options the
* player controls go to the platform window; elsewhere they do nothing.
*/
public final class MacosUtil {
public static final boolean IS_MACOS = Util.getPlatform() == Util.OS.OSX;
private MacosUtil() {}
/**
* Mojang hides the "Close Window" menu item, which would close the game without saving.
* Incari's desktop runtime doesn't drive the macOS menu (it would need the Objective-C bridge
* the browser build leaves out), so the item stays; Command+W then asks the game to close,
* which saves as usual.
*/
public static void disableCloseWindowMenuItem() {}
public static void setFullscreenMenuVisibility(final boolean visible) {
setBehavior(SystemBehavior.MENU_BAR_IN_FULLSCREEN, visible);
}
public static void setCtrlClickEmulatesRightClick(final boolean enabled) {
setBehavior(SystemBehavior.CTRL_CLICK_IS_RIGHT_CLICK, enabled);
}
private static void setBehavior(final SystemBehavior behavior, final boolean enabled) {
PlatformWindow window = ClientPlatform.window();
if (IS_MACOS && window != null) {
window.setSystemBehavior(behavior, enabled);
}
}
}
@@ -0,0 +1,21 @@
package com.mojang.blaze3d.platform;
import incari.client.platform.ClientPlatform;
/**
* Incari's replacement for Mojang's native message boxes (patches/classes.txt): the dialogs shown
* when something fails before or outside the game's own UI.
*/
public class MessageBox {
private static final String TITLE = "Minecraft";
public static void error(final String message) {
ClientPlatform.get().shell().showErrorDialog(TITLE, message, false);
}
/** Shows the error with Yes/No buttons; true if the player chose to continue. */
public static boolean errorWithContinue(final String message) {
return ClientPlatform.get().shell().showErrorDialog(TITLE, message, true);
}
}
@@ -0,0 +1,68 @@
package com.mojang.blaze3d.platform;
import com.mojang.logging.LogUtils;
import incari.client.platform.ClientPlatform;
import incari.client.platform.DisplayModes;
import incari.platform.api.window.DisplayInfo;
import incari.platform.api.window.DisplayMode;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
/**
* Incari's replacement for Mojang's monitor record (patches/classes.txt): one display and the
* fullscreen modes the game offers on it, built from what the platform reports.
*/
public record Monitor(
String name, int id, List<VideoMode> videoModes, VideoMode currentMode, int x, int y, int w, int h) {
private static final Logger LOGGER = LogUtils.getLogger();
/** The display with this id, or null (and a warning) if the platform can't describe it. */
public static @Nullable Monitor tryCreate(final int id) {
DisplayInfo display = ClientPlatform.get().displays().get(id);
if (display == null) {
LOGGER.warn("Failed to query monitor {}", id);
return null;
}
// The game's fullscreen resolutions need true colour; anything less isn't offered.
List<VideoMode> modes = display.fullscreenModes().stream()
.filter(mode -> mode.redBits() >= 8 && mode.greenBits() >= 8 && mode.blueBits() >= 8)
.map(DisplayModes::toVideoMode)
.toList();
DisplayMode desktop = display.desktopMode();
return new Monitor(
display.name() + "[0x" + Integer.toHexString(id).toUpperCase(Locale.ROOT) + "]",
id,
modes,
DisplayModes.toVideoMode(desktop),
display.x(),
display.y(),
display.width(),
display.height());
}
/** The player's chosen mode if this monitor has it, otherwise the desktop's. */
public VideoMode getPreferredVideoMode(final Optional<VideoMode> chosen) {
return chosen.filter(this.videoModes::contains).orElse(this.currentMode);
}
public int indexOfMode(final VideoMode mode) {
return this.videoModes.indexOf(mode);
}
public VideoMode mode(final int index) {
return this.videoModes.get(index);
}
public int modeCount() {
return this.videoModes.size();
}
@Override
public String toString() {
return this.name + "(" + this.currentMode + " at (" + this.x + "," + this.y + "))";
}
}
@@ -0,0 +1,65 @@
package com.mojang.blaze3d.platform;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.logging.LogUtils;
import incari.client.platform.ClientPlatform;
import incari.platform.api.window.DisplayInfo;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
/**
* Incari's replacement for Mojang's monitor list (patches/classes.txt): the connected displays by
* platform id, kept current by the platform's display events on the render thread.
*/
public class MonitorManager {
private static final Logger LOGGER = LogUtils.getLogger();
private final Int2ObjectMap<Monitor> byId = new Int2ObjectOpenHashMap<>();
public MonitorManager() {
for (DisplayInfo display : ClientPlatform.get().displays().all()) {
this.update(display.id(), "found");
}
}
// Display events arrive on the render thread, which also owns the map.
public void onDisplayConnected(final int id) {
RenderSystem.assertOnRenderThread();
this.update(id, "connected");
}
public void onDisplayModeChanged(final int id) {
RenderSystem.assertOnRenderThread();
this.update(id, "changed mode");
}
public void onDisplayDisconnected(final int id) {
RenderSystem.assertOnRenderThread();
Monitor gone = this.byId.remove(id);
if (gone != null) {
LOGGER.debug("Display {} disconnected; displays now {}", gone, this.byId.values());
}
}
/** Re-reads one display from the platform; one that can't be read is left out. */
private void update(final int id, final String what) {
Monitor fresh = Monitor.tryCreate(id);
if (fresh == null) {
return;
}
this.byId.put(id, fresh);
LOGGER.debug("Display {} {}; displays now {}", fresh, what, this.byId.values());
}
public @Nullable Monitor getMonitor(final int id) {
return this.byId.get(id);
}
/** The monitor the window is mostly on. */
public @Nullable Monitor findBestMonitor(final Window window) {
return this.byId.get(window.platformWindow().displayId());
}
}
@@ -0,0 +1,247 @@
package com.mojang.blaze3d.platform;
import incari.client.modules.IncariModules;
import incari.client.platform.ClientPlatform;
import incari.client.platform.PlatformNotices;
import incari.platform.api.PlatformNotice;
import incari.platform.api.input.KeyAction;
import incari.platform.api.input.KeyModifiers;
import incari.platform.api.window.PlatformEventListener;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.options.controls.KeyBindsScreen;
import net.minecraft.client.input.InputQuirks;
import net.minecraft.client.input.KeyEvent;
import net.minecraft.client.input.MouseButtonInfo;
import net.minecraft.client.input.PreeditEvent;
import net.minecraft.client.server.IntegratedServer;
import org.jspecify.annotations.Nullable;
/**
* Incari's replacement for Mojang's SDL event pump (patches/classes.txt). The name stays because
* the game refers to it; the events now come from the platform, and go to the same handlers.
*
* <p>Window events update the {@link Window} at once. Input events are handed to the game through
* {@link Minecraft#execute}, as before, so they run in the game's task order.
*/
public class SDLEventHandler implements PlatformEventListener {
/** The game's key action codes (see {@code KeyEvent.Action}). */
private static final int ACTION_RELEASE = 0;
private static final int ACTION_PRESS = 1;
private static final int ACTION_REPEAT = -1;
private final Minecraft minecraft;
private final Window window;
/** The game loop has run a pass, so frames have begun ({@link #pumpEvents}). */
private boolean looping;
/** The game's one handler, for Incari's own wait loops (singleplayer's server in a worker). */
private static @Nullable SDLEventHandler current;
public SDLEventHandler(final Minecraft minecraft, final Window window) {
this.minecraft = minecraft;
this.window = window;
current = this;
}
/** The game's handler, once its window exists; null before. */
public static @Nullable SDLEventHandler current() {
return current;
}
/**
* Once per pass of the game loop ({@code Minecraft.run}): ends the frame, which lets a browser
* page run (its input, drawing and timers happen between the game's frames), then handles the
* events that arrived.
*/
public void pollEvents() {
looping = true;
ClientPlatform.get().endFrame();
ClientPlatform.get().pollEvents(this);
// In a world, closing the page loses what the last save didn't keep (a browser asks first),
// and Ctrl+W, sprinting forward, is the browser's close-tab shortcut.
this.window.platformWindow().setLeaveWarning(this.minecraft.level != null);
PlatformNotices.tick(this.minecraft);
}
/**
* Drops input queued during a stall, then handles what's left (window events). The game's wait
* loops call it between the frames they draw themselves (loading a singleplayer world, saving
* one on the way out), so once the game loop runs it ends the frame too: in the page, a loop
* that never ends its frame never lets the integrated server and the background pool run,
* which only get the page's thread between frames (world creation waited forever for its
* first chunk). Before the first frame (start-up) it only handles events.
*/
public void pumpEvents() {
if (looping) {
ClientPlatform.get().endFrame();
}
this.flushInputEvents();
ClientPlatform.get().pollEvents(this);
}
public void flushInputEvents() {
ClientPlatform.get().flushInputEvents();
}
// --- Window ---
@Override
public void closeRequested() {
this.window.onCloseRequested();
}
@Override
public void terminating() {
this.window.onTerminating();
}
@Override
public void windowMoved(final int x, final int y) {
this.window.onMoved(x, y);
}
@Override
public void windowResized(final int width, final int height) {
this.window.onResized(width, height);
}
@Override
public void framebufferResized(final int width, final int height) {
this.window.onFramebufferResized(width, height);
}
@Override
public void minimizedChanged(final boolean minimized) {
if (minimized) {
// A hidden page may be closed next, with nothing run after.
IncariModules.saveNow();
// Singleplayer's server on the page saves now too, as it does when the game pauses (a
// world in a worker is told by the page itself: PlatformChannel.sendWhenLeaving).
IntegratedServer server = this.minecraft.getSingleplayerServer();
if (server != null) {
server.execute(() -> server.saveEverything(true, false, false));
}
}
this.window.onMinimized(minimized);
}
@Override
public void focusChanged(final boolean focused) {
this.window.onFocusChanged(focused);
}
@Override
public void cursorEnteredOrLeft() {
this.window.onCursorEnteredOrLeft();
}
@Override
public void displayChanged() {
this.window.onDisplayChanged();
}
@Override
public void fullscreenChanged(final boolean fullscreen) {
this.window.onFullscreenChanged();
}
@Override
public void displayAdded(final int displayId) {
this.window.onDisplayAdded(displayId);
}
@Override
public void displayRemoved(final int displayId) {
this.window.onDisplayRemoved(displayId);
}
@Override
public void displayModeChanged(final int displayId) {
this.window.onDisplayModeChanged(displayId);
}
// --- Keyboard ---
@Override
public void key(final int scancode, final int keyCode, final int modifiers, final KeyAction action) {
int gameAction =
switch (action) {
case PRESS -> ACTION_PRESS;
case RELEASE -> ACTION_RELEASE;
case REPEAT -> ACTION_REPEAT;
};
KeyEvent event = new KeyEvent(scancode, keyCode, modifiers);
long handle = this.window.handle();
this.minecraft.execute(() -> this.minecraft.keyboardHandler.keyPress(handle, gameAction, event));
}
@Override
public void keymapChanged() {
// Key names depend on the layout: refresh them where they're shown (the modules' HUD
// names keys too, Keystrokes).
this.minecraft.execute(() -> {
IncariModules.keymapChanged();
if (this.minecraft.gui.screen() instanceof KeyBindsScreen keyBinds) {
keyBinds.refreshKeybindLabels();
}
});
}
@Override
public void textInput(final String text) {
long handle = this.window.handle();
this.minecraft.execute(() -> this.minecraft.keyboardHandler.textInput(handle, text));
}
@Override
public void textEditing(final String text, final int start, final int length) {
PreeditEvent preedit = PreeditEvent.fromSdlTextEditing(text, start, length);
long handle = this.window.handle();
this.minecraft.execute(() -> this.minecraft.keyboardHandler.textEditing(handle, preedit));
}
// --- Mouse ---
@Override
public void mouseMoved(final double x, final double y, final double dx, final double dy) {
long handle = this.window.handle();
this.minecraft.execute(() -> this.minecraft.mouseHandler.onMove(handle, x, y, dx, dy));
}
@Override
public void mouseButton(final int button, final boolean pressed, final int modifiers) {
MouseButtonInfo info = new MouseButtonInfo(button, modifiers);
int action = pressed ? ACTION_PRESS : ACTION_RELEASE;
long handle = this.window.handle();
this.minecraft.execute(() -> this.minecraft.mouseHandler.onButton(handle, info, action));
}
@Override
public void mouseWheel(final double dx, final double dy, final int modifiers) {
double scrollX = dx;
double scrollY = dy;
// macOS turns Shift+wheel into horizontal scrolling; the game wants it vertical again.
if (InputQuirks.SHIFT_INVERTS_SCROLL_AXIS && dy == 0.0 && dx != 0.0 && (modifiers & KeyModifiers.SHIFT) != 0) {
scrollX = 0.0;
scrollY = -dx;
}
double finalX = scrollX;
double finalY = scrollY;
long handle = this.window.handle();
this.minecraft.execute(() -> this.minecraft.mouseHandler.onScroll(handle, finalX, finalY));
}
@Override
public void notice(final PlatformNotice notice) {
PlatformNotices.show(this.minecraft, notice);
}
@Override
public void filesDropped(final List<String> paths) {
long handle = this.window.handle();
this.minecraft.execute(() -> this.minecraft.mouseHandler.onDrop(handle, paths));
}
}
@@ -0,0 +1,76 @@
package com.mojang.blaze3d.platform;
import java.util.Objects;
import org.jspecify.annotations.Nullable;
/**
* Incari's replacement for Mojang's text input manager (patches/classes.txt): turns text input on
* for whichever widget has focus, and tells the input method where that widget is.
*/
public class TextInputManager {
private final Window window;
/** The widget text input is on for; only it may turn it off again. */
private @Nullable Object owner;
private boolean active;
private @Nullable Area area;
/** The text area in window coordinates. */
private record Area(int x, int y, int width, int height) {}
public TextInputManager(final Window window) {
this.window = window;
}
/**
* Sets where the text being edited is, in GUI coordinates (corners x0,y0 and x1,y1). The
* platform wants window coordinates: GUI units times the GUI scale gives pixels, and pixels
* over the pixel density gives window coordinates.
*/
public void setTextInputArea(final int x0, final int y0, final int x1, final int y1) {
double toWindow = this.window.getGuiScale() / (double) this.window.getPixelDensity();
Area updated = new Area(
(int) Math.round(x0 * toWindow),
(int) Math.round(y0 * toWindow),
Math.max(1, (int) Math.round((x1 - x0) * toWindow)),
Math.max(1, (int) Math.round((y1 - y0) * toWindow)));
if (!Objects.equals(updated, this.area)) {
this.area = updated;
this.window.platformWindow().setTextInputArea(updated.x(), updated.y(), updated.width(), updated.height());
}
}
public void startTextInput(final Object newOwner) {
this.owner = newOwner;
if (!this.active) {
this.active = true;
this.window.platformWindow().startTextInput();
}
}
/** Turns text input off, if {@code previousOwner} is the widget that turned it on. */
// Identity is the point: the owner is one particular widget, whatever its equals says.
@SuppressWarnings("ReferenceEquality")
public void stopTextInput(final Object previousOwner) {
if (this.owner == previousOwner) {
this.stopTextInput();
}
}
public void stopTextInput() {
this.owner = null;
if (this.active) {
this.active = false;
this.window.platformWindow().stopTextInput();
}
}
public void onTextInputFocusChange(final Object widget, final boolean focused) {
if (focused) {
this.startTextInput(widget);
} else {
this.stopTextInput(widget);
}
}
}
@@ -0,0 +1,602 @@
package com.mojang.blaze3d.platform;
import com.mojang.blaze3d.platform.cursor.CursorType;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.logging.LogUtils;
import com.mojang.renderpearl.api.device.GpuBackend;
import incari.client.platform.ClientPlatform;
import incari.client.platform.DisplayModes;
import incari.platform.api.window.DisplayMode;
import incari.platform.api.window.IconImage;
import incari.platform.api.window.PlatformWindow;
import incari.platform.api.window.WindowSpec;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import net.minecraft.CrashReport;
import net.minecraft.CrashReportCategory;
import net.minecraft.ReportedException;
import net.minecraft.client.Minecraft;
import net.minecraft.client.input.InputQuirks;
import net.minecraft.client.main.SilentInitException;
import net.minecraft.server.packs.PackMetadataResources;
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
/**
* Incari's replacement for Mojang's window (patches/classes.txt). It keeps the game-facing state
* and rules (sizes, GUI scale, the fullscreen request, crash details) and leaves the operating
* system to a {@link PlatformWindow}: SDL on the desktop, the canvas in the browser.
*/
public final class Window implements AutoCloseable {
private static final Logger LOGGER = LogUtils.getLogger();
public static final int MIN_WINDOW_WIDTH = WindowSpec.MIN_WIDTH;
public static final int MIN_WINDOW_HEIGHT = WindowSpec.MIN_HEIGHT;
/** The GUI's design size at scale 1: the scale grows while a whole multiple of it still fits. */
public static final int BASE_WIDTH = 320;
public static final int BASE_HEIGHT = 240;
private final WindowEventHandler eventHandler;
private final MonitorManager monitorManager;
private final PlatformWindow platformWindow;
/** Where the window goes back to when it leaves fullscreen. */
private int restoreX;
private int restoreY;
private int restoreWidth;
private int restoreHeight;
private int screenX;
private int screenY;
private int screenWidth;
private int screenHeight;
private int pixelWidth;
private int pixelHeight;
private int scaleFactor;
private int scaledWidth;
private int scaledHeight;
private Optional<VideoMode> preferredFullscreenVideoMode;
private boolean exclusiveFullscreen;
/** Whether the game wants fullscreen; {@link #fullscreen} is whether the window is. */
private boolean fullscreenRequested;
private boolean fullscreen;
private boolean fullscreenModeDirty;
private String errorSection = "Startup";
private boolean minimized;
private boolean hasFocus = true;
private boolean shouldClose;
private @Nullable Runnable closeCallback;
private boolean allowCursorChanges;
private boolean quitShortcuts;
private CursorType currentCursor = CursorType.DEFAULT;
public Window(
final WindowEventHandler handler,
final DisplayData startup,
final @Nullable String savedFullscreenMode,
final boolean wantExclusive,
final String windowTitle,
final MonitorManager monitors,
final GpuBackend gpuBackend) {
this(handler, startup, savedFullscreenMode, wantExclusive, windowTitle, monitors, gpuBackend, 0);
}
/**
* @param sizeLimit the largest the window may be in either dimension, or 0 for no limit
*/
public Window(
final WindowEventHandler handler,
final DisplayData startup,
final @Nullable String savedFullscreenMode,
final boolean wantExclusive,
final String windowTitle,
final MonitorManager monitors,
final GpuBackend gpuBackend,
final int sizeLimit) {
this.eventHandler = handler;
this.monitorManager = monitors;
this.exclusiveFullscreen = wantExclusive;
this.preferredFullscreenVideoMode = initialFullscreenMode(savedFullscreenMode, startup);
this.fullscreenRequested = startup.isFullscreen();
this.screenWidth = Math.max(startup.width(), MIN_WINDOW_WIDTH);
this.screenHeight = Math.max(startup.height(), MIN_WINDOW_HEIGHT);
this.restoreWidth = this.screenWidth;
this.restoreHeight = this.screenHeight;
WindowSpec spec = new WindowSpec(windowTitle, this.screenWidth, this.screenHeight, sizeLimit);
this.platformWindow = ClientPlatform.get().createWindow(spec, gpuBackend::createWindow);
ClientPlatform.windowCreated(this.platformWindow);
MacosUtil.disableCloseWindowMenuItem();
// Start centred on the primary display; where the platform can't say, keep where it put us.
Monitor primary = monitors.getMonitor(ClientPlatform.get().displays().primaryId());
this.screenX = primary == null ? this.platformWindow.x() : primary.x() + (primary.w() - this.screenWidth) / 2;
this.screenY = primary == null ? this.platformWindow.y() : primary.y() + (primary.h() - this.screenHeight) / 2;
this.restoreX = this.screenX;
this.restoreY = this.screenY;
this.applyRequestedMode();
this.refreshFramebufferSize();
}
private static Optional<VideoMode> initialFullscreenMode(
final @Nullable String fromOptions, final DisplayData startup) {
Optional<VideoMode> saved = VideoMode.read(fromOptions);
if (saved.isPresent()) {
return saved;
}
if (startup.fullscreenWidth().isPresent() && startup.fullscreenHeight().isPresent()) {
// Sizes from the command line: assume the everyday 24-bit, 60 Hz mode.
return Optional.of(new VideoMode(
startup.fullscreenWidth().getAsInt(),
startup.fullscreenHeight().getAsInt(),
8,
8,
8,
60));
}
return Optional.empty();
}
/** The platform's name for crash reports, for example "SDL on Linux (wayland)". */
public static String getPlatform() {
return ClientPlatform.get().description();
}
/** The platform window behind this one, for Incari code that needs more than the game uses. */
public PlatformWindow platformWindow() {
return this.platformWindow;
}
public @Nullable VideoMode getActiveVideoMode() {
RenderSystem.assertOnRenderThread();
DisplayMode mode = this.platformWindow.currentDisplayMode();
return mode == null ? null : DisplayModes.toVideoMode(mode);
}
public boolean shouldClose() {
return this.shouldClose;
}
// --- Events from the platform, delivered by SDLEventHandler on the render thread ---
void onCloseRequested() {
// The system's quit shortcut (Alt+F4, Command+Q) closes the game only when the player
// hasn't bound it to something else.
if (this.quitShortcuts || !InputQuirks.isQuitShortcutDown()) {
this.requestClose();
}
}
void onTerminating() {
this.requestClose();
}
void onDisplayAdded(final int displayId) {
this.monitorManager.onDisplayConnected(displayId);
}
void onDisplayRemoved(final int displayId) {
this.monitorManager.onDisplayDisconnected(displayId);
}
void onDisplayModeChanged(final int displayId) {
this.monitorManager.onDisplayModeChanged(displayId);
this.refreshFramebufferSize();
this.eventHandler.framebufferSizeChanged();
}
void onDisplayChanged() {
this.eventHandler.framebufferSizeChanged();
}
void onMoved(final int newX, final int newY) {
this.screenX = newX;
this.screenY = newY;
if (!this.platformWindow.isFullscreen()) {
this.restoreX = newX;
this.restoreY = newY;
}
}
void onResized(final int newWidth, final int newHeight) {
this.screenWidth = newWidth;
this.screenHeight = newHeight;
if (!this.platformWindow.isFullscreen()) {
this.restoreWidth = Math.max(newWidth, MIN_WINDOW_WIDTH);
this.restoreHeight = Math.max(newHeight, MIN_WINDOW_HEIGHT);
}
// Keep the pointer lock centred in the new size.
if (Minecraft.getInstance().mouseHandler.isMouseGrabbed()) {
InputConstants.grabMouse(this, this.getScreenWidth() / 2.0, this.getScreenHeight() / 2.0);
}
}
void onFramebufferResized(final int pixelWidth, final int pixelHeight) {
if (pixelWidth <= 0 || pixelHeight <= 0) {
return;
}
int previousWidth = this.pixelWidth;
int previousHeight = this.pixelHeight;
this.pixelWidth = pixelWidth - this.platformWindow.unusedWidth();
this.pixelHeight = pixelHeight;
try {
this.eventHandler.framebufferSizeChanged();
} catch (Exception e) {
CrashReport report = CrashReport.forThrowable(e, "Window resize");
CrashReportCategory sizes = report.addCategory("Window Dimensions");
sizes.setDetail("Old", previousWidth + "x" + previousHeight);
sizes.setDetail("New", pixelWidth + "x" + pixelHeight);
throw new ReportedException(report);
}
}
void onMinimized(final boolean minimized) {
this.minimized = minimized;
Minecraft.getInstance().invalidateSurfaceConfiguration();
}
void onFocusChanged(final boolean hasFocus) {
this.hasFocus = hasFocus;
}
void onCursorEnteredOrLeft() {
this.eventHandler.cursorEntered();
}
void onFullscreenChanged() {
this.syncFullscreenState();
}
private void syncFullscreenState() {
boolean nowFullscreen = this.platformWindow.isFullscreen();
if (nowFullscreen != this.fullscreen) {
this.fullscreen = nowFullscreen;
this.eventHandler.fullscreenStateChanged(nowFullscreen);
}
}
private void requestClose() {
this.shouldClose = true;
if (this.closeCallback != null) {
this.closeCallback.run();
}
}
// --- Icon ---
/** Incari's icon in each size the window can pick from (tools/icon), in the Incari pack. */
private static final int[] ICON_SIZES = {16, 32, 48, 128, 256};
/**
* Shows Incari's icon, not the game's: {@code resources} and {@code iconSet} name the game's,
* and are left unread.
*/
public void setIcon(final PackMetadataResources resources, final IconSet iconSet) throws IOException {
List<IconImage> sizes = new ArrayList<>(ICON_SIZES.length);
for (int size : ICON_SIZES) {
String path = "/incari-pack/assets/incari/textures/gui/icon_" + size + ".png";
try (InputStream in = Window.class.getResourceAsStream(path)) {
if (in == null) {
throw new IOException("Incari's pack has no " + path);
}
try (NativeImage image = NativeImage.read(in)) {
sizes.add(new IconImage(image.getWidth(), image.getHeight(), rgbaBytes(image)));
}
}
}
this.platformWindow.setIcon(sizes);
}
/** The image's pixels as R, G, B, A bytes, row by row. */
private static byte[] rgbaBytes(final NativeImage image) {
int width = image.getWidth();
int height = image.getHeight();
byte[] rgba = new byte[width * height * 4];
int at = 0;
for (int row = 0; row < height; row++) {
for (int column = 0; column < width; column++) {
// NativeImage.getPixel is ARGB.
int argb = image.getPixel(column, row);
rgba[at++] = (byte) (argb >> 16);
rgba[at++] = (byte) (argb >> 8);
rgba[at++] = (byte) argb;
rgba[at++] = (byte) (argb >>> 24);
}
}
return rgba;
}
// --- Crash reporting ---
public String getErrorSection() {
return this.errorSection;
}
public void setErrorSection(final String section) {
this.errorSection = section;
}
@Override
public void close() {
RenderSystem.assertOnRenderThread();
ClientPlatform.windowClosed();
this.platformWindow.close();
}
// --- Size and mode ---
private void refreshFramebufferSize() {
FramebufferSize size = this.queryFramebufferSize();
this.pixelWidth = size.width() - this.platformWindow.unusedWidth();
this.pixelHeight = size.height();
}
/** The whole drawable surface in pixels, which is what the graphics surface is sized to. */
public FramebufferSize queryFramebufferSize() {
return new FramebufferSize(
Math.max(this.platformWindow.framebufferWidth(), 1),
Math.max(this.platformWindow.framebufferHeight(), 1));
}
public void updateFullscreenIfChanged() {
RenderSystem.assertOnRenderThread();
if (this.fullscreenRequested != this.fullscreen) {
this.applyRequestedMode();
this.eventHandler.framebufferSizeChanged();
}
}
public Optional<VideoMode> getPreferredFullscreenVideoMode() {
return this.preferredFullscreenVideoMode;
}
public void setPreferredFullscreenVideoMode(final Optional<VideoMode> mode) {
if (!mode.equals(this.preferredFullscreenVideoMode)) {
this.preferredFullscreenVideoMode = mode;
this.fullscreenModeDirty = true;
}
}
public void changeFullscreenVideoMode() {
RenderSystem.assertOnRenderThread();
if (this.fullscreenRequested && this.fullscreenModeDirty) {
this.fullscreenModeDirty = false;
this.applyRequestedMode();
this.eventHandler.framebufferSizeChanged();
}
}
/** Puts the window into the mode the game asked for: windowed, borderless or exclusive. */
private void applyRequestedMode() {
RenderSystem.assertOnRenderThread();
if (this.fullscreenRequested && !this.fullscreen) {
// Remember the windowed placement to come back to.
this.restoreX = this.screenX;
this.restoreY = this.screenY;
this.restoreWidth = Math.max(this.screenWidth, MIN_WINDOW_WIDTH);
this.restoreHeight = Math.max(this.screenHeight, MIN_WINDOW_HEIGHT);
}
boolean applied;
if (this.fullscreenRequested) {
applied = this.platformWindow.setFullscreen(this.exclusiveFullscreen ? this.exclusiveTarget() : null);
} else {
int windowWidth = Math.max(this.restoreWidth, MIN_WINDOW_WIDTH);
int windowHeight = Math.max(this.restoreHeight, MIN_WINDOW_HEIGHT);
applied = this.platformWindow.setWindowed(this.restoreX, this.restoreY, windowWidth, windowHeight);
if (applied) {
this.screenX = this.restoreX;
this.screenY = this.restoreY;
this.screenWidth = windowWidth;
this.screenHeight = windowHeight;
}
}
if (!applied) {
LOGGER.error("Couldn't {} fullscreen", this.fullscreenRequested ? "enter" : "leave");
this.fullscreenRequested = this.fullscreen;
this.eventHandler.fullscreenStateChanged(this.fullscreen);
return;
}
if (this.fullscreenRequested) {
this.screenX = this.platformWindow.x();
this.screenY = this.platformWindow.y();
this.screenWidth = this.platformWindow.width();
this.screenHeight = this.platformWindow.height();
}
this.syncFullscreenState();
this.refreshFramebufferSize();
if (this.exclusiveFullscreen && this.fullscreen && !this.platformWindow.isExclusiveFullscreen()) {
LOGGER.info("Exclusive fullscreen request resolved to borderless desktop");
}
}
/** The display mode exclusive fullscreen asks for: the player's choice if this monitor has it. */
private @Nullable DisplayMode exclusiveTarget() {
Monitor monitor = this.monitorManager.findBestMonitor(this);
if (monitor == null) {
LOGGER.warn(
"Failed to find suitable monitor for exclusive fullscreen, falling back to borderless fullscreen");
return null;
}
VideoMode mode = monitor.getPreferredVideoMode(this.preferredFullscreenVideoMode);
LOGGER.info("Exclusive target {} on monitor {}", mode, monitor);
return DisplayModes.toPlatform(mode);
}
public boolean isExclusiveFullscreen() {
return this.platformWindow.isExclusiveFullscreen();
}
public void setExclusiveFullscreen(final boolean exclusive) {
if (this.exclusiveFullscreen != exclusive) {
this.exclusiveFullscreen = exclusive;
if (this.fullscreenRequested) {
this.applyRequestedMode();
this.eventHandler.framebufferSizeChanged();
}
}
}
public void setWindowed(final int windowWidth, final int windowHeight) {
this.restoreWidth = Math.max(windowWidth, MIN_WINDOW_WIDTH);
this.restoreHeight = Math.max(windowHeight, MIN_WINDOW_HEIGHT);
this.fullscreenRequested = false;
this.applyRequestedMode();
}
/**
* The largest GUI scale up to {@code maxScale} (0 for no limit) at which the GUI's base size
* still fits the framebuffer; with {@code enforceUnicode}, rounded up to even so the Unicode
* font's half-pixel glyphs land on whole pixels.
*/
public int calculateScale(final int maxScale, final boolean enforceUnicode) {
int fitsWidth = Math.max(1, this.pixelWidth / BASE_WIDTH);
int fitsHeight = Math.max(1, this.pixelHeight / BASE_HEIGHT);
int scale = Math.min(fitsWidth, fitsHeight);
if (maxScale > 0) {
scale = Math.min(scale, maxScale);
}
if (enforceUnicode && scale % 2 != 0) {
scale++;
}
return scale;
}
public void setTitle(final String title) {
this.platformWindow.setTitle(title);
}
public void setWindowMaxSize(final int maxWidth, final int maxHeight) {
this.platformWindow.setMaximumSize(maxWidth, maxHeight);
}
/** The id input events carry, so handlers can tell this window's events apart. */
public long handle() {
return this.platformWindow.nativeHandle();
}
// Framebuffer, in pixels: what rendering uses.
public int getWidth() {
return this.pixelWidth;
}
public int getHeight() {
return this.pixelHeight;
}
public void setWidth(final int pixels) {
this.pixelWidth = pixels;
}
public void setHeight(final int pixels) {
this.pixelHeight = pixels;
}
// The window on the desktop, in screen coordinates.
public int getX() {
return this.screenX;
}
public int getY() {
return this.screenY;
}
public int getScreenWidth() {
return this.screenWidth;
}
public int getScreenHeight() {
return this.screenHeight;
}
// The GUI: pixels divided by the GUI scale.
public int getGuiScale() {
return this.scaleFactor;
}
public int getGuiScaledWidth() {
return this.scaledWidth;
}
public int getGuiScaledHeight() {
return this.scaledHeight;
}
public void setGuiScale(final int scale) {
this.scaleFactor = scale;
// Round up so the GUI always covers the whole framebuffer.
this.scaledWidth = (this.pixelWidth + scale - 1) / scale;
this.scaledHeight = (this.pixelHeight + scale - 1) / scale;
}
// State.
public boolean isIconified() {
return this.minimized;
}
public boolean isFocused() {
return this.hasFocus;
}
public void setFullscreen(final boolean wanted) {
this.fullscreenRequested = wanted;
}
public float getPixelDensity() {
return this.platformWindow.pixelDensity();
}
public @Nullable Monitor findBestMonitor() {
return this.monitorManager.findBestMonitor(this);
}
public void setWindowCloseCallback(final Runnable task) {
this.closeCallback = task;
}
public void setAllowCursorChanges(final boolean allow) {
this.allowCursorChanges = allow;
}
public void setQuitShortcuts(final boolean enabled) {
this.quitShortcuts = enabled;
this.platformWindow.setQuitShortcutEnabled(enabled);
}
public void selectCursor(final CursorType cursor) {
CursorType wanted = this.allowCursorChanges ? cursor : CursorType.DEFAULT;
if (!wanted.equals(this.currentCursor)) {
this.currentCursor = wanted;
wanted.select();
}
}
/** Outline width for debug shapes: 2.5 at 1080p and below, scaling up with the framebuffer. */
public float getAppropriateLineWidth() {
return Math.max(2.5F, this.getWidth() / 1920.0F * 2.5F);
}
public record FramebufferSize(int width, int height) {}
public static class WindowInitFailed extends SilentInitException {
private static final long serialVersionUID = 1L;
public WindowInitFailed(final String message) {
super(message);
}
}
}
@@ -0,0 +1,55 @@
package com.mojang.blaze3d.platform.cursor;
import incari.client.platform.ClientPlatform;
import incari.platform.api.window.PlatformWindow;
import incari.platform.api.window.SystemCursor;
/**
* Incari's replacement for Mojang's cursor type (patches/classes.txt). A cursor is one of the
* platform's standard shapes; the platform creates the native cursor when it's first shown.
*/
public class CursorType {
public static final CursorType DEFAULT = new CursorType("default", SystemCursor.DEFAULT);
private final String name;
private final SystemCursor cursor;
private CursorType(final String name, final SystemCursor cursor) {
this.name = name;
this.cursor = cursor;
}
public void select() {
PlatformWindow window = ClientPlatform.window();
if (window != null) {
window.setCursor(this.cursor);
}
}
@Override
public String toString() {
return this.name;
}
/**
* Makes a cursor from one of the standard shapes {@code CursorTypes} names by SDL's
* {@code SDL_SystemCursor} number; a shape the platform can't show falls back to
* {@code fallback}.
*/
public static CursorType createStandardCursor(final int shape, final String name, final CursorType fallback) {
SystemCursor cursor =
switch (shape) {
case 0 -> SystemCursor.ARROW;
case 1 -> SystemCursor.TEXT;
case 3 -> SystemCursor.CROSSHAIR;
case 7 -> SystemCursor.RESIZE_EW;
case 8 -> SystemCursor.RESIZE_NS;
case 9 -> SystemCursor.RESIZE_ALL;
case 10 -> SystemCursor.NOT_ALLOWED;
case 11 -> SystemCursor.POINTING_HAND;
default -> null;
};
return cursor == null ? fallback : new CursorType(name, cursor);
}
}
@@ -0,0 +1,51 @@
package incari.client;
import net.minecraft.client.KeyMapping;
/**
* Incari's key mappings, added to the game's list by one hook in {@code Options} so they show in
* the controls screen and are saved with the rest.
*
* <p>The names are shown as they are: the game translates a key mapping's name, and Incari has no
* language files yet, so an English name is its own fallback. A name is also the key's line in
* {@code options.txt} ({@code key_<name>:<key>}), which the game splits at the first colon, so a
* name must have none: with one, the bind was read back as an unknown option on every start and
* went back to its default.
*/
public final class IncariKeys {
/** Voice chat: held to talk. B, as in Eagler's clients. */
public static final KeyMapping PUSH_TO_TALK =
new KeyMapping("Voice - Push to Talk", 5, KeyMapping.Category.MULTIPLAYER);
/**
* The profiler overlay, on and off. F9: the game leaves it free, and browsers don't take
* it for themselves.
*/
public static final KeyMapping PROFILER_OVERLAY = new KeyMapping("Profiler Overlay", 66, KeyMapping.Category.DEBUG);
/**
* The module menu. Right Shift, as in other clients; the game leaves it free. Modules' own
* binds aren't here: they're in each module's settings and its profile ({@code GameKeys}).
*/
public static final KeyMapping MODULE_MENU = new KeyMapping("Incari - Modules", 229, KeyMapping.Category.MISC);
/**
* The emote wheel (ADR 0061), held open. G: the game leaves it free, and B is push to talk's.
*/
public static final KeyMapping EMOTE_WHEEL = new KeyMapping("Incari - Emote Wheel", 10, KeyMapping.Category.MISC);
/**
* The screen recorder, on and off (ADR 0062; the browser only). F8: the game leaves it free, and
* Chrome takes F6 and F7 for itself.
*/
public static final KeyMapping RECORD_SCREEN =
new KeyMapping("Incari - Record Screen", 65, KeyMapping.Category.MISC);
/** Every Incari key mapping, as a new array for the game's list. */
public static KeyMapping[] all() {
return new KeyMapping[] {PUSH_TO_TALK, PROFILER_OVERLAY, MODULE_MENU, EMOTE_WHEEL, RECORD_SCREEN};
}
private IncariKeys() {}
}
@@ -0,0 +1,46 @@
package incari.client;
import incari.client.cosmetics.Cosmetics;
import incari.client.eagler.EaglerVoice;
import incari.client.legacy.LegacyRules;
import incari.client.look.Looks;
import incari.client.modules.IncariModules;
import incari.client.net.ServerConnections;
import incari.client.online.IncariOnline;
import incari.client.profiler.Profiling;
import incari.client.recorder.ScreenRecorder;
import incari.client.render.mesher.ChestBaking;
import incari.client.singleplayer.QuickWorlds;
import net.minecraft.client.Minecraft;
/**
* What Incari does once a client tick, from one hook in {@code Minecraft.tick} (after the GUI's
* tick, before key bindings): the legacy behaviour layer follows the server's version, voice
* chat runs, the profiler overlay's key is read, the benchmark's quick worlds are made and left, and
* the Incari account's connection runs, and the modules tick (their keybinds, then their listeners). The first tick also puts on the client's
* look. Game thread.
*/
public final class IncariTicks {
private IncariTicks() {}
public static void tick(Minecraft minecraft) {
Looks.start(minecraft);
// A join that reached a world: a kick from here on isn't a refusal of its version.
ServerConnections.tick(minecraft);
// First: the rest of the tick moves the player by the rules of the server it's on.
LegacyRules.update(minecraft);
// Push to talk works with no screen open, as other keys do, and while chat is closed.
boolean pushToTalk = minecraft.gui.screen() == null && IncariKeys.PUSH_TO_TALK.isDown();
EaglerVoice.tick(minecraft, pushToTalk);
Profiling.tick();
ScreenRecorder.tick(minecraft);
ChestBaking.tick(minecraft.level);
QuickWorlds.tick(minecraft);
// Before the modules: they read who's an Incari player (ADR 0058).
IncariOnline.tick(minecraft);
// Cosmetics read the service's emotes and what Incari players wear (ADR 0061).
Cosmetics.tick(minecraft);
IncariModules.tick(minecraft);
}
}
@@ -0,0 +1,69 @@
package incari.client;
/**
* Catch-up ticks spread over frames (ADR 0032). After a slow frame the game runs every tick it
* missed back to back, up to ten, in the next frame, which makes that frame slow as well: on the
* floor stand-in the slowest 1% of frames were mostly these runs. Here the ticks due are owed
* instead, and each frame runs as many as the frame rate needs on average, rounded up, so the debt
* drains a tick a frame over the next few frames. The game still runs every tick it would have (up to
* the ten it would run at once; it drops the rest, and so does this), a few frames later.
*
* <p>While the debt drains the game runs a little behind the clock: entities move a tick a frame
* until it's paid. A debt of more than two frames' worth runs one tick more a frame. The debt never
* exceeds the ten ticks the game would run at once, so after a long stall no more ticks run than the
* game would run (an earlier version kept a second's worth, and after the stalls of a busy fight
* ran twice the game's ticks, each a heavy one); bursts that come back to back can then drop a few
* ticks the game would have run. Off unless the page turns it on ({@code ?ticks=game} leaves it off, to compare); the
* desktop runs the game's way. Game thread.
*/
public final class TickPacing {
/** The most ticks the game runs in one frame; it drops any more. */
private static final int GAME_LIMIT = 10;
/** The weight of each frame in the average of ticks due a frame. */
private static final float SMOOTHING = 1.0F / 16.0F;
private static boolean enabled;
private static int debt;
// Ticks due a frame, averaged: one at 20 fps, a third at 60.
private static float average = 1.0F;
private TickPacing() {}
public static void setEnabled(boolean on) {
enabled = on;
debt = 0;
average = 1.0F;
}
/**
* Hook ({@code Minecraft.runTick}, after the ticks due are worked out): how many of the ticks due
* to run this frame. {@code advancing} is whether game time moves at all; while it doesn't, the
* debt waits.
*/
public static int ticksToRun(int due, boolean advancing) {
if (!enabled) {
return due;
}
if (!advancing) {
return 0;
}
average += (due - average) * SMOOTHING;
debt = Math.min(GAME_LIMIT, debt + Math.min(GAME_LIMIT, due));
int limit = Math.max(1, (int) Math.ceil(average));
if (debt > 2 * limit) {
limit++;
}
int run = Math.min(debt, limit);
debt -= run;
return run;
}
/** The ticks owed to later frames. */
public static int debt() {
return debt;
}
}
@@ -0,0 +1,204 @@
package incari.client.account;
import com.mojang.logging.LogUtils;
import incari.client.net.WispServers;
import incari.client.platform.ClientPlatform;
import incari.net.https.HttpsClient;
import incari.net.msa.MicrosoftAccount;
import incari.net.msa.MicrosoftEndpoints;
import incari.net.msa.MicrosoftSignIn;
import incari.net.tls.Transport;
import incari.platform.api.net.PlatformNetwork;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.PosixFilePermission;
import java.util.EnumSet;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import net.minecraft.client.User;
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
/**
* The Microsoft account the player signed in with (ADR 0070), if any: kept in
* {@code incari/microsoft-account.json} in the game directory (the browser's own storage for the
* page), and answered as the player wherever the game asks ({@code PlayerName.user}).
*
* <p>The file holds the Minecraft token and Microsoft's refresh token, so it never leaves this
* device: nothing logs it, and signing out deletes it. Sign-in's requests go straight to the hosts
* on the desktop and through the player's Wisp proxy in a browser, end-to-end encrypted either way.
*/
public final class MicrosoftAccounts {
private static final Logger LOGGER = LogUtils.getLogger();
private static final String FILE = "microsoft-account.json";
// Set once, on the first question.
private static @Nullable Path file;
private static volatile @Nullable MicrosoftAccount account;
private static volatile @Nullable User user;
/** The account's chat keys, made when it's first asked for. */
private static volatile @Nullable MicrosoftProfileKeys keys;
private MicrosoftAccounts() {}
/** Reads the saved account, once, from {@code gameDirectory}. */
public static synchronized void load(Path gameDirectory) {
if (file != null) {
return;
}
Path saved = gameDirectory.resolve("incari").resolve(FILE);
file = saved;
if (!Files.isRegularFile(saved)) {
return;
}
try {
MicrosoftAccount read = MicrosoftAccount.fromJson(Files.readString(saved, StandardCharsets.UTF_8));
if (read == null) {
LOGGER.warn("Ignoring {}: it isn't a saved account", saved);
return;
}
use(read);
LOGGER.info("Playing as Microsoft account {}", read.name());
} catch (IOException e) {
LOGGER.warn("Couldn't read {}: {}", saved, e.toString());
}
}
/** The signed-in account, or null. */
public static @Nullable MicrosoftAccount account() {
return account;
}
/** The player as the game knows them while signed in, or null when not. */
public static @Nullable User user() {
return user;
}
/** Signs in as {@code signedIn} and keeps it for the next start. */
public static synchronized void signedIn(MicrosoftAccount signedIn) {
MicrosoftAccount previous = account;
use(signedIn);
if (previous == null || !previous.id().equals(signedIn.id())) {
keys = null;
}
save(signedIn);
}
/** Signs out and deletes the saved tokens. */
public static synchronized void signOut() {
account = null;
user = null;
keys = null;
Path target = file;
if (target != null) {
try {
Files.deleteIfExists(target);
} catch (IOException e) {
LOGGER.warn("Couldn't delete {}: {}", target, e.toString());
}
}
}
/**
* The account with a Minecraft token good for a while yet, renewed through Microsoft if it was
* about to expire (and saved). Fails if there's no account or the renewal was refused.
*/
public static CompletableFuture<MicrosoftAccount> fresh() {
MicrosoftAccount current = account;
if (current == null) {
return CompletableFuture.failedFuture(new IOException("Not signed in"));
}
return signIn().renew(current).thenApply(renewed -> {
if (!renewed.equals(current)) {
synchronized (MicrosoftAccounts.class) {
// Only if nobody signed out or in meanwhile.
if (current.equals(account)) {
signedIn(renewed);
}
}
}
return renewed;
});
}
/** A sign-in client over this platform's route: a socket, or the Wisp proxy in a browser. */
public static MicrosoftSignIn signIn() {
PlatformNetwork network = ClientPlatform.get().network();
Transport transport = network.canOpenSockets()
? Transport.direct(network)
: Transport.wisp(network, WispServers.signInProxy());
return new MicrosoftSignIn(HttpsClient.pinned(transport, MicrosoftEndpoints.HOSTS), System::currentTimeMillis);
}
/** How sign-in reaches Microsoft, for the screen: "directly", or the proxy's address. */
public static String route() {
return ClientPlatform.get().network().canOpenSockets() ? "directly" : "through " + WispServers.signInProxy();
}
/** The chat keys for the signed-in account, or null when signed out. */
static @Nullable MicrosoftProfileKeys keys() {
MicrosoftAccount current = account;
if (current == null) {
return null;
}
MicrosoftProfileKeys made = keys;
if (made == null || !made.isFor(current)) {
made = new MicrosoftProfileKeys(current.id());
keys = made;
}
return made;
}
private static void use(MicrosoftAccount signedIn) {
account = signedIn;
user = new User(
signedIn.name(),
UUID.fromString(signedIn.dashedId()),
signedIn.minecraftToken(),
Optional.empty(),
Optional.empty());
}
private static void save(MicrosoftAccount signedIn) {
Path target = file;
if (target == null) {
return;
}
// Owner-only (it's a refresh token: on a shared machine, others could take the account
// with it), and written beside then moved over, so a crash never leaves half a file.
Path temporary = target.resolveSibling(FILE + ".tmp");
try {
Files.createDirectories(target.getParent());
Files.deleteIfExists(temporary);
Files.createFile(temporary);
try {
Files.setPosixFilePermissions(
temporary, EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE));
} catch (UnsupportedOperationException e) {
// Windows: the user's profile folder is already private.
}
Files.writeString(temporary, signedIn.toJson(), StandardCharsets.UTF_8);
try {
Files.move(temporary, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
} catch (AtomicMoveNotSupportedException e) {
Files.move(temporary, target, StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException e) {
LOGGER.warn("Couldn't save the Microsoft account: {}", e.toString());
}
}
/** Forgets everything, as a new start would. Tests only. */
public static synchronized void reset() {
file = null;
account = null;
user = null;
keys = null;
}
}
@@ -0,0 +1,96 @@
package incari.client.account;
import com.mojang.logging.LogUtils;
import incari.net.msa.MicrosoftAccount;
import incari.net.msa.ProfileCertificates;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import net.minecraft.client.multiplayer.ProfileKeyPairManager;
import net.minecraft.util.Crypt;
import net.minecraft.util.CryptException;
import net.minecraft.world.entity.player.ProfileKeyPair;
import net.minecraft.world.entity.player.ProfilePublicKey;
import org.slf4j.Logger;
/**
* The signed-in account's chat-signing keys, as the game asks for them (ADR 0070): fetched from
* Mojang through Incari's sign-in client, kept in memory only, and fetched again once Mojang says
* they're due. Servers that enforce secure chat refuse players without them.
*
* <p>The game polls the future from the render thread only once it's done, so it never waits.
*/
public final class MicrosoftProfileKeys implements ProfileKeyPairManager {
private static final Logger LOGGER = LogUtils.getLogger();
/** At most one fetch an hour, as the game's own manager, whatever happens. */
private static final Duration MINIMUM_REFRESH = Duration.ofHours(1);
private final String accountId;
private CompletableFuture<Optional<ProfileKeyPair>> keyPair = CompletableFuture.completedFuture(Optional.empty());
private Instant nextFetch = Instant.EPOCH;
MicrosoftProfileKeys(String accountId) {
this.accountId = accountId;
}
/** Hook ({@code Minecraft.getProfileKeyPairManager}): these keys while signed in, else the game's. */
public static ProfileKeyPairManager manager(ProfileKeyPairManager vanilla) {
MicrosoftProfileKeys keys = MicrosoftAccounts.keys();
return keys != null ? keys : vanilla;
}
boolean isFor(MicrosoftAccount account) {
return accountId.equals(account.id());
}
@Override
public synchronized CompletableFuture<Optional<ProfileKeyPair>> prepareKeyPair() {
Optional<ProfileKeyPair> current = keyPair.getNow(Optional.empty());
boolean fetching = !keyPair.isDone();
if (fetching || (current.isPresent() && !current.get().dueRefresh())) {
return keyPair;
}
nextFetch = Instant.now().plus(MINIMUM_REFRESH);
keyPair = MicrosoftAccounts.fresh()
.thenCompose(account -> MicrosoftAccounts.signIn().certificates(account))
.thenApply(MicrosoftProfileKeys::keyPair)
.exceptionally(failure -> {
LOGGER.warn("Couldn't get the chat key: {}", reason(failure));
return current;
});
return keyPair;
}
@Override
public synchronized boolean shouldRefreshKeyPair() {
if (!keyPair.isDone() || Instant.now().isBefore(nextFetch)) {
return false;
}
return keyPair.getNow(Optional.empty()).map(ProfileKeyPair::dueRefresh).orElse(true);
}
private static Optional<ProfileKeyPair> keyPair(ProfileCertificates certificates) {
try {
ProfilePublicKey.Data publicKey = new ProfilePublicKey.Data(
Instant.parse(certificates.expiresAt()),
Crypt.stringToRsaPublicKey(certificates.publicKeyPem()),
certificates.publicKeySignature());
return Optional.of(new ProfileKeyPair(
Crypt.stringToPemRsaPrivateKey(certificates.privateKeyPem()),
new ProfilePublicKey(publicKey),
Instant.parse(certificates.refreshedAfter())));
} catch (CryptException | RuntimeException e) {
// Never the key itself in the message: just what kind of failure.
throw new IllegalStateException(
"Mojang's chat key can't be read (" + e.getClass().getSimpleName() + ")");
}
}
private static String reason(Throwable failure) {
Throwable cause = failure.getCause() != null ? failure.getCause() : failure;
String message = cause.getMessage();
return message != null ? message : cause.getClass().getSimpleName();
}
}
@@ -0,0 +1,325 @@
package incari.client.account;
import incari.client.ui.Theme;
import incari.net.msa.DeviceCode;
import incari.net.msa.MicrosoftAccount;
import incari.net.msa.MicrosoftSignIn;
import incari.net.msa.SignInException;
import java.net.URI;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.function.Consumer;
import net.minecraft.ChatFormatting;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.MultiLineTextWidget;
import net.minecraft.client.gui.components.StringWidget;
import net.minecraft.client.gui.layouts.HeaderAndFooterLayout;
import net.minecraft.client.gui.layouts.LinearLayout;
import net.minecraft.client.gui.screens.ConfirmLinkScreen;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.CommonComponents;
import net.minecraft.network.chat.Component;
import org.jspecify.annotations.Nullable;
/**
* Microsoft sign-in (ADR 0070), opened from Edit Profile: the device-code flow, so the password is
* typed on Microsoft's own page, on any device, never into the game. Shows the code, waits for the
* player to enter it, then signs in to Minecraft; or shows who's signed in, with Sign Out.
*
* <p>English only for now; Incari's screens don't have language files yet.
*/
public final class MicrosoftScreen extends Screen {
private static final int TEXT_WIDTH = 300;
private static final int BUTTON_WIDTH = 150;
private enum State {
IDLE,
REQUESTING,
CODE,
SIGNING_IN
}
private final Screen parent;
/** Made again on each init: the screen rebuilds itself as the sign-in moves on. */
private HeaderAndFooterLayout layout = new HeaderAndFooterLayout(this);
private State state = State.IDLE;
private Component message = CommonComponents.EMPTY;
private @Nullable DeviceCode code;
private @Nullable MicrosoftSignIn signIn;
/** Bumped when a sign-in is started or abandoned, so a late answer for an old one is dropped. */
private int attempt;
private boolean polling;
private long nextPollMillis;
private int intervalSeconds;
/** Polls in a row that didn't get through: retried, further apart, until {@link #MAX_POLL_FAILURES}. */
private int pollFailures;
/** Polls in a row that may fail to get through before the sign-in gives up: minutes of trying. */
private static final int MAX_POLL_FAILURES = 8;
/** The longest wait between polls that didn't get through. */
private static final long MAX_RETRY_MILLIS = 30_000;
public MicrosoftScreen(Screen parent) {
super(Component.literal("Microsoft Account"));
this.parent = parent;
}
@Override
protected void init() {
layout = new HeaderAndFooterLayout(this);
layout.addTitleHeader(this.title, this.font);
LinearLayout contents = layout.addToContents(LinearLayout.vertical().spacing(Theme.GAP));
contents.defaultCellSetting().alignHorizontallyCenter();
LinearLayout footer = layout.addToFooter(LinearLayout.horizontal().spacing(8));
MicrosoftAccount account = MicrosoftAccounts.account();
boolean inWorld = this.minecraft.level != null;
switch (state) {
case IDLE -> {
if (account != null) {
contents.addChild(text(Component.literal("Signed in as ")
.append(Component.literal(account.name()).withStyle(ChatFormatting.YELLOW))));
contents.addChild(
text(
Component.literal(
"Servers that check accounts see you as this player. Your password never passes through Incari.")));
Button signOut = footer.addChild(Button.builder(Component.literal("Sign Out"), button -> signOut())
.build());
signOut.active = !inWorld;
} else {
contents.addChild(text(Component.literal(
"Sign in to join servers that check Minecraft accounts (online mode). You sign in on"
+ " Microsoft's own page, on this or any other device.")));
contents.addChild(text(
Component.literal("Sign-in goes " + MicrosoftAccounts.route() + ", encrypted end to end.")
.withStyle(ChatFormatting.GRAY)));
Button start = footer.addChild(Button.builder(Component.literal("Sign In"), button -> start())
.build());
start.active = !inWorld;
}
if (inWorld) {
contents.addChild(text(Component.literal("Leave the world to change accounts.")
.withStyle(ChatFormatting.GRAY)));
}
footer.addChild(Button.builder(CommonComponents.GUI_DONE, button -> onClose())
.build());
}
case REQUESTING -> {
contents.addChild(text(Component.literal("Asking Microsoft for a sign-in code...")));
footer.addChild(Button.builder(CommonComponents.GUI_CANCEL, button -> cancel())
.build());
}
case CODE -> {
DeviceCode current = code;
if (current != null) {
contents.addChild(
text(Component.literal("On any device, open microsoft.com/link and enter this code:")));
contents.addChild(new StringWidget(
Component.literal(current.userCode()).withStyle(ChatFormatting.YELLOW, ChatFormatting.BOLD),
this.font));
LinearLayout actions =
contents.addChild(LinearLayout.horizontal().spacing(8));
actions.addChild(Button.builder(
Component.literal("Open Page"),
ConfirmLinkScreen.confirmLink(this, URI.create(current.pageWithCode())))
.width(BUTTON_WIDTH / 2 + 20)
.build());
actions.addChild(Button.builder(Component.literal("Copy Code"), button -> {
this.minecraft.keyboardHandler.setClipboard(current.userCode());
message = Component.literal("Code copied.");
rebuildWidgets();
})
.width(BUTTON_WIDTH / 2 + 20)
.build());
contents.addChild(text(
Component.literal("Waiting for you to sign in...").withStyle(ChatFormatting.GRAY)));
}
footer.addChild(Button.builder(CommonComponents.GUI_CANCEL, button -> cancel())
.build());
}
case SIGNING_IN -> {
contents.addChild(text(Component.literal("Signing in to Minecraft...")));
footer.addChild(Button.builder(CommonComponents.GUI_CANCEL, button -> cancel())
.build());
}
}
if (!message.equals(CommonComponents.EMPTY)) {
contents.addChild(text(message));
}
layout.visitWidgets(this::addRenderableWidget);
repositionElements();
}
private MultiLineTextWidget text(Component text) {
return new MultiLineTextWidget(text, this.font)
.setMaxWidth(Math.min(TEXT_WIDTH, this.width - 20))
.setMaxRows(4)
.setCentered(true);
}
@Override
protected void repositionElements() {
layout.arrangeElements();
}
// --- The flow ------------------------------------------------------------------------------
private void start() {
int mine = ++attempt;
MicrosoftSignIn client = MicrosoftAccounts.signIn();
signIn = client;
message = CommonComponents.EMPTY;
show(State.REQUESTING);
whenDone(client.requestCode(), mine, requested -> {
code = requested;
pollFailures = 0;
intervalSeconds = requested.intervalSeconds();
nextPollMillis = System.currentTimeMillis() + intervalSeconds * 1000L;
show(State.CODE);
});
}
@Override
public void tick() {
DeviceCode current = code;
MicrosoftSignIn client = signIn;
if (state != State.CODE || current == null || client == null || polling) {
return;
}
if (System.currentTimeMillis() < nextPollMillis) {
return;
}
polling = true;
int mine = attempt;
// Not whenDone: a poll that didn't get through (school Wi-Fi, the proxy) is tried again, and
// only Microsoft's own answer (expired, declined) ends the sign-in.
var _ = client.poll(current).handle((poll, failure) -> {
this.minecraft.execute(() -> {
if (mine != attempt) {
return;
}
if (failure != null) {
pollFailed(failure);
} else {
polled(poll, client, mine);
}
});
return null;
});
}
private void polled(MicrosoftSignIn.Poll poll, MicrosoftSignIn client, int mine) {
polling = false;
if (pollFailures > 0) {
pollFailures = 0;
message = CommonComponents.EMPTY;
rebuildWidgets();
}
switch (poll.state()) {
case WAITING -> nextPollMillis = System.currentTimeMillis() + intervalSeconds * 1000L;
case SLOW_DOWN -> {
intervalSeconds += 5;
nextPollMillis = System.currentTimeMillis() + intervalSeconds * 1000L;
}
case DONE -> {
MicrosoftSignIn.MicrosoftTokens tokens = poll.tokens();
if (tokens != null) {
show(State.SIGNING_IN);
whenDone(client.signIn(tokens), mine, this::signedIn);
}
}
}
}
/** A poll failed: tried again later if it only didn't get through, else the sign-in ends. */
private void pollFailed(Throwable failure) {
Throwable cause = unwrap(failure);
if (cause instanceof SignInException signInFailure
&& signInFailure.temporary()
&& ++pollFailures <= MAX_POLL_FAILURES) {
polling = false;
long wait = Math.min(MAX_RETRY_MILLIS, (intervalSeconds * 1000L) << Math.min(pollFailures, 4));
nextPollMillis = System.currentTimeMillis() + wait;
message = Component.literal("Can't reach Microsoft right now. Still trying...")
.withStyle(ChatFormatting.GRAY);
rebuildWidgets();
return;
}
failed(failure);
}
private static Throwable unwrap(Throwable failure) {
Throwable cause = failure;
while (cause instanceof CompletionException && cause.getCause() != null) {
cause = cause.getCause();
}
return cause;
}
private void signedIn(MicrosoftAccount account) {
MicrosoftAccounts.signedIn(account);
code = null;
message = Component.literal("Signed in.").withStyle(ChatFormatting.GREEN);
show(State.IDLE);
}
private void signOut() {
MicrosoftAccounts.signOut();
message = Component.literal("Signed out. Your saved sign-in was deleted.");
show(State.IDLE);
}
private void cancel() {
attempt++;
code = null;
polling = false;
message = CommonComponents.EMPTY;
show(State.IDLE);
}
/** Runs {@code then} on the game thread once {@code future} succeeds, unless the attempt was abandoned. */
private <T> void whenDone(CompletableFuture<T> future, int mine, Consumer<T> then) {
// Answers arrive on the transport's thread; the screen changes on the game's.
var _ = future.handle((value, failure) -> {
this.minecraft.execute(() -> {
if (mine != attempt) {
return;
}
if (failure != null) {
failed(failure);
} else {
then.accept(value);
}
});
return null;
});
}
private void failed(Throwable failure) {
Throwable cause = unwrap(failure);
String reason = cause instanceof SignInException && cause.getMessage() != null
? cause.getMessage()
: "Sign-in failed. Try again.";
attempt++;
code = null;
polling = false;
pollFailures = 0;
message = Component.literal(reason).withStyle(ChatFormatting.RED);
show(State.IDLE);
}
private void show(State next) {
state = next;
rebuildWidgets();
}
@Override
public void onClose() {
attempt++;
this.minecraft.gui.setScreen(parent);
}
}
@@ -0,0 +1,81 @@
package incari.client.account;
import com.mojang.logging.LogUtils;
import incari.client.profile.PlayerName;
import incari.net.msa.JoinResult;
import incari.net.msa.MicrosoftAccount;
import incari.net.msa.SignInException;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import net.minecraft.network.chat.Component;
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
/**
* Online-mode joins (ADR 0070): when a server asks the client to prove who it is, tell Mojang's
* session server through Incari's sign-in client, so the server finds the player there. Without an
* account, say how to get one instead of the game's bare "invalid session".
*
* <p>Runs on the game's IO pool, where the handshake already waits for the session server; in a
* browser that thread suspends, so the page carries on.
*/
public final class ServerJoins {
private static final Logger LOGGER = LogUtils.getLogger();
/** Renewing the token and joining: a few requests through a proxy at most. */
private static final long TIMEOUT_SECONDS = 60;
private ServerJoins() {}
/**
* Hook ({@code ClientHandshakePacketListenerImpl.authenticateServer}): whether Incari answers
* this join. Not for a launcher's own account (the desktop launched with a real token), which the
* game's session service answers as before.
*/
public static boolean handles() {
return MicrosoftAccounts.account() != null || PlayerName.launchedOffline();
}
/**
* Hook (same): joins the server whose hash is {@code serverHash} as the signed-in account.
*
* @return null when joined, else why not, for the disconnect screen
*/
public static @Nullable Component authenticate(String serverHash) {
if (MicrosoftAccounts.account() == null) {
return failed(Component.literal(
"This server checks Minecraft accounts. Sign in with Microsoft in Edit Profile to join it."));
}
try {
MicrosoftAccount account = MicrosoftAccounts.fresh().get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
JoinResult result =
MicrosoftAccounts.signIn().join(account, serverHash).get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
return switch (result) {
case OK -> null;
case INVALID_SESSION -> failed(Component.translatable("disconnect.loginFailedInfo.invalidSession"));
case INSUFFICIENT_PRIVILEGES ->
failed(Component.translatable("disconnect.loginFailedInfo.insufficientPrivileges"));
case BANNED -> failed(Component.translatable("disconnect.loginFailedInfo.userBanned"));
case UNAVAILABLE -> failed(Component.translatable("disconnect.loginFailedInfo.serversUnavailable"));
};
} catch (ExecutionException | CompletionException e) {
Throwable cause = e.getCause() != null ? e.getCause() : e;
if (cause instanceof SignInException && cause.getMessage() != null) {
return failed(Component.literal(cause.getMessage()));
}
LOGGER.warn("Joining with the Microsoft account failed: {}", cause.toString());
return failed(Component.translatable("disconnect.loginFailedInfo.serversUnavailable"));
} catch (TimeoutException e) {
return failed(Component.literal("Mojang's session server took too long to answer."));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return failed(Component.translatable("disconnect.loginFailedInfo.serversUnavailable"));
}
}
private static Component failed(Component reason) {
return Component.translatable("disconnect.loginFailedInfo", reason);
}
}
@@ -0,0 +1,9 @@
/**
* Microsoft accounts for online-mode servers (ADR 0070): the signed-in account and its file, the
* sign-in screen, the handshake's session join and the chat-signing keys. The protocol work is in
* {@code incari.net.msa}; this package adapts it to the game.
*/
@NullMarked
package incari.client.account;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,68 @@
package incari.client.audio;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import javax.sound.sampled.AudioFormat;
import net.minecraft.client.sounds.AudioStream;
import net.minecraft.client.sounds.JOrbisAudioStream;
import net.minecraft.client.sounds.LoopingAudioStream;
import org.jspecify.annotations.Nullable;
/**
* A whole Ogg Vorbis file, handed to the device to stream (music, records) instead of being
* decoded a second at a time on the game's side. A device that can't stream compressed files still
* gets PCM: the game's own decoder starts on the first {@link #read}.
*/
public final class CompressedSoundStream implements AudioStream {
private final byte[] file;
private final boolean looping;
private @Nullable AudioStream decoder;
public CompressedSoundStream(byte[] file, boolean looping) {
this.file = file;
this.looping = looping;
}
/** The whole file, not a copy (a track of music is megabytes): the caller mustn't change it. */
public byte[] file() {
return file;
}
public boolean looping() {
return looping;
}
@Override
public AudioFormat getFormat() {
try {
return decoder().getFormat();
} catch (IOException e) {
throw new IllegalStateException("Can't read the sound's header", e);
}
}
@Override
public ByteBuffer read(final int expectedSize) throws IOException {
return decoder().read(expectedSize);
}
private AudioStream decoder() throws IOException {
AudioStream current = decoder;
if (current == null) {
ByteArrayInputStream input = new ByteArrayInputStream(file);
current = looping ? new LoopingAudioStream(JOrbisAudioStream::new, input) : new JOrbisAudioStream(input);
decoder = current;
}
return current;
}
@Override
public void close() throws IOException {
AudioStream current = decoder;
if (current != null) {
current.close();
}
}
}
@@ -0,0 +1,68 @@
package incari.client.audio;
import com.mojang.blaze3d.audio.SoundBuffer;
import incari.client.tier.DeviceTier;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import net.minecraft.resources.Identifier;
/**
* How much decoded sound the platform's cache keeps (ADR 0025). The game keeps every sound it
* has decoded until the next resource reload; the browser's are 32-bit float samples at the output
* rate, about 190 kB a second of mono sound, held by the page outside the JavaScript heap but in the
* tab's memory all the same. Past the tier's budget, the sounds played longest ago leave the cache:
* one still playing finishes (its source holds the samples), and the next time it's played it's
* decoded again from the file, which the service worker keeps.
*/
final class DecodedSoundBudget {
/** Decoded sounds by when they were last asked for, oldest first; sizes in bytes. */
private final LinkedHashMap<Identifier, Integer> sizes = new LinkedHashMap<>(64, 0.75f, true);
private long total;
/** The bytes of decoded sound kept at {@code tier}. */
static long budget(DeviceTier tier) {
return switch (tier) {
case POTATO -> 16L << 20;
case STANDARD -> 32L << 20;
case HIGH -> 96L << 20;
};
}
/** {@code location} was asked for again. */
synchronized void used(Identifier location) {
sizes.get(location);
}
/** {@code location} finished decoding into {@code bytes} bytes. */
synchronized void decoded(Identifier location, int bytes) {
Integer previous = sizes.put(location, bytes);
total += bytes - (previous == null ? 0 : previous);
}
/** Bytes of decoded sound counted now. */
synchronized long total() {
return total;
}
/**
* Drops the sounds asked for longest ago from {@code cache} until what's left is within
* {@code budget}, never {@code keep} (the sound being asked for now).
*/
synchronized void trim(Map<Identifier, CompletableFuture<SoundBuffer>> cache, Identifier keep, long budget) {
Iterator<Map.Entry<Identifier, Integer>> oldest = sizes.entrySet().iterator();
while (total > budget && oldest.hasNext()) {
Map.Entry<Identifier, Integer> entry = oldest.next();
if (entry.getKey().equals(keep)) {
continue;
}
oldest.remove();
total -= entry.getValue();
// Gone already if the game cleared its cache (a resource reload).
cache.remove(entry.getKey());
}
}
}
@@ -0,0 +1,167 @@
package incari.client.audio;
import com.mojang.blaze3d.audio.SoundBuffer;
import com.mojang.logging.LogUtils;
import incari.client.tier.DeviceTier;
import incari.platform.api.Platforms;
import incari.platform.api.audio.AudioDecoder;
import incari.platform.api.audio.AudioException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import javax.sound.sampled.AudioFormat;
import net.minecraft.client.sounds.AudioStream;
import net.minecraft.client.sounds.JOrbisAudioStream;
import net.minecraft.resources.Identifier;
import net.minecraft.server.packs.resources.ResourceProvider;
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
/**
* Loads the game's sounds through the platform's own decoder, where it has one (the browser,
* ADR 0013). {@code SoundBufferLibrary} asks here first; null sends it down its own path, the
* game's Java decoder, which is all the desktop ever uses.
*
* <p>Whole sounds are decoded by the platform (natively, off the page's thread) and cached as the
* game caches them, within the tier's budget ({@link DecodedSoundBudget}). Streams (music, records) aren't decoded here at all: the file goes to the
* device, which decodes it as it plays ({@link CompressedSoundStream}). Files the page only has a
* placeholder for are fetched first ({@link RemoteSounds}).
*
* <p>A sound that can't be read (its download failed: a dropped connection, a host refusing a burst
* of requests) is played as a moment of silence and fetched again the next time it's asked for, a
* few seconds later. The game only plays a channel once its buffer arrives and only reclaims a
* channel that has played, so a failed future would leave that sound silent until the next
* resource reload and hold one of its channels for good; enough of them and no new sound plays.
*/
public final class PlatformSoundLoading {
private static final Logger LOGGER = LogUtils.getLogger();
private static final SoundLoader LOADER = new SoundLoader();
static final DecodedSoundBudget BUDGET = new DecodedSoundBudget();
/** How long a sound that couldn't be read stays silent before it's tried again. */
static final long RETRY_MILLIS = 5000;
private PlatformSoundLoading() {}
/**
* The decoded sound at {@code location}, cached in the game's own {@code cache}; null if the
* platform leaves decoding to the game.
*/
public static @Nullable CompletableFuture<SoundBuffer> completeBuffer(
final Map<Identifier, CompletableFuture<SoundBuffer>> cache,
final ResourceProvider resources,
final Identifier location) {
return completeBuffer(Platforms.current().audio().decoder(), cache, resources, location);
}
static @Nullable CompletableFuture<SoundBuffer> completeBuffer(
final @Nullable AudioDecoder decoder,
final Map<Identifier, CompletableFuture<SoundBuffer>> cache,
final ResourceProvider resources,
final Identifier location) {
if (decoder == null) {
return null;
}
CompletableFuture<SoundBuffer> buffer = cache.get(location);
if (buffer != null
&& buffer.getNow(null) instanceof Silence silence
&& System.currentTimeMillis() - silence.failedAt >= RETRY_MILLIS) {
buffer = null;
}
if (buffer == null) {
buffer = CompletableFuture.supplyAsync(() -> decode(decoder, resources, location), LOADER)
.exceptionally(failure -> {
LOGGER.warn("Couldn't load the sound {}; trying again when it next plays", location, failure);
return new Silence(System.currentTimeMillis());
});
cache.put(location, buffer);
var _ = buffer.thenAccept(decoded -> BUDGET.decoded(location, decoded.size()));
} else {
BUDGET.used(location);
}
BUDGET.trim(cache, location, DecodedSoundBudget.budget(DeviceTier.current()));
return buffer;
}
/**
* What a sound that couldn't be read plays instead: a hundredth of a second of silence, so its
* channel plays, finishes and goes back to the pool.
*/
static final class Silence extends SoundBuffer {
private static final int FRAMES = 480;
final long failedAt;
Silence(long failedAt) {
super(
ByteBuffer.allocate(FRAMES * 2),
new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 48000, 16, 1, 2, 48000, false));
this.failedAt = failedAt;
}
}
/**
* The file at {@code location} as a stream the device plays compressed; null if the platform
* leaves decoding to the game.
*/
public static @Nullable CompletableFuture<AudioStream> stream(
final ResourceProvider resources, final Identifier location, final boolean looping) {
return stream(Platforms.current().audio().decoder(), resources, location, looping);
}
static @Nullable CompletableFuture<AudioStream> stream(
final @Nullable AudioDecoder decoder,
final ResourceProvider resources,
final Identifier location,
final boolean looping) {
if (decoder == null) {
return null;
}
return CompletableFuture.supplyAsync(
() -> new CompressedSoundStream(read(resources, location), looping), LOADER);
}
private static SoundBuffer decode(
final AudioDecoder decoder, final ResourceProvider resources, final Identifier location) {
byte[] file = read(resources, location);
try {
return new SoundBuffer(decoder.decodeOggVorbis(file));
} catch (AudioException e) {
// A browser without Ogg Vorbis (older Safari): the game's decoder still can.
LOGGER.warn("The platform couldn't decode {} ({}); decoding it in Java", location, e.getMessage());
}
try (JOrbisAudioStream stream = new JOrbisAudioStream(new ByteArrayInputStream(file))) {
ByteBuffer samples = stream.readAll();
return new SoundBuffer(samples, stream.getFormat());
} catch (IOException e) {
throw new UncheckedIOException("Couldn't decode " + location, e);
}
}
/** The file's bytes, fetched first if the page has only a placeholder for it. */
private static byte[] read(final ResourceProvider resources, final Identifier location) {
try {
byte[] file;
try (InputStream in = resources.open(location)) {
file = in.readAllBytes();
}
if (file.length == 0) {
byte[] fetched = RemoteSounds.fetch(location.getNamespace() + "/" + location.getPath());
if (fetched != null) {
return fetched;
}
}
return file;
} catch (IOException e) {
throw new UncheckedIOException("Couldn't read " + location, e);
}
}
}
@@ -0,0 +1,41 @@
package incari.client.audio;
import java.io.IOException;
import org.jspecify.annotations.Nullable;
/**
* Where sound files come from when the page has only a placeholder for them. The browser build
* lists every sound of the asset index in its file system without downloading them (they're
* hundreds of megabytes); a placeholder is an empty file, and its contents are fetched the first
* time the sound plays. The entry point installs the source; the desktop has the real files and
* installs none.
*/
public final class RemoteSounds {
/** Fetches an asset's contents by its name in the asset index. */
@FunctionalInterface
public interface Source {
/**
* The contents of {@code assetName} (like {@code minecraft/sounds/random/click.ogg}), or null
* if it isn't an asset this source has. Waits for the download: only the sound loader's
* threads call it.
*/
byte @Nullable [] fetch(String assetName) throws IOException;
}
private static volatile @Nullable Source source;
private RemoteSounds() {}
/** Installs the source; null removes it. */
public static void install(@Nullable Source remote) {
source = remote;
}
/** The asset's contents from the installed source, or null if there's none or it doesn't have it. */
static byte @Nullable [] fetch(String assetName) throws IOException {
Source current = source;
return current == null ? null : current.fetch(assetName);
}
}
@@ -0,0 +1,54 @@
package incari.client.audio;
import java.util.ArrayDeque;
import java.util.concurrent.Executor;
/**
* A few threads of its own that read and decode sounds for the platform's decoder. They aren't
* the game's I/O pool because in the browser that pool runs tasks inline on the game's thread (the
* platform reports no background threads), and decoding waits for the browser: a wait there
* would stall the frame. Here it suspends only this thread's coroutine.
*/
final class SoundLoader implements Executor {
/** Enough that a long file (a track of music) being fetched doesn't hold up short ones. */
private static final int THREADS = 3;
private final ArrayDeque<Runnable> tasks = new ArrayDeque<>();
private boolean started;
@Override
public void execute(Runnable task) {
synchronized (tasks) {
if (!started) {
started = true;
for (int i = 0; i < THREADS; i++) {
Thread thread = new Thread(this::run, "Sound loader " + (i + 1));
thread.setDaemon(true);
thread.start();
}
}
tasks.addLast(task);
tasks.notifyAll();
}
}
private void run() {
while (true) {
Runnable task;
synchronized (tasks) {
while (tasks.isEmpty()) {
try {
tasks.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
task = tasks.removeFirst();
}
// Tasks complete their own futures, failures included (CompletableFuture.supplyAsync).
task.run();
}
}
}
@@ -0,0 +1,5 @@
/** Loading the game's sounds through the platform's decoder and streams (ADR 0013). */
@NullMarked
package incari.client.audio;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,142 @@
package incari.client.cosmetics;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.function.Predicate;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.FontDescription;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.Style;
import net.minecraft.resources.Identifier;
/**
* Incari's badge beside an Incari player's name tag, their name in the tab list and their name in chat (ADR 0062), so
* Incari players know each other without asking. The badge is one glyph of Incari's pack's {@code incari:badge} font (Incari's
* mark at 32 pixels, white so the glyph keeps its own colours), so the game's own name tag and tab list drawing carry it:
* nothing new is drawn. Shown for players whose account lets it show, while the player's
* "Show Incari badges" switch is on.
*
* <p>Render thread. A badged name is made once per player and name, not each frame; name tags and
* the tab list keep their own, as the two names differ.
*/
final class Badges {
private static final Component BADGE = Component.literal("")
.withStyle(Style.EMPTY
.withFont(new FontDescription.Resource(Identifier.fromNamespaceAndPath("incari", "badge")))
.withColor(0xFFFFFF));
private record Badged(Component from, Component to) {}
private static final Map<UUID, Badged> NAME_TAGS = new HashMap<>();
private static final Map<UUID, Badged> TAB_LIST = new HashMap<>();
private Badges() {}
/** The name tag {@code tag} with the badge before it, for the player {@code id}. */
static Component badged(UUID id, Component tag) {
return badged(NAME_TAGS, id, tag);
}
/** The tab list's {@code name} with the badge before it, for the player {@code id}. */
static Component badgedInTabList(UUID id, Component name) {
return badged(TAB_LIST, id, name);
}
/**
* Chat's {@code message} with the badge before the first mention of each name {@code badged}
* takes, or {@code message} when it names none. Names are runs of name characters in the
* message's text; legacy {@code §} codes (1.8 servers' chat) are skipped over and carried past
* the badge, so a coloured name keeps its colour. Once per chat line, not per frame.
*/
static Component badgedInChat(Component message, Predicate<String> badged) {
String text = message.getString();
List<Integer> at = new ArrayList<>();
Set<String> seen = new HashSet<>();
int n = text.length();
for (int i = 0; i < n; ) {
char c = text.charAt(i);
if (c == '§') {
i += 2;
} else if (!isNameChar(c)) {
i++;
} else {
int start = i;
while (i < n && isNameChar(text.charAt(i))) {
i++;
}
String name = text.substring(start, i);
if (i - start <= 16 && seen.add(name) && badged.test(name)) {
at.add(start);
}
}
}
if (at.isEmpty()) {
return message;
}
// The message rebuilt piece by piece in the same styles, each piece cut where a badge goes.
MutableComponent out = Component.empty();
int[] offset = {0};
int[] next = {0};
message.visit(
(style, piece) -> {
int end = offset[0] + piece.length();
int from = 0;
String carried = "";
while (next[0] < at.size() && at.get(next[0]) < end) {
int cut = at.get(next[0]++) - offset[0];
String before = piece.substring(from, cut);
if (!before.isEmpty()) {
out.append(Component.literal(carried + before).setStyle(style));
}
carried += legacyCodes(before);
out.append(BADGE).append(" ");
from = cut;
}
out.append(
Component.literal(carried + piece.substring(from)).setStyle(style));
offset[0] = end;
return Optional.empty();
},
Style.EMPTY);
return out;
}
private static boolean isNameChar(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';
}
/** The {@code §} codes in {@code text}, in order: what a later cut of the same text must repeat. */
private static String legacyCodes(String text) {
StringBuilder codes = new StringBuilder();
for (int i = text.indexOf('§'); i >= 0 && i + 1 < text.length(); i = text.indexOf('§', i + 2)) {
codes.append(text, i, i + 2);
}
return codes.toString();
}
private static Component badged(Map<UUID, Badged> made, UUID id, Component name) {
Badged last = made.get(id);
if (last != null && last.from().equals(name)) {
return last.to();
}
MutableComponent badged = Component.empty().append(BADGE).append(" ").append(name);
if (made.size() > 512) {
made.clear();
}
made.put(id, new Badged(name, badged));
return badged;
}
/** Players who left, forgotten (on leaving a world). */
static void clear() {
NAME_TAGS.clear();
TAB_LIST.clear();
}
}
@@ -0,0 +1,480 @@
package incari.client.cosmetics;
/**
* The cosmetics' pictures, painted in code (ADR 0061): Incari's own art, so nothing is shipped as
* an image and nothing is Mojang's. Capes are painted into the game's 64x32 cape layout (the outer
* side, the inner side, the edges and an elytra), some again and again as time passes; the cards in
* the wardrobe get small icons. Pixels are ARGB.
*
* <p>Any thread: pure functions of their arguments.
*/
final class CosmeticArt {
static final int CAPE_WIDTH = 64;
static final int CAPE_HEIGHT = 32;
/** A wardrobe card's icon, square. */
static final int ICON = 24;
private CosmeticArt() {}
/** Whether the cape {@code id} moves: it's painted again as time passes. */
static boolean animated(String id) {
return switch (id) {
case "cape.aurora", "cape.midnight", "cape.ember", "cape.tide" -> true;
default -> false;
};
}
// ---------------------------------------------------------------------------------------------
// Capes
// ---------------------------------------------------------------------------------------------
/**
* Paints the cape {@code id} at time {@code t} (seconds) into {@code out}, 64x32: the outer side
* at (1, 1), 10x16, as the game's cape model reads it; the inner side darker; the edges; and the
* elytra's wing at (22, 0), so an elytra worn with it matches.
*/
static void cape(String id, float t, int[] out) {
java.util.Arrays.fill(out, 0);
for (int py = 0; py < 16; py++) {
for (int px = 0; px < 10; px++) {
int color = design(id, px + 0.5F, py + 0.5F, t);
out[(py + 1) * CAPE_WIDTH + px + 1] = color;
// The inner side faces the player: the same, mirrored and in shade.
out[(py + 1) * CAPE_WIDTH + 12 + (9 - px)] = shade(color, 0.55F);
}
}
int edge = shade(design(id, 5, 8, t), 0.7F);
for (int py = 1; py <= 16; py++) {
out[py * CAPE_WIDTH] = edge;
out[py * CAPE_WIDTH + 11] = edge;
}
for (int px = 1; px <= 20; px++) {
out[px] = edge;
}
for (int y = 0; y < 22; y++) {
for (int x = 22; x < 46; x++) {
out[y * CAPE_WIDTH + x] = design(id, (x - 22 + 0.5F) * 10 / 24.0F, (y + 0.5F) * 16 / 22.0F, t);
}
}
}
/** One cape's picture at (px, py) in its 10x16 face, at time {@code t}: opaque. */
private static int design(String id, float px, float py, float t) {
float v = py / 16;
return 0xFF000000
| switch (id) {
case "cape.frost" -> frost(px, py, v);
case "cape.aurora" -> aurora(px, py, v, t);
case "cape.midnight" -> midnight(px, py, v, t);
case "cape.ember" -> ember(px, py, v, t);
case "cape.sakura" -> sakura(px, py, v);
case "cape.tide" -> tide(px, py, v, t);
case "cape.mono" -> mono(px, py);
default -> 0x808080;
};
}
private static int frost(float px, float py, float v) {
int color = mix(0x9FD3F5, 0x1E3F66, v);
if (px < 1 || px > 9 || py < 1 || py > 15) {
color = mix(color, 0xFFFFFF, 0.35F);
}
// A snowflake in the middle: three strokes and a branch at each arm's end.
float dx = px - 5;
float dy = py - 6.5F;
boolean flake = (Math.abs(dx) < 0.6F && Math.abs(dy) < 3.4F)
|| (Math.abs(dy) < 0.6F && Math.abs(dx) < 3.4F)
|| (Math.abs(dx - dy) < 0.75F && Math.abs(dx) < 2.4F)
|| (Math.abs(dx + dy) < 0.75F && Math.abs(dx) < 2.4F);
if (flake) {
return 0xF4FBFF;
}
// Frost glinting further down.
if (py > 11 && hash((int) px, (int) py, 3) < 0.12F) {
return mix(color, 0xFFFFFF, 0.6F);
}
return color;
}
private static int aurora(float px, float py, float v, float t) {
int color = mix(0x0E1B33, 0x050A15, v);
int[] bands = {0x3CF2A0, 0x3CC8F2, 0xA05CF2};
for (int k = 0; k < bands.length; k++) {
float centre = 3.5F + k * 4.2F + 1.6F * (float) Math.sin(px * 0.7F + t * 1.3F + k * 2.1F);
float d = (py - centre) / 1.7F;
float glow = (float) Math.exp(-d * d) * (0.65F + 0.35F * (float) Math.sin(t * 0.9F + px * 0.5F + k));
color = add(color, bands[k], glow * 0.85F);
}
if (hash((int) px, (int) py, 11) < 0.05F) {
color = mix(color, 0xFFFFFF, 0.5F + 0.5F * (float) Math.sin(t * 4 + px));
}
return color;
}
private static int midnight(float px, float py, float v, float t) {
int color = mix(0x1F2A5C, 0x05081A, v);
// A crescent moon in the top right.
float mx = px - 7;
float my = py - 3.2F;
float ox = px - 7.9F;
float oy = py - 2.5F;
if (mx * mx + my * my < 4.4F && ox * ox + oy * oy > 3.0F) {
return 0xF2EFD0;
}
float star = hash((int) px, (int) py, 7);
if (star < 0.1F) {
float phase = hash((int) px, (int) py, 13) * 6.283F;
float twinkle = 0.5F + 0.5F * (float) Math.sin(t * 2.6F + phase);
return mix(color, 0xFFFFFF, 0.35F + 0.65F * twinkle);
}
return color;
}
private static int ember(float px, float py, float v, float t) {
float flame = noise(px * 0.55F, py * 0.45F + t * 2.2F);
float heat = clamp(v * 1.25F + (flame - 0.5F) * 0.9F - 0.2F);
int color;
if (heat < 0.33F) {
color = mix(0x140806, 0x7A1708, heat / 0.33F);
} else if (heat < 0.66F) {
color = mix(0x7A1708, 0xE5481A, (heat - 0.33F) / 0.33F);
} else {
color = mix(0xE5481A, 0xFFC94A, (heat - 0.66F) / 0.34F);
}
// Sparks rising.
int cell = (int) Math.floor(py + t * 5);
if (hash((int) px, cell, 5) < 0.045F) {
return 0xFFE38A;
}
return color;
}
private static int sakura(float px, float py, float v) {
int color = mix(0xFCDCE8, 0xE597B6, v);
// A branch across, from the bottom left to the top right.
float branch = Math.abs((py - 12.5F) + (px * 0.8F)) / 1.28F;
if (branch < 0.55F && px < 9.5F) {
color = 0x5E3B3B;
}
float[][] blossoms = {{2, 10.5F}, {5, 8}, {8, 5.5F}, {3, 4}, {7.5F, 12.5F}, {1.5F, 1.8F}};
for (float[] b : blossoms) {
float dx = px - b[0];
float dy = py - b[1];
float d = dx * dx + dy * dy;
if (d < 0.5F) {
return 0xFFE9A8;
}
if (d < 2.1F) {
return 0xF4F0F2;
}
}
return color;
}
private static int tide(float px, float py, float v, float t) {
int color = mix(0x3D9FE0, 0x0A2552, v);
for (int k = 0; k < 5; k++) {
float crest = 2.5F + k * 3 + 0.9F * (float) Math.sin(px * 0.9F + t * 2.0F + k * 1.7F);
if (Math.abs(py - crest) < 0.55F) {
return mix(color, 0xD8F1FF, 0.75F);
}
}
if (hash((int) px, (int) Math.floor(py + t), 9) < 0.04F) {
return mix(color, 0xFFFFFF, 0.5F);
}
return color;
}
private static int mono(float px, float py) {
if (px < 1 || px > 9 || py < 1 || py > 15 || (px > 4 && px < 6)) {
return 0xEDEDED;
}
return 0x151515;
}
// ---------------------------------------------------------------------------------------------
// Wings
// ---------------------------------------------------------------------------------------------
/**
* A wing at (sx, sy) on its panel: sx from the root (0) to the tip (1), sy from the top (0) to
* the bottom (1). Transparent outside the wing.
*/
static int wing(String id, float sx, float sy) {
return switch (id) {
case "back.bat_wings" -> batWing(sx, sy);
case "back.frost_wings" -> frostWing(sx, sy);
default -> angelWing(sx, sy);
};
}
private static float wingTop(float sx) {
return 0.34F - 0.3F * (float) Math.sin(sx * Math.PI * 0.5);
}
private static float featherBottom(float sx) {
float scallop = 0.06F * (float) Math.abs(Math.sin(sx * Math.PI * 5));
return 0.97F - 0.62F * (float) Math.pow(sx, 1.15) - scallop;
}
private static int angelWing(float sx, float sy) {
float top = wingTop(sx);
float bottom = featherBottom(sx);
if (sy < top || sy > bottom) {
return 0;
}
int color = mix(0xFFFFFF, 0xDCE3EC, clamp((sy - top) / Math.max(0.05F, bottom - top)) * 0.6F);
// Rows of feathers: lines across, and their tips toward the bottom.
float row = (sy - top) / Math.max(0.05F, bottom - top) * 4;
if (row - (float) Math.floor(row) < 0.12F && row > 0.8F) {
color = 0xC9D3E0;
}
if (sx < 0.12F) {
color = mix(color, 0xB8C3D2, 0.5F);
}
return 0xFF000000 | color;
}
private static int frostWing(float sx, float sy) {
float top = wingTop(sx);
float bottom = featherBottom(sx);
if (sy < top || sy > bottom) {
return 0;
}
float facet = sx * 4 + sy * 2.5F;
boolean edge = facet - (float) Math.floor(facet) < 0.09F || sy - top < 0.03F || bottom - sy < 0.03F;
if (edge) {
return 0xF0F4FBFF;
}
int color = mix(0xCDEBFF, 0x7FB8E8, clamp(sy));
return 0xA8000000 | color;
}
private static int batWing(float sx, float sy) {
// The arm along the top, the fingers fanning down from the wrist, the skin scalloped
// between them.
float top = 0.12F + 0.12F * sx;
float fingers = sx * 3;
float between = fingers - (float) Math.floor(fingers);
float bottom = 0.9F - 0.5F * sx - 0.22F * (float) Math.sin(between * Math.PI);
if (sy < top || sy > bottom) {
return 0;
}
if (sy - top < 0.07F) {
return 0xFF3A2A40;
}
for (int finger = 1; finger <= 3; finger++) {
float endX = finger / 3.0F;
float endY = 0.9F - 0.5F * endX;
float along = sx / endX;
if (along <= 1 && Math.abs(sy - (top + (endY - top) * along)) < 0.035F) {
return 0xFF22182A;
}
}
return 0xFF000000 | mix(0x62486E, 0x3E2D47, clamp(sy));
}
// ---------------------------------------------------------------------------------------------
// Icons
// ---------------------------------------------------------------------------------------------
/** The wardrobe card's icon for a hat or a back cosmetic, {@link #ICON} square, into {@code out}. */
static void icon(String id, int[] out) {
java.util.Arrays.fill(out, 0);
for (int y = 0; y < ICON; y++) {
for (int x = 0; x < ICON; x++) {
out[y * ICON + x] = iconPixel(id, x + 0.5F, y + 0.5F);
}
}
}
private static int iconPixel(String id, float x, float y) {
return switch (id) {
case "hat.crown" -> crownIcon(x, y);
case "hat.halo" -> haloIcon(x, y);
case "hat.top_hat" -> topHatIcon(x, y);
case "hat.beanie" -> beanieIcon(x, y);
case "hat.horns" -> hornsIcon(x, y);
case "hat.cat_ears" -> earsIcon(x, y);
case "back.backpack" -> backpackIcon(x, y);
case "back.angel_wings", "back.frost_wings", "back.bat_wings" -> wingsIcon(id, x, y);
default -> 0;
};
}
private static int crownIcon(float x, float y) {
boolean band = y >= 13 && y < 19 && x >= 4 && x < 20;
boolean points = false;
for (float peak : new float[] {5, 12, 19}) {
float dx = Math.abs(x - peak);
if (y < 13 && y >= 6 + dx * 2.2F && dx < 3) {
points = true;
}
}
if (Math.abs(x - 12) < 1.6F && Math.abs(y - 16) < 1.6F) {
return 0xFFE0344B;
}
if (band || points) {
return 0xFF000000 | mix(0xFFE58A, 0xD69A1E, (y - 6) / 13);
}
return 0;
}
private static int haloIcon(float x, float y) {
float dx = (x - 12) / 9;
float dy = (y - 12) / 4;
float d = dx * dx + dy * dy;
if (d < 1 && d > 0.45F) {
return 0xFFFFF0B0;
}
if (d < 1.4F && d > 0.3F) {
return 0x60FFE68A;
}
return 0;
}
private static int topHatIcon(float x, float y) {
if (y >= 17 && y < 19 && x >= 2 && x < 22) {
return 0xFF1C1C22;
}
if (y >= 4 && y < 17 && x >= 6 && x < 18) {
return y >= 13 ? 0xFFC0263A : 0xFF26262E;
}
return 0;
}
private static int beanieIcon(float x, float y) {
float dx = (x - 12) / 9;
float dy = (y - 17) / 11;
if (y < 17 && dx * dx + dy * dy < 1) {
int row = (int) (y / 2.5F);
return (row & 1) == 0 ? 0xFF7FC3F2 : 0xFFEAF6FF;
}
if (y >= 17 && y < 20 && x >= 3 && x < 21) {
return 0xFF4F8FC7;
}
float px = x - 12;
float py = y - 5;
if (px * px + py * py < 6) {
return 0xFFFFFFFF;
}
return 0;
}
private static int hornsIcon(float x, float y) {
for (int side = -1; side <= 1; side += 2) {
float baseX = 12 + side * 5;
float t = (20 - y) / 15;
if (t < 0 || t > 1) {
continue;
}
float centre = baseX + side * 5 * t * t;
float half = 2.6F * (1 - t) + 0.4F;
if (Math.abs(x - centre) < half) {
return 0xFF000000 | mix(0xF2E6CC, 0x9C8A6A, t);
}
}
return 0;
}
private static int earsIcon(float x, float y) {
for (int side = -1; side <= 1; side += 2) {
float cx = 12 + side * 6;
float t = (19 - y) / 13;
if (t < 0 || t > 1) {
continue;
}
float half = 4.5F * (1 - t);
float d = Math.abs(x - cx);
if (d < half) {
if (d < half - 1.6F && t < 0.7F) {
return 0xFFF2A6BC;
}
// A light rim, so dark ears read on a dark card.
return d > half - 0.8F || t > 0.92F ? 0xFF9A9AAE : 0xFF4A4A58;
}
}
return 0;
}
private static int backpackIcon(float x, float y) {
if (x >= 6 && x < 18 && y >= 4 && y < 21) {
if (y < 9) {
return 0xFF7FC3F2;
}
if (x >= 8 && x < 16 && y >= 12 && y < 18) {
return (x < 8.8F || x > 15.2F || y < 12.8F || y > 17.2F) ? 0xFFA9DCFF : 0xFF2C4A72;
}
return 0xFF22385A;
}
return 0;
}
private static int wingsIcon(String id, float x, float y) {
// Both wings, spread from the middle.
float sx = Math.abs(x - 12) / 11;
float sy = (y - 2) / 20;
if (Math.abs(x - 12) < 1 || sy < 0 || sy > 1 || sx > 1) {
return 0;
}
int color = wing(id, sx, sy);
return (color >>> 24) == 0 ? 0 : 0xFF000000 | color;
}
// ---------------------------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------------------------
/** A colour between {@code a} and {@code b} (RGB), {@code t} of the way. */
static int mix(int a, int b, float t) {
float k = clamp(t);
int r = Math.round(((a >> 16) & 255) + (((b >> 16) & 255) - ((a >> 16) & 255)) * k);
int g = Math.round(((a >> 8) & 255) + (((b >> 8) & 255) - ((a >> 8) & 255)) * k);
int bl = Math.round((a & 255) + ((b & 255) - (a & 255)) * k);
return r << 16 | g << 8 | bl;
}
private static int add(int base, int light, float amount) {
int r = Math.min(255, ((base >> 16) & 255) + Math.round(((light >> 16) & 255) * amount));
int g = Math.min(255, ((base >> 8) & 255) + Math.round(((light >> 8) & 255) * amount));
int b = Math.min(255, (base & 255) + Math.round((light & 255) * amount));
return r << 16 | g << 8 | b;
}
/** {@code argb} darker by {@code factor}, alpha kept. */
static int shade(int argb, float factor) {
int r = Math.round(((argb >> 16) & 255) * factor);
int g = Math.round(((argb >> 8) & 255) * factor);
int b = Math.round((argb & 255) * factor);
return (argb & 0xFF000000) | r << 16 | g << 8 | b;
}
static float clamp(float value) {
return Math.max(0, Math.min(1, value));
}
/** A number in [0, 1) for a cell: the same for the same cell and salt. */
static float hash(int x, int y, int salt) {
int h = x * 374761393 + y * 668265263 + salt * 1274126177;
h = (h ^ (h >>> 13)) * 1274126177;
h ^= h >>> 16;
return (h & 0xFFFFFF) / (float) 0x1000000;
}
/** Smooth value noise in [0, 1). */
private static float noise(float x, float y) {
int ix = (int) Math.floor(x);
int iy = (int) Math.floor(y);
float fx = x - ix;
float fy = y - iy;
float sx = fx * fx * (3 - 2 * fx);
float sy = fy * fy * (3 - 2 * fy);
float a = hash(ix, iy, 1);
float b = hash(ix + 1, iy, 1);
float c = hash(ix, iy + 1, 1);
float d = hash(ix + 1, iy + 1, 1);
return a + (b - a) * sx + (c - a) * sy + (a - b - c + d) * sx * sy;
}
}
@@ -0,0 +1,382 @@
package incari.client.cosmetics;
import com.mojang.blaze3d.platform.NativeImage;
import incari.online.Cosmetic;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.minecraft.client.Minecraft;
import net.minecraft.client.model.Model;
import net.minecraft.client.model.geom.ModelPart;
import net.minecraft.client.model.geom.PartPose;
import net.minecraft.client.model.geom.builders.CubeDeformation;
import net.minecraft.client.model.geom.builders.CubeListBuilder;
import net.minecraft.client.model.geom.builders.LayerDefinition;
import net.minecraft.client.model.geom.builders.MeshDefinition;
import net.minecraft.client.model.geom.builders.PartDefinition;
import net.minecraft.client.renderer.entity.state.AvatarRenderState;
import net.minecraft.client.renderer.rendertype.RenderType;
import net.minecraft.client.renderer.rendertype.RenderTypes;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.core.Direction;
import net.minecraft.resources.Identifier;
import org.jspecify.annotations.Nullable;
/**
* The hats and back cosmetics as models (ADR 0061): each a few boxes, described here, baked once,
* with a texture painted from the same description, so the boxes and their pictures never disagree.
* Coordinates are the player model's: a hat's from the head's pivot (the head's box is -4..4 across,
* -8..0 up), a back cosmetic's from the body's (the body's back is at z = 2).
*
* <p>Render thread. A model and its texture are made the first time something wears it.
*/
final class CosmeticModels {
/** Where a cosmetic sits on the player. */
enum Anchor {
HEAD,
BODY
}
/** How a cosmetic is drawn. */
enum Look {
/** Opaque, with see-through pixels cut out. */
CUTOUT,
/** Partly see-through. */
TRANSLUCENT,
/** Glowing: lit by itself, at full brightness. */
GLOW
}
/** What a box is painted with. */
enum Material {
GOLD,
GOLD_GEM,
VELVET,
HALO,
FELT,
FELT_BAND,
KNIT,
POM,
BONE,
EAR,
PACK,
POCKET,
WING
}
/** A box: where, how big, how much bigger than that, and what it's painted with. */
private record Box(float x, float y, float z, int w, int h, int d, float grow, Material material, boolean mirror) {}
/** A part: where it turns about, how it's turned, and its boxes. */
private record Part(String name, PartPose pose, List<Box> boxes) {}
/** A cosmetic's model as described. */
private record Spec(Anchor anchor, Look look, List<Part> parts) {}
private static final int TEXTURE = 64;
/** Each cosmetic's model, made the first time it's drawn: null for one that isn't a model. */
private static final Map<String, @Nullable Made> MADE = new HashMap<>();
/** A model ready to draw, with its texture and where it sits. */
record Made(CosmeticModel model, Identifier texture, Anchor anchor, Look look) {}
private CosmeticModels() {}
/** The model for {@code cosmetic}, made now if it's the first time; null if it isn't one. */
static @Nullable Made of(Cosmetic cosmetic) {
if (MADE.containsKey(cosmetic.id())) {
return MADE.get(cosmetic.id());
}
Spec spec = spec(cosmetic.id());
Made made = spec == null ? null : make(cosmetic.id(), spec);
MADE.put(cosmetic.id(), made);
return made;
}
// ---------------------------------------------------------------------------------------------
// The descriptions
// ---------------------------------------------------------------------------------------------
private static @Nullable Spec spec(String id) {
return switch (id) {
case "hat.crown" -> {
List<Box> boxes = new ArrayList<>();
// A band round the top of the head, outside the skin's hat layer, its top velvet.
boxes.add(box(-4, -10, -4, 8, 2, 8, 0.6F, Material.GOLD_GEM));
for (float[] at : new float[][] {
{-4.6F, -4.6F},
{3.6F, -4.6F},
{-4.6F, 3.6F},
{3.6F, 3.6F},
{-0.5F, -4.6F},
{-0.5F, 3.6F},
{-4.6F, -0.5F},
{3.6F, -0.5F}
}) {
boxes.add(box(at[0], -12.6F, at[1], 1, 2, 1, 0.05F, Material.GOLD));
}
yield new Spec(Anchor.HEAD, Look.CUTOUT, List.of(new Part("crown", PartPose.ZERO, boxes)));
}
case "hat.halo" ->
new Spec(
Anchor.HEAD,
Look.GLOW,
List.of(new Part(
"ring",
PartPose.offset(0, -12.5F, 0),
List.of(
box(-3, -0.5F, -3.5F, 6, 1, 1, 0, Material.HALO),
box(-3, -0.5F, 2.5F, 6, 1, 1, 0, Material.HALO),
box(-3.5F, -0.5F, -3, 1, 1, 6, 0, Material.HALO),
box(2.5F, -0.5F, -3, 1, 1, 6, 0, Material.HALO)))));
case "hat.top_hat" ->
new Spec(
Anchor.HEAD,
Look.CUTOUT,
List.of(new Part(
"hat",
PartPose.ZERO,
List.of(
box(-5, -9, -5, 10, 1, 10, 0.1F, Material.FELT),
box(-4, -15, -4, 8, 6, 8, -0.5F, Material.FELT_BAND)))));
case "hat.beanie" ->
new Spec(
Anchor.HEAD,
Look.CUTOUT,
List.of(new Part(
"beanie",
PartPose.ZERO,
List.of(
box(-4, -9, -4, 8, 3, 8, 0.7F, Material.KNIT),
box(-1, -12, -1, 2, 2, 2, 0.3F, Material.POM)))));
case "hat.horns" -> new Spec(Anchor.HEAD, Look.CUTOUT, List.of(horn("left", 1), horn("right", -1)));
case "hat.cat_ears" -> new Spec(Anchor.HEAD, Look.CUTOUT, List.of(ear("left", 1), ear("right", -1)));
case "back.angel_wings", "back.bat_wings" -> wings(Look.CUTOUT);
case "back.frost_wings" -> wings(Look.TRANSLUCENT);
case "back.backpack" ->
new Spec(
Anchor.BODY,
Look.CUTOUT,
List.of(new Part(
"pack",
PartPose.ZERO,
List.of(
box(-4, 1, 2, 8, 10, 4, 0, Material.PACK),
box(-3, 5, 6, 6, 4, 1, 0, Material.POCKET)))));
default -> null;
};
}
private static Box box(float x, float y, float z, int w, int h, int d, float grow, Material material) {
return new Box(x, y, z, w, h, d, grow, material, false);
}
private static Part horn(String name, int side) {
return new Part(
name,
PartPose.offsetAndRotation(side * 2.5F, -8, -1, -0.2F, 0, side * 0.45F),
List.of(
box(-1, -3, -1, 2, 3, 2, 0, Material.BONE),
box(-0.5F + side * 0.4F, -5.5F, -0.5F, 1, 3, 1, 0, Material.BONE)));
}
private static Part ear(String name, int side) {
return new Part(
name,
PartPose.offsetAndRotation(side * 2.6F, -8.2F, -0.5F, 0, 0, side * 0.28F),
List.of(
box(-1.5F, -3, -0.5F, 3, 3, 1, 0, Material.EAR),
box(-0.5F, -4, -0.5F, 1, 1, 1, 0, Material.EAR)));
}
/** How far back the wings are swept at rest, in radians. */
private static final float WING_SWEEP = 0.28F;
/** Two wings, panels with nothing but a front and a back, from the shoulder blades. */
private static Spec wings(Look look) {
// From the shoulder blades, out past the shoulders and up past them, swept back a little:
// turning the left wing (+x) by a negative yRot takes its tip back (+z), away from the arms.
Part left = new Part(
"left_wing",
PartPose.offsetAndRotation(1, 3, 2.4F, 0, -WING_SWEEP, -0.12F),
List.of(new Box(0, -9, 0, 16, 16, 0, 0, Material.WING, false)));
Part right = new Part(
"right_wing",
PartPose.offsetAndRotation(-1, 3, 2.4F, 0, WING_SWEEP, 0.12F),
List.of(new Box(-16, -9, 0, 16, 16, 0, 0, Material.WING, true)));
return new Spec(Anchor.BODY, look, List.of(left, right));
}
// ---------------------------------------------------------------------------------------------
// Baking and painting
// ---------------------------------------------------------------------------------------------
private static Made make(String id, Spec spec) {
MeshDefinition mesh = new MeshDefinition();
PartDefinition root = mesh.getRoot();
NativeImage image = new NativeImage(TEXTURE, TEXTURE, true);
int shelfX = 0;
int shelfY = 0;
int shelfHeight = 0;
for (Part part : spec.parts()) {
CubeListBuilder cubes = CubeListBuilder.create();
for (Box box : part.boxes()) {
int width = 2 * box.d() + 2 * box.w();
int height = box.d() + box.h();
if (shelfX + width > TEXTURE) {
shelfX = 0;
shelfY += shelfHeight;
shelfHeight = 0;
}
int u = shelfX;
int v = shelfY;
shelfX += width;
shelfHeight = Math.max(shelfHeight, height);
cubes.texOffs(u, v).mirror(box.mirror());
if (box.d() == 0) {
Set<Direction> sides = EnumSet.of(Direction.NORTH, Direction.SOUTH);
cubes.addBox(box.x(), box.y(), box.z(), box.w(), box.h(), box.d(), sides);
} else {
cubes.addBox(box.x(), box.y(), box.z(), box.w(), box.h(), box.d(), new CubeDeformation(box.grow()));
}
paint(image, id, box, u, v);
}
root.addOrReplaceChild(part.name(), cubes, part.pose());
}
ModelPart baked = LayerDefinition.create(mesh, TEXTURE, TEXTURE).bakeRoot();
Identifier texture = Identifier.fromNamespaceAndPath("incari", "cosmetics/" + id.replace('.', '/'));
Minecraft.getInstance().getTextureManager().register(texture, new DynamicTexture(texture::toString, image));
CosmeticModel model = new CosmeticModel(baked, renderType(spec.look()), id);
return new Made(model, texture, spec.anchor(), spec.look());
}
private static java.util.function.Function<Identifier, RenderType> renderType(Look look) {
// Culled: a wing is a panel whose front and back lie in one plane, and drawn both ways they
// fight for the same depth (and, translucent, swap as their sort changes with the camera).
return switch (look) {
case CUTOUT -> RenderTypes::entityCutoutCull;
case TRANSLUCENT -> RenderTypes::entityTranslucentCull;
case GLOW -> RenderTypes::eyes;
};
}
/** Paints a box's six faces where the game's box mapping reads them. */
private static void paint(NativeImage image, String id, Box box, int u, int v) {
int w = box.w();
int h = box.h();
int d = box.d();
// The game's layout of a box's faces, from (u, v): down and up along the top, then west,
// north (the front), east and south (the back) side by side.
face(image, id, box, 0, u + d, v, w, d);
face(image, id, box, 1, u + d + w, v, w, d);
face(image, id, box, 2, u, v + d, d, h);
face(image, id, box, 3, u + d, v + d, w, h);
face(image, id, box, 4, u + d + w, v + d, d, h);
face(image, id, box, 5, u + 2 * d + w, v + d, w, h);
}
private static void face(NativeImage image, String id, Box box, int face, int x0, int y0, int width, int height) {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int px = x0 + x;
int py = y0 + y;
if (px < TEXTURE && py < TEXTURE) {
image.setPixel(px, py, color(id, box.material(), face, x, y, width, height));
}
}
}
}
/** A face's pixel: face 0 and 1 the bottom and top, 3 the front, 5 the back. */
private static int color(String id, Material material, int face, int x, int y, int width, int height) {
boolean flat = face <= 1;
float row = height <= 1 ? 0 : y / (float) (height - 1);
float grain = CosmeticArt.hash(x, y, face + material.name().length() * 7);
return switch (material) {
case GOLD, GOLD_GEM -> {
if (material == Material.GOLD_GEM && flat) {
yield 0xFF000000 | CosmeticArt.mix(0x8E1B2E, 0x6A1222, grain);
}
if (material == Material.GOLD_GEM && face == 3 && Math.abs(x - (width - 1) / 2.0F) < 1 && y == 0) {
yield 0xFFE0344B;
}
int gold = CosmeticArt.mix(0xFFE58A, 0xD69A1E, flat ? 0.1F : row);
yield 0xFF000000 | (grain < 0.08F ? CosmeticArt.mix(gold, 0xFFFFFF, 0.6F) : gold);
}
case VELVET -> 0xFF000000 | CosmeticArt.mix(0x8E1B2E, 0x6A1222, grain);
case HALO -> 0xFF000000 | CosmeticArt.mix(0xFFF6D2, 0xFFDB7A, grain * 0.6F);
case FELT -> 0xFF000000 | CosmeticArt.mix(0x2A2A33, 0x1A1A20, grain);
case FELT_BAND ->
!flat && y >= height - 2 ? 0xFFC0263A : 0xFF000000 | CosmeticArt.mix(0x2A2A33, 0x1A1A20, grain);
case KNIT -> {
if (!flat && y == height - 1) {
yield 0xFF4F8FC7;
}
int stripe = flat ? (x + y) / 2 : y;
yield (stripe & 1) == 0 ? 0xFF7FC3F2 : 0xFFEAF6FF;
}
case POM -> 0xFF000000 | CosmeticArt.mix(0xFFFFFF, 0xDDE8F2, grain);
case BONE -> 0xFF000000 | CosmeticArt.mix(0xF2E6CC, 0x9C8A6A, flat ? 0.3F : 1 - row);
case EAR -> face == 3 && x > 0 && x < width - 1 && y > 0 ? 0xFFF2A6BC : 0xFF4A4A58;
case PACK -> {
if (face == 1) {
yield 0xFF7FC3F2;
}
boolean seam = x == 0 || y == 0 || x == width - 1 || y == height - 1;
yield seam ? 0xFF3B5B8A : 0xFF000000 | CosmeticArt.mix(0x22385A, 0x1B2D49, grain);
}
case POCKET -> (x == 0 || y == 0 || x == width - 1 || y == height - 1) ? 0xFFA9DCFF : 0xFF2C4A72;
case WING -> {
// The back (south) face has the root on its left; the front shows it mirrored, so
// the two sides of the panel line up.
float sx = (x + 0.5F) / width;
float sy = (y + 0.5F) / height;
yield CosmeticArt.wing(id, face == 5 ? sx : 1 - sx, sy);
}
};
}
/** A cosmetic's model: its parts posed from the player's state as it's drawn (halo, wings). */
static final class CosmeticModel extends Model<AvatarRenderState> {
private final @Nullable ModelPart ring;
private final @Nullable ModelPart leftWing;
private final @Nullable ModelPart rightWing;
CosmeticModel(ModelPart root, java.util.function.Function<Identifier, RenderType> renderType, String id) {
super(root, renderType);
this.ring = id.equals("hat.halo") ? root.getChild("ring") : null;
boolean wings = id.endsWith("_wings");
this.leftWing = wings ? root.getChild("left_wing") : null;
this.rightWing = wings ? root.getChild("right_wing") : null;
}
@Override
public void setupAnim(AvatarRenderState state) {
super.setupAnim(state);
float age = state.ageInTicks;
ModelPart halo = ring;
if (halo != null) {
halo.yRot = age * 0.04F;
halo.y += (float) Math.sin(age * 0.08F) * 0.4F;
}
ModelPart left = leftWing;
ModelPart right = rightWing;
if (left != null && right != null) {
// Swept further back by a slow beat at rest, folded back while sneaking, spread while
// gliding; never swept forward far enough to reach the arms.
float beat = (float) Math.sin(age * 0.12F) * 0.08F + 0.08F;
float fold = state.isCrouching ? 0.25F : 0;
float spread = state.isFallFlying ? 0.2F : 0;
float sweep = Math.max(-WING_SWEEP + 0.1F, beat + fold - spread);
left.yRot -= sweep;
right.yRot += sweep;
}
}
}
}
@@ -0,0 +1,127 @@
package incari.client.cosmetics;
import com.mojang.blaze3d.platform.NativeImage;
import incari.online.Cosmetic;
import java.util.HashMap;
import java.util.Map;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.core.ClientAsset;
import net.minecraft.resources.Identifier;
import net.minecraft.util.Util;
import org.jspecify.annotations.Nullable;
/**
* The capes' textures and the wardrobe's icons (ADR 0061), painted by {@link CosmeticArt} the first
* time each is needed. A moving cape is painted again ten times a second while something has drawn
* it in the last two seconds, and left as it is otherwise: a cape nobody sees costs nothing.
*
* <p>Render thread (the game's thread in Incari's builds).
*/
final class CosmeticTextures {
/** How long a moving cape goes on moving after it was last drawn. */
private static final long IDLE_MILLIS = 2_000;
/** A cape's texture, and when it was last drawn. */
private static final class Cape {
final Identifier id;
final ClientAsset.Texture asset;
final DynamicTexture texture;
final int[] pixels = new int[CosmeticArt.CAPE_WIDTH * CosmeticArt.CAPE_HEIGHT];
final boolean animated;
long lastDrawn;
Cape(Identifier id, DynamicTexture texture, boolean animated) {
this.id = id;
this.asset = new ClientAsset.ResourceTexture(id, id);
this.texture = texture;
this.animated = animated;
}
}
private static final Map<String, Cape> CAPES = new HashMap<>();
private static final Map<String, Identifier> ICONS = new HashMap<>();
private static final long START = Util.getMillis();
private CosmeticTextures() {}
/** The cape's texture, as a skin's cape: made now if it's the first time. */
static ClientAsset.Texture cape(Cosmetic cape) {
Cape made = capeTexture(cape);
made.lastDrawn = Util.getMillis();
return made.asset;
}
/** The cape's texture by id, for the wardrobe's cards (which show its outer side). */
static Identifier capeId(Cosmetic cape) {
Cape made = capeTexture(cape);
made.lastDrawn = Util.getMillis();
return made.id;
}
private static Cape capeTexture(Cosmetic cape) {
Cape made = CAPES.get(cape.id());
if (made == null) {
Identifier id = Identifier.fromNamespaceAndPath(
"incari", "cosmetics/" + cape.id().replace('.', '/'));
NativeImage image = new NativeImage(CosmeticArt.CAPE_WIDTH, CosmeticArt.CAPE_HEIGHT, true);
DynamicTexture texture = new DynamicTexture(id::toString, image);
made = new Cape(id, texture, CosmeticArt.animated(cape.id()));
paint(cape.id(), made);
texture.upload();
Minecraft.getInstance().getTextureManager().register(id, texture);
CAPES.put(cape.id(), made);
}
return made;
}
/** Once a client tick: moving capes drawn lately are painted again, every other tick. */
static void tick(long tick) {
if ((tick & 1) != 0 || CAPES.isEmpty()) {
return;
}
long now = Util.getMillis();
for (Map.Entry<String, Cape> each : CAPES.entrySet()) {
Cape cape = each.getValue();
if (cape.animated && now - cape.lastDrawn < IDLE_MILLIS) {
paint(each.getKey(), cape);
cape.texture.upload();
}
}
}
private static void paint(String id, Cape cape) {
CosmeticArt.cape(id, (Util.getMillis() - START) / 1000.0F, cape.pixels);
NativeImage image = cape.texture.getPixels();
for (int y = 0; y < CosmeticArt.CAPE_HEIGHT; y++) {
for (int x = 0; x < CosmeticArt.CAPE_WIDTH; x++) {
image.setPixel(x, y, cape.pixels[y * CosmeticArt.CAPE_WIDTH + x]);
}
}
}
/** A hat's or back cosmetic's icon for its wardrobe card; null for one with none. */
static @Nullable Identifier icon(Cosmetic cosmetic) {
if (cosmetic.slot() != Cosmetic.Slot.HAT && cosmetic.slot() != Cosmetic.Slot.BACK) {
return null;
}
Identifier id = ICONS.get(cosmetic.id());
if (id == null) {
int[] pixels = new int[CosmeticArt.ICON * CosmeticArt.ICON];
CosmeticArt.icon(cosmetic.id(), pixels);
NativeImage image = new NativeImage(CosmeticArt.ICON, CosmeticArt.ICON, true);
for (int y = 0; y < CosmeticArt.ICON; y++) {
for (int x = 0; x < CosmeticArt.ICON; x++) {
image.setPixel(x, y, pixels[y * CosmeticArt.ICON + x]);
}
}
id = Identifier.fromNamespaceAndPath(
"incari", "cosmetics/icon/" + cosmetic.id().replace('.', '/'));
Identifier label = id;
Minecraft.getInstance().getTextureManager().register(id, new DynamicTexture(label::toString, image));
ICONS.put(cosmetic.id(), id);
}
return id;
}
}
@@ -0,0 +1,421 @@
package incari.client.cosmetics;
import incari.client.IncariKeys;
import incari.client.online.IncariOnline;
import incari.client.settings.ClientSettings;
import incari.framework.online.IncariPlayer;
import incari.framework.online.Online;
import incari.online.Cosmetic;
import incari.online.Loadout;
import incari.online.OnlineService;
import incari.online.Wardrobe;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import net.minecraft.client.CameraType;
import net.minecraft.client.Minecraft;
import net.minecraft.client.model.player.PlayerModel;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.multiplayer.ClientPacketListener;
import net.minecraft.client.multiplayer.PlayerInfo;
import net.minecraft.client.player.AbstractClientPlayer;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.renderer.entity.RenderLayerParent;
import net.minecraft.client.renderer.entity.layers.RenderLayer;
import net.minecraft.client.renderer.entity.state.AvatarRenderState;
import net.minecraft.core.ClientAsset;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.network.chat.Component;
import net.minecraft.util.RandomSource;
import net.minecraft.world.entity.Avatar;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.player.PlayerSkin;
import org.jspecify.annotations.Nullable;
/**
* Cosmetics in the world (ADR 0061): what each player wears and plays, from the player's own
* wardrobe or, for others, the online service, put on each player's render state for the layers to
* draw. Others' are drawn only for Incari players the service named, and only while
* {@link Wardrobe#showOthers} is on.
*
* <p>The game calls in from six hooks: the player renderer's layers ({@link #layer}) and its
* render state ({@link #extract}), the player model's pose ({@link #pose}), the tab list's names
* ({@link #tabListName}), chat ({@link #chatMessage}), and once a tick ({@link #tick}): emotes start and end, trails are left,
* moving capes are painted.
*
* <p>Render thread (the game's thread in Incari's builds). {@link #extract} runs for every player
* every frame: a lookup, and nothing made unless what someone wears changed.
*/
public final class Cosmetics {
/** Trails are left only by players this near. */
private static final double TRAIL_DISTANCE = 32;
/** At most this many trail particles a tick, however many players are about. */
private static final int TRAIL_BUDGET = 12;
/**
* An emote playing: which, the player's tick it started on (its pose counts from it), and the
* client tick it ends on. The end is in client ticks because a respawn or dimension change makes
* a new player, whose ticks restart at 0.
*/
private record Play(Cosmetic emote, int startTick, long endsAt) {
Play(Cosmetic emote, int startTick) {
this(emote, startTick, ticks + Emotes.duration(emote));
}
}
/** What another player was last seen wearing and playing, and what that came to. */
private record Seen(List<String> source, @Nullable Play play, Worn worn) {}
private static final Map<UUID, Seen> OTHERS = new HashMap<>();
private static final Map<UUID, Play> PLAYS = new HashMap<>();
/** Skins with a cosmetic cape, by cape and by the skin they were made from. */
private static final Map<Cosmetic, Map<PlayerSkin, PlayerSkin>> DRESSED = new HashMap<>();
private static Worn self = Worn.NONE;
private static Loadout selfLoadout = Loadout.EMPTY;
private static @Nullable Play selfPlay;
/** The camera to go back to once the player's own emote ends; null when it wasn't moved. */
private static @Nullable CameraType cameraBefore;
private static long ticks;
private Cosmetics() {}
// ---------------------------------------------------------------------------------------------
// The game's hooks
// ---------------------------------------------------------------------------------------------
/** {@code AvatarRenderer}'s constructor: the layer that draws hats and back cosmetics. */
public static RenderLayer<AvatarRenderState, PlayerModel> layer(
RenderLayerParent<AvatarRenderState, PlayerModel> parent) {
return new CosmeticsLayer(parent);
}
/** {@code AvatarRenderer.extractRenderState}'s end: what this player wears, on their state. */
public static void extract(Avatar avatar, AvatarRenderState state) {
if (avatar instanceof AbstractClientPlayer player) {
Worn worn = wornBy(player);
if (worn != Worn.NONE) {
dress(state, worn, player.getUUID());
}
// Incari's badge (ADR 0062): other Incari players who show it, while the player wants it.
if (state.nameTag != null && !(player instanceof LocalPlayer) && ClientSettings.SHOW_BADGES.get()) {
IncariPlayer incari = IncariOnline.service().player(player.getUUID());
if (incari != null && incari.badge()) {
state.nameTag = Badges.badged(player.getUUID(), state.nameTag);
}
}
}
}
/**
* {@code PlayerTabOverlay}'s list: the player {@code id}'s {@code name} with Incari's badge before
* it, as their name tag has it (ADR 0062), or {@code name}. The player's own name has it too while
* they show others they use Incari.
*/
public static Component tabListName(UUID id, Component name) {
OnlineService online = IncariOnline.service();
if (online.status() != Online.Status.SIGNED_IN) {
return name;
}
return showsBadge(online, id) ? Badges.badgedInTabList(id, name) : name;
}
/**
* {@code ChatComponent.addMessage}: {@code message} with Incari's badge before the first mention
* of each Incari player in it, as the tab list has it, or {@code message}. Players are found by
* their name in the tab list, since most servers send chat as plain text with no sender.
*/
public static Component chatMessage(Component message) {
OnlineService online = IncariOnline.service();
ClientPacketListener connection = Minecraft.getInstance().getConnection();
if (online.status() != Online.Status.SIGNED_IN || connection == null) {
return message;
}
return Badges.badgedInChat(message, name -> {
PlayerInfo info = connection.getPlayerInfo(name);
return info != null && showsBadge(online, info.getProfile().id());
});
}
/** Whether the player {@code id}'s badge shows: theirs if they let it, the player's own if they do. */
private static boolean showsBadge(OnlineService online, UUID id) {
LocalPlayer me = Minecraft.getInstance().player;
if (me != null && me.getUUID().equals(id)) {
return online.showsBadge();
}
IncariPlayer incari = online.player(id);
return incari != null && incari.badge() && ClientSettings.SHOW_BADGES.get();
}
/** {@code PlayerModel.setupAnim}'s end: an emote's pose over the game's. */
public static void pose(PlayerModel model, AvatarRenderState state) {
Emotes.pose(model, state);
}
/** Whether the player wears any cosmetic: the title screen's player then shows them. */
public static boolean wearsAny() {
return !IncariOnline.service().wardrobe().worn().isEmpty();
}
/** What the player wears. */
public static Loadout ownLoadout() {
return IncariOnline.service().wardrobe().worn();
}
/** The player's {@code name} in their name tag cosmetic, or plain. */
public static Component ownName(String name) {
Cosmetic nametag = ownLoadout().in(Cosmetic.Slot.NAMETAG);
return nametag == null ? Component.literal(name) : NameTags.styled(name, nametag);
}
/** The emote {@code state}'s player is playing, or null (the smoke tests' check). */
public static @Nullable Cosmetic emoteOf(AvatarRenderState state) {
return state.incariWorn.emote;
}
/** What {@code state} carries. */
static Worn worn(AvatarRenderState state) {
return state.incariWorn;
}
/**
* Puts {@code worn} on {@code state}: for the layers, the cape as the skin's own, and the name tag
* styled. The wardrobe's preview dresses its state the same way.
*/
static void dress(AvatarRenderState state, Worn worn, UUID id) {
state.incariWorn = worn;
Cosmetic cape = worn.cape;
if (cape != null) {
state.skin = withCape(state.skin, cape);
}
Cosmetic back = worn.back;
if (back != null && back.id().equals("back.backpack")) {
// A backpack and a cape would go through each other.
state.showCape = false;
}
Cosmetic nametag = worn.nametag;
if (nametag != null && state.nameTag != null) {
state.nameTag = NameTags.style(id, state.nameTag, nametag);
}
}
private static PlayerSkin withCape(PlayerSkin skin, Cosmetic cape) {
ClientAsset.Texture texture = CosmeticTextures.cape(cape);
Map<PlayerSkin, PlayerSkin> bySkin = DRESSED.computeIfAbsent(cape, key -> new HashMap<>());
PlayerSkin dressed = bySkin.get(skin);
if (dressed == null) {
if (bySkin.size() > 256) {
bySkin.clear();
}
// The elytra matches the cape, as it does with the game's capes.
dressed = new PlayerSkin(skin.body(), texture, texture, skin.model(), skin.secure());
bySkin.put(skin, dressed);
}
return dressed;
}
// ---------------------------------------------------------------------------------------------
// Who wears what
// ---------------------------------------------------------------------------------------------
@SuppressWarnings("ReferenceEquality") // the same loadout, list and play objects, not equal ones
private static Worn wornBy(AbstractClientPlayer player) {
UUID id = player.getUUID();
OnlineService online = IncariOnline.service();
Wardrobe wardrobe = online.wardrobe();
Play play = PLAYS.get(id);
if (player instanceof LocalPlayer) {
Loadout loadout = wardrobe.worn();
if (loadout != selfLoadout || play != selfPlay) {
selfLoadout = loadout;
selfPlay = play;
self = loadout.isEmpty() && play == null
? Worn.NONE
: new Worn(loadout, play == null ? null : play.emote(), play == null ? 0 : play.startTick());
}
return self;
}
if (!wardrobe.showOthers()) {
return Worn.NONE;
}
IncariPlayer incari = online.player(id);
if (incari == null && play == null) {
return Worn.NONE;
}
List<String> source = incari == null ? List.of() : incari.cosmetics();
Seen seen = OTHERS.get(id);
if (seen == null || seen.source() != source || seen.play() != play) {
Loadout loadout = Loadout.of(source);
Worn worn = loadout.isEmpty() && play == null
? Worn.NONE
: new Worn(loadout, play == null ? null : play.emote(), play == null ? 0 : play.startTick());
seen = new Seen(source, play, worn);
OTHERS.put(id, seen);
}
return seen.worn();
}
// ---------------------------------------------------------------------------------------------
// Emotes
// ---------------------------------------------------------------------------------------------
/**
* The player plays {@code emote} (the emote wheel): the camera turns to face them while it plays,
* and Incari players on the server see it too. False if it can't play now (one every two
* seconds, and only in a world).
*/
public static boolean playEmote(Cosmetic emote) {
Minecraft minecraft = Minecraft.getInstance();
LocalPlayer player = minecraft.player;
if (player == null || !IncariOnline.service().playEmote(emote)) {
return false;
}
PLAYS.put(player.getUUID(), new Play(emote, player.tickCount));
if (minecraft.options.getCameraType() == CameraType.FIRST_PERSON) {
cameraBefore = CameraType.FIRST_PERSON;
minecraft.options.setCameraType(CameraType.THIRD_PERSON_FRONT);
}
return true;
}
private static void emotesEnded(Minecraft minecraft) {
CameraType before = cameraBefore;
cameraBefore = null;
// Unless the player moved the camera themselves meanwhile.
if (before != null && minecraft.options.getCameraType() == CameraType.THIRD_PERSON_FRONT) {
minecraft.options.setCameraType(before);
}
}
// ---------------------------------------------------------------------------------------------
// Each tick
// ---------------------------------------------------------------------------------------------
/** From {@code IncariTicks}, after the online service's tick. */
public static void tick(Minecraft minecraft) {
ticks++;
CosmeticTextures.tick(ticks);
OnlineService online = IncariOnline.service();
List<OnlineService.PlayedEmote> played = online.takeEmotes();
ClientLevel level = minecraft.level;
if (level == null) {
if (!PLAYS.isEmpty() || !OTHERS.isEmpty()) {
PLAYS.clear();
OTHERS.clear();
NameTags.clear();
Badges.clear();
}
// Left the world mid-emote: the camera goes back now, not with the next world.
emotesEnded(minecraft);
return;
}
// The wheel opens with its key over the game, not over another screen.
while (IncariKeys.EMOTE_WHEEL.consumeClick()) {
if (minecraft.gui.screen() == null && minecraft.player != null) {
minecraft.gui.setScreen(new EmoteWheelScreen());
}
}
boolean showOthers = online.wardrobe().showOthers();
for (OnlineService.PlayedEmote each : played) {
Player player = level.getPlayerByUUID(each.player());
if (player != null && showOthers) {
PLAYS.put(each.player(), new Play(each.emote(), player.tickCount));
}
}
endEmotes(minecraft, level, showOthers);
trails(minecraft, level);
if (ticks % 200 == 0) {
OTHERS.keySet().removeIf(id -> level.getPlayerByUUID(id) == null);
}
}
private static void endEmotes(Minecraft minecraft, ClientLevel level, boolean showOthers) {
LocalPlayer me = minecraft.player;
boolean mineEnded = false;
for (Iterator<Map.Entry<UUID, Play>> each = PLAYS.entrySet().iterator(); each.hasNext(); ) {
Map.Entry<UUID, Play> entry = each.next();
Player player = level.getPlayerByUUID(entry.getKey());
Play play = entry.getValue();
boolean mine = me != null && entry.getKey().equals(me.getUUID());
boolean over = player == null
|| ticks >= play.endsAt()
|| (!mine && !showOthers)
// Moving cuts an emote short: the player's own by their keys, others' by their legs.
|| ((me != null && mine) ? moving(me) : player.walkAnimation.speed() > 0.35F);
if (over) {
each.remove();
mineEnded |= mine;
}
}
if (mineEnded || (cameraBefore != null && (me == null || !PLAYS.containsKey(me.getUUID())))) {
emotesEnded(minecraft);
}
}
private static boolean moving(LocalPlayer player) {
return player.input.getMoveVector().lengthSquared() > 0
|| player.input.keyPresses.jump()
|| player.isSwinging();
}
private static void trails(Minecraft minecraft, ClientLevel level) {
if ((ticks & 1) != 0) {
return;
}
LocalPlayer me = minecraft.player;
if (me == null) {
return;
}
int left = TRAIL_BUDGET;
RandomSource random = level.getRandom();
for (AbstractClientPlayer player : level.players()) {
if (left <= 0) {
break;
}
Cosmetic trail = wornBy(player).trail;
if (trail == null || player.isInvisible() || player.isSpectator()) {
continue;
}
if (player.distanceToSqr(me) > TRAIL_DISTANCE * TRAIL_DISTANCE) {
continue;
}
double dx = player.getX() - player.xo;
double dy = player.getY() - player.yo;
double dz = player.getZ() - player.zo;
if (dx * dx + dy * dy + dz * dz < 0.0004) {
continue;
}
// Hearts are big: fewer of them.
if (trail.id().equals("trail.hearts") && (ticks / 2 + player.getId()) % 3 != 0) {
continue;
}
double x = player.getX() + (random.nextDouble() - 0.5) * 0.5;
double y = player.getY() + 0.1 + random.nextDouble() * 0.2;
double z = player.getZ() + (random.nextDouble() - 0.5) * 0.5;
switch (trail.id()) {
case "trail.snow" -> level.addParticle(ParticleTypes.SNOWFLAKE, x, y, z, 0, 0.02, 0);
case "trail.hearts" -> level.addParticle(ParticleTypes.HEART, x, y + 0.3, z, 0, 0, 0);
case "trail.sparkles" ->
level.addParticle(
ParticleTypes.END_ROD,
x,
y + 0.2,
z,
(random.nextDouble() - 0.5) * 0.02,
0.02,
(random.nextDouble() - 0.5) * 0.02);
// A note's color is its first speed (a pitch, 0 to 1).
case "trail.notes" -> level.addParticle(ParticleTypes.NOTE, x, y + 0.4, z, random.nextDouble(), 0, 0);
default -> {}
}
left--;
}
}
}
@@ -0,0 +1,113 @@
package incari.client.cosmetics;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.math.Axis;
import incari.online.Cosmetic;
import net.minecraft.client.model.player.PlayerModel;
import net.minecraft.client.renderer.SubmitNodeCollector;
import net.minecraft.client.renderer.entity.LivingEntityRenderer;
import net.minecraft.client.renderer.entity.RenderLayerParent;
import net.minecraft.client.renderer.entity.layers.RenderLayer;
import net.minecraft.client.renderer.entity.state.AvatarRenderState;
import net.minecraft.core.component.DataComponents;
import net.minecraft.util.Mth;
import org.jspecify.annotations.Nullable;
/**
* Draws a player's hat and back cosmetic (ADR 0061), from what their render state carries ({@link
* Worn}). The cape is the game's own cape layer's, with the cosmetic's texture as the skin's cape
* ({@link Cosmetics#dress}), so it moves as capes do.
*
* <p>A hat hides under a helmet (the halo floats above one); a back cosmetic hides under an elytra,
* stands off a chestplate and hangs behind a cape. Nothing is drawn for an invisible player, or past {@link
* #MAX_DISTANCE} blocks, where a hat is a pixel or two. Render thread; per player per frame, so
* nothing here allocates.
*/
final class CosmeticsLayer extends RenderLayer<AvatarRenderState, PlayerModel> {
/** Past this, worn models aren't drawn. */
static final double MAX_DISTANCE = 48;
/** The cape's top edge from the body's pivot, in blocks: the body's back. */
private static final float CAPE_TOP = 2.0F / 16.0F;
/** How far a back cosmetic moves back to clear a cape: its pixel, and a gap. */
private static final float BEHIND_CAPE = 1.0F / 16.0F;
CosmeticsLayer(RenderLayerParent<AvatarRenderState, PlayerModel> parent) {
super(parent);
}
@Override
public void submit(
PoseStack poseStack,
SubmitNodeCollector submitNodeCollector,
int lightCoords,
AvatarRenderState state,
float yRot,
float xRot) {
Worn worn = Cosmetics.worn(state);
if (worn.isEmpty() || state.isInvisible || state.distanceToCameraSq > MAX_DISTANCE * MAX_DISTANCE) {
return;
}
Cosmetic hat = worn.hat;
if (hat != null && (state.headEquipment.isEmpty() || hat.id().equals("hat.halo"))) {
draw(poseStack, submitNodeCollector, lightCoords, state, CosmeticModels.of(hat), true);
}
Cosmetic back = worn.back;
if (back != null && !state.chestEquipment.has(DataComponents.GLIDER)) {
draw(poseStack, submitNodeCollector, lightCoords, state, CosmeticModels.of(back), false);
}
}
private void draw(
PoseStack poseStack,
SubmitNodeCollector submitNodeCollector,
int lightCoords,
AvatarRenderState state,
CosmeticModels.@Nullable Made made,
boolean onHead) {
if (made == null) {
return;
}
PlayerModel parent = getParentModel();
poseStack.pushPose();
parent.root().translateAndRotate(poseStack);
if (onHead) {
parent.head.translateAndRotate(poseStack);
} else {
parent.body.translateAndRotate(poseStack);
if (!state.chestEquipment.isEmpty()) {
// A chestplate stands a pixel out from the body.
poseStack.translate(0.0F, 0.0F, 0.0625F);
}
if (state.showCape && state.skin.cape() != null) {
behindCape(poseStack, state);
}
}
boolean glow = made.look() == CosmeticModels.Look.GLOW;
submitNodeCollector.submitModel(
made.model(),
state,
poseStack,
made.model().renderType(made.texture()),
glow ? 0xF000F0 : lightCoords,
LivingEntityRenderer.getOverlayCoords(state, 0.0F),
state.outlineColor);
poseStack.popPose();
}
/**
* Over a cape, a back cosmetic hangs behind it and swings out with it, as the cape layer turns
* the cape ({@code PlayerCapeModel.setupAnim}): otherwise the cape, which hangs from the
* shoulders a pixel thick and swings back as the player moves, cuts through it. (A backpack
* hides the cape instead, {@link Cosmetics#dress}.)
*/
private static void behindCape(PoseStack poseStack, AvatarRenderState state) {
float swing = (6.0F + state.capeLean / 2.0F + state.capeFlap) * Mth.DEG_TO_RAD;
// About the cape's top edge, at the body's back (z = 2 pixels).
poseStack.translate(0.0F, 0.0F, CAPE_TOP);
poseStack.rotate(Axis.XP, swing);
poseStack.translate(0.0F, 0.0F, -CAPE_TOP + BEHIND_CAPE);
}
}
@@ -0,0 +1,144 @@
package incari.client.cosmetics;
import incari.client.IncariKeys;
import incari.client.online.IncariOnline;
import incari.client.ui.Circles;
import incari.client.ui.Look;
import incari.client.ui.RoundRects;
import incari.client.ui.Theme;
import incari.online.Cosmetic;
import java.util.List;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.input.KeyEvent;
import net.minecraft.client.input.MouseButtonEvent;
import net.minecraft.network.chat.Component;
import org.jspecify.annotations.Nullable;
/**
* The emote wheel (ADR 0061): held open by its key (G), the player's emotes round a circle; the one
* the pointer points toward plays when the key is let go, or when it's clicked. Escape, or letting
* go with the pointer in the middle, plays nothing. A quick tap of the key, let go before the wheel
* opened, leaves it open to click an emote; the key again closes it. The game goes on behind it.
*/
public final class EmoteWheelScreen extends Screen {
private static final float RADIUS = 78;
private static final float INNER = 24;
private static final float LABEL_RADIUS = 54;
private final List<Cosmetic> emotes;
private int hovered = -1;
/**
* Whether the key was let go before the wheel opened (it opens on the tick after the press): its
* release is gone, so the wheel waits for a click instead.
*/
private final boolean tapped;
public EmoteWheelScreen() {
super(Component.literal("Emotes"));
this.emotes = IncariOnline.service().wardrobe().emotes();
this.tapped = !IncariKeys.EMOTE_WHEEL.isDown();
}
@Override
public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
float cx = width / 2.0F;
float cy = height / 2.0F;
hovered = pointedAt(mouseX, mouseY);
Circles.disc(graphics, cx, cy, RADIUS, Look.normal() ? 0xB0101822 : Theme.GLASS_SOLID);
Circles.ring(graphics, cx, cy, RADIUS, 1, Theme.GLASS_EDGE);
Circles.ring(graphics, cx, cy, INNER, 1, Theme.GLASS_EDGE);
int count = emotes.size();
for (int i = 0; i < count; i++) {
double angle = angle(i, count);
int x = Math.round(cx + (float) Math.sin(angle) * LABEL_RADIUS);
int y = Math.round(cy - (float) Math.cos(angle) * LABEL_RADIUS);
Component name = Component.literal(emotes.get(i).name());
int textWidth = font.width(name);
boolean on = i == hovered;
if (on) {
RoundRects.fill(graphics, x - textWidth / 2 - 6, y - 8, textWidth + 12, 16, 8, Theme.ACCENT);
}
graphics.text(font, name, x - textWidth / 2, y - 4, on ? Theme.ON_ACCENT : Theme.TEXT, false);
}
Component middle = hovered >= 0
? Component.literal(emotes.get(hovered).name())
: Component.literal(count == 0 ? "No emotes" : "Emotes");
graphics.centeredText(font, middle, (int) cx, (int) cy - 4, hovered >= 0 ? Theme.ACCENT : Theme.MUTED);
String key = IncariKeys.EMOTE_WHEEL.getTranslatedKeyMessage().getString();
Component hint = Component.literal(
tapped
? "Click an emote to play it, or press " + key + " to close"
: "Release " + key + " or click to play");
graphics.centeredText(font, hint, (int) cx, (int) (cy + RADIUS + 10), Theme.MUTED);
}
/** The angle of emote {@code i} of {@code count}, clockwise from straight up. */
private static double angle(int i, int count) {
return Math.PI * 2 * i / Math.max(1, count);
}
/** The emote the pointer points toward, or -1 in the middle or with none. */
private int pointedAt(double mouseX, double mouseY) {
double dx = mouseX - width / 2.0;
double dy = mouseY - height / 2.0;
if (emotes.isEmpty() || dx * dx + dy * dy < INNER * INNER) {
return -1;
}
double angle = Math.atan2(dx, -dy);
if (angle < 0) {
angle += Math.PI * 2;
}
double slice = Math.PI * 2 / emotes.size();
return (int) Math.round(angle / slice) % emotes.size();
}
private void play(int index) {
onClose();
if (index >= 0 && index < emotes.size()) {
Cosmetics.playEmote(emotes.get(index));
}
}
@Override
public boolean keyPressed(KeyEvent event) {
if (tapped && IncariKeys.EMOTE_WHEEL.matches(event)) {
onClose();
return true;
}
return super.keyPressed(event);
}
@Override
public boolean keyReleased(KeyEvent event) {
if (!tapped && IncariKeys.EMOTE_WHEEL.matches(event)) {
play(hovered);
return true;
}
return super.keyReleased(event);
}
@Override
public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) {
play(pointedAt(event.x(), event.y()));
return true;
}
@Override
public boolean isPauseScreen() {
return false;
}
@Override
public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
// The world stays as it is behind the wheel: the player is in the middle of a game.
}
/** The emote under the pointer, for tests. */
@Nullable
Cosmetic hovered() {
return hovered >= 0 && hovered < emotes.size() ? emotes.get(hovered) : null;
}
}
@@ -0,0 +1,103 @@
package incari.client.cosmetics;
import incari.online.Cosmetic;
import net.minecraft.client.model.geom.ModelPart;
import net.minecraft.client.model.player.PlayerModel;
import net.minecraft.client.renderer.entity.state.AvatarRenderState;
import net.minecraft.util.Mth;
/**
* Emotes as the player model plays them (ADR 0061): each a pose for the arms and head, eased in and
* out, some moving as they go (a wave, a clap). Laid over the game's own pose at the end of {@code
* PlayerModel.setupAnim}, so the legs still walk if the player does, and sleeves, hats and capes
* follow the parts they hang from.
*
* <p>Render thread; the pose is set while the model is drawn, so nothing here allocates.
*/
final class Emotes {
/** Ticks an emote takes to ease in, and out. */
private static final float EASE = 4;
private Emotes() {}
/** How long {@code emote} plays, in ticks. */
static int duration(Cosmetic emote) {
return switch (emote.id()) {
case "emote.wave", "emote.clap", "emote.facepalm" -> 50;
case "emote.cheer" -> 45;
case "emote.salute", "emote.bow" -> 40;
case "emote.shrug" -> 35;
case "emote.dab" -> 30;
default -> 40;
};
}
/** {@code PlayerModel.setupAnim}'s hook: the emote's pose over the game's, if one is playing. */
static void pose(PlayerModel model, AvatarRenderState state) {
Worn worn = Cosmetics.worn(state);
Cosmetic emote = worn.emote;
if (emote == null) {
return;
}
float elapsed = state.ageInTicks - worn.emoteStart;
int duration = duration(emote);
if (elapsed < 0 || elapsed >= duration) {
return;
}
float weight = Math.min(1, Math.min(elapsed / EASE, (duration - elapsed) / EASE));
float e = elapsed;
ModelPart head = model.head;
ModelPart right = model.rightArm;
ModelPart left = model.leftArm;
switch (emote.id()) {
case "emote.wave" -> arm(right, weight, 0, 0, 2.6F + 0.35F * Mth.sin(e * 0.6F));
case "emote.clap" -> {
float swing = 0.25F + 0.3F * (0.5F + 0.5F * Mth.sin(e * 0.9F));
arm(right, weight, -1.35F, -swing, 0);
arm(left, weight, -1.35F, swing, 0);
}
case "emote.cheer" -> {
float bounce = 0.15F * Mth.sin(e * 0.5F);
arm(right, weight, -2.9F + bounce, 0, 0.35F);
arm(left, weight, -2.9F - bounce, 0, -0.35F);
turn(head, weight, -0.25F, 0, 0);
}
case "emote.salute" -> {
arm(right, weight, -2.3F, -0.55F, 0.1F);
turn(head, weight, -0.05F, 0, 0);
}
case "emote.facepalm" -> {
arm(right, weight, -2.1F, -0.75F, 0);
turn(head, weight, 0.35F, 0, 0);
}
case "emote.shrug" -> {
float lift = 0.1F * Mth.sin(e * 0.4F);
arm(right, weight, -0.45F, 0, 0.75F + lift);
arm(left, weight, -0.45F, 0, -0.75F - lift);
turn(head, weight, -0.1F, 0, 0.12F * Mth.sin(e * 0.3F));
}
case "emote.dab" -> {
arm(right, weight, -1.6F, -1.0F, 0);
arm(left, weight, -0.4F, 0, -2.3F);
turn(head, weight, 0.55F, 0.6F, 0);
}
case "emote.bow" -> {
arm(right, weight, -0.9F, -0.6F, 0);
arm(left, weight, 0.3F, 0, 0);
turn(head, weight, 0.75F, 0, 0);
}
default -> {}
}
}
private static void arm(ModelPart arm, float weight, float xRot, float yRot, float zRot) {
turn(arm, weight, xRot, yRot, zRot);
}
private static void turn(ModelPart part, float weight, float xRot, float yRot, float zRot) {
part.xRot = Mth.lerp(weight, part.xRot, xRot);
part.yRot = Mth.lerp(weight, part.yRot, yRot);
part.zRot = Mth.lerp(weight, part.zRot, zRot);
}
}
@@ -0,0 +1,83 @@
package incari.client.cosmetics;
import incari.online.Cosmetic;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.Style;
/**
* Name tag cosmetics (ADR 0061): the name over a player's head in a color, or fading from one color
* to another across it. Only where the server leaves the name uncolored: a team's or a rank's color
* means something in the game, and wins.
*
* <p>Render thread. Each player's last name tag and its styled copy are kept, so a name that doesn't
* change is styled once.
*/
public final class NameTags {
/** Each player's last name tag in, and what it became. */
private record Styled(Component from, Cosmetic style, Component to) {}
private static final Map<UUID, Styled> LAST = new HashMap<>();
private NameTags() {}
/** The colors of {@code style}: one for a plain color, two for a fade. */
public static int[] colors(Cosmetic style) {
return switch (style.id()) {
case "nametag.ice" -> new int[] {0xA9DCFF};
case "nametag.gold" -> new int[] {0xFFD36A};
case "nametag.mint" -> new int[] {0x8FE3B0};
case "nametag.rose" -> new int[] {0xFF9BB8};
case "nametag.violet" -> new int[] {0xC6A2FF};
case "nametag.frost" -> new int[] {0xFFFFFF, 0x7FC8FF};
case "nametag.sunset" -> new int[] {0xFFB36A, 0xFF6FA8};
case "nametag.aurora" -> new int[] {0x6AF2B0, 0xA06CFF};
default -> new int[] {0xFFFFFF};
};
}
/** {@code tag} styled for the player {@code id}, or {@code tag} itself where the server colored it. */
static Component style(UUID id, Component tag, Cosmetic style) {
Styled last = LAST.get(id);
if (last != null && last.style().equals(style) && last.from().equals(tag)) {
return last.to();
}
Component styled = colored(tag) ? tag : styled(tag.getString(), style);
LAST.put(id, new Styled(tag, style, styled));
return styled;
}
/** {@code name} in {@code style}: for the wardrobe's preview and cards, too. */
public static Component styled(String name, Cosmetic style) {
int[] colors = colors(style);
if (colors.length == 1 || name.length() < 2) {
return Component.literal(name).withColor(colors[0]);
}
MutableComponent out = Component.empty();
int last = name.length() - 1;
for (int i = 0; i < name.length(); i++) {
int color = CosmeticArt.mix(colors[0], colors[1], i / (float) last);
out.append(Component.literal(String.valueOf(name.charAt(i))).withColor(color));
}
return out;
}
/** Whether any part of {@code tag} has a color of the server's. */
private static boolean colored(Component tag) {
Optional<Boolean> found = tag.visit(
(Style style, String text) ->
style.getColor() != null && !text.isEmpty() ? Optional.of(Boolean.TRUE) : Optional.empty(),
Style.EMPTY);
return found.isPresent();
}
/** Players who left, forgotten (on leaving a world). */
static void clear() {
LAST.clear();
}
}
@@ -0,0 +1,155 @@
package incari.client.cosmetics;
import incari.client.skins.OwnSkin;
import incari.client.startup.DeferredModels;
import incari.online.Cosmetic;
import incari.online.Loadout;
import java.util.UUID;
import java.util.function.Supplier;
import net.minecraft.client.gui.ComponentPath;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.gui.components.AbstractWidget;
import net.minecraft.client.gui.narration.NarrationElementOutput;
import net.minecraft.client.gui.navigation.FocusNavigationEvent;
import net.minecraft.client.input.MouseButtonEvent;
import net.minecraft.client.renderer.entity.state.AvatarRenderState;
import net.minecraft.network.chat.Component;
import net.minecraft.util.Util;
import org.joml.Quaternionf;
import org.joml.Vector3f;
import org.jspecify.annotations.Nullable;
/**
* The player in 3D wearing a loadout (ADR 0061), drawn by the game's own player renderer with every
* layer, so what shows here is what others see: the Wardrobe's preview, and the title screen's
* player while they wear something. Dragged to turn; left alone, it turns to show what was picked
* last (the back for a cape or wings, the front otherwise).
*
* <p>Render thread. The game draws one 3D picture of this kind a frame, so a screen has one of these.
*/
public final class PlayerPreview extends AbstractWidget {
/** Blocks of height the widget's height holds: a player is 1.8, a halo or wings stand above. */
private static final float BLOCKS = 2.6F;
/** Turned to show the front, a little from the side. */
private static final float FRONT = -28;
/** Turned to show the back: a cape, wings. */
private static final float BACK = 152;
/** A stand-in id: the preview's name tag is styled by name, not looked up by player. */
private static final UUID PREVIEW = new UUID(0, 0);
private final Supplier<Loadout> loadout;
private final long start = Util.getMillis();
private float yaw = FRONT;
private float targetYaw = FRONT;
private long draggedAt = -1;
private @Nullable Cosmetic emote;
private float emoteStart;
private Worn worn = Worn.NONE;
private @Nullable Loadout wornFor;
private @Nullable Cosmetic wornEmote;
public PlayerPreview(int x, int y, int width, int height, Supplier<Loadout> loadout) {
super(x, y, width, height, Component.literal("Preview"));
this.loadout = loadout;
}
/** Turns to show {@code cosmetic} best: capes and wings from behind, the rest from the front. */
public void show(Cosmetic cosmetic) {
show(cosmetic.slot());
}
/** Turns to show {@code slot} best; the first time, at once. */
public void show(Cosmetic.Slot slot) {
targetYaw = slot == Cosmetic.Slot.CAPE || slot == Cosmetic.Slot.BACK ? BACK : FRONT;
draggedAt = -1;
}
/** Stands turned as {@link #show} would, without turning there. */
public void face(Cosmetic.Slot slot) {
show(slot);
yaw = targetYaw;
}
/** Plays {@code emote} now, from the front. */
public void play(Cosmetic emote) {
this.emote = emote;
this.emoteStart = ticks();
targetYaw = FRONT;
draggedAt = -1;
}
private float ticks() {
return (Util.getMillis() - start) / 50.0F;
}
@Override
@SuppressWarnings("ReferenceEquality") // the same loadout object, not an equal one
protected void extractWidgetRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
// The player renderer comes with the entity models, just after the title screen shows.
if (!DeferredModels.ready()) {
return;
}
float age = ticks();
Cosmetic playing = emote;
if (playing != null && age - emoteStart >= Emotes.duration(playing)) {
emote = null;
playing = null;
}
Loadout now = loadout.get();
if (now != wornFor || playing != wornEmote) {
wornFor = now;
wornEmote = playing;
worn = new Worn(now, playing, emoteStart);
}
if (draggedAt < 0 || Util.getMillis() - draggedAt > 4_000) {
yaw += (targetYaw - yaw) * 0.12F;
}
AvatarRenderState state = new AvatarRenderState();
state.skin = OwnSkin.shared().playerSkin();
state.ageInTicks = age;
state.bodyRot = 180 + yaw;
state.yRot = 0;
state.xRot = 0;
state.boundingBoxWidth = 0.6F;
state.boundingBoxHeight = 1.8F;
state.scale = 1;
state.capeLean = 6;
state.outlineColor = 0;
Cosmetics.dress(state, worn, PREVIEW);
float scale = getHeight() / BLOCKS;
Quaternionf rotation = new Quaternionf().rotateZ((float) Math.PI);
Quaternionf tilt = new Quaternionf().rotateX(-0.12F);
rotation.mul(tilt);
// Centered on the middle of what's shown: from the feet to a halo's top.
graphics.entity(
state, scale, new Vector3f(0, 1.12F, 0), rotation, tilt, getX(), getY(), getRight(), getBottom());
}
@Override
public void onClick(MouseButtonEvent event, boolean doubleClick) {
draggedAt = Util.getMillis();
}
@Override
protected void onDrag(MouseButtonEvent event, double dx, double dy) {
yaw -= (float) dx * 2.5F;
targetYaw = yaw;
draggedAt = Util.getMillis();
}
@Override
protected void updateWidgetNarration(NarrationElementOutput output) {
defaultButtonNarrationText(output);
}
@Override
public @Nullable ComponentPath nextFocusPath(FocusNavigationEvent navigationEvent) {
// For the pointer: turned by dragging.
return null;
}
}
@@ -0,0 +1,779 @@
package incari.client.cosmetics;
import incari.client.IncariKeys;
import incari.client.online.AccountScreen;
import incari.client.online.IncariOnline;
import incari.client.profile.PlayerName;
import incari.client.ui.Icons;
import incari.client.ui.Panels;
import incari.client.ui.RoundRects;
import incari.client.ui.ScreenPanels;
import incari.client.ui.Theme;
import incari.client.ui.Ui;
import incari.framework.online.Online;
import incari.online.Catalog;
import incari.online.Cosmetic;
import incari.online.Loadout;
import incari.online.OnlineService;
import incari.online.Wardrobe;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.gui.components.AbstractButton;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.EditBox;
import net.minecraft.client.gui.narration.NarrationElementOutput;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.input.InputWithModifiers;
import net.minecraft.client.input.MouseButtonEvent;
import net.minecraft.client.renderer.RenderPipelines;
import net.minecraft.network.chat.CommonComponents;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.Identifier;
import net.minecraft.util.ARGB;
import net.minecraft.util.FormattedCharSequence;
import org.jspecify.annotations.Nullable;
/**
* The Wardrobe (ADR 0061): the player's cosmetics, laid out as the module menu is. Kinds down the
* left (Capes, Hats, Wings & Back, Name Tags, Trails, Emotes, Outfits), a grid of cards in the
* middle, and the player on the right wearing what's picked. Pointing at a card tries it on; a
* click puts it on, and a click on what's worn (or on None) takes it off. Emotes play on the
* preview. Outfits are what's worn saved under a name, put on again in a click.
*
* <p>Under the preview: whether other Incari players see what's worn (signed in) or only the player
* does (with Sign In beside it), and the switch that hides other players' cosmetics for anyone who
* finds them distracting.
*
* <p>Opened from the title screen's player card and the pause menu. Changes are made at once and
* reach the service a moment later ({@link Wardrobe}).
*/
public final class WardrobeScreen extends Screen {
private static final int SIDEBAR = 104;
private static final int PREVIEW = 128;
private static final int PADDING = 10;
private static final int ENTRY = 16;
private static final int CARD_WIDTH = 64;
private static final int CARD_HEIGHT = 74;
private static final int GAP = 6;
private static final int SCROLL_STEP = 24;
private static final String[] LETTERS = {"W", "A", "R", "D", "R", "O", "B", "E"};
/** A kind of cosmetic down the left, and Outfits. */
private enum Tab {
CAPES(Cosmetic.Slot.CAPE),
HATS(Cosmetic.Slot.HAT),
BACK(Cosmetic.Slot.BACK),
NAMETAGS(Cosmetic.Slot.NAMETAG),
TRAILS(Cosmetic.Slot.TRAIL),
EMOTES(Cosmetic.Slot.EMOTE),
OUTFITS(null);
final Cosmetic.@Nullable Slot slot;
Tab(Cosmetic.@Nullable Slot slot) {
this.slot = slot;
}
String label() {
return slot == null ? "Outfits" : slot.label();
}
}
/** The tab shown last, shown again next time. */
private static Tab lastTab = Tab.CAPES;
private final @Nullable Screen parent;
private final OnlineService online = IncariOnline.service();
private final Wardrobe wardrobe = online.wardrobe();
private final List<Card> cards = new ArrayList<>();
private Tab tab = lastTab;
private double scroll;
private int panelX;
private int panelY;
private int panelWidth;
private int panelHeight;
private int gridX;
private int gridY;
private int gridWidth;
private int gridHeight;
private int contentHeight;
private int previewX;
/** The preview's width: {@link #PREVIEW}, less on a narrow screen so a card still fits beside. */
private int previewWidth = PREVIEW;
private @Nullable PlayerPreview preview;
private @Nullable Button signIn;
private @Nullable EditBox outfitName;
/** What the pointer is on, tried on in the preview: a card's loadout. */
private @Nullable Loadout tryOn;
private @Nullable Component notice;
public WardrobeScreen(@Nullable Screen parent) {
super(Component.literal("Wardrobe"));
this.parent = parent;
}
/** The Wardrobe open on {@code slot}'s kind, or on Outfits for null (the smoke test's screenshots). */
public static WardrobeScreen showing(@Nullable Screen parent, Cosmetic.@Nullable Slot slot) {
WardrobeScreen screen = new WardrobeScreen(parent);
for (Tab each : Tab.values()) {
if (each.slot == slot) {
screen.tab = each;
}
}
return screen;
}
@Override
protected void init() {
panelWidth = Math.min(width - 24, 560);
panelHeight = Math.min(height - 20, 300);
panelX = (width - panelWidth) / 2;
panelY = (height - panelHeight) / 2;
ScreenPanels.clear(this);
ScreenPanels.add(this, panelX, panelY, panelWidth, panelHeight);
// The kinds, down the left.
int x = panelX + 8;
int entryWidth = SIDEBAR - 16;
int y = panelY + 34;
for (Tab each : Tab.values()) {
addRenderableWidget(new Entry(Component.literal(each.label()), count(each), x, y, entryWidth, each));
y += ENTRY + 2;
}
Button done = Ui.button(CommonComponents.GUI_DONE, entryWidth, this::onClose);
done.setPosition(x, panelY + panelHeight - 8 - Theme.CONTROL_HEIGHT);
addRenderableWidget(done);
// The player, on the right, with whether others see it and the switch for others' below.
previewWidth = Math.clamp(panelWidth - SIDEBAR - 2 * PADDING - 2 * CARD_WIDTH - GAP, 88, PREVIEW);
previewX = panelX + panelWidth - PADDING - previewWidth;
int previewTop = panelY + PADDING + 14;
int previewHeight = panelHeight - PADDING - 14 - 64;
PlayerPreview player =
new PlayerPreview(previewX + 8, previewTop, previewWidth - 16, previewHeight, this::shown);
Cosmetic.Slot facing = tab.slot;
if (facing != null) {
player.face(facing);
}
preview = player;
addRenderableWidget(player);
int belowY = previewTop + previewHeight + 4;
Button signInButton = Ui.button(Component.literal("Sign In"), previewWidth, () -> {
if (minecraft != null) {
minecraft.gui.setScreen(new AccountScreen(this));
}
});
signInButton.setPosition(previewX, belowY + 12);
signInButton.setTooltip(Ui.tooltip("Sign in so other Incari players can see your cosmetics"));
signIn = signInButton;
addRenderableWidget(signInButton);
addRenderableWidget(new OthersSwitch(previewX, panelY + panelHeight - 8 - 14, previewWidth));
gridX = panelX + SIDEBAR + PADDING;
gridWidth = previewX - PADDING - gridX;
gridY = panelY + PADDING + 14;
outfitName = null;
if (tab == Tab.OUTFITS) {
int saveWidth = 70;
// A grid too narrow for both side by side puts Save under the name.
boolean stacked = gridWidth < saveWidth + Theme.GAP + 80;
int nameWidth = stacked ? gridWidth : gridWidth - saveWidth - Theme.GAP;
EditBox name = Ui.textField(font, Component.literal("Outfit name"), nameWidth, 24);
name.setMaxLength(Wardrobe.MAX_OUTFIT_NAME);
name.setHint(Component.literal(Ui.fit(font, "Name this outfit", nameWidth - 8)));
name.setPosition(gridX, gridY);
addRenderableWidget(name);
outfitName = name;
if (stacked) {
gridY += Theme.CONTROL_HEIGHT + Theme.GAP;
}
Button save = Ui.button(Component.literal("Save"), stacked ? gridWidth : saveWidth, this::saveOutfit);
save.setPosition(stacked ? gridX : gridX + gridWidth - saveWidth, gridY);
save.setTooltip(Ui.tooltip("Save what you're wearing as an outfit"));
addRenderableWidget(save);
gridY += Theme.CONTROL_HEIGHT + PADDING;
}
gridHeight = panelY + panelHeight - PADDING - gridY;
cards.clear();
if (tab == Tab.OUTFITS) {
cards.add(new Card(null, null, null));
for (Wardrobe.Outfit outfit : wardrobe.outfits()) {
cards.add(new Card(null, null, outfit));
}
} else {
Cosmetic.Slot slot = tab.slot;
if (slot != null) {
if (slot.worn()) {
cards.add(new Card(null, slot, null));
}
for (Cosmetic each : Catalog.inSlot(slot)) {
cards.add(new Card(each, slot, null));
}
}
}
for (Card card : cards) {
// Drawn by this screen inside the grid's clip, not with the other widgets.
addWidget(card);
}
layOutCards();
}
private String count(Tab each) {
if (each.slot == null) {
return String.valueOf(wardrobe.outfits().size());
}
int owned = 0;
for (Cosmetic cosmetic : Catalog.inSlot(each.slot)) {
if (wardrobe.owns(cosmetic)) {
owned++;
}
}
return String.valueOf(owned);
}
private void choose(Tab chosen) {
tab = chosen;
lastTab = chosen;
scroll = 0;
notice = null;
rebuildWidgets();
}
private void layOutCards() {
int columns = Math.max(1, (gridWidth + GAP) / (CARD_WIDTH + GAP));
int cardWidth = (gridWidth - (columns - 1) * GAP) / columns;
int shown = 0;
for (Card card : cards) {
int column = shown % columns;
int row = shown / columns;
card.setRectangle(
cardWidth,
CARD_HEIGHT,
gridX + column * (cardWidth + GAP),
gridY + row * (CARD_HEIGHT + GAP) - (int) scroll);
shown++;
}
int rows = (shown + columns - 1) / columns;
contentHeight = Math.max(0, rows * (CARD_HEIGHT + GAP) - GAP);
double max = Math.max(0, contentHeight - gridHeight);
if (scroll > max) {
scroll = max;
layOutCards();
}
}
/** What the preview wears: what the pointer is on, or what's worn. */
private Loadout shown() {
Loadout trying = tryOn;
return trying != null ? trying : wardrobe.worn();
}
private void saveOutfit() {
EditBox name = outfitName;
String typed = name == null ? "" : name.getValue();
if (wardrobe.saveOutfit(typed)) {
notice = Component.literal("Outfit saved.");
rebuildWidgets();
} else {
notice = Component.literal("No room for more outfits. Delete one first.")
.withStyle(style -> style.withColor(Theme.WARNING));
}
}
@Override
public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) {
if (mouseX >= gridX && mouseX < gridX + gridWidth && mouseY >= gridY && mouseY < gridY + gridHeight) {
scroll = Math.max(0, Math.min(Math.max(0, contentHeight - gridHeight), scroll - scrollY * SCROLL_STEP));
layOutCards();
return true;
}
return super.mouseScrolled(mouseX, mouseY, scrollX, scrollY);
}
@Override
public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
// Whatever the pointer is on is tried on.
tryOn = null;
for (Card card : cards) {
if (card.isMouseOver(mouseX, mouseY)) {
tryOn = card.tryOn();
}
}
Button signInButton = signIn;
if (signInButton != null) {
signInButton.visible = !wardrobe.shared() && online.status() == Online.Status.SIGNED_OUT;
}
// The sidebar's mark, and the lines between the columns.
Icons.HANGER.draw(graphics, panelX + 10, panelY + 10, 13, Theme.TEXT);
int letterX = panelX + 28;
for (String letter : LETTERS) {
graphics.text(font, letter, letterX, panelY + 14, Theme.TEXT, false);
letterX += font.width(letter) + 2;
}
graphics.fill(panelX + SIDEBAR, panelY + 8, panelX + SIDEBAR + 1, panelY + panelHeight - 8, 0x1AFFFFFF);
graphics.fill(previewX - 5, panelY + 8, previewX - 4, panelY + panelHeight - 8, 0x1AFFFFFF);
// The grid's heading: the kind, and a hint for the ones that need one.
if (tab != Tab.OUTFITS) {
String label = tab.label();
graphics.text(font, label, gridX, panelY + PADDING, Theme.TEXT, false);
// Cut on a narrow grid rather than run into the label.
String hint = Ui.fit(font, hint(), gridWidth - font.width(label) - 8);
graphics.text(font, hint, gridX + gridWidth - font.width(hint), panelY + PADDING, Theme.MUTED, false);
}
// The name over the preview, in the name tag cosmetic if one's shown.
Cosmetic nametag = shown().in(Cosmetic.Slot.NAMETAG);
String name = PlayerName.name();
Component styled = nametag == null ? Component.literal(name) : NameTags.styled(name, nametag);
FormattedCharSequence label = Ui.fit(font, styled, previewWidth - 6);
int labelWidth = font.width(label);
int labelX = previewX + (previewWidth - labelWidth) / 2;
int labelY = panelY + PADDING;
graphics.fill(labelX - 3, labelY - 2, labelX + labelWidth + 2, labelY + 9, 0x40000000);
graphics.text(font, label, labelX, labelY, 0xFFFFFFFF, false);
super.extractRenderState(graphics, mouseX, mouseY, a);
// Who sees what's worn.
PlayerPreview player = preview;
int statusY = player == null ? panelY : player.getBottom() + 4;
boolean shared = wardrobe.shared();
String status = Ui.fit(font, shared ? "Incari players see these" : "Only you see these", previewWidth - 12);
int statusWidth = font.width(status) + 12;
int statusX = previewX + (previewWidth - statusWidth) / 2;
(shared ? Icons.CHECK : Icons.EYE).draw(graphics, statusX, statusY, 9, shared ? Theme.POSITIVE : Theme.MUTED);
graphics.text(font, status, statusX + 12, statusY + 1, shared ? Theme.POSITIVE : Theme.MUTED, false);
graphics.enableScissor(gridX - 6, gridY, gridX + gridWidth + 6, gridY + gridHeight);
for (Card card : cards) {
if (card.getBottom() > gridY && card.getY() < gridY + gridHeight) {
card.extractRenderState(graphics, mouseX, mouseY, a);
}
}
graphics.disableScissor();
if (tab == Tab.OUTFITS && cards.size() <= 1) {
int lineY = gridY + CARD_HEIGHT + 16;
for (FormattedCharSequence line :
Ui.wrap(font, "Put on what you like, name it above and press Save.", gridWidth, 3)) {
graphics.centeredText(font, line, gridX + gridWidth / 2, lineY, Theme.MUTED);
lineY += font.lineHeight + 1;
}
}
Component shownNotice = notice;
if (shownNotice != null) {
graphics.text(
font,
Component.literal(Ui.fit(font, shownNotice.getString(), gridWidth))
.withStyle(shownNotice.getStyle()),
gridX,
panelY + panelHeight - PADDING + 1,
Theme.MUTED,
false);
}
if (contentHeight > gridHeight) {
int thumb = Math.max(16, gridHeight * gridHeight / contentHeight);
int top = gridY + (int) ((gridHeight - thumb) * scroll / (contentHeight - gridHeight));
RoundRects.fill(graphics, gridX + gridWidth + 3, top, 2, thumb, 1, 0x80FFFFFF);
}
}
private String hint() {
return switch (tab) {
case EMOTES ->
"In a world, hold "
+ IncariKeys.EMOTE_WHEEL.getTranslatedKeyMessage().getString();
case NAMETAGS -> "Unless the server colors names";
case HATS -> "Hidden under a helmet";
case BACK -> "Hidden under an elytra";
default -> "";
};
}
@Override
public void onClose() {
if (minecraft != null) {
minecraft.gui.setScreen(parent);
}
}
@Override
public boolean isPauseScreen() {
return true;
}
/** A line in the sidebar: one kind of cosmetic, with how many the player has. */
private final class Entry extends AbstractButton {
private final String value;
private final Tab target;
Entry(Component label, String value, int x, int y, int width, Tab target) {
super(x, y, width, ENTRY, label);
this.value = value;
this.target = target;
}
@Override
public void onPress(InputWithModifiers input) {
choose(target);
}
@Override
protected void extractContents(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
boolean on = tab == target;
if (on || isHoveredOrFocused()) {
RoundRects.fill(
graphics,
getX(),
getY(),
getWidth(),
getHeight(),
Theme.RADIUS,
on ? Theme.BUTTON_HOT : Theme.BUTTON);
}
if (on) {
RoundRects.fill(graphics, getX(), getY() + 4, 2, getHeight() - 8, 1, Theme.ACCENT);
}
int textY = getY() + (getHeight() - 7) / 2;
graphics.text(font, getMessage(), getX() + 7, textY, on ? Theme.TEXT : Theme.MUTED, false);
graphics.text(font, value, getRight() - 6 - font.width(value), textY, Theme.MUTED, false);
}
@Override
protected void updateWidgetNarration(NarrationElementOutput output) {
defaultButtonNarrationText(output);
}
}
/** The switch for other players' cosmetics. */
private final class OthersSwitch extends AbstractButton {
OthersSwitch(int x, int y, int width) {
super(x, y, width, 12, Component.literal("Show others' cosmetics"));
setTooltip(Ui.tooltip("Off hides other players' capes, hats, wings, trails and emotes. Yours still show."));
}
@Override
public void onPress(InputWithModifiers input) {
wardrobe.setShowOthers(!wardrobe.showOthers());
}
@Override
protected void extractContents(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
boolean on = wardrobe.showOthers();
// Cut short of the switch beside a narrow preview; the tooltip says what it does.
graphics.text(
font,
Ui.fit(font, getMessage(), getWidth() - Panels.SWITCH_WIDTH - 4),
getX(),
getY() + 2,
isHoveredOrFocused() ? Theme.TEXT : Theme.MUTED,
false);
Panels.toggle(graphics, getRight() - Panels.SWITCH_WIDTH, getY() + 1, on, 1.0F);
}
@Override
protected void updateWidgetNarration(NarrationElementOutput output) {
defaultButtonNarrationText(output);
}
}
/**
* A card: a cosmetic, None for a kind (takes it off), an outfit, or, on the Outfits tab with
* neither, Take Off All.
*/
private final class Card extends AbstractButton {
private static final int TRASH = 9;
private final @Nullable Cosmetic cosmetic;
private final Cosmetic.@Nullable Slot slot;
private final Wardrobe.@Nullable Outfit outfit;
private @Nullable Loadout tried;
private @Nullable Loadout triedFrom;
Card(@Nullable Cosmetic cosmetic, Cosmetic.@Nullable Slot slot, Wardrobe.@Nullable Outfit outfit) {
super(0, 0, CARD_WIDTH, CARD_HEIGHT, label(cosmetic, outfit, slot));
this.cosmetic = cosmetic;
this.slot = slot;
this.outfit = outfit;
}
private static Component label(
@Nullable Cosmetic cosmetic, Wardrobe.@Nullable Outfit outfit, Cosmetic.@Nullable Slot slot) {
if (cosmetic != null) {
return Component.literal(cosmetic.name());
}
if (outfit != null) {
return Component.literal(outfit.name());
}
return Component.literal(slot == null ? "Take Off All" : "None");
}
/** What the preview wears while the pointer's here. */
@SuppressWarnings("ReferenceEquality") // the same loadout object, not an equal one
@Nullable
Loadout tryOn() {
Loadout worn = wardrobe.worn();
if (tried != null && triedFrom == worn) {
return tried;
}
Loadout next;
if (cosmetic != null) {
next = cosmetic.slot().worn() && wardrobe.owns(cosmetic) ? worn.with(cosmetic) : null;
} else if (outfit != null) {
next = outfit.loadout();
} else if (slot != null) {
next = worn.without(slot);
} else {
next = Loadout.EMPTY;
}
tried = next;
triedFrom = worn;
return next;
}
private boolean worn() {
Loadout worn = wardrobe.worn();
if (cosmetic != null) {
return worn.wears(cosmetic);
}
if (outfit != null) {
return worn.equals(outfit.loadout());
}
return slot != null && slot.worn() && worn.in(slot) == null;
}
@Override
public void onPress(InputWithModifiers input) {
press(false);
}
@Override
public void onClick(MouseButtonEvent event, boolean doubleClick) {
press(outfit != null && overTrash(event.x(), event.y()));
}
private void press(boolean trash) {
PlayerPreview player = preview;
Wardrobe.Outfit saved = outfit;
if (saved != null) {
if (trash) {
wardrobe.deleteOutfit(saved);
notice = Component.literal("Deleted " + saved.name() + ".");
rebuildWidgets();
} else {
wardrobe.wear(saved.loadout());
}
return;
}
Cosmetic picked = cosmetic;
if (picked == null) {
if (slot != null) {
wardrobe.takeOff(slot);
} else {
wardrobe.wear(Loadout.EMPTY);
}
return;
}
if (!wardrobe.owns(picked)) {
return;
}
if (picked.slot() == Cosmetic.Slot.EMOTE) {
if (player != null) {
player.play(picked);
}
return;
}
if (wardrobe.worn().wears(picked)) {
wardrobe.takeOff(picked.slot());
} else {
wardrobe.wear(picked);
if (player != null) {
player.show(picked);
}
}
}
private boolean overTrash(double x, double y) {
return x >= getRight() - 5 - TRASH - 2 && y <= getY() + 5 + TRASH + 2;
}
@Override
public boolean isMouseOver(double mouseX, double mouseY) {
return super.isMouseOver(mouseX, mouseY) && mouseY >= gridY && mouseY < gridY + gridHeight;
}
@Override
protected void extractContents(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
boolean on = worn();
boolean owned = cosmetic == null || wardrobe.owns(cosmetic);
Panels.card(
graphics, getX(), getY(), getWidth(), getHeight(), isHoveredOrFocused(), on, owned ? 1.0F : 0.5F);
int artX = getX() + getWidth() / 2;
int artY = getY() + 6;
picture(graphics, artX, artY);
// An outfit's name can be 24 characters: cut to the card, not into the next one.
String message = Ui.fit(font, getMessage().getString(), getWidth() - 8);
int textWidth = font.width(message);
int textX = getX() + Math.max(4, (getWidth() - textWidth) / 2);
graphics.text(font, message, textX, getBottom() - 14, owned ? Theme.TEXT : Theme.MUTED, false);
if (on) {
Icons.CHECK.draw(graphics, getRight() - 13, getY() + 5, 8, Theme.ACCENT);
}
if (outfit != null && isHovered()) {
boolean hot = overTrash(mouseX, mouseY);
Icons.TRASH.draw(
graphics, getRight() - 5 - TRASH, getY() + 5, TRASH, hot ? Theme.NEGATIVE : Theme.MUTED);
}
if (!owned) {
graphics.text(font, "Locked", getX() + 5, getY() + 5, Theme.MUTED, false);
}
}
/** The card's picture, 44 tall, centered on {@code x}. */
private void picture(GuiGraphicsExtractor graphics, int x, int y) {
Cosmetic shown = cosmetic;
if (shown == null) {
if (outfit != null) {
outfitPicture(graphics, x, y, outfit.loadout());
} else {
Icons.CLOSE.draw(graphics, x - 8, y + 14, 16, Theme.MUTED);
}
return;
}
switch (shown.slot()) {
case CAPE -> {
// The cape's outer side, as it hangs: 10x16 pixels at twice the size.
Identifier texture = CosmeticTextures.capeId(shown);
graphics.blit(
RenderPipelines.GUI_TEXTURED,
texture,
x - 13,
y + 1,
1,
1,
26,
42,
10,
16,
CosmeticArt.CAPE_WIDTH,
CosmeticArt.CAPE_HEIGHT);
}
case HAT, BACK -> {
Identifier icon = CosmeticTextures.icon(shown);
if (icon != null) {
graphics.blit(
RenderPipelines.GUI_TEXTURED,
icon,
x - 18,
y + 4,
0,
0,
36,
36,
CosmeticArt.ICON,
CosmeticArt.ICON,
CosmeticArt.ICON,
CosmeticArt.ICON);
}
}
case NAMETAG -> {
Component name = NameTags.styled(PlayerName.name(), shown);
int nameWidth = Math.min(getWidth() - 8, font.width(name));
graphics.fill(x - nameWidth / 2 - 3, y + 15, x + nameWidth / 2 + 3, y + 27, 0x60000000);
graphics.enableScissor(getX() + 3, y, getRight() - 3, y + 40);
graphics.text(font, name, x - font.width(name) / 2, y + 17, 0xFFFFFFFF, false);
graphics.disableScissor();
}
case TRAIL -> trailPicture(graphics, x, y, shown);
case EMOTE -> Icons.PERSON.draw(graphics, x - 12, y + 8, 24, Theme.TEXT);
}
}
private void trailPicture(GuiGraphicsExtractor graphics, int x, int y, Cosmetic trail) {
int[] colors =
switch (trail.id()) {
case "trail.hearts" -> new int[] {0xFFFF5A7A, 0xFFFF8FA6};
case "trail.sparkles" -> new int[] {0xFFFFF4C2, 0xFFFFFFFF};
case "trail.notes" -> new int[] {0xFF6AF2B0, 0xFFA06CFF, 0xFFFFD36A};
default -> new int[] {0xFFFFFFFF, 0xFFA9DCFF};
};
// Dots drifting up from the bottom left, bigger toward the start.
for (int i = 0; i < 7; i++) {
int dotX = x - 16 + i * 5;
int dotY = y + 34 - i * 4 - (i % 2) * 3;
int size = Math.max(2, 6 - i / 2);
RoundRects.fill(graphics, dotX, dotY, size, size, size / 2, colors[i % colors.length]);
}
}
private void outfitPicture(GuiGraphicsExtractor graphics, int x, int y, Loadout loadout) {
// Up to four of what the outfit wears, small, in a row.
List<Cosmetic> worn = new ArrayList<>();
for (Cosmetic.Slot each : Cosmetic.Slot.values()) {
Cosmetic in = loadout.in(each);
if (in != null && worn.size() < 4) {
worn.add(in);
}
}
if (worn.isEmpty()) {
Icons.HANGER.draw(graphics, x - 10, y + 12, 20, Theme.MUTED);
return;
}
int each = 14;
int startX = x - (worn.size() * (each + 2)) / 2;
for (int i = 0; i < worn.size(); i++) {
Cosmetic c = worn.get(i);
int cx = startX + i * (each + 2);
Identifier icon = c.slot() == Cosmetic.Slot.CAPE ? null : CosmeticTextures.icon(c);
if (c.slot() == Cosmetic.Slot.CAPE) {
graphics.blit(
RenderPipelines.GUI_TEXTURED,
CosmeticTextures.capeId(c),
cx + 2,
y + 10,
1,
1,
10,
16,
10,
16,
CosmeticArt.CAPE_WIDTH,
CosmeticArt.CAPE_HEIGHT);
} else if (icon != null) {
graphics.blit(
RenderPipelines.GUI_TEXTURED,
icon,
cx,
y + 12,
0,
0,
each,
each,
CosmeticArt.ICON,
CosmeticArt.ICON,
CosmeticArt.ICON,
CosmeticArt.ICON);
} else {
int color = c.slot() == Cosmetic.Slot.NAMETAG ? 0xFF000000 | NameTags.colors(c)[0] : Theme.MUTED;
RoundRects.fill(graphics, cx + 3, y + 15, 8, 8, 4, ARGB.opaque(color));
}
}
}
@Override
protected void updateWidgetNarration(NarrationElementOutput output) {
defaultButtonNarrationText(output);
}
}
}
@@ -0,0 +1,43 @@
package incari.client.cosmetics;
import incari.online.Cosmetic;
import incari.online.Loadout;
import org.jspecify.annotations.Nullable;
/**
* What one player shows, as their render state carries it (ADR 0061): what they wear, and the emote
* they're playing, if any. Made when that changes, not each frame.
*
* <p>Immutable; render thread.
*/
public final class Worn {
/** Nothing: what every player the client draws no cosmetics for carries. */
public static final Worn NONE = new Worn(Loadout.EMPTY, null, 0);
final Loadout loadout;
final @Nullable Cosmetic cape;
final @Nullable Cosmetic hat;
final @Nullable Cosmetic back;
final @Nullable Cosmetic nametag;
final @Nullable Cosmetic trail;
final @Nullable Cosmetic emote;
/** When the emote started, in the player's own ticks ({@code ageInTicks}). */
final float emoteStart;
Worn(Loadout loadout, @Nullable Cosmetic emote, float emoteStart) {
this.loadout = loadout;
this.cape = loadout.in(Cosmetic.Slot.CAPE);
this.hat = loadout.in(Cosmetic.Slot.HAT);
this.back = loadout.in(Cosmetic.Slot.BACK);
this.nametag = loadout.in(Cosmetic.Slot.NAMETAG);
this.trail = loadout.in(Cosmetic.Slot.TRAIL);
this.emote = emote;
this.emoteStart = emoteStart;
}
/** Whether there's nothing to show. */
boolean isEmpty() {
return loadout.isEmpty() && emote == null;
}
}
@@ -0,0 +1,9 @@
/**
* Cosmetics (ADR 0061): what players wear and play, drawn on them, the Wardrobe screen that picks
* it, and the emote wheel. What's owned and worn is kept by {@code :online}'s wardrobe and the
* online service; this draws it.
*/
@NullMarked
package incari.client.cosmetics;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,23 @@
package incari.client.credits;
import java.net.URI;
import org.jspecify.annotations.Nullable;
/**
* One entry on the credits screen: a piece of software in this build, under its own license.
*
* @param name what the software is called
* @param version the version in this build, shown after the name; null when it isn't known here
* @param authors who holds its copyright
* @param license the license's short name, as SPDX names it where it can
* @param licenseText where the license's full text is
* @param source where its source code is
*/
public record Credit(
String name, @Nullable String version, String authors, String license, URI licenseText, URI source) {
/** The name with the version after it, if there is one. */
public String title() {
return version == null ? name : name + " " + version;
}
}
@@ -0,0 +1,130 @@
package incari.client.credits;
import com.viaversion.viaversion.util.VersionInfo;
import incari.client.IncariBuild;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
/**
* What the credits screen lists: Incari and the third-party software it adds to the game, in
* every build. Minecraft's own libraries are Mojang's to credit, which the vanilla screen beside
* this one does.
*
* <p>A build adds what only it contains (the browser build: TeaVM's runtime) with {@link #add},
* at start-up, before the game's first screen. Adding a library to every build means adding it to
* {@code COMMON} here.
*/
public final class Credits {
/**
* Incari's public source (incari.properties' {@code incari.repository}). GPL-3.0's source offer
* for every build points here.
*/
public static final URI INCARI_SOURCE = URI.create(IncariBuild.REPOSITORY);
/** The pause menu's Report Bugs: a new issue on the repository, from its bug template. */
public static final URI REPORT_BUGS = URI.create(IncariBuild.REPOSITORY + "/issues/new?template=bug_report.yml");
/** The pause menu's Give Feedback: a new discussion in the repository's Feedback category. */
public static final URI FEEDBACK = URI.create(IncariBuild.REPOSITORY + "/discussions/new?category=feedback");
public static final URI GPL_3 = URI.create("https://www.gnu.org/licenses/gpl-3.0.html");
public static final URI APACHE_2 = URI.create("https://www.apache.org/licenses/LICENSE-2.0");
public static final URI BSD_3_CLAUSE = URI.create("https://opensource.org/license/bsd-3-clause");
public static final URI OFL_1_1 = URI.create("https://openfontlicense.org/open-font-license-official-text/");
private static final List<Credit> COMMON = List.of(
new Credit(
"Incari Client",
null,
"The Incari Client contributors",
"GPL-3.0-or-later, with an exception for Minecraft",
URI.create(INCARI_SOURCE + "/blob/main/LICENSE-EXCEPTION.txt"),
INCARI_SOURCE),
// VERSION is a constant, so these are the versions the client was compiled against,
// which are the ones the build bundles.
new Credit(
"ViaVersion",
VersionInfo.VERSION,
"ViaVersion and contributors",
"GPL-3.0",
GPL_3,
URI.create("https://github.com/ViaVersion/ViaVersion")),
new Credit(
"ViaBackwards",
com.viaversion.viabackwards.utils.VersionInfo.VERSION,
"ViaVersion and contributors",
"GPL-3.0",
GPL_3,
URI.create("https://github.com/ViaVersion/ViaBackwards")),
// Microsoft sign-in's TLS, and the browser build's AES, RSA and chat signing (ADR 0070).
new Credit(
"Bouncy Castle",
null,
"The Legion of the Bouncy Castle Inc.",
"MIT",
URI.create("https://www.bouncycastle.org/about/license/"),
URI.create("https://github.com/bcgit/bc-java")),
// The look's fonts, in Incari's pack with their licences beside them.
new Credit(
"Red Hat Display",
null,
"The Red Hat Project Authors",
"OFL-1.1",
OFL_1_1,
URI.create("https://github.com/RedHatOfficial/RedHatFont")),
new Credit(
"Michroma",
null,
"The Michroma Project Authors",
"OFL-1.1",
OFL_1_1,
URI.create("https://github.com/googlefonts/Michroma-font")),
// A theme's other fonts, subset to Red Hat Display's characters.
new Credit(
"Inter",
null,
"The Inter Project Authors",
"OFL-1.1",
OFL_1_1,
URI.create("https://github.com/rsms/inter")),
new Credit(
"Nunito",
null,
"The Nunito Project Authors",
"OFL-1.1",
OFL_1_1,
URI.create("https://github.com/googlefonts/nunito")),
new Credit(
"Poppins",
null,
"The Poppins Project Authors",
"OFL-1.1",
OFL_1_1,
URI.create("https://github.com/itfoundry/Poppins")),
new Credit(
"JetBrains Mono",
null,
"The JetBrains Mono Project Authors",
"OFL-1.1",
OFL_1_1,
URI.create("https://github.com/JetBrains/JetBrainsMono")));
// Written at start-up, read by the screen later on the same thread.
private static final List<Credit> added = new ArrayList<>();
private Credits() {}
/** Adds software only this build contains. */
public static void add(Credit credit) {
added.add(credit);
}
/** Everything this build credits: Incari's own entries first, then what the build added. */
public static List<Credit> all() {
List<Credit> all = new ArrayList<>(COMMON);
all.addAll(added);
return List.copyOf(all);
}
}
@@ -0,0 +1,108 @@
package incari.client.credits;
import net.minecraft.ChatFormatting;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.MultiLineTextWidget;
import net.minecraft.client.gui.components.ScrollableLayout;
import net.minecraft.client.gui.components.StringWidget;
import net.minecraft.client.gui.layouts.HeaderAndFooterLayout;
import net.minecraft.client.gui.layouts.LinearLayout;
import net.minecraft.client.gui.screens.ConfirmLinkScreen;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.CommonComponents;
import net.minecraft.network.chat.Component;
import org.jspecify.annotations.Nullable;
/**
* Incari's credits and the licenses of what it adds to the game ({@link Credits}), reached from
* the vanilla Credits & Attribution screen. Each entry links to its source and its license, which
* is what GPL-3.0 asks a build to come with.
*
* <p>English only for now; Incari's screens don't have language files yet.
*/
public final class CreditsScreen extends Screen {
private static final Component TITLE = Component.literal("Incari & Open Source");
private static final Component NOTICE = Component.literal(
"Incari Client is free software that runs on Minecraft: Java Edition. It is not an official Minecraft"
+ " product, and is not approved by or associated with Mojang or Microsoft. This build contains"
+ " the software below, each under its own license.");
private static final int BODY_WIDTH = 300;
private static final int BUTTON_WIDTH = 103;
private static final int BUTTON_SPACING = 4;
private final Screen parent;
private final HeaderAndFooterLayout layout = new HeaderAndFooterLayout(this);
private @Nullable ScrollableLayout body;
public CreditsScreen(Screen parent) {
super(TITLE);
this.parent = parent;
}
/** The button that opens this screen from {@code parent}, for the vanilla screen's list. */
public static Button button(Screen parent, int width) {
return Button.builder(TITLE, button -> Minecraft.getInstance().gui.setScreen(new CreditsScreen(parent)))
.width(width)
.build();
}
@Override
protected void init() {
this.layout.addTitleHeader(TITLE, this.font);
LinearLayout content = LinearLayout.vertical().spacing(12);
content.defaultCellSetting().alignHorizontallyCenter();
content.addChild(new MultiLineTextWidget(NOTICE, this.font)
.setMaxWidth(BODY_WIDTH)
.setCentered(true));
for (Credit credit : Credits.all()) {
content.addChild(entry(credit));
}
ScrollableLayout scroll =
new ScrollableLayout(Minecraft.getInstance(), content, this.layout.getContentHeight());
body = scroll;
this.layout.addToContents(scroll);
this.layout.addToFooter(Button.builder(CommonComponents.GUI_DONE, button -> onClose())
.width(200)
.build());
this.layout.visitWidgets(this::addRenderableWidget);
repositionElements();
}
private LinearLayout entry(Credit credit) {
LinearLayout entry = LinearLayout.vertical().spacing(2);
entry.defaultCellSetting().alignHorizontallyCenter();
entry.addChild(new StringWidget(Component.literal(credit.title()), this.font));
entry.addChild(new MultiLineTextWidget(
Component.literal(credit.authors() + " · " + credit.license())
.withStyle(ChatFormatting.GRAY),
this.font)
.setMaxWidth(BODY_WIDTH)
.setCentered(true));
LinearLayout links = entry.addChild(LinearLayout.horizontal().spacing(BUTTON_SPACING));
links.addChild(Button.builder(Component.literal("Source"), ConfirmLinkScreen.confirmLink(this, credit.source()))
.width(BUTTON_WIDTH)
.build());
links.addChild(
Button.builder(Component.literal("License"), ConfirmLinkScreen.confirmLink(this, credit.licenseText()))
.width(BUTTON_WIDTH)
.build());
return entry;
}
@Override
protected void repositionElements() {
ScrollableLayout scroll = body;
if (scroll != null) {
scroll.arrangeElements();
scroll.setMaxHeight(this.layout.getContentHeight());
}
this.layout.arrangeElements();
}
@Override
public void onClose() {
Minecraft.getInstance().gui.setScreen(parent);
}
}
@@ -0,0 +1,8 @@
/**
* Incari's credits: the software a build contains beside Minecraft, each under its own license,
* and the screen that lists them.
*/
@NullMarked
package incari.client.credits;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,46 @@
package incari.client.datafix;
import com.mojang.datafixers.DSL;
import com.mojang.datafixers.DataFixer;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import net.minecraft.SharedConstants;
import net.minecraft.util.datafix.DataFixers;
/**
* Whether the game builds its data fixer at start or when it's first needed.
*
* <p>The game builds every schema since 2013's at start-up (the class initializer of
* {@code DataFixers}), optimizes the world list's types on a thread of their own, and waits for that
* before its window opens. A browser client almost never needs any of it: its options, servers and
* worlds were written by this version, and a multiplayer client upgrades nothing. Lazily, the game
* keeps a stand-in fixer that passes data already at the current version through untouched (what
* the real fixer does with it) and builds the real one the first time something older arrives: an
* imported world, an old options file.
*/
public final class DataFixing {
private static volatile boolean lazy;
private DataFixing() {}
/**
* Builds the data fixer only when it's first needed. Also turns off the game's check, at
* bootstrap, that every entity and block entity type has a schema: a development check whose
* answer is discarded, which would build the fixer to ask.
*/
public static void buildLazily() {
lazy = true;
SharedConstants.CHECK_DATA_FIXER_SCHEMA = false;
}
/** The fixer {@code Minecraft} keeps: the game's, or the stand-in that builds it on first use. */
public static DataFixer fixer() {
return lazy ? LazyDataFixer.INSTANCE : DataFixers.getDataFixer();
}
/** {@code Main}'s start-up optimization of {@code types}: none when the fixer may never be built. */
public static CompletableFuture<?> optimizeAtStart(Set<DSL.TypeReference> types) {
return lazy ? CompletableFuture.completedFuture(null) : DataFixers.optimize(types);
}
}
@@ -0,0 +1,29 @@
package incari.client.datafix;
import com.mojang.datafixers.DSL;
import com.mojang.datafixers.DataFixer;
import com.mojang.datafixers.schemas.Schema;
import com.mojang.serialization.Dynamic;
import net.minecraft.util.datafix.DataFixers;
/**
* The game's data fixer, built the first time something needs upgrading. Data already at (or
* past) the version it's being upgraded to comes back untouched, as the real fixer returns it,
* without building anything; everything else goes to the real fixer.
*/
final class LazyDataFixer implements DataFixer {
static final LazyDataFixer INSTANCE = new LazyDataFixer();
private LazyDataFixer() {}
@Override
public <T> Dynamic<T> update(DSL.TypeReference type, Dynamic<T> input, int version, int newVersion) {
return version >= newVersion ? input : DataFixers.getDataFixer().update(type, input, version, newVersion);
}
@Override
public Schema getSchema(int key) {
return DataFixers.getDataFixer().getSchema(key);
}
}
@@ -0,0 +1,5 @@
/** The game's data fixer, built only when something old needs upgrading (ADR 0025). */
@NullMarked
package incari.client.datafix;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,71 @@
package incari.client.eagler;
import incari.net.WebSocketUrl;
import incari.net.eagler.EaglerPassword;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.jspecify.annotations.Nullable;
/**
* Passwords for Eagler servers that ask for one (ADR 0019). A password is kept in memory for
* the session, by server URL, and never written to disk: servers that want the player to stay
* logged in set a cookie instead ({@link EaglerCookies}).
*
* <p>When a login fails for want of a password, the Eagler session records it here, and the
* disconnection screen asks for one ({@link PasswordScreen}) instead of showing the refusal.
*/
public final class EaglerAuth {
/** A server's request for a password, from the login that just failed. */
public record Request(String server, int method, String message) {}
private static final Object LOCK = new Object();
private static final Map<String, EaglerPassword> PASSWORDS = new HashMap<>();
private static @Nullable Request pending;
private EaglerAuth() {}
/** The password to offer {@code server}, if the player gave one this session. */
public static @Nullable EaglerPassword password(String server) {
synchronized (LOCK) {
return PASSWORDS.get(key(server));
}
}
/** Remembers the password for {@code server} for this session. */
public static void remember(String server, EaglerPassword password) {
synchronized (LOCK) {
PASSWORDS.put(key(server), password);
}
}
/** Forgets the password for {@code server}, as a new session would. */
public static void forget(String server) {
synchronized (LOCK) {
PASSWORDS.remove(key(server));
}
}
/** The Eagler session: {@code server} refused the login for want of a password. */
static void required(String server, int method, String message) {
synchronized (LOCK) {
pending = new Request(server, method, message);
}
}
/** The request the last failed login left, once; null if it wasn't a password matter. */
public static @Nullable Request takePending() {
synchronized (LOCK) {
Request request = pending;
pending = null;
return request;
}
}
/** The server's URL as the client writes it, so "ws://host:1" and "ws://HOST:1/" are one. */
private static String key(String server) {
WebSocketUrl url = WebSocketUrl.tryParse(server.trim());
return (url != null ? url.toString() : server.trim()).toLowerCase(Locale.ROOT);
}
}
@@ -0,0 +1,166 @@
package incari.client.eagler;
import com.mojang.logging.LogUtils;
import incari.net.WebSocketUrl;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
/**
* Eagler server cookies (ADR 0019): up to 255 bytes a server stores in the client, for at
* most a week, and gets back with the next login. Auth plugins use them as session tokens, so a
* player logs in once rather than every join. A server chooses whether its cookie outlives the
* session; those are kept in {@code incari/eagler-cookies.txt}, the rest in memory only.
*
* <p>A cookie goes back only to the server that set it: the key is the server's WebSocket URL.
*/
public final class EaglerCookies {
private static final Logger LOGGER = LogUtils.getLogger();
private static final String FILE = "eagler-cookies.txt";
/** The longest a server may keep a cookie, as Eagler's clients hold it to. */
private static final long MAX_SECONDS = TimeUnit.DAYS.toSeconds(7);
private static final int MAX_BYTES = 255;
/** One server's cookie: its bytes, when it expires, whether it's kept on disk. */
private static final class Cookie {
final byte[] data;
final long expiresMillis;
final boolean onDisk;
Cookie(byte[] data, long expiresMillis, boolean onDisk) {
this.data = data;
this.expiresMillis = expiresMillis;
this.onDisk = onDisk;
}
}
private static final Object LOCK = new Object();
private static @Nullable EaglerCookies instance;
private final Path file;
private final Map<String, Cookie> cookies = new HashMap<>();
private EaglerCookies(Path file) {
this.file = file;
}
/** The store for the game in {@code gameDirectory}, loaded the first time it's asked for. */
public static EaglerCookies get(Path gameDirectory) {
synchronized (LOCK) {
EaglerCookies store = instance;
if (store == null) {
store = new EaglerCookies(gameDirectory.resolve("incari").resolve(FILE));
store.load();
instance = store;
}
return store;
}
}
/** The cookie {@code server} set, if it hasn't expired. */
public byte @Nullable [] cookie(String server) {
synchronized (LOCK) {
Cookie cookie = cookies.get(key(server));
if (cookie == null) {
return null;
}
if (System.currentTimeMillis() > cookie.expiresMillis) {
cookies.remove(key(server));
if (cookie.onDisk) {
save();
}
return null;
}
return cookie.data.clone();
}
}
/**
* {@code server} sets its cookie: {@code data} for {@code seconds}, kept on disk if {@code
* onDisk}. Empty data, a negative lifetime, or one past the limits clears it instead.
*/
public void set(String server, byte[] data, long seconds, boolean onDisk) {
synchronized (LOCK) {
Cookie previous;
if (data.length == 0 || seconds < 0 || seconds > MAX_SECONDS || data.length > MAX_BYTES) {
if (seconds > MAX_SECONDS || data.length > MAX_BYTES) {
LOGGER.warn(
"{} set a cookie past Eagler's limits ({} bytes, {} s); cleared",
server,
data.length,
seconds);
}
previous = cookies.remove(key(server));
} else {
long expires = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(seconds);
previous = cookies.put(key(server), new Cookie(data.clone(), expires, onDisk));
}
if (onDisk || (previous != null && previous.onDisk)) {
save();
}
}
}
private void load() {
if (!Files.isRegularFile(file)) {
return;
}
try {
long now = System.currentTimeMillis();
for (String line : Files.readAllLines(file, StandardCharsets.UTF_8)) {
String[] parts = line.split("\t", -1);
if (parts.length != 3) {
continue;
}
long expires = Long.parseLong(parts[1]);
if (expires > now) {
cookies.put(parts[0], new Cookie(unhex(parts[2]), expires, true));
}
}
} catch (IOException | RuntimeException e) {
LOGGER.warn("Couldn't read {}: {}", file, e.toString());
}
}
private void save() {
StringBuilder text = new StringBuilder();
cookies.forEach((server, cookie) -> {
if (cookie.onDisk) {
text.append(server).append('\t').append(cookie.expiresMillis).append('\t');
for (byte b : cookie.data) {
text.append(Character.forDigit((b >> 4) & 15, 16)).append(Character.forDigit(b & 15, 16));
}
text.append('\n');
}
});
try {
Files.createDirectories(file.getParent());
Files.writeString(file, text, StandardCharsets.UTF_8);
} catch (IOException e) {
LOGGER.warn("Couldn't save {}: {}", file, e.toString());
}
}
private static byte[] unhex(String hex) {
byte[] out = new byte[hex.length() / 2];
for (int i = 0; i < out.length; i++) {
out[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
}
return out;
}
/** The server's URL as the client writes it, so "ws://host:1" and "ws://HOST:1/" are one. */
private static String key(String server) {
WebSocketUrl url = WebSocketUrl.tryParse(server.trim());
return (url != null ? url.toString() : server.trim()).toLowerCase(Locale.ROOT);
}
}
@@ -0,0 +1,107 @@
package incari.client.eagler;
import com.mojang.logging.LogUtils;
import incari.client.skins.EaglerSkins;
import incari.client.skins.OwnSkin;
import incari.net.eagler.EaglerMessages;
import incari.net.eagler.EaglerPauseMenu;
import incari.net.eagler.EaglerSession;
import io.netty.buffer.ByteBuf;
import java.nio.file.Path;
import java.util.UUID;
import net.minecraft.client.Minecraft;
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
/**
* Everything an Eagler connection the player joins does beside the game's packets:
* skins, voice, the server's cookie, its requests for a password, its redirects, and its pause menu. The
* connection's event loop calls in; each part takes what's its own.
*/
public final class EaglerJoin implements EaglerSession {
private static final Logger LOGGER = LogUtils.getLogger();
private final String server;
private final Path gameDirectory;
private final EaglerSkins skins;
private final @Nullable EaglerVoice voice;
private int capabilities;
private EaglerJoin(String server, Path gameDirectory, EaglerSkins skins, @Nullable EaglerVoice voice) {
this.server = server;
this.gameDirectory = gameDirectory;
this.skins = skins;
this.voice = voice;
}
/** The session for a join of {@code server} (its WebSocket URL). */
public static EaglerJoin start(String server) {
Path gameDirectory = Minecraft.getInstance().gameDirectory.toPath();
EaglerSkins skins = EaglerSkins.start(OwnSkin.load(gameDirectory));
return new EaglerJoin(server, gameDirectory, skins, EaglerVoice.start());
}
@Override
public void capabilities(int accepted) {
capabilities = accepted;
}
@Override
public void loggedIn(String name, UUID uuid, EaglerMessages messages) {
skins.loggedIn(name, uuid, messages);
if (voice != null) {
voice.loggedIn(uuid, messages, (capabilities & incari.net.eagler.EaglerLogin.VOICE) != 0);
}
}
@Override
public void received(int id, ByteBuf body) {
switch (id) {
case EaglerMessages.S_SET_COOKIE -> setCookie(body);
case EaglerMessages.S_REDIRECT -> ServerRedirects.redirect(EaglerMessages.readShortAscii(body));
case EaglerMessages.S_CUSTOMIZE_PAUSE_MENU -> ServerPauseMenu.received(EaglerPauseMenu.read(body));
case EaglerMessages.S_VOICE_ALLOWED,
EaglerMessages.S_VOICE_CONNECT,
EaglerMessages.S_VOICE_CONNECT_ANNOUNCE,
EaglerMessages.S_VOICE_DISCONNECT_PEER,
EaglerMessages.S_VOICE_ICE,
EaglerMessages.S_VOICE_DESCRIPTION,
EaglerMessages.S_VOICE_GLOBAL -> {
if (voice != null) {
voice.received(id, body);
}
}
default -> skins.received(id, body);
}
}
@Override
public void authenticationRequired(int method, String message) {
EaglerAuth.required(server, method, message);
}
@Override
public void redirected(String address) {
ServerRedirects.pending(address);
}
@Override
public void closed() {
skins.closed();
ServerPauseMenu.closed();
if (voice != null) {
voice.closed();
}
}
private void setCookie(ByteBuf body) {
int flags = body.readUnsignedByte();
long seconds = EaglerMessages.readVarLong(body);
byte[] data = new byte[body.readUnsignedByte()];
body.readBytes(data);
boolean onDisk = (flags & 2) != 0;
LOGGER.info("{} set a {}-byte cookie for {} s{}", server, data.length, seconds, onDisk ? ", kept on disk" : "");
EaglerCookies.get(gameDirectory).set(server, data, seconds, onDisk);
}
}
@@ -0,0 +1,32 @@
package incari.client.eagler;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.multiplayer.ServerData;
import net.minecraft.client.multiplayer.resolver.ServerAddress;
/** An Eagler login that ended in a redirect or a request for a password (ADR 0019). */
public final class EaglerJoinFailures {
private EaglerJoinFailures() {}
/**
* Follows a redirect, or asks for the password, left by the login that just failed. Returns
* false if it left neither. Render thread.
*/
public static boolean handle(Minecraft minecraft, Screen parent, ServerData server, ServerAddress address) {
String redirect = ServerRedirects.takePending();
if (redirect != null) {
EaglerAuth.takePending();
// Starting a connection replaces the screen being set up: after its init.
minecraft.execute(() -> ServerRedirects.join(minecraft, parent, redirect));
return true;
}
EaglerAuth.Request request = EaglerAuth.takePending();
if (request != null) {
minecraft.execute(() -> minecraft.gui.setScreen(new PasswordScreen(parent, server, address, request)));
return true;
}
return false;
}
}
@@ -0,0 +1,579 @@
package incari.client.eagler;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mojang.logging.LogUtils;
import incari.client.platform.ClientPlatform;
import incari.net.eagler.EaglerMessages;
import incari.platform.api.rtc.IceServer;
import incari.platform.api.rtc.Microphone;
import incari.platform.api.rtc.PlatformRtc;
import incari.platform.api.rtc.RtcPeer;
import io.netty.buffer.ByteBuf;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import net.minecraft.client.Minecraft;
import net.minecraft.client.player.AbstractClientPlayer;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.phys.Vec3;
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
/**
* Eagler voice chat on one connection (ADR 0019). The server only signals: it tells each
* client who else has voice on, pairs two clients up when one asks ({@code C_VOICE_REQUEST}), and
* relays their WebRTC offers, answers and ICE candidates. The audio goes peer to peer, through the
* platform's WebRTC ({@link PlatformRtc}), which only the browser has.
*
* <p>In the global channel every voice player is paired up; in proximity, those within range,
* whose voices then fade with distance and pan with direction. Talking is push to talk.
*
* <p>Messages arrive on the connection's event loop and are handed to the game's thread; everything
* else happens there.
*/
public final class EaglerVoice {
private static final Logger LOGGER = LogUtils.getLogger();
/** Proximity peers are asked for this much beyond the range, so they're ready before heard. */
private static final double CONNECT_MARGIN = 6.0;
/** A proximity peer out of range this long is let go. */
private static final long LINGER_MILLIS = 5000;
/** A level over this means a peer is talking. */
private static final float TALKING_LEVEL = 0.06F;
/** How long a peer still counts as talking after its last loud moment: speech has gaps. */
private static final long TALKING_HOLD_MILLIS = 600;
private static @Nullable EaglerVoice current;
private static @Nullable VoiceSettings settings;
private final PlatformRtc rtc;
private final Map<UUID, Peer> peers = new HashMap<>();
/** Everyone with voice on, from the server's list: names by UUID. */
private final Map<UUID, String> voicePlayers = new LinkedHashMap<>();
/** Peers asked for and not yet connected, so each is asked once. */
private final Set<UUID> requested = new HashSet<>();
/** When a proximity peer was last in range. */
private final Map<UUID, Long> lastInRange = new HashMap<>();
/** The players the player muted on this connection, whether paired with them now or not. */
private final Set<UUID> muted = new HashSet<>();
private @Nullable EaglerMessages messages;
private @Nullable UUID self;
private boolean capability;
private boolean serverAllows;
private List<IceServer> iceServers = List.of();
/** The channel the server was told about: OFF until connected. */
private VoiceSettings.Channel joined = VoiceSettings.Channel.OFF;
private boolean transmitting;
private EaglerVoice(PlatformRtc rtc) {
this.rtc = rtc;
}
/** Whether this platform can do voice at all. */
public static boolean supported() {
return ClientPlatform.get().rtc().supported();
}
/** Voice for a new connection, or null where there's no WebRTC. */
static @Nullable EaglerVoice start() {
if (!supported()) {
return null;
}
EaglerVoice voice = new EaglerVoice(ClientPlatform.get().rtc());
Minecraft.getInstance().execute(() -> {
EaglerVoice previous = current;
if (previous != null) {
previous.shutDown();
}
current = voice;
});
return voice;
}
/** The voice of the connection the player is on, if it has any. Game thread. */
public static @Nullable EaglerVoice current() {
return current;
}
/** The player's voice settings. Game thread. */
public static VoiceSettings settings() {
VoiceSettings loaded = settings;
if (loaded == null) {
loaded = VoiceSettings.load(Minecraft.getInstance().gameDirectory.toPath());
settings = loaded;
}
return loaded;
}
// --- The connection's event loop ---------------------------------------------------------
void loggedIn(UUID uuid, EaglerMessages sender, boolean accepted) {
Minecraft.getInstance().execute(() -> {
self = uuid;
messages = sender;
capability = accepted;
});
}
void received(int id, ByteBuf body) {
// Parsed here, where the buffer is valid; acted on, on the game's thread.
Runnable action = parse(id, body);
if (action != null) {
Minecraft.getInstance().execute(action);
}
}
void closed() {
Minecraft.getInstance().execute(() -> {
shutDown();
if (current == this) {
current = null;
}
});
}
private @Nullable Runnable parse(int id, ByteBuf body) {
return switch (id) {
case EaglerMessages.S_VOICE_ALLOWED -> {
boolean allowed = body.readBoolean();
List<IceServer> servers = new ArrayList<>();
if (allowed) {
int count = EaglerMessages.readVarInt(body);
for (int i = 0; i < count && i < 64; i++) {
IceServer server = IceServer.parseEagler(EaglerMessages.readString(body));
if (server != null) {
servers.add(server);
}
}
}
yield () -> allowed(allowed, servers);
}
case EaglerMessages.S_VOICE_CONNECT -> {
UUID peer = uuid(body);
boolean offer = body.readBoolean();
yield () -> connect(peer, offer);
}
case EaglerMessages.S_VOICE_CONNECT_ANNOUNCE -> {
UUID peer = uuid(body);
yield () -> announced(peer);
}
case EaglerMessages.S_VOICE_DISCONNECT_PEER -> {
UUID peer = uuid(body);
yield () -> close(peer, false);
}
case EaglerMessages.S_VOICE_ICE -> {
UUID peer = uuid(body);
String json = bytesText(body);
yield () -> remoteCandidate(peer, json);
}
case EaglerMessages.S_VOICE_DESCRIPTION -> {
UUID peer = uuid(body);
String json = bytesText(body);
yield () -> remoteDescription(peer, json);
}
case EaglerMessages.S_VOICE_GLOBAL -> {
int count = EaglerMessages.readVarInt(body);
List<UUID> uuids = new ArrayList<>();
for (int i = 0; i < count; i++) {
uuids.add(uuid(body));
}
List<String> names = new ArrayList<>();
if (body.isReadable()) {
for (int i = 0; i < count; i++) {
names.add(EaglerMessages.readString(body));
}
}
yield () -> global(uuids, names);
}
default -> null;
};
}
// --- The game's thread -------------------------------------------------------------------
/** Whether this server has voice and the player may use it. */
public boolean available() {
return capability && serverAllows;
}
/** The channel the player chose; takes effect on this server at once. */
public void setChannel(VoiceSettings.Channel channel) {
settings().setChannel(channel);
apply();
}
public void setListenVolume(float volume) {
settings().setListenVolume(volume);
}
public void setMicrophoneVolume(float volume) {
settings().setMicrophoneVolume(volume);
rtc.microphone().setVolume(volume);
}
public void setRange(int blocks) {
settings().setRange(blocks);
}
/** The microphone's state, for the voice screen. */
public Microphone.State microphone() {
return rtc.microphone().state();
}
/** Whether the player is sending their voice now. */
public boolean transmitting() {
return transmitting;
}
/** Players connected by voice now: their names, and whether each is talking. */
public List<Speaker> speakers() {
List<Speaker> speakers = new ArrayList<>();
for (Map.Entry<UUID, Peer> entry : peers.entrySet()) {
Peer peer = entry.getValue();
if (peer.audio) {
speakers.add(new Speaker(
entry.getKey(), name(entry.getKey()), peer.talking, muted.contains(entry.getKey())));
}
}
return speakers;
}
/** One voice: who, whether they're talking, whether the player muted them. */
public record Speaker(UUID uuid, String name, boolean talking, boolean muted) {}
/**
* Mutes or unmutes one player's voice, for this connection: kept by UUID, so it holds when the
* two are paired again (out of range and back, or a dropped peer).
*/
public void setMuted(UUID player, boolean mute) {
if (mute) {
muted.add(player);
} else {
muted.remove(player);
}
}
/** {@link incari.client.IncariTicks}: once a tick, on the game's thread. */
public static void tick(Minecraft minecraft, boolean pushToTalk) {
EaglerVoice voice = current;
if (voice != null) {
voice.update(minecraft, pushToTalk);
}
}
private void allowed(boolean allowed, List<IceServer> servers) {
serverAllows = allowed;
iceServers = List.copyOf(servers);
LOGGER.info("The server {} voice chat ({} ICE servers)", allowed ? "has" : "doesn't have", servers.size());
apply();
}
/** Brings this server in line with the player's channel. */
private void apply() {
VoiceSettings.Channel wanted = available() ? settings().channel() : VoiceSettings.Channel.OFF;
if (wanted == joined) {
return;
}
if (joined != VoiceSettings.Channel.OFF) {
closeAll(true);
send(EaglerMessages.C_VOICE_DISCONNECT, body -> {});
if (wanted == VoiceSettings.Channel.OFF) {
// Voice off: the microphone goes too, and the browser stops showing it recording.
releaseMicrophone();
}
}
joined = wanted;
LOGGER.info("Voice: {} channel", wanted.name().toLowerCase(java.util.Locale.ROOT));
if (wanted != VoiceSettings.Channel.OFF) {
Microphone microphone = rtc.microphone();
microphone.open();
microphone.setVolume(settings().microphoneVolume());
send(EaglerMessages.C_VOICE_CONNECT, body -> {});
if (wanted == VoiceSettings.Channel.GLOBAL) {
voicePlayers.keySet().forEach(this::request);
}
}
}
private void global(List<UUID> uuids, List<String> names) {
LOGGER.info("Voice: {} players have voice on", uuids.size());
voicePlayers.clear();
for (int i = 0; i < uuids.size(); i++) {
voicePlayers.put(
uuids.get(i), i < names.size() ? names.get(i) : uuids.get(i).toString());
}
if (joined == VoiceSettings.Channel.GLOBAL) {
uuids.forEach(this::request);
}
}
/** {@code peer} turned voice on: asked for now in global chat, when in range in proximity. */
private void announced(UUID peer) {
requested.remove(peer);
if (joined == VoiceSettings.Channel.GLOBAL) {
request(peer);
}
}
/** Asks the server to pair this client with {@code peer}. */
private void request(UUID peer) {
if (joined == VoiceSettings.Channel.OFF
|| peer.equals(self)
|| peers.containsKey(peer)
|| !requested.add(peer)) {
return;
}
LOGGER.info("Voice: asking to pair with {}", name(peer));
send(EaglerMessages.C_VOICE_REQUEST, body -> writeUuid(body, peer));
}
private void connect(UUID uuid, boolean offer) {
if (joined == VoiceSettings.Channel.OFF) {
return;
}
requested.remove(uuid);
close(uuid, true);
LOGGER.info("Voice: pairing with {}{}", name(uuid), offer ? ", offering" : "");
Peer peer = new Peer(uuid);
peer.connection = rtc.createPeer(iceServers, peer);
peer.connection.sendMicrophone();
peers.put(uuid, peer);
if (offer) {
peer.connection.createOffer();
}
}
private void remoteDescription(UUID uuid, String json) {
Peer peer = peers.get(uuid);
if (peer != null && peer.connection != null) {
peer.connection.setRemoteDescription(json);
}
}
private void remoteCandidate(UUID uuid, String json) {
Peer peer = peers.get(uuid);
if (peer == null || peer.connection == null) {
return;
}
try {
JsonObject candidate = JsonParser.parseString(json).getAsJsonObject();
// Eagler's clients send the line index as a string.
int index = Integer.parseInt(candidate.get("sdpMLineIndex").getAsString());
peer.connection.addIceCandidate(candidate.get("candidate").getAsString(), index);
} catch (RuntimeException e) {
LOGGER.warn("Unreadable ICE candidate from {}: {}", uuid, e.toString());
}
}
/** Ends the connection to {@code uuid}; tells the server unless {@code quietly}. */
private void close(UUID uuid, boolean quietly) {
requested.remove(uuid);
Peer peer = peers.remove(uuid);
if (peer == null) {
return;
}
if (peer.connection != null) {
peer.connection.close();
}
if (!quietly) {
send(EaglerMessages.C_VOICE_DISCONNECT_PEER, body -> writeUuid(body, uuid));
}
}
private void closeAll(boolean quietly) {
for (UUID uuid : new ArrayList<>(peers.keySet())) {
close(uuid, quietly);
}
requested.clear();
lastInRange.clear();
}
private void shutDown() {
boolean wasOn = joined != VoiceSettings.Channel.OFF;
closeAll(true);
joined = VoiceSettings.Channel.OFF;
// Only the voice that opened it lets it go: an old connection closing after the next one
// turned voice on leaves the new one's microphone be.
if (wasOn) {
releaseMicrophone();
}
}
/** Stops sending and closes the microphone (the platform's one, shared by every connection). */
private void releaseMicrophone() {
if (transmitting) {
rtc.microphone().setTransmitting(false);
transmitting = false;
}
rtc.microphone().close();
}
private void update(Minecraft minecraft, boolean pushToTalk) {
if (joined == VoiceSettings.Channel.OFF) {
return;
}
boolean talk = pushToTalk && rtc.microphone().state() == Microphone.State.OPEN;
if (talk != transmitting) {
transmitting = talk;
rtc.microphone().setTransmitting(talk);
}
Player player = minecraft.player;
if (player == null || minecraft.level == null) {
return;
}
VoiceSettings settings = settings();
long now = System.currentTimeMillis();
Vec3 ear = player.getEyePosition();
Vec3 right = Vec3.directionFromRotation(0, player.getYRot() + 90);
for (AbstractClientPlayer other : minecraft.level.players()) {
if (other.getUUID().equals(player.getUUID())) {
continue;
}
UUID uuid = other.getUUID();
Vec3 toPeer = other.getEyePosition().subtract(ear);
double distance = toPeer.length();
Peer peer = peers.get(uuid);
if (joined == VoiceSettings.Channel.PROXIMITY) {
if (distance <= settings.range() + CONNECT_MARGIN) {
lastInRange.put(uuid, now);
request(uuid);
}
if (peer != null && peer.connection != null) {
float falloff = (float) Math.max(0, 1 - distance / settings.range());
float pan = distance < 0.5 ? 0 : (float) (toPeer.normalize().dot(right) * 0.8);
peer.connection.voice().setVolume(muted.contains(uuid) ? 0 : settings.listenVolume() * falloff);
peer.connection.voice().setPan(pan);
}
}
}
for (Map.Entry<UUID, Peer> entry : new ArrayList<>(peers.entrySet())) {
Peer peer = entry.getValue();
if (peer.connection == null) {
continue;
}
if (joined == VoiceSettings.Channel.GLOBAL) {
peer.connection.voice().setVolume(muted.contains(entry.getKey()) ? 0 : settings.listenVolume());
peer.connection.voice().setPan(0);
} else if (now - lastInRange.getOrDefault(entry.getKey(), 0L) > LINGER_MILLIS) {
// Gone out of range (or out of sight): let go, and tell the server.
close(entry.getKey(), false);
continue;
}
if (!muted.contains(entry.getKey()) && peer.connection.voice().level() > TALKING_LEVEL) {
peer.lastLoud = now;
}
boolean talking = now - peer.lastLoud < TALKING_HOLD_MILLIS;
if (talking && !peer.talking) {
// Once per stretch of talk: the browser checks watch for it.
LOGGER.info("Voice: {} is talking", name(entry.getKey()));
}
peer.talking = talking;
}
}
private String name(UUID uuid) {
String name = voicePlayers.get(uuid);
if (name != null) {
return name;
}
Minecraft minecraft = Minecraft.getInstance();
if (minecraft.getConnection() != null) {
var info = minecraft.getConnection().getPlayerInfo(uuid);
if (info != null) {
return info.getProfile().name();
}
}
return uuid.toString();
}
private void send(int id, java.util.function.Consumer<ByteBuf> body) {
EaglerMessages sender = messages;
if (sender != null) {
sender.send(id, body);
}
}
private static UUID uuid(ByteBuf body) {
return new UUID(body.readLong(), body.readLong());
}
private static void writeUuid(ByteBuf body, UUID uuid) {
body.writeLong(uuid.getMostSignificantBits());
body.writeLong(uuid.getLeastSignificantBits());
}
private static String bytesText(ByteBuf body) {
int length = EaglerMessages.readVarInt(body);
String text = body.toString(body.readerIndex(), length, StandardCharsets.UTF_8);
body.skipBytes(length);
return text;
}
private static void writeBytesText(ByteBuf body, String text) {
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
EaglerMessages.writeVarInt(body, bytes.length);
body.writeBytes(bytes);
}
/** One voice connection, and what its WebRTC peer says. Game thread. */
private final class Peer implements RtcPeer.Listener {
final UUID uuid;
@Nullable
RtcPeer connection;
boolean audio;
boolean talking;
/** When the peer was last louder than {@link #TALKING_LEVEL}. */
long lastLoud = Long.MIN_VALUE / 2;
Peer(UUID uuid) {
this.uuid = uuid;
}
@Override
public void localDescription(String json) {
send(EaglerMessages.C_VOICE_DESCRIPTION, body -> {
writeUuid(body, uuid);
writeBytesText(body, json);
});
}
@Override
public void iceCandidate(String candidate, int sdpMLineIndex) {
JsonObject json = new JsonObject();
// As Eagler's clients write it: the index as a string.
json.addProperty("sdpMLineIndex", Integer.toString(sdpMLineIndex));
json.addProperty("candidate", candidate);
String text = json.toString();
send(EaglerMessages.C_VOICE_ICE, body -> {
writeUuid(body, uuid);
writeBytesText(body, text);
});
}
@Override
public void remoteAudio() {
audio = true;
LOGGER.info("Voice: connected to {}", name(uuid));
}
@Override
public void stateChanged(String state) {
if (("failed".equals(state) || "disconnected".equals(state)) && peers.get(uuid) == this) {
LOGGER.info("Voice connection to {} {}", name(uuid), state);
close(uuid, false);
}
}
}
}
@@ -0,0 +1,152 @@
package incari.client.eagler;
import incari.net.eagler.EaglerPassword;
import java.util.List;
import net.minecraft.ChatFormatting;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.CycleButton;
import net.minecraft.client.gui.components.EditBox;
import net.minecraft.client.gui.components.MultiLineTextWidget;
import net.minecraft.client.gui.screens.ConnectScreen;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.input.KeyEvent;
import net.minecraft.client.multiplayer.ServerData;
import net.minecraft.client.multiplayer.resolver.ServerAddress;
import net.minecraft.network.chat.CommonComponents;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.Style;
import net.minecraft.util.FormattedCharSequence;
import org.jspecify.annotations.Nullable;
/**
* Asks for the password an Eagler server's auth plugin wants (ADR 0019), then joins again
* with it. The server's own words are shown above the field. A server that wants the password
* unhashed gets it only if the player agrees on this screen: anyone between the player and the
* server could read it.
*
* <p>English only for now; Incari's screens don't have language files yet.
*/
public final class PasswordScreen extends Screen {
/** Below the title (drawn at 17): where the server's message may start. */
private static final int TITLE_BOTTOM = 32;
private final Screen parent;
private final ServerData server;
private final ServerAddress address;
private final EaglerAuth.Request request;
private boolean plaintextAllowed;
private @Nullable EditBox password;
private @Nullable Button logIn;
public PasswordScreen(Screen parent, ServerData server, ServerAddress address, EaglerAuth.Request request) {
super(Component.literal("Password"));
this.parent = parent;
this.server = server;
this.address = address;
this.request = request;
}
private boolean plaintext() {
return request.method() == EaglerPassword.PLAINTEXT;
}
/** Where the plain-text notice is drawn: just above the password field. */
private int noticeY() {
return this.height / 2 - 20 - 14;
}
@Override
protected void init() {
int x = this.width / 2 - 100;
int y = this.height / 2 - 20;
String said = request.message().isBlank() ? "This server needs a password." : request.message();
// The server's message sits just above the field (and the plain-text notice), as many lines
// as fit below the title: a long one is cut, never drawn over the notice or the field.
int bottom = noticeY() - (plaintext() ? 4 : -5);
int rows = Math.max(1, (bottom - TITLE_BOTTOM) / this.font.lineHeight);
MultiLineTextWidget message = new MultiLineTextWidget(Component.literal(said), this.font)
.setMaxWidth(300)
.setMaxRows(rows)
.setCentered(true);
// The widget is as wide as its longest line: centred over the field, not left-aligned to it.
message.setPosition(this.width / 2 - message.getWidth() / 2, bottom - message.getHeight());
this.addRenderableWidget(message);
EditBox box = new EditBox(this.font, x, y, 200, 20, password, Component.literal("Password"));
box.setMaxLength(127);
// Shown as stars; the text itself stays in the box.
box.addFormatter((text, offset) -> FormattedCharSequence.forward("*".repeat(text.length()), Style.EMPTY));
box.setResponder(text -> updateLogIn());
password = this.addRenderableWidget(box);
int buttons = y + 30;
if (plaintext()) {
this.addRenderableWidget(
CycleButton.<Boolean>builder(allowed -> Component.literal(allowed ? "Yes" : "No"), plaintextAllowed)
.withValues(List.of(false, true))
.create(x, buttons, 200, 20, Component.literal("Send as plain text"), (button, allowed) -> {
plaintextAllowed = allowed;
updateLogIn();
}));
buttons += 24;
}
logIn = this.addRenderableWidget(Button.builder(Component.literal("Log In"), button -> logIn())
.bounds(x, buttons, 98, 20)
.build());
this.addRenderableWidget(Button.builder(CommonComponents.GUI_CANCEL, button -> onClose())
.bounds(x + 102, buttons, 98, 20)
.build());
this.setInitialFocus(box);
updateLogIn();
}
private void updateLogIn() {
Button button = logIn;
if (button != null) {
button.active = !typed().isEmpty() && (!plaintext() || plaintextAllowed);
}
}
private String typed() {
EditBox box = password;
return box == null ? "" : box.getValue();
}
private void logIn() {
EaglerAuth.remember(request.server(), new EaglerPassword(typed(), plaintextAllowed));
Minecraft minecraft = Minecraft.getInstance();
ConnectScreen.startConnecting(parent, minecraft, address, server, false, null);
}
@Override
public boolean keyPressed(KeyEvent event) {
Button button = logIn;
if (event.isConfirmation() && button != null && button.active) {
logIn();
return true;
}
return super.keyPressed(event);
}
@Override
public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
super.extractRenderState(graphics, mouseX, mouseY, a);
graphics.centeredText(this.font, this.title, this.width / 2, 17, 0xFFFFFFFF);
if (plaintext()) {
graphics.centeredText(
this.font,
Component.literal("This server wants your password as plain text.")
.withStyle(ChatFormatting.YELLOW),
this.width / 2,
noticeY(),
0xFFFFFFFF);
}
}
@Override
public void onClose() {
Minecraft.getInstance().gui.setScreen(parent);
}
}
@@ -0,0 +1,53 @@
package incari.client.eagler;
import incari.client.settings.IncariSettingsScreen;
import incari.client.ui.Icons;
import incari.client.ui.Ui;
import java.util.function.Consumer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.components.AbstractWidget;
import net.minecraft.client.gui.components.Renderable;
import net.minecraft.client.gui.layouts.GridLayout;
import net.minecraft.client.gui.screens.Screen;
/**
* What Incari adds to the pause menu: Incari Settings' button, an Eagler server's own buttons and
* icons, and voice chat.
*/
public final class PauseMenuHooks {
private PauseMenuHooks() {}
/**
* {@code PauseScreen}, in the button grid below the row of icon buttons: Incari Settings, with
* Incari's badge (everything else of Incari's is behind it), then the server's own buttons.
*/
public static void addButtons(GridLayout.RowHelper row) {
row.addChild(
Ui.menuButton(IncariSettingsScreen.TITLE, Icons.INCARI, 204, () -> {
Minecraft minecraft = Minecraft.getInstance();
minecraft.gui.setScreen(new IncariSettingsScreen(minecraft.gui.screen()));
})
.centered(),
2);
ServerPauseMenu.addButtons(row);
}
/**
* {@code PauseScreen.getCustomAdditions}: whether the server sent pause menu buttons of its
* own, which take the Server Links button's place.
*/
public static boolean replacesServerLinks() {
return ServerPauseMenu.active();
}
/** {@code PauseScreen}, after its widgets: the voice panel, and the icons over the buttons. */
public static void addOverlays(
Screen screen, Consumer<AbstractWidget> addWidget, Consumer<Renderable> addRenderable) {
ServerPauseMenu.addIcons(screen, addRenderable);
VoicePanel voice = VoicePanel.create(screen);
if (voice != null) {
addWidget.accept(voice);
}
}
}
@@ -0,0 +1,290 @@
package incari.client.eagler;
import com.mojang.blaze3d.Blaze3D;
import com.mojang.blaze3d.platform.NativeImage;
import com.mojang.logging.LogUtils;
import incari.client.ui.Ui;
import incari.net.eagler.EaglerPauseMenu;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.gui.components.AbstractWidget;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.Renderable;
import net.minecraft.client.gui.components.StringWidget;
import net.minecraft.client.gui.components.events.GuiEventListener;
import net.minecraft.client.gui.layouts.GridLayout;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.renderer.RenderPipelines;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.contents.TranslatableContents;
import net.minecraft.resources.Identifier;
import net.minecraft.util.FormattedCharSequence;
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
/**
* The pause menu an EaglerXServer customizes (its {@code pause_menu.yml}): a "server info" button
* and a Discord button, which open their links, and small icons beside the menu's buttons and title,
* as Eagler's 1.8 client shows them. Kept for the connection that sent it. The game's thread only.
*
* <p>A server info button that shows markup the server sends, in a web view, isn't shown: the page
* has no web view yet. One that shows an address in a web view opens it in a new tab instead.
*/
public final class ServerPauseMenu {
private static final Logger LOGGER = LogUtils.getLogger();
private static final int FULL_WIDTH = 204;
private static final int HALF_WIDTH = 98;
private static final int ICON_SIZE = 16;
private static final int ICON_GAP = 4;
/** The vanilla buttons' labels, by the name Eagler's icon keys give each. */
private static final Map<String, String> BUTTON_KEYS = Map.of(
"menu.returnToGame", "backToGame",
"gui.advancements", "achievements",
"gui.stats", "statistics",
"menu.options", "options",
"menu.disconnect", "disconnect",
"menu.returnToMenu", "disconnect");
private static @Nullable ServerPauseMenu current;
private final EaglerPauseMenu menu;
/** Each icon key's texture, and its image's size. */
private final Map<String, Icon> icons = new HashMap<>();
private record Icon(Identifier texture, int width, int height) {}
private ServerPauseMenu(EaglerPauseMenu menu) {
this.menu = menu;
Map<EaglerPauseMenu.Image, Identifier> uploaded = new HashMap<>();
menu.icons().forEach((key, image) -> {
// Keys often share an image (the server sends each once); upload each once.
Identifier texture = uploaded.computeIfAbsent(image, _ -> upload(uploaded.size(), image));
icons.put(key, new Icon(texture, image.width(), image.height()));
});
}
/** The message arrived (any thread): this connection's menu from now on. */
static void received(EaglerPauseMenu menu) {
Minecraft.getInstance().execute(() -> {
clear();
current = new ServerPauseMenu(menu);
});
}
/** The connection ended (any thread). */
static void closed() {
Minecraft.getInstance().execute(ServerPauseMenu::clear);
}
private static void clear() {
ServerPauseMenu menu = current;
if (menu != null) {
for (Icon icon : Map.copyOf(menu.icons).values()) {
Minecraft.getInstance().getTextureManager().release(icon.texture());
}
current = null;
}
}
private static Identifier upload(int index, EaglerPauseMenu.Image image) {
Identifier id = Identifier.fromNamespaceAndPath("incari", "pause_menu/icon_" + index);
NativeImage pixels = new NativeImage(image.width(), image.height(), false);
for (int y = 0; y < image.height(); y++) {
for (int x = 0; x < image.width(); x++) {
pixels.setPixel(x, y, image.pixel(x, y));
}
}
// Registering again under the same id closes the texture it replaces.
Minecraft.getInstance().getTextureManager().register(id, new DynamicTexture(id::toString, pixels));
return id;
}
/** Whether this connection's server sent a pause menu with any button of its own. */
static boolean active() {
ServerPauseMenu menu = current;
return menu != null && (menu.menu.serverInfo() != null || menu.menu.discord() != null);
}
// --- The pause screen ----------------------------------------------------------------------
/**
* {@code PauseScreen}, below the row of icon buttons: the server's own buttons, side by side if
* both fit in half the width.
*/
public static void addButtons(GridLayout.RowHelper row) {
ServerPauseMenu menu = current;
if (menu == null) {
return;
}
List<Button> buttons = new ArrayList<>();
EaglerPauseMenu.Button serverInfo = menu.menu.serverInfo();
if (serverInfo != null && serverInfo.url() != null) {
buttons.add(menu.linkButton(serverInfo, "serverInfo"));
} else if (serverInfo != null) {
LOGGER.debug("The server's info button shows markup in a web view, which the page doesn't have");
}
EaglerPauseMenu.Button discord = menu.menu.discord();
if (discord != null && discord.url() != null) {
buttons.add(menu.linkButton(discord, "discord"));
}
Font font = Minecraft.getInstance().font;
boolean halves = buttons.size() == 2
&& buttons.stream()
.allMatch(button ->
menu.contentWidth(font, button.getMessage(), keyOf(button)) <= HALF_WIDTH - 8);
for (Button button : buttons) {
button.setWidth(halves ? HALF_WIDTH : FULL_WIDTH);
row.addChild(button, halves ? 1 : 2);
}
}
/**
* {@code PauseScreen}, after its widgets: the icons beside the buttons and the title, drawn over
* them.
*/
public static void addIcons(Screen screen, java.util.function.Consumer<Renderable> addRenderableOnly) {
ServerPauseMenu menu = current;
if (menu == null || menu.icons.isEmpty()) {
return;
}
// Read as each frame draws, not copied now: the pause screen adds its title after this hook,
// and ScreenEdits moves widgets after each layout.
addRenderableOnly.accept((graphics, mouseX, mouseY, a) -> menu.extractIcons(graphics, screen.children()));
}
private Button linkButton(EaglerPauseMenu.Button button, String key) {
URI uri = safeUri(button.url());
Button widget = new KeyedButton(Component.literal(button.text()), key, pressed -> {
if (uri != null) {
Blaze3D.openUri(uri);
}
});
widget.active = uri != null;
return widget;
}
/** {@code url} if it's a web address; a server mustn't make the page run a {@code javascript:} one. */
static @Nullable URI safeUri(@Nullable String url) {
if (url == null) {
return null;
}
try {
URI uri = new URI(url.trim());
String scheme = uri.getScheme() == null ? "" : uri.getScheme().toLowerCase(Locale.ROOT);
return scheme.equals("https") || scheme.equals("http") ? uri : null;
} catch (URISyntaxException e) {
return null;
}
}
private void extractIcons(GuiGraphicsExtractor graphics, List<? extends GuiEventListener> children) {
Font font = Minecraft.getInstance().font;
// Indexed: a frame's draw allocates no iterator.
for (int i = 0; i < children.size(); i++) {
GuiEventListener child = children.get(i);
if (child instanceof AbstractWidget widget && widget.visible && !(child instanceof KeyedButton)) {
String key = child instanceof StringWidget ? titleKey(widget.getMessage()) : keyOf(widget);
if (key != null) {
int textWidth = font.width(widget.getMessage());
int middle = widget.getX() + widget.getWidth() / 2;
int y = widget.getY() + widget.getHeight() / 2 - ICON_SIZE / 2;
extractIcon(graphics, "icon_" + key + "_L", middle - textWidth / 2 - ICON_GAP - ICON_SIZE, y);
extractIcon(graphics, "icon_" + key + "_R", middle + (textWidth + 1) / 2 + ICON_GAP, y);
}
}
}
}
private void extractIcon(GuiGraphicsExtractor graphics, String key, int x, int y) {
Icon icon = icons.get(key);
if (icon != null) {
graphics.blit(
RenderPipelines.GUI_TEXTURED,
icon.texture(),
x,
y,
0,
0,
ICON_SIZE,
ICON_SIZE,
icon.width(),
icon.height(),
icon.width(),
icon.height());
}
}
private int contentWidth(Font font, Component message, @Nullable String key) {
int width = font.width(message);
for (String side : new String[] {"_L", "_R"}) {
if (key != null && icons.containsKey("icon_" + key + side)) {
width += ICON_SIZE + ICON_GAP;
}
}
return width;
}
/** A button's name in Eagler's icon keys: one of the server's, or a vanilla one by its label. */
private static @Nullable String keyOf(AbstractWidget widget) {
if (widget instanceof KeyedButton keyed) {
return keyed.key;
}
return widget.getMessage().getContents() instanceof TranslatableContents label
? BUTTON_KEYS.get(label.getKey())
: null;
}
private static @Nullable String titleKey(Component message) {
return message.getContents() instanceof TranslatableContents label
&& label.getKey().equals("menu.game")
? "title"
: null;
}
/**
* One of the server's buttons, with the name its icons are keyed by. It draws its icons itself,
* centred with its text as one group, as Eagler's client does.
*/
private final class KeyedButton extends Button.Plain {
final String key;
KeyedButton(Component message, String key, OnPress onPress) {
super(0, 0, FULL_WIDTH, 20, message, onPress, DEFAULT_NARRATION);
this.key = key;
}
@Override
protected void extractContents(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
extractDefaultSprite(graphics);
Font font = Minecraft.getInstance().font;
boolean left = icons.containsKey("icon_" + key + "_L");
boolean right = icons.containsKey("icon_" + key + "_R");
int iconsWidth = (left ? ICON_SIZE + ICON_GAP : 0) + (right ? ICON_SIZE + ICON_GAP : 0);
// The server's own words: cut to fit the button with its pictures, never drawn past it.
FormattedCharSequence text = Ui.fit(font, getMessage(), Math.max(0, getWidth() - 8 - iconsWidth));
int textWidth = font.width(text);
int groupWidth = textWidth + iconsWidth;
int x = getX() + (getWidth() - groupWidth) / 2;
int iconY = getY() + (getHeight() - ICON_SIZE) / 2;
if (left) {
extractIcon(graphics, "icon_" + key + "_L", x, iconY);
x += ICON_SIZE + ICON_GAP;
}
graphics.text(font, text, x, getY() + (getHeight() - 8) / 2, active ? 0xFFFFFFFF : 0xFFA0A0A0);
if (right) {
extractIcon(graphics, "icon_" + key + "_R", x + textWidth + ICON_GAP, iconY);
}
}
}
}
@@ -0,0 +1,69 @@
package incari.client.eagler;
import com.mojang.logging.LogUtils;
import incari.client.net.ServerVersions;
import incari.net.WebSocketUrl;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.ConnectScreen;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.gui.screens.TitleScreen;
import net.minecraft.client.gui.screens.multiplayer.JoinMultiplayerScreen;
import net.minecraft.client.multiplayer.ServerData;
import net.minecraft.client.multiplayer.resolver.ServerAddress;
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
/**
* An Eagler server sending the player to another server (ADR 0019): during login, in place
* of letting them in, or during play. Only WebSocket addresses are followed; the player joins the
* new server as a server of their list would be, with "Auto" for its version.
*/
public final class ServerRedirects {
private static final Logger LOGGER = LogUtils.getLogger();
private static final Object LOCK = new Object();
private static @Nullable String pending;
private ServerRedirects() {}
/** The login ended in a redirect; the disconnection that follows joins {@code address}. */
static void pending(String address) {
synchronized (LOCK) {
pending = address;
}
}
/** The redirect the last failed login left, once. */
static @Nullable String takePending() {
synchronized (LOCK) {
String address = pending;
pending = null;
return address;
}
}
/** During play: leaves this server for {@code address}. Any thread. */
static void redirect(String address) {
Minecraft minecraft = Minecraft.getInstance();
minecraft.execute(() -> {
if (minecraft.level != null) {
minecraft.disconnectFromWorld(net.minecraft.network.chat.Component.literal("Redirected"));
}
join(minecraft, new JoinMultiplayerScreen(new TitleScreen()), address);
});
}
/** Joins {@code address} from {@code parent}, if it's a WebSocket address. Render thread. */
static boolean join(Minecraft minecraft, Screen parent, String address) {
if (!WebSocketUrl.isWebSocketUrl(address)) {
LOGGER.warn("Not following a redirect to {}: only ws:// and wss:// addresses", address);
return false;
}
LOGGER.info("Redirected to {}", address);
ServerData server = new ServerData(address, address, ServerData.Type.OTHER);
// Via as the player set it for the server that sent them on.
server.incariVersion = ServerVersions.redirectChoice();
ConnectScreen.startConnecting(parent, minecraft, ServerAddress.parseString(address), server, false, null);
return true;
}
}
@@ -0,0 +1,37 @@
package incari.client.eagler;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphicsExtractor;
/**
* Who is talking, in the HUD's top left corner, from one hook in {@code Hud}. Shown only
* while someone is, or the player is.
*/
public final class VoiceOverlay {
private static final int MAX_SHOWN = 5;
private VoiceOverlay() {}
public static void extract(GuiGraphicsExtractor graphics) {
EaglerVoice voice = EaglerVoice.current();
if (voice == null || !voice.available() || EaglerVoice.settings().channel() == VoiceSettings.Channel.OFF) {
return;
}
Minecraft minecraft = Minecraft.getInstance();
int y = 4;
if (voice.transmitting()) {
graphics.text(minecraft.font, "▶ " + minecraft.getUser().getName(), 4, y, 0xFF55FF55);
y += 10;
}
List<EaglerVoice.Speaker> talking = voice.speakers().stream()
.filter(EaglerVoice.Speaker::talking)
.limit(MAX_SHOWN)
.toList();
for (EaglerVoice.Speaker speaker : talking) {
graphics.text(minecraft.font, "▶ " + speaker.name(), 4, y, 0xFFFFFFFF);
y += 10;
}
}
}
@@ -0,0 +1,340 @@
package incari.client.eagler;
import incari.client.IncariKeys;
import incari.client.ui.Panels;
import incari.client.ui.RoundRects;
import incari.client.ui.ScreenPanels;
import incari.client.ui.Theme;
import incari.platform.api.rtc.Microphone;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.gui.components.AbstractWidget;
import net.minecraft.client.gui.narration.NarrationElementOutput;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.input.MouseButtonEvent;
import net.minecraft.client.resources.sounds.SimpleSoundInstance;
import net.minecraft.network.chat.Component;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.util.Util;
import org.jspecify.annotations.Nullable;
/**
* Voice chat in the pause menu's top right corner, where Eagler's 1.8 client has it: the channel
* (off, nearby or global) in one click, whether the microphone is live, who is connected and who is
* talking, a click to mute anyone, and a link to the full settings ({@link VoiceScreen}). Shown on
* servers with Eagler voice.
*
* <p>Laid out again every frame (the speakers come and go): its height follows its contents, and
* its click targets are where they were last drawn.
*/
final class VoicePanel extends AbstractWidget {
private static final int MAX_WIDTH = 150;
private static final int MIN_WIDTH = 108;
private static final int MARGIN = 6;
private static final int PADDING = 6;
private static final int ROW = 11;
private static final int SEGMENT_HEIGHT = 14;
private static final int MAX_SPEAKERS = 6;
/** Half the game's pause menu, its buttons 204 wide, and the card's padding: where no card was laid out. */
private static final int MENU_HALF_WIDTH = 114;
/** The compact panel's margin to the screen's edge: it fits where the full one doesn't. */
private static final int COMPACT_MARGIN = 3;
private static final int COMPACT_PADDING = 4;
private static final int BORDER = 0x1FFFFFFF;
private static final VoiceSettings.Channel[] CHANNELS = {
VoiceSettings.Channel.OFF, VoiceSettings.Channel.PROXIMITY, VoiceSettings.Channel.GLOBAL
};
private final Screen screen;
private final EaglerVoice voice;
private final Font font;
/** What was drawn where, for clicks: each a rectangle and what a click on it does. */
private final List<Target> targets = new ArrayList<>();
private record Target(int x0, int y0, int x1, int y1, Runnable action) {
boolean contains(double x, double y) {
return x >= x0 && x < x1 && y >= y0 && y < y1;
}
}
private VoicePanel(Screen screen, EaglerVoice voice) {
super(0, MARGIN, MAX_WIDTH, 40, Component.literal("Voice Chat"));
this.screen = screen;
this.voice = voice;
this.font = Minecraft.getInstance().font;
}
/** {@code PauseScreen}: the panel, on a server with Eagler voice; else null. */
static @Nullable VoicePanel create(Screen screen) {
EaglerVoice voice = EaglerVoice.current();
return voice == null || !voice.available() ? null : new VoicePanel(screen, voice);
}
@Override
protected void extractWidgetRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
targets.clear();
// Beside the menu's card, never over it: where the full panel doesn't fit, a small one that
// opens the voice settings.
int cardRight = ScreenPanels.right(screen);
int room = (cardRight < 0 ? screen.width - (screen.width / 2 + MENU_HALF_WIDTH) : screen.width - cardRight)
- MARGIN * 2;
if (room < MIN_WIDTH) {
extractCompact(graphics, mouseX, mouseY);
return;
}
int width = Math.min(MAX_WIDTH, room);
setWidth(width);
setY(MARGIN);
setX(screen.width - width - MARGIN);
int x = getX() + PADDING;
int right = getRight() - PADDING;
VoiceSettings.Channel channel = EaglerVoice.settings().channel();
boolean on = channel != VoiceSettings.Channel.OFF;
int top = getY();
List<EaglerVoice.Speaker> speakers = on ? voice.speakers() : List.of();
setHeight(height(on, speakers.size()));
Panels.panel(graphics, getX(), top, getWidth(), getHeight(), 1.0F);
int y = top + PADDING;
graphics.text(font, "Voice Chat", x, y, Theme.TEXT);
extractState(graphics, right, y, on);
y += ROW + 3;
y = extractChannels(graphics, x, right, y, channel, mouseX, mouseY);
y += 4;
if (on) {
Status status = status();
graphics.text(font, font.plainSubstrByWidth(status.text, right - x), x, y, status.color);
y += ROW + 2;
graphics.fill(x, y, right, y + 1, BORDER);
y += 4;
y = extractSpeakers(graphics, speakers, x, right, y, mouseX, mouseY);
} else {
graphics.text(font, "Pick a channel to talk", x, y, Theme.MUTED);
y += ROW;
}
y += 2;
String settings = "Settings...";
int settingsWidth = font.width(settings);
boolean settingsHovered = mouseX >= x && mouseX < x + settingsWidth && mouseY >= y - 1 && mouseY < y + 9;
graphics.text(font, settings, x, y, settingsHovered ? Theme.TEXT : Theme.MUTED);
if (settingsHovered) {
graphics.fill(x, y + 9, x + settingsWidth, y + 10, Theme.TEXT);
}
targets.add(new Target(
x,
y - 1,
x + settingsWidth,
y + 10,
() -> Minecraft.getInstance().gui.setScreen(new VoiceScreen(screen, voice))));
}
/**
* The panel in a narrow window: a dot that says whether voice is on, and "Voice", which opens the
* voice settings. Small enough for the room beside the card at the smallest window and largest
* GUI scale.
*/
private void extractCompact(GuiGraphicsExtractor graphics, int mouseX, int mouseY) {
String label = "Voice";
int width = COMPACT_PADDING + 7 + font.width(label) + COMPACT_PADDING;
int height = 9 + COMPACT_PADDING * 2;
setWidth(width);
setHeight(height);
setX(screen.width - width - COMPACT_MARGIN);
setY(COMPACT_MARGIN);
boolean hovered = isMouseOver(mouseX, mouseY);
Panels.panel(graphics, getX(), getY(), width, height, 1.0F);
boolean on = EaglerVoice.settings().channel() != VoiceSettings.Channel.OFF;
int color = on ? Theme.POSITIVE : Theme.MUTED;
// The dot pulses while the player talks, as the full panel's does.
boolean lit = !voice.transmitting() || (Util.getMillis() / 400) % 2 == 0;
int x = getX() + COMPACT_PADDING;
int y = getY() + COMPACT_PADDING;
graphics.fill(x, y + 2, x + 4, y + 6, lit ? color : (color & 0x00FFFFFF) | 0x60000000);
graphics.text(font, label, x + 7, y, hovered ? Theme.TEXT : Theme.MUTED);
targets.add(new Target(
getX(),
getY(),
getRight(),
getBottom(),
() -> Minecraft.getInstance().gui.setScreen(new VoiceScreen(screen, voice))));
}
/** The panel's height: what {@link #extractWidgetRenderState} draws, row by row. */
private static int height(boolean on, int speakers) {
int height = PADDING + ROW + 3 + SEGMENT_HEIGHT + 4;
if (on) {
height += ROW + 2 + 4;
height += speakers == 0 ? ROW : ROW + 1 + Math.min(speakers, MAX_SPEAKERS) * ROW;
height += speakers > MAX_SPEAKERS ? ROW : 0;
} else {
height += ROW;
}
return height + 2 + ROW + PADDING - 2;
}
/** A dot and a word at the top right: off, live, or talking now. */
private void extractState(GuiGraphicsExtractor graphics, int right, int y, boolean on) {
String word;
int color;
if (!on) {
word = "Off";
color = Theme.MUTED;
} else if (voice.transmitting()) {
word = "Talking";
color = Theme.POSITIVE;
} else {
word = "On";
color = Theme.POSITIVE;
}
int wordX = right - font.width(word);
graphics.text(font, word, wordX, y, color);
// The dot pulses while the player talks.
boolean lit = !voice.transmitting() || (Util.getMillis() / 400) % 2 == 0;
int dotX = wordX - 7;
graphics.fill(dotX, y + 2, dotX + 4, y + 6, lit ? color : (color & 0x00FFFFFF) | 0x60000000);
}
/** Off, Nearby and Global as one segmented control; returns the y below it. */
private int extractChannels(
GuiGraphicsExtractor graphics,
int x,
int right,
int y,
VoiceSettings.Channel chosen,
int mouseX,
int mouseY) {
int segmentWidth = (right - x) / CHANNELS.length;
for (int i = 0; i < CHANNELS.length; i++) {
VoiceSettings.Channel channel = CHANNELS[i];
int x0 = x + i * segmentWidth;
int x1 = i == CHANNELS.length - 1 ? right : x0 + segmentWidth;
boolean selected = channel == chosen;
boolean hovered = mouseX >= x0 && mouseX < x1 && mouseY >= y && mouseY < y + SEGMENT_HEIGHT;
int fill = selected
? (channel == VoiceSettings.Channel.OFF ? Theme.BUTTON_HOT : (Theme.ACCENT & 0x59FFFFFF))
: hovered ? Theme.BUTTON : 0x14FFFFFF;
RoundRects.fill(graphics, x0 + 1, y, x1 - x0 - 2, SEGMENT_HEIGHT, Theme.RADIUS, fill);
if (selected) {
RoundRects.outline(
graphics,
x0 + 1,
y,
x1 - x0 - 2,
SEGMENT_HEIGHT,
Theme.RADIUS,
channel == VoiceSettings.Channel.OFF ? BORDER : Theme.ACCENT);
}
String label = label(channel);
graphics.text(
font,
label,
(x0 + x1 - font.width(label)) / 2,
y + (SEGMENT_HEIGHT - 8) / 2,
selected || hovered ? Theme.TEXT : Theme.MUTED);
if (!selected) {
targets.add(new Target(x0, y, x1, y + SEGMENT_HEIGHT, () -> voice.setChannel(channel)));
}
}
return y + SEGMENT_HEIGHT;
}
/** Everyone connected, talking ones lit, each with a mute toggle; returns the y below them. */
private int extractSpeakers(
GuiGraphicsExtractor graphics,
List<EaglerVoice.Speaker> speakers,
int x,
int right,
int y,
int mouseX,
int mouseY) {
if (speakers.isEmpty()) {
graphics.text(font, "No one else connected", x, y, Theme.MUTED);
return y + ROW;
}
graphics.text(font, "Connected (" + speakers.size() + ")", x, y, Theme.MUTED);
y += ROW + 1;
for (EaglerVoice.Speaker speaker : speakers.stream().limit(MAX_SPEAKERS).toList()) {
String toggle = speaker.muted() ? "Muted" : "Mute";
int toggleX = right - font.width(toggle);
boolean hovered = mouseX >= toggleX - 2 && mouseX < right && mouseY >= y - 1 && mouseY < y + 9;
int dot = speaker.muted() ? Theme.NEGATIVE : speaker.talking() ? Theme.POSITIVE : 0xFF505058;
graphics.fill(x, y + 2, x + 4, y + 6, dot);
String name = font.plainSubstrByWidth(speaker.name(), toggleX - x - 12);
graphics.text(
font,
name,
x + 7,
y,
speaker.muted() ? Theme.MUTED : speaker.talking() ? Theme.POSITIVE : Theme.TEXT);
graphics.text(
font, toggle, toggleX, y, speaker.muted() ? Theme.NEGATIVE : hovered ? Theme.TEXT : Theme.MUTED);
UUID uuid = speaker.uuid();
boolean muted = speaker.muted();
targets.add(new Target(toggleX - 2, y - 1, right, y + 9, () -> voice.setMuted(uuid, !muted)));
y += ROW;
}
if (speakers.size() > MAX_SPEAKERS) {
graphics.text(font, "+" + (speakers.size() - MAX_SPEAKERS) + " more in Settings", x, y, Theme.MUTED);
y += ROW;
}
return y;
}
private record Status(String text, int color) {}
private Status status() {
Microphone.State microphone = voice.microphone();
String key = IncariKeys.PUSH_TO_TALK.getTranslatedKeyMessage().getString();
return switch (microphone) {
case OPEN ->
voice.transmitting()
? new Status("Talking...", Theme.POSITIVE)
: new Status("Hold " + key + " to talk", Theme.MUTED);
case OPENING, CLOSED -> new Status("Waiting for microphone", Theme.WARNING);
case UNAVAILABLE -> new Status("No mic: listening only", Theme.NEGATIVE);
};
}
private static String label(VoiceSettings.Channel channel) {
return switch (channel) {
case OFF -> "Off";
case PROXIMITY -> "Nearby";
case GLOBAL -> "Global";
};
}
@Override
public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) {
if (!isMouseOver(event.x(), event.y()) || !isValidClickButton(event.buttonInfo())) {
return false;
}
for (Target target : List.copyOf(targets)) {
if (target.contains(event.x(), event.y())) {
Minecraft.getInstance()
.getSoundManager()
.play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0F));
target.action.run();
return true;
}
}
// A click on the panel's background goes nowhere else.
return true;
}
@Override
protected void updateWidgetNarration(NarrationElementOutput output) {
defaultButtonNarrationText(output);
}
}
@@ -0,0 +1,151 @@
package incari.client.eagler;
import incari.client.IncariKeys;
import incari.platform.api.rtc.Microphone;
import java.util.List;
import java.util.function.DoubleConsumer;
import java.util.function.DoubleFunction;
import net.minecraft.ChatFormatting;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.gui.components.AbstractSliderButton;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.CycleButton;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.CommonComponents;
import net.minecraft.network.chat.Component;
/**
* Voice chat's settings and the voices connected now, opened from the pause menu's voice
* panel ({@link VoicePanel}) on a server with Eagler voice. Mutes last for the connection.
*
* <p>English only for now; Incari's screens don't have language files yet.
*/
public final class VoiceScreen extends Screen {
private static final int MAX_LISTED = 8;
private final Screen parent;
private final EaglerVoice voice;
public VoiceScreen(Screen parent, EaglerVoice voice) {
super(Component.literal("Voice Chat"));
this.parent = parent;
this.voice = voice;
}
@Override
protected void init() {
VoiceSettings settings = EaglerVoice.settings();
int x = this.width / 2 - 155;
int y = 40;
this.addRenderableWidget(CycleButton.<VoiceSettings.Channel>builder(
VoiceScreen::channelName, settings.channel())
.withValues(List.of(VoiceSettings.Channel.values()))
.create(x, y, 150, 20, Component.literal("Channel"), (button, channel) -> voice.setChannel(channel)));
this.addRenderableWidget(slider(
x + 160,
y,
settings.range(),
VoiceSettings.MIN_RANGE,
VoiceSettings.MAX_RANGE,
value -> "Proximity: " + Math.round(value) + " blocks",
value -> voice.setRange((int) Math.round(value))));
this.addRenderableWidget(slider(
x,
y + 24,
settings.listenVolume(),
0,
2,
value -> "Voices: " + Math.round(value * 100) + "%",
value -> voice.setListenVolume((float) value)));
this.addRenderableWidget(slider(
x + 160,
y + 24,
settings.microphoneVolume(),
0,
2,
value -> "Microphone: " + Math.round(value * 100) + "%",
value -> voice.setMicrophoneVolume((float) value)));
int row = y + 72;
for (EaglerVoice.Speaker speaker :
voice.speakers().stream().limit(MAX_LISTED).toList()) {
this.addRenderableWidget(Button.builder(Component.literal(speaker.muted() ? "Unmute" : "Mute"), button -> {
voice.setMuted(speaker.uuid(), !speaker.muted());
this.rebuildWidgets();
})
.bounds(x + 250, row, 60, 18)
.build());
row += 20;
}
this.addRenderableWidget(Button.builder(CommonComponents.GUI_DONE, button -> onClose())
.bounds(this.width / 2 - 100, this.height - 28, 200, 20)
.build());
}
private static Component channelName(VoiceSettings.Channel channel) {
return Component.literal(
switch (channel) {
case OFF -> "Off";
case GLOBAL -> "Global";
case PROXIMITY -> "Nearby";
});
}
private static AbstractSliderButton slider(
int x, int y, double value, double min, double max, DoubleFunction<String> label, DoubleConsumer set) {
return new AbstractSliderButton(x, y, 150, 20, Component.empty(), (value - min) / (max - min)) {
{
updateMessage();
}
@Override
protected void updateMessage() {
setMessage(Component.literal(label.apply(min + this.value * (max - min))));
}
@Override
protected void applyValue() {
set.accept(min + this.value * (max - min));
}
};
}
@Override
public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
super.extractRenderState(graphics, mouseX, mouseY, a);
graphics.centeredText(this.font, this.title, this.width / 2, 15, 0xFFFFFFFF);
int x = this.width / 2 - 155;
graphics.text(this.font, status(), x, 90, 0xFFFFFFFF);
int row = 112 + 5;
for (EaglerVoice.Speaker speaker :
voice.speakers().stream().limit(MAX_LISTED).toList()) {
Component name = Component.literal(speaker.name())
.withStyle(speaker.talking() ? ChatFormatting.GREEN : ChatFormatting.WHITE);
graphics.text(this.font, name, x, row, 0xFFFFFFFF);
row += 20;
}
}
private Component status() {
if (EaglerVoice.settings().channel() == VoiceSettings.Channel.OFF) {
return Component.literal("Voice is off. Pick a channel to turn on your microphone.")
.withStyle(ChatFormatting.GRAY);
}
Microphone.State microphone = voice.microphone();
String key = IncariKeys.PUSH_TO_TALK.getTranslatedKeyMessage().getString();
return switch (microphone) {
case OPEN -> Component.literal("Hold " + key + " to talk." + (voice.transmitting() ? " Talking." : ""));
case OPENING, CLOSED ->
Component.literal("Waiting for the microphone...").withStyle(ChatFormatting.YELLOW);
case UNAVAILABLE ->
Component.literal("No microphone found. You can listen but not talk.")
.withStyle(ChatFormatting.RED);
};
}
@Override
public void onClose() {
Minecraft.getInstance().gui.setScreen(parent);
}
}
@@ -0,0 +1,128 @@
package incari.client.eagler;
import com.mojang.logging.LogUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Locale;
import org.slf4j.Logger;
/**
* The player's voice chat settings, kept in {@code incari/voice.txt}: which channel to join
* on servers that have voice, how loud others are, how loud the microphone is, and how far
* proximity chat carries. Voice starts off: joining a channel shares the microphone, which is the
* player's call.
*/
public final class VoiceSettings {
private static final Logger LOGGER = LogUtils.getLogger();
private static final String FILE = "voice.txt";
/** Which voices the player hears and speaks to. */
public enum Channel {
OFF,
/** Everyone on the server with voice on. */
GLOBAL,
/** Players nearby, louder the closer they are. */
PROXIMITY
}
private final Path file;
private Channel channel = Channel.OFF;
private float listenVolume = 1.0F;
private float microphoneVolume = 1.0F;
private int range = 16;
private VoiceSettings(Path file) {
this.file = file;
}
static VoiceSettings load(Path gameDirectory) {
VoiceSettings settings =
new VoiceSettings(gameDirectory.resolve("incari").resolve(FILE));
if (!Files.isRegularFile(settings.file)) {
return settings;
}
try {
for (String line : Files.readAllLines(settings.file, StandardCharsets.UTF_8)) {
int split = line.indexOf('=');
if (split < 0) {
continue;
}
String key = line.substring(0, split).trim();
String value = line.substring(split + 1).trim();
try {
switch (key) {
case "channel" -> settings.channel = Channel.valueOf(value.toUpperCase(Locale.ROOT));
case "listen" -> settings.listenVolume = clamp(Float.parseFloat(value), 0, 2);
case "microphone" -> settings.microphoneVolume = clamp(Float.parseFloat(value), 0, 2);
case "range" -> settings.range = (int) clamp(Integer.parseInt(value), MIN_RANGE, MAX_RANGE);
default -> {}
}
} catch (IllegalArgumentException e) {
// A hand-edited line; keep the default.
}
}
} catch (IOException e) {
LOGGER.warn("Couldn't read {}: {}", settings.file, e.toString());
}
return settings;
}
/** The shortest and longest proximity range, in blocks. */
public static final int MIN_RANGE = 5;
public static final int MAX_RANGE = 32;
public Channel channel() {
return channel;
}
public float listenVolume() {
return listenVolume;
}
public float microphoneVolume() {
return microphoneVolume;
}
public int range() {
return range;
}
void setChannel(Channel channel) {
this.channel = channel;
save();
}
void setListenVolume(float volume) {
listenVolume = clamp(volume, 0, 2);
save();
}
void setMicrophoneVolume(float volume) {
microphoneVolume = clamp(volume, 0, 2);
save();
}
void setRange(int blocks) {
range = (int) clamp(blocks, MIN_RANGE, MAX_RANGE);
save();
}
private void save() {
String text = "channel=" + channel.name().toLowerCase(Locale.ROOT) + "\nlisten=" + listenVolume
+ "\nmicrophone=" + microphoneVolume + "\nrange=" + range + "\n";
try {
Files.createDirectories(file.getParent());
Files.writeString(file, text, StandardCharsets.UTF_8);
} catch (IOException e) {
LOGGER.warn("Couldn't save {}: {}", file, e.toString());
}
}
private static float clamp(float value, float min, float max) {
return Math.max(min, Math.min(max, value));
}
}
@@ -0,0 +1,8 @@
/**
* What Eagler servers offer beside the game (ADR 0019): passwords, cookies, redirects and
* voice chat, with their screens.
*/
@NullMarked
package incari.client.eagler;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,137 @@
package incari.client.gui;
import com.mojang.blaze3d.pipeline.RenderTarget;
import com.mojang.blaze3d.pipeline.TextureTarget;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.renderpearl.api.GpuFormat;
import com.mojang.renderpearl.api.textures.GpuTexture;
import incari.client.ui.Look;
import net.minecraft.client.Minecraft;
import net.minecraft.util.Util;
import org.jspecify.annotations.Nullable;
/**
* A screen's blurred backdrop kept between refreshes, a few a second, while the UI over it runs at
* the full frame rate: the HUD editor's, in the Potato GUI preset. The editor blurs the world and
* the game's HUD behind it in either preset, so its own elements stand out; on a Chromebook a
* full-screen blur each frame, on top of the world, is what the Potato preset exists to avoid.
*
* <p>On a refresh the frame is drawn as usual, and right after the blur the screen is copied into a
* texture. Until the next refresh the level is neither extracted nor drawn, nor the HUD (the level
* isn't drawn that frame, as far as the GUI knows), and the copy takes the blur's place. The world
* behind moves at {@link #REFRESHES_PER_SECOND}; under a blur that hardly shows. Those frames don't
* age the game's pooled render targets either: it keeps one only three frames after its last use,
* so each refresh would otherwise make the world's and the blur's full-screen targets again (on the
* stand-in laptop, 15 ms of the refresh frame's CPU, and a missed display refresh).
*
* <p>Render thread only.
*/
public final class BackdropCache {
/** How often the backdrop is drawn again while it's kept. */
private static final int REFRESHES_PER_SECOND = 10;
private static final long INTERVAL_MILLIS = 1000 / REFRESHES_PER_SECOND;
/** Whether a screen asked for its backdrop to be kept. */
private static boolean held;
private static boolean reusing;
private static int refreshes;
private static boolean valid;
private static long refreshedAt;
private static @Nullable TextureTarget copy;
private BackdropCache() {}
/**
* The HUD editor's, while it's shown: keep its backdrop in the Potato preset. Off frees the
* copy.
*/
public static void hold(boolean on) {
held = on;
valid = false;
reusing = false;
if (!on && copy != null) {
copy.destroyBuffers();
copy = null;
}
}
/** How many times the backdrop has been drawn and kept: the smoke test's measure. */
public static int refreshes() {
return refreshes;
}
/** Whether frames draw the kept backdrop this frame: the panorama needn't be drawn either. */
public static boolean reusing() {
return reusing;
}
/**
* Hook ({@code GameRenderer.extract}, before the level's extraction): a frame begins.
*
* @return true if it reuses the kept backdrop, so the level isn't extracted or drawn
*/
public static boolean beginFrame(RenderTarget main) {
reusing = false;
if (!held || Look.normal()) {
valid = false;
return false;
}
TextureTarget kept = copy;
if (kept == null || kept.width != main.width || kept.height != main.height) {
valid = false;
}
reusing = valid && Util.getMillis() - refreshedAt < INTERVAL_MILLIS;
return reusing;
}
/**
* Hook ({@code GuiRenderer.draw}, in place of the blur): the kept backdrop copied onto the
* screen, or the blur run and kept.
*
* @return false for the game to blur as usual: nothing is kept
*/
public static boolean blur(RenderTarget main) {
if (!held || Look.normal()) {
return false;
}
GpuTexture screen = main.getColorTexture();
if (screen == null) {
return false;
}
if (reusing) {
GpuTexture kept = copy == null ? null : copy.getColorTexture();
if (kept != null) {
RenderSystem.getDevice()
.createCommandEncoder()
.copyTextureToTexture(kept, screen, 0, 0, 0, 0, 0, main.width, main.height);
return true;
}
}
Minecraft.getInstance().gameRenderer.processBlurEffect();
GpuTexture target = target(main).getColorTexture();
if (target != null) {
RenderSystem.getDevice()
.createCommandEncoder()
.copyTextureToTexture(screen, target, 0, 0, 0, 0, 0, main.width, main.height);
valid = true;
refreshedAt = Util.getMillis();
refreshes++;
}
return true;
}
private static TextureTarget target(RenderTarget main) {
TextureTarget kept = copy;
if (kept == null || kept.width != main.width || kept.height != main.height) {
if (kept != null) {
kept.destroyBuffers();
}
kept = new TextureTarget("Incari backdrop", main.width, main.height, GpuFormat.RGBA8_UNORM, null);
copy = kept;
}
return kept;
}
}
@@ -0,0 +1,133 @@
package incari.client.gui;
import java.util.Locale;
import java.util.Set;
import net.minecraft.client.gui.components.EditBox;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.Style;
import net.minecraft.util.FormattedCharSequence;
/**
* Passwords shown as stars while they're typed: a login plugin's command in chat ({@code /login},
* {@code /register} and their kin), and a server dialog's text box whose label names a password.
* Only what's drawn changes; the box holds and sends the text as typed. The stars take the place of
* the characters through the box's formatter, so the cursor follows the stars, though a selection
* or a click lands by the hidden characters' widths.
*/
public final class HiddenPasswords {
/**
* Login plugins' commands whose arguments are passwords (AuthMe, nLogin, LibreLogin, Eagler's
* own and their aliases).
*/
private static final Set<String> COMMANDS = Set.of(
"login",
"l",
"log",
"logar",
"register",
"reg",
"registrar",
"changepassword",
"changepass",
"changepw",
"unregister",
"unreg");
/** Words a password box's label holds, in the languages login plugins most often speak. */
private static final String[] PASSWORD_WORDS = {
"password", "passwort", "contraseña", "senha", "mot de passe", "пароль"
};
private static final int STAR = '*';
private HiddenPasswords() {}
/** {@code ChatScreen.init}: the chat box's stars, ahead of its other formatters. */
public static void hideInChat(EditBox input) {
input.addFormatter((text, offset) -> {
int from = hiddenFrom(input.getValue());
return from < 0 ? null : starred(text, offset, from);
});
}
/** {@code InputControlHandlers}: a dialog's text box, starred if its label names a password. */
public static void hideInDialog(EditBox box, Component label) {
if (isPasswordLabel(label.getString())) {
box.addFormatter((text, offset) -> starred(text, offset, 0));
}
}
/**
* A password field of Incari's own (the account screens, ADR 0058): every character a star,
* spaces too. A pass phrase's spaces would show its words' lengths.
*/
public static void hide(EditBox box) {
box.addFormatter((text, offset) -> sink -> {
int i = 0;
while (i < text.length()) {
int codePoint = text.codePointAt(i);
if (!sink.accept(i, Style.EMPTY, STAR)) {
return false;
}
i += Character.charCount(codePoint);
}
return true;
});
}
/**
* {@code ChatComponent.addRecentChat} and {@code CommandHistory}'s load: whether {@code line}
* holds a password, so it's kept out of the chat's history and {@code command_history.txt}. The
* stars only hide it while it's typed; the up arrow and the file would show it whole.
*/
public static boolean hasPassword(String line) {
return hiddenFrom(line) >= 0;
}
/**
* Where a chat line's password starts: after the command word, if the line is a login command
* (namespaced or not, any case); -1 if it isn't one.
*/
static int hiddenFrom(String line) {
if (!line.startsWith("/")) {
return -1;
}
int end = line.indexOf(' ');
if (end < 0) {
return -1;
}
String command = line.substring(1, end).toLowerCase(Locale.ROOT);
command = command.substring(command.indexOf(':') + 1);
return COMMANDS.contains(command) ? end + 1 : -1;
}
static boolean isPasswordLabel(String label) {
String lower = label.toLowerCase(Locale.ROOT);
for (String word : PASSWORD_WORDS) {
if (lower.contains(word)) {
return true;
}
}
return false;
}
/**
* {@code text}, which starts at {@code offset} in the box's value, with every character from
* {@code from} on drawn as a star. Spaces stay, so a password and its confirmation show as two.
*/
static FormattedCharSequence starred(String text, int offset, int from) {
return sink -> {
int i = 0;
while (i < text.length()) {
int codePoint = text.codePointAt(i);
boolean hidden = offset + i >= from && codePoint != ' ';
if (!sink.accept(i, Style.EMPTY, hidden ? STAR : codePoint)) {
return false;
}
i += Character.charCount(codePoint);
}
return true;
};
}
}
@@ -0,0 +1,201 @@
package incari.client.gui;
import com.mojang.blaze3d.pipeline.RenderTarget;
import com.mojang.blaze3d.pipeline.TextureTarget;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.renderpearl.api.GpuFormat;
import com.mojang.renderpearl.api.commands.RenderPass;
import com.mojang.renderpearl.api.pipeline.BlendFunction;
import com.mojang.renderpearl.api.pipeline.ColorTargetState;
import com.mojang.renderpearl.api.pipeline.PrimitiveTopology;
import com.mojang.renderpearl.api.pipeline.RenderPipeline;
import com.mojang.renderpearl.api.textures.FilterMode;
import com.mojang.renderpearl.api.textures.GpuTexture;
import com.mojang.renderpearl.api.textures.GpuTextureView;
import incari.client.tier.DeviceTier;
import java.util.Optional;
import java.util.OptionalDouble;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BindGroupLayouts;
import net.minecraft.client.renderer.state.gui.GuiRenderState;
import net.minecraft.resources.Identifier;
import net.minecraft.util.Util;
import org.joml.Vector4f;
import org.jspecify.annotations.Nullable;
/**
* The HUD drawn into a texture a few dozen times a second and reused in between (ADR 0030),
* Exordium's idea. With no screen open, the GUI is the HUD: the hotbar and its items, hearts, food
* and experience, the chat, the sidebar, boss bars, toasts, F3's text. The game extracts, lays out,
* uploads and draws all of it every frame, though it changes a few times a second at most.
*
* <p>The HUD's first stratum stays live: the camera overlays (vignette, pumpkin, spyglass, powder
* snow, the portal) and the crosshair, whose blends depend on the world behind them. Everything the
* HUD puts above it goes, on a refresh, into a texture of its own instead of the screen, the GUI's
* usual blending leaving its colors premultiplied by their coverage; every frame that texture is
* blended over the screen. Between refreshes nothing above the first stratum is extracted at all.
* Only while frames come faster than refreshes: at a lower frame rate every frame would refresh,
* and the texture would only add a pass, so the HUD is drawn the game's way.
* So the HUD lags the game by up to one refresh interval (50 ms at Standard, 66 at Potato), and its
* colors can differ from the game's by the rounding of one 8-bit step. High, the desktop, and
* {@code ?hud=live} draw it every frame, as the game does.
*
* <p>The split rides on the GUI's own one place to divide a frame's strata (where a screen blurs
* what's behind it): with no screen open nothing else uses it. Render thread only.
*/
public final class HudCache {
private static final RenderPipeline COMPOSITE = RenderPipeline.builder()
.withLocation(Identifier.fromNamespaceAndPath("incari", "pipeline/hud_composite"))
.withBindGroupLayout(BindGroupLayouts.GLOBALS)
.withBindGroupLayout(BindGroupLayouts.IN_SAMPLER)
// The game's screen quad and plain blit: the stages the page already has translated.
.withVertexShader("core/screenquad")
.withFragmentShader("core/blit_screen")
.withColorTargetState(new ColorTargetState(
Optional.of(BlendFunction.TRANSLUCENT_PREMULTIPLIED_ALPHA), GpuFormat.RGBA8_UNORM, 15))
.withPrimitiveTopology(PrimitiveTopology.TRIANGLES)
.build();
private static final Vector4f CLEAR = new Vector4f(0.0F);
private static volatile boolean enabled = true;
private static boolean candidate;
private static boolean reuse;
private static boolean split;
private static boolean cleared;
/** Whether the last refresh drew anything above the split: an empty HUD isn't blended. */
private static boolean drawn;
private static boolean valid;
private static long refreshedAt;
private static long lastFrameAt;
/** The frames' recent length, smoothed: the texture only pays off when frames come faster. */
private static float frameMillis;
private static @Nullable TextureTarget target;
private HudCache() {}
/** The page's {@code ?hud=live}: the HUD drawn every frame, as the game does. */
public static void setEnabled(boolean on) {
enabled = on;
}
/** How long a drawn HUD is reused for; 0 for every frame. */
private static long intervalMillis() {
return switch (DeviceTier.current()) {
case POTATO -> 66;
case STANDARD -> 50;
case HIGH -> 0;
};
}
/**
* Hook ({@code Gui.extractRenderState}, first): a frame's GUI is about to be extracted.
*
* @param hudOnly whether it's the level's HUD alone: a level drawn, no screen or overlay open
*/
public static void beginFrame(boolean hudOnly) {
split = false;
long interval = intervalMillis();
long now = Util.getMillis();
if (lastFrameAt != 0) {
frameMillis += (Math.min(now - lastFrameAt, 1000) - frameMillis) * 0.1F;
}
lastFrameAt = now;
// Frames as long as a refresh interval would refresh every frame: drawing into the texture and
// blending it back would only add a pass. Then the HUD is drawn the game's way.
candidate = enabled && hudOnly && interval > 0 && frameMillis < interval * 0.8F;
if (!candidate) {
valid = false;
reuse = false;
return;
}
RenderTarget main = Minecraft.getInstance().gameRenderer.mainRenderTarget();
TextureTarget kept = target;
if (kept == null || kept.width != main.width || kept.height != main.height) {
valid = false;
}
reuse = valid && now - refreshedAt < interval;
}
/**
* Hook ({@code Hud.extractRenderState}, after the crosshair's stratum): divides the frame there.
*
* @return true to skip the rest of the HUD, which the last drawing still holds
*/
public static boolean split(GuiRenderState state) {
if (!candidate) {
return false;
}
state.blurBeforeThisStratum();
split = true;
if (!reuse) {
refreshedAt = Util.getMillis();
cleared = false;
drawn = false;
valid = true;
}
return reuse;
}
/** Hook ({@code Gui.extractRenderState}): skip the rest of the GUI, the last drawing has it. */
public static boolean reusing() {
return split && reuse;
}
/**
* Hook ({@code GuiRenderer.draw}): whether the strata above the split go into the HUD's texture
* ({@link #target}) rather than after a blur.
*/
public static boolean divided() {
return split;
}
/** The HUD's texture, cleared the first time it's asked for on a refresh. */
public static RenderTarget target() {
RenderTarget main = Minecraft.getInstance().gameRenderer.mainRenderTarget();
TextureTarget kept = target;
if (kept == null || kept.width != main.width || kept.height != main.height) {
if (kept != null) {
kept.destroyBuffers();
}
kept = new TextureTarget("Incari HUD", main.width, main.height, GpuFormat.RGBA8_UNORM, GpuFormat.D32_FLOAT);
target = kept;
cleared = false;
}
GpuTexture color = kept.getColorTexture();
GpuTexture depth = kept.getDepthTexture();
drawn = true;
if (!cleared && color != null && depth != null) {
cleared = true;
RenderSystem.getDevice().createCommandEncoder().clearColorAndDepthTextures(color, CLEAR, depth, 0.0);
}
return kept;
}
/** Hook ({@code GuiRenderer.render}, after its draws): blends the HUD's texture over the screen. */
public static void composite() {
// Nothing above the split (a spectator's HUD, say): nothing to blend.
if (!split || !drawn) {
return;
}
TextureTarget kept = target;
GpuTextureView hud = kept == null ? null : kept.getColorTextureView();
RenderTarget main = Minecraft.getInstance().gameRenderer.mainRenderTarget();
GpuTextureView screen = main.getColorTextureView();
if (hud == null || screen == null) {
return;
}
try (RenderPass pass = RenderSystem.getDevice()
.createCommandEncoder()
.createRenderPass(() -> "Incari HUD", screen, Optional.empty(), null, OptionalDouble.empty())) {
pass.setPipeline(RenderSystem.getCompiledPipeline(COMPOSITE));
RenderSystem.bindDefaultUniforms(pass);
pass.setUniform("InSampler", hud, RenderSystem.getSamplerCache().getClampToEdge(FilterMode.NEAREST));
pass.draw(3, 1, 0, 0);
}
}
}
@@ -0,0 +1,72 @@
package incari.client.gui;
import com.mojang.renderpearl.api.textures.GpuTextureView;
import net.minecraft.client.Minecraft;
import net.minecraft.client.model.Model;
import net.minecraft.client.renderer.state.gui.pip.GuiSkinRenderState;
import org.jspecify.annotations.Nullable;
/**
* A player's skin drawn in the GUI (the title screen's player, the skin customization screen) kept
* between frames while it holds still. The game draws such a model into a texture of its own and
* blits that, but drew it again every frame: a pass with depth, the whole model and its lighting
* for the same picture. Now it's drawn again only when something it's drawn from changes: the
* model, the skin's texture (a new skin is a new texture under the same name), the turn, the size
* or the GUI scale.
*
* <p>Render thread.
*/
public final class SkinPictures {
private SkinPictures() {}
/** What one renderer drew last. */
public static final class Last {
private Model.@Nullable Simple model;
private @Nullable GpuTextureView texture;
private float rotationX;
private float rotationY;
private float pivotY;
private float scale;
private int width;
private int height;
private int guiScale;
/**
* {@code GuiSkinRenderer.textureIsReadyToBlit}: whether the texture already holds {@code
* state}'s picture. If not, the renderer draws it now, and that's remembered.
*/
@SuppressWarnings("ReferenceEquality") // the same model and texture objects, not equal ones
public boolean unchanged(GuiSkinRenderState state) {
GpuTextureView view = Minecraft.getInstance()
.getTextureManager()
.getTexture(state.texture())
.getTextureView();
int scaleNow = Minecraft.getInstance().getWindow().getGuiScale();
int widthNow = state.x1() - state.x0();
int heightNow = state.y1() - state.y0();
if (state.playerModel() == model
&& view == texture
&& state.rotationX() == rotationX
&& state.rotationY() == rotationY
&& state.pivotY() == pivotY
&& state.scale() == scale
&& widthNow == width
&& heightNow == height
&& scaleNow == guiScale) {
return true;
}
model = state.playerModel();
texture = view;
rotationX = state.rotationX();
rotationY = state.rotationY();
pivotY = state.pivotY();
scale = state.scale();
width = widthNow;
height = heightNow;
guiScale = scaleNow;
return false;
}
}
}
@@ -0,0 +1,20 @@
package incari.client.gui;
import incari.client.profiler.ProfilerOverlay;
import incari.client.recorder.ScreenRecorder;
import net.minecraft.client.gui.GuiGraphicsExtractor;
/**
* What Incari draws over everything, screens included, after the game's debug overlay: the
* profiler's overlay and the screen recorder's REC (ADR 0062). Render thread.
*/
public final class TopOverlays {
private TopOverlays() {}
/** Hook ({@code Gui}, after the debug overlay). */
public static void extract(GuiGraphicsExtractor graphics) {
ProfilerOverlay.extract(graphics);
ScreenRecorder.extract(graphics);
}
}
@@ -0,0 +1,5 @@
/** The game's GUI drawn more cheaply (ADR 0030): the HUD kept in a texture between refreshes. */
@NullMarked
package incari.client.gui;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,83 @@
package incari.client.legacy;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.component.SwingAnimation;
import org.jspecify.annotations.Nullable;
/**
* 1.8's combat, on 1.8 servers (ADR 0020):
*
* <ul>
* <li><b>No attack cooldown.</b> Every hit is at full strength, so the held item never dips after
* a swing and the attack indicator never shows; the server decides the damage as 1.8 did.
* <li><b>Sword blocking.</b> Using a sword raises it to block, as long as the use key is held; the
* game sends the use and its release as for a shield, which Via turns into 1.8's block and
* unblock, and the server halves the damage. The first- and third-person poses are the game's
* own for a blocking item that isn't a shield.
* <li><b>The swing before the attack.</b> 1.8 clients swing, then attack or dig; servers' combat
* checks count on that order.
* <li><b>A 0.1 margin around every entity's box</b> when aiming at it, as 1.8 aimed.
* </ul>
*/
public final class LegacyCombat {
/** How far 1.8 grows an entity's box when picking it with the crosshair. */
private static final float PICK_MARGIN_18 = 0.1F;
/** How long a sword can be held up: as long as the key is, like a shield. */
private static final int BLOCK_TICKS = 72000;
private LegacyCombat() {}
/** {@code Player.getAttackStrengthScale}: full strength always, or null for the game's rule. */
public static boolean noCooldown() {
return LegacyRules.combat18;
}
/** {@code Entity.getPickRadius}: 1.8's margin, or {@code current} when that's off. */
public static float pickRadius(float current) {
return LegacyRules.combat18 ? PICK_MARGIN_18 : current;
}
/** Whether {@code stack} is a sword that blocks here. */
public static boolean blocksWith(ItemStack stack) {
return LegacyRules.combat18 && !stack.isEmpty() && isSword(stack);
}
/** {@code Item.use}: raises a sword to block, or null to use the item as the game does. */
public static @Nullable InteractionResult use(Player player, InteractionHand hand) {
ItemStack stack = player.getItemInHand(hand);
if (!blocksWith(stack)) {
return null;
}
player.startUsingItem(hand);
return InteractionResult.CONSUME;
}
/** {@code Item.getUseDuration}: a blocking sword's, or -1 for the item's own. */
public static int useDuration(ItemStack stack) {
return blocksWith(stack) ? BLOCK_TICKS : -1;
}
/**
* {@code Minecraft.startAttack}, before the attack: swings now if 1.8's order is on, and says
* whether it did, so the swing after the attack is skipped.
*/
public static boolean swingFirst(LocalPlayer player, SwingAnimation animation) {
if (!LegacyRules.combat18) {
return false;
}
player.swing(InteractionHand.MAIN_HAND, animation, false);
return true;
}
private static boolean isSword(ItemStack stack) {
// By name, not by tag: the tags an old server's world comes with are Via's, and may not
// list swords.
return BuiltInRegistries.ITEM.getKey(stack.getItem()).getPath().endsWith("_sword");
}
}
@@ -0,0 +1,31 @@
package incari.client.legacy;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.phys.Vec3;
/**
* 1.8's cut-off for slow movement (ADR 0020): each axis of the player's motion under 0.005
* a tick stops, where later versions stop a player's horizontal motion under 0.003 overall. The
* difference decides where a player comes to rest after being knocked back or sliding off an edge,
* which a 1.8 server checks against its own simulation.
*/
public final class LegacyMovement {
private static final double CUT_OFF_18 = 0.005;
private LegacyMovement() {}
/** {@code LivingEntity.aiStep}: whether {@code entity}'s slow motion stops as in 1.8. */
public static boolean cutsLikeOld(LivingEntity entity) {
return LegacyRules.movement18 && entity instanceof LocalPlayer;
}
/** {@code movement} with each axis under 1.8's cut-off stopped. */
public static Vec3 cut(Vec3 movement) {
return new Vec3(
Math.abs(movement.x) < CUT_OFF_18 ? 0 : movement.x,
Math.abs(movement.y) < CUT_OFF_18 ? 0 : movement.y,
Math.abs(movement.z) < CUT_OFF_18 ? 0 : movement.z);
}
}
@@ -0,0 +1,68 @@
package incari.client.legacy;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityDimensions;
import net.minecraft.world.entity.Pose;
import net.minecraft.world.entity.player.Player;
import org.jspecify.annotations.Nullable;
/**
* Players' size and poses as older versions had them (ADR 0020):
*
* <ul>
* <li>sneaking lowers the eyes to 1.54 and keeps the box 1.8 high (1.8), or makes it 1.65
* (1.9 to 1.13); since 1.14 it's 1.5 with the eyes at 1.27, which lets a player under a
* slab where the server says they can't be, and moves the camera and the hitbox other
* players aim at;
* <li>before 1.13 there's no swimming or crawling: sprinting in water is fast walking, and a
* player in a one-block gap stands in it.
* </ul>
*/
public final class LegacyPlayer {
private static final EntityDimensions SNEAKING_18 =
EntityDimensions.scalable(0.6F, 1.8F).withEyeHeight(1.54F);
private static final EntityDimensions SNEAKING_19 =
EntityDimensions.scalable(0.6F, 1.65F).withEyeHeight(1.54F);
private LegacyPlayer() {}
/** {@code Avatar.getDefaultDimensions}: an old version's size for {@code pose}, or null. */
public static @Nullable EntityDimensions dimensions(Pose pose) {
if (!LegacyRules.oldSneak || pose != Pose.CROUCHING) {
return null;
}
return LegacyRules.sneak18() ? SNEAKING_18 : SNEAKING_19;
}
/**
* {@code Player.updatePlayerPose}: before 1.13, sets the pose the old way (sleeping, gliding,
* sneaking or standing, never swimming or crawling) and returns true; false otherwise.
*/
public static boolean updatePose(Player player) {
if (!LegacyRules.noSwimming) {
return false;
}
Pose pose;
if (player.isSleeping()) {
pose = Pose.SLEEPING;
} else if (player.isFallFlying()) {
pose = Pose.FALL_FLYING;
} else if (player.isShiftKeyDown() && !player.getAbilities().flying) {
pose = Pose.CROUCHING;
} else {
pose = Pose.STANDING;
}
player.setPose(pose);
return true;
}
/** {@code Entity.updateSwimming}: before 1.13 nobody swims; true if that's the rule now. */
public static boolean noSwimming(Entity entity) {
if (!LegacyRules.noSwimming || !(entity instanceof Player)) {
return false;
}
entity.setSwimming(false);
return true;
}
}
@@ -0,0 +1,68 @@
package incari.client.legacy;
import incari.client.net.ServerConnections;
import net.minecraft.SharedConstants;
import net.minecraft.client.Minecraft;
/**
* Which of the old versions' behaviours are on (ADR 0020), from the protocol of the server
* the player is on: set once a tick, read everywhere as plain fields. Some reads are in hot paths
* (every collision query asks {@link #blockShapes18}), and a stale read for one tick after joining
* does no harm, so the fields are neither volatile nor locked.
*
* <p>Versions, by protocol: 47 is 1.8, 340 is 1.12.2, 404 is 1.13.2.
*/
public final class LegacyRules {
static final int V1_8 = 47;
static final int V1_12_2 = 340;
static final int V1_13_2 = 404;
/** The protocol the rules follow now: the server's, or the game's own. */
private static int protocol = -1;
/** 1.8's combat: no cooldown, sword blocking, the swing before the attack, 0.1 pick margin. */
static boolean combat18;
/** 1.8's cut-off for slow movement: 0.005 on each axis. */
static boolean movement18;
/** Before 1.14: sneaking keeps eye height 1.54 and the box 1.8 (1.8) or 1.65 (1.9 to 1.13). */
static boolean oldSneak;
/** Before 1.13: no swimming or crawling pose. */
static boolean noSwimming;
/** 1.8's block shapes: ladders, lily pads, panes, anvils, farmland. */
static boolean blockShapes18;
private LegacyRules() {}
/** {@link incari.client.IncariTicks}: follows the server the player is on. Game thread. */
public static void update(Minecraft minecraft) {
int now = minecraft.getConnection() == null || minecraft.isLocalServer()
? SharedConstants.getCurrentVersion().protocolVersion()
: ServerConnections.lastJoinedProtocol();
if (now == protocol) {
return;
}
protocol = now;
boolean current = now == SharedConstants.getCurrentVersion().protocolVersion() || now < 0;
combat18 = !current && now <= V1_8;
movement18 = !current && now <= V1_8;
blockShapes18 = !current && now <= V1_8;
oldSneak = !current && now <= V1_13_2;
noSwimming = !current && now <= V1_12_2;
}
/** The protocol the rules follow, for the debug screen and checks. */
public static int protocol() {
return protocol;
}
/** Whether 1.8's combat is on, for checks. */
public static boolean combat18() {
return combat18;
}
/** Whether sneaking keeps 1.8's box, for checks. */
public static boolean sneak18() {
return oldSneak && protocol <= V1_8;
}
}
@@ -0,0 +1,149 @@
package incari.client.legacy;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.block.AnvilBlock;
import net.minecraft.world.level.block.CrossCollisionBlock;
import net.minecraft.world.level.block.FarmlandBlock;
import net.minecraft.world.level.block.IronBarsBlock;
import net.minecraft.world.level.block.LadderBlock;
import net.minecraft.world.level.block.LilyPadBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape;
import org.jspecify.annotations.Nullable;
/**
* Blocks whose shape changed after 1.8, as a 1.8 server simulates them (ADR 0020). A 1.8
* server moves the player against these shapes; a client that collides with the newer ones
* rubber-bands (a ladder a sixteenth thicker, a lily pad six times taller) or is flagged by the
* server's movement checks.
*
* <ul>
* <li>ladders: 2/16 thick, against the wall they hang on (3/16 since 1.9);
* <li>lily pads: a full square, 1/64 high (a smaller square 1.5/16 high since 1.9);
* <li>glass panes and iron bars: arms along the directions they connect in, an arm through the
* whole block where they connect both ways or not at all, no post; the outline is the box
* around them (a post with arms since 1.9);
* <li>anvils: a full-height box, 12/16 wide across their length (a stepped shape since 1.13);
* <li>farmland: a full block to collide with, 15/16 to look at (15/16 both since 1.10).
* </ul>
*
* Called from the two shape getters of every block state, in hot paths: one field read when off.
*/
public final class LegacyShapes {
private static final VoxelShape LADDER_NORTH = Shapes.box(0, 0, 14 / 16.0, 1, 1, 1);
private static final VoxelShape LADDER_SOUTH = Shapes.box(0, 0, 0, 1, 1, 2 / 16.0);
private static final VoxelShape LADDER_WEST = Shapes.box(14 / 16.0, 0, 0, 1, 1, 1);
private static final VoxelShape LADDER_EAST = Shapes.box(0, 0, 0, 2 / 16.0, 1, 1);
private static final VoxelShape LILY_PAD = Shapes.box(0, 0, 0, 1, 1 / 64.0, 1);
private static final VoxelShape ANVIL_X = Shapes.box(0, 0, 2 / 16.0, 1, 1, 14 / 16.0);
private static final VoxelShape ANVIL_Z = Shapes.box(2 / 16.0, 0, 0, 14 / 16.0, 1, 1);
/** Panes by their connections (north 1, east 2, south 4, west 8): what collides, and the outline. */
private static final VoxelShape[] PANE_COLLISION = new VoxelShape[16];
private static final VoxelShape[] PANE_OUTLINE = new VoxelShape[16];
static {
double thin0 = 7 / 16.0;
double thin1 = 9 / 16.0;
for (int mask = 0; mask < 16; mask++) {
boolean north = (mask & 1) != 0;
boolean east = (mask & 2) != 0;
boolean south = (mask & 4) != 0;
boolean west = (mask & 8) != 0;
boolean any = mask != 0;
// East-west arm: through the block if it connects both ways or not at all, else half.
double x0 = 0;
double x1 = 1;
boolean xArm = true;
if ((!west || !east) && any) {
if (west) {
x1 = 0.5;
} else if (east) {
x0 = 0.5;
} else {
xArm = false;
}
}
double z0 = 0;
double z1 = 1;
boolean zArm = true;
if ((!north || !south) && any) {
if (north) {
z1 = 0.5;
} else if (south) {
z0 = 0.5;
} else {
zArm = false;
}
}
VoxelShape collision = Shapes.empty();
if (xArm) {
collision = Shapes.or(collision, Shapes.box(x0, 0, thin0, x1, 1, thin1));
}
if (zArm) {
collision = Shapes.or(collision, Shapes.box(thin0, 0, z0, thin1, 1, z1));
}
PANE_COLLISION[mask] = collision;
PANE_OUTLINE[mask] =
Shapes.box(xArm ? x0 : thin0, 0, zArm ? z0 : thin0, xArm ? x1 : thin1, 1, zArm ? z1 : thin1);
}
}
private LegacyShapes() {}
/** {@code BlockStateBase.getShape}: the outline 1.8 gives {@code state}, or null for the current one. */
public static @Nullable VoxelShape outline(BlockState state, BlockGetter level, BlockPos pos) {
if (!LegacyRules.blockShapes18) {
return null;
}
return shared(state);
}
/** {@code BlockStateBase.getCollisionShape}: what 1.8 collides with, or null for the current shape. */
public static @Nullable VoxelShape collision(BlockState state, BlockGetter level, BlockPos pos) {
if (!LegacyRules.blockShapes18) {
return null;
}
if (state.getBlock() instanceof FarmlandBlock) {
return Shapes.block();
}
if (state.getBlock() instanceof IronBarsBlock) {
return PANE_COLLISION[paneMask(state)];
}
return shared(state);
}
/** Shapes that are the same to look at and to collide with. */
private static @Nullable VoxelShape shared(BlockState state) {
var block = state.getBlock();
if (block instanceof LadderBlock) {
return switch (state.getValue(LadderBlock.FACING)) {
case SOUTH -> LADDER_SOUTH;
case WEST -> LADDER_WEST;
case EAST -> LADDER_EAST;
default -> LADDER_NORTH;
};
}
if (block instanceof LilyPadBlock) {
return LILY_PAD;
}
if (block instanceof AnvilBlock) {
return state.getValue(AnvilBlock.FACING).getAxis() == Direction.Axis.X ? ANVIL_X : ANVIL_Z;
}
if (block instanceof IronBarsBlock) {
return PANE_OUTLINE[paneMask(state)];
}
return null;
}
private static int paneMask(BlockState state) {
return (state.getValue(CrossCollisionBlock.NORTH) ? 1 : 0)
| (state.getValue(CrossCollisionBlock.EAST) ? 2 : 0)
| (state.getValue(CrossCollisionBlock.SOUTH) ? 4 : 0)
| (state.getValue(CrossCollisionBlock.WEST) ? 8 : 0);
}
}
@@ -0,0 +1,10 @@
/**
* The legacy behaviour layer (ADR 0020): how the client moves, fights and collides on servers
* of older versions, 1.8 above all, so it plays as those versions' clients did. Everything keys off
* the version of the server the player is on ({@link incari.client.legacy.LegacyRules}); in
* singleplayer and on current servers nothing changes.
*/
@NullMarked
package incari.client.legacy;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,117 @@
package incari.client.look;
import incari.client.ui.Panels;
import incari.client.ui.RoundRects;
import incari.client.ui.Skins;
import incari.client.ui.Theme;
import net.minecraft.client.gui.GuiGraphicsExtractor;
/**
* The HUD's text panels in the client's look, from hooks where the game fills them: the tab
* list's header, players and footer as rounded tinted glass, the scoreboard sidebar on one card,
* chat's lines on a cold tint, the chat field as a rounded well. Each returns false, for the game
* to draw its own, when the look is off. No blur and no animation: the HUD is drawn into a texture
* between refreshes in the browser (ADR 0030), and its cost is every frame's.
*
* <p>Render thread. Hot path: nothing allocates.
*/
public final class HudLook {
/** Chat's lines: the game's background opacity over a cold dark instead of black. */
private static final int CHAT_TINT = 0x0C1219;
/** How far the scoreboard's card reaches past the game's box on each side. */
private static final int SCOREBOARD_PAD = 2;
private HudLook() {}
/**
* How far {@link #scoreboard}'s card reaches past the box it's given on each side: 0 when the
* game draws its own. What places the sidebar measures the card, not the box.
*/
public static int scoreboardPad() {
return on() ? SCOREBOARD_PAD : 0;
}
private static boolean on() {
return Skins.current() != null;
}
/**
* {@code PlayerTabOverlay}: one of the tab list's boxes (header, players, footer), from
* ({@code x0}, {@code y0}) to ({@code x1}, {@code y1}). The game's boxes touch, so they're drawn
* as pieces of one card: rounded and padded only at its {@code first} box's top and {@code
* last} box's bottom, a hairline at each seam. Cards of their own would overlap there, and the
* glass doubled into a dark band.
*/
public static boolean tabBox(
GuiGraphicsExtractor graphics, int x0, int y0, int x1, int y1, boolean first, boolean last) {
if (!on()) {
return false;
}
int top = first ? y0 - 2 : y0;
int bottom = last ? y1 + 2 : y1;
if (first && last) {
RoundRects.fill(graphics, x0 - 3, top, x1 - x0 + 6, bottom - top, Theme.RADIUS, Theme.BACKGROUND);
return true;
}
// The card's straight ends reach past the seam, cut there.
graphics.enableScissor(x0 - 3, top, x1 + 3, bottom);
int reach = Theme.RADIUS + 1;
int y = first ? top : top - reach;
int height = (last ? bottom : bottom + reach) - y;
RoundRects.fill(graphics, x0 - 3, y, x1 - x0 + 6, height, Theme.RADIUS, Theme.BACKGROUND);
graphics.disableScissor();
if (!first) {
RoundRects.hairline(graphics, x0 + 1, y0, x1 - x0 - 2, 0x26FFFFFF);
}
return true;
}
/**
* {@code PlayerTabOverlay}: a player's row in the list, left on the card's glass. The game's
* rows are a unit apart, and a tint on each showed the gaps as dark lines.
*/
public static boolean tabRow(GuiGraphicsExtractor graphics, int x0, int y0, int x1, int y1) {
return on();
}
/** {@code Hud.displayScoreboardSidebar}: the sidebar's card, its title row above a hairline. */
public static boolean scoreboard(GuiGraphicsExtractor graphics, int x0, int y0, int x1, int y1, int titleBottom) {
if (!on()) {
return false;
}
RoundRects.fill(
graphics,
x0 - SCOREBOARD_PAD,
y0 - SCOREBOARD_PAD,
x1 - x0 + 2 * SCOREBOARD_PAD,
y1 - y0 + 2 * SCOREBOARD_PAD,
Theme.RADIUS,
Theme.BACKGROUND);
RoundRects.hairline(graphics, x0 + 2, titleBottom, x1 - x0 - 4, 0x26FFFFFF);
return true;
}
/** {@code ChatComponent}: a line's background, {@code argb} as the game would fill it. */
public static int chatLine(int argb) {
return on() ? (argb & 0xFF000000) | CHAT_TINT : argb;
}
/** {@code ChatScreen}: the field chat is typed into. */
public static boolean chatField(GuiGraphicsExtractor graphics, int x0, int y0, int x1, int y1) {
if (!on()) {
return false;
}
RoundRects.box(
graphics,
x0,
y0 - 1,
x1 - x0,
y1 - y0 + 2,
Theme.RADIUS,
Panels.alpha(Theme.FLOATING, 0.85F),
Theme.ACCENT & 0x66FFFFFF);
return true;
}
}
@@ -0,0 +1,196 @@
package incari.client.look;
import com.mojang.blaze3d.platform.NativeImage;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.renderpearl.api.textures.FilterMode;
import incari.client.ui.Logo;
import incari.client.ui.MenuBackdrop;
import incari.client.ui.RoundRects;
import incari.client.ui.Theme;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.renderer.RenderPipelines;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.resources.Identifier;
import net.minecraft.util.ARGB;
import net.minecraft.util.Util;
import org.jspecify.annotations.Nullable;
/**
* The loading screen in the client's look: the menus' photo ({@link MenuBackdrop}), Incari's mark
* in a soft glow, and a loading bar drawn as the mark's comet, an ice-blue trail with a bright head.
* The game's {@code LoadingOverlay} stays the overlay and keeps its timing (when it fades in and
* out); two hooks hand its backdrop and its logo and bar over to this.
*
* <p>It draws during the first resource reload, so it uses nothing a reload loads: no text (the
* fonts aren't there yet), only the photo and the mark, read from the class path, and the look's
* painted shapes. The same screen starts the title, so the fade out into it changes nothing behind.
*
* <p>Render thread.
*/
public final class LoadingLook {
/** A light dim over the photo so the mark stands out. */
private static final int DIM = 0x330C131B;
/** The backdrop when the player asked for a dark loading screen (Monochrome Logo). */
private static final int DARK = 0xFF0C131B;
private static final int BAR_HEIGHT = 4;
/** How quickly the bar catches up with the reload's progress: about two thirds in this time. */
private static final float CATCH_UP_MILLIS = 180.0F;
/** One pulse of the bar's head, in milliseconds. */
private static final float PULSE_MILLIS = 1400.0F;
/** The overlay the bar's progress belongs to: a new one starts it at 0. */
private static @Nullable Object overlay;
private static final Identifier GLOW = Identifier.fromNamespaceAndPath("incari", "loading_glow");
private static final int GLOW_PIXELS = 64;
private static boolean glowMade;
private static float shown;
private static long shownAt;
private LoadingLook() {}
/** {@code LoadingOverlay}'s backdrop, over the whole screen at {@code alpha} (0 to 255). */
public static void background(GuiGraphicsExtractor graphics, int width, int height, int alpha) {
float fade = Math.max(0, Math.min(255, alpha)) / 255.0F;
if (Minecraft.getInstance().options.darkMojangStudiosBackground().get()) {
graphics.fill(0, 0, width, height, ARGB.multiplyAlpha(DARK, fade));
return;
}
MenuBackdrop.extract(graphics, width, height, fade);
graphics.fill(0, 0, width, height, ARGB.multiplyAlpha(DIM, fade));
}
/**
* {@code LoadingOverlay}'s logo and bar: the mark at {@code markAlpha} (0 to 1) and the bar
* toward {@code progress} (0 to 1) at {@code barAlpha}, for {@code owner}, the overlay. Returns
* true: the game's logo and bar are left out.
*/
@SuppressWarnings("ReferenceEquality") // the overlay object, not an equal one
public static boolean content(
Object owner, GuiGraphicsExtractor graphics, float markAlpha, float progress, float barAlpha) {
int width = graphics.guiWidth();
int height = graphics.guiHeight();
long now = Util.getMillis();
if (owner != overlay) {
overlay = owner;
shown = 0.0F;
shownAt = now;
}
// By time, not by frame: the game's per-frame smoothing lags far behind at a low frame rate.
float step = 1.0F - (float) Math.exp(-(now - shownAt) / CATCH_UP_MILLIS);
shown = Math.max(shown, shown + (Math.max(0, Math.min(1, progress)) - shown) * step);
shownAt = now;
int scale = Math.max(1, Minecraft.getInstance().getWindow().getGuiScale());
// A quarter of the screen's smaller side, at most the mark's 256 source pixels.
int size = Math.max(24, Math.min(Math.min(width, height) / 4, 256 / scale));
int gap = Math.max(14, size / 4);
int top = (height - size - gap - BAR_HEIGHT) / 2;
int markX = (width - size) / 2;
if (markAlpha > 0.0F) {
// A soft round glow behind the mark, half again its size.
RoundRects.pixels(graphics);
glow(
graphics,
(markX + size / 2) * scale,
(top + size / 2) * scale,
size * scale * 3 / 2,
ARGB.multiplyAlpha(Theme.ACCENT & 0x8CFFFFFF, markAlpha));
graphics.pose().popMatrix();
Logo.draw(graphics, markX, top, size, markAlpha);
}
if (barAlpha > 0.0F) {
int barWidth = Math.max(size, Math.min(240, width * 2 / 5));
bar(graphics, (width - barWidth) / 2, top + size + gap, barWidth, barAlpha, now);
}
return true;
}
/** The comet: a faint track, the trail filled to {@link #shown} in a glow, its head a bright dot. */
private static void bar(GuiGraphicsExtractor graphics, int x, int y, int width, float alpha, long now) {
int radius = BAR_HEIGHT / 2;
RoundRects.box(
graphics,
x,
y,
width,
BAR_HEIGHT,
radius,
ARGB.multiplyAlpha(0x2EFFFFFF, alpha),
ARGB.multiplyAlpha(0x1FFFFFFF, alpha));
int filled = Math.max(BAR_HEIGHT, Math.round(width * shown));
RoundRects.box(
graphics,
x,
y,
filled,
BAR_HEIGHT,
radius,
ARGB.multiplyAlpha(Theme.ACCENT, alpha),
0,
6,
0,
ARGB.multiplyAlpha(Theme.ACCENT & 0x66FFFFFF, alpha));
// The head pulses gently, so a long wait on one step still looks alive.
float pulse = 0.5F + 0.5F * (float) Math.sin(now % (long) PULSE_MILLIS / PULSE_MILLIS * 2 * Math.PI);
int scale = RoundRects.pixels(graphics);
int centerX = (x + filled) * scale - scale;
int centerY = (y * 2 + BAR_HEIGHT) * scale / 2;
int halo = Math.round(BAR_HEIGHT * scale * (4.0F + pulse));
int head = BAR_HEIGHT * scale * 4;
glow(graphics, centerX, centerY, halo, ARGB.multiplyAlpha(Theme.ACCENT & 0xE6FFFFFF, alpha));
glow(graphics, centerX, centerY, head, ARGB.white(alpha));
graphics.pose().popMatrix();
}
/**
* A soft round glow {@code diameter} screen pixels across, centred on ({@code centerX}, {@code
* centerY}) in screen pixels: call between {@link RoundRects#pixels} and its {@code popMatrix}.
* Its own smoothly sampled texture: the look's dots are small and sampled to the pixel, and
* blow up blocky at this size.
*/
private static void glow(GuiGraphicsExtractor graphics, int centerX, int centerY, int diameter, int argb) {
if (!glowMade) {
glowMade = true;
NativeImage image = new NativeImage(GLOW_PIXELS, GLOW_PIXELS, false);
for (int py = 0; py < GLOW_PIXELS; py++) {
for (int px = 0; px < GLOW_PIXELS; px++) {
float dx = (px + 0.5F) / GLOW_PIXELS * 2 - 1;
float dy = (py + 0.5F) / GLOW_PIXELS * 2 - 1;
float t = Math.max(0, 1 - (float) Math.sqrt(dx * dx + dy * dy));
image.setPixel(px, py, Math.round(t * t * 255.0F) << 24 | 0xFFFFFF);
}
}
Minecraft.getInstance().getTextureManager().register(GLOW, new Smooth(image));
}
graphics.blit(
RenderPipelines.GUI_TEXTURED,
GLOW,
centerX - diameter / 2,
centerY - diameter / 2,
0,
0,
diameter,
diameter,
GLOW_PIXELS,
GLOW_PIXELS,
GLOW_PIXELS,
GLOW_PIXELS,
argb);
}
/** A painted texture sampled smoothly and clamped at its edges, its pixels freed once uploaded. */
private static final class Smooth extends DynamicTexture {
Smooth(NativeImage image) {
super(GLOW::toString, image);
sampler = RenderSystem.getSamplerCache().getClampToEdge(FilterMode.LINEAR);
image.close();
}
}
}
@@ -0,0 +1,38 @@
package incari.client.look;
import incari.client.net.ConnectionDetailsScreen;
import incari.client.net.DirectJoinVia;
import incari.client.net.Reconnect;
import incari.client.net.WispServers;
import incari.client.relay.RelayScreen;
import incari.client.ui.Look;
import incari.client.ui.ScreenEdits;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.DirectJoinServerScreen;
import net.minecraft.client.gui.screens.DisconnectedScreen;
import net.minecraft.client.gui.screens.ManageServerScreen;
import net.minecraft.client.gui.screens.PauseScreen;
import net.minecraft.client.gui.screens.multiplayer.JoinMultiplayerScreen;
/** Puts the client's look on: the skin ({@link Look}) and the edits to the game's screens. */
public final class Looks {
private static boolean started;
private Looks() {}
/** From the first client tick, or the title screen's first layout if that comes first. */
public static void start(Minecraft minecraft) {
if (started) {
return;
}
started = true;
Look.start(minecraft);
ScreenEdits.edit(PauseScreen.class, PauseLook::edit);
ScreenEdits.edit(JoinMultiplayerScreen.class, RelayScreen::fitRow);
ScreenEdits.edit(ManageServerScreen.class, WispServers::editServerScreen);
ScreenEdits.edit(DirectJoinServerScreen.class, DirectJoinVia::edit);
ScreenEdits.edit(DisconnectedScreen.class, Reconnect::edit);
ScreenEdits.edit(DisconnectedScreen.class, ConnectionDetailsScreen::edit);
}
}
@@ -0,0 +1,22 @@
package incari.client.look;
import incari.client.ui.Icons;
import org.jspecify.annotations.Nullable;
/** The icons modules name for their menu buttons ({@code MenuButton.icon}). */
final class MenuIcons {
private MenuIcons() {}
/** The icon called {@code name}, or null for none. */
static @Nullable Icons of(String name) {
return switch (name) {
case "camera" -> Icons.CAMERA;
case "palette" -> Icons.PALETTE;
case "grid" -> Icons.GRID;
case "layout" -> Icons.LAYOUT;
case "incari" -> Icons.INCARI;
default -> null;
};
}
}
@@ -0,0 +1,93 @@
package incari.client.look;
import incari.client.modules.IncariModules;
import incari.client.ui.EditedScreen;
import incari.client.ui.ScreenPanels;
import incari.client.ui.Ui;
import incari.framework.MenuButton;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.gui.components.AbstractWidget;
import net.minecraft.client.gui.components.StringWidget;
import net.minecraft.client.gui.screens.PauseScreen;
import net.minecraft.network.chat.Component;
/**
* The pause menu in the client's look: its buttons gathered on one glass card in the middle
* of the screen, the title at the card's top left. The game lays the menu out; this moves it, after
* each layout. The voice panel and an Eagler server's icons keep their places (the icons follow
* their buttons when drawn).
*/
final class PauseLook {
private static final int PADDING = 12;
private static final int HEADER = 9 + 9;
/** Half the widest row of the game's menu, and a margin: what's further out isn't the menu. */
private static final int MENU_HALF_WIDTH = 120;
private PauseLook() {}
static void edit(EditedScreen<PauseScreen> edited) {
PauseScreen screen = edited.screen();
ScreenPanels.clear(screen);
StringWidget title = null;
List<AbstractWidget> menu = new ArrayList<>();
int middle = edited.width() / 2;
for (AbstractWidget widget : edited.widgets()) {
if (title == null && widget instanceof StringWidget text) {
title = text;
} else if (Math.abs(widget.getX() + widget.getWidth() / 2 - middle) < MENU_HALF_WIDTH
&& widget.getX() >= middle - MENU_HALF_WIDTH) {
menu.add(widget);
}
}
if (menu.isEmpty()) {
// The menu hidden (F3 and Escape): only "Game Paused" at the top.
return;
}
int left = Integer.MAX_VALUE;
int top = Integer.MAX_VALUE;
int right = Integer.MIN_VALUE;
int bottom = Integer.MIN_VALUE;
for (AbstractWidget widget : menu) {
left = Math.min(left, widget.getX());
top = Math.min(top, widget.getY());
right = Math.max(right, widget.getRight());
bottom = Math.max(bottom, widget.getBottom());
}
// Modules' own buttons (Screenshot Manager's gallery), a row under the game's.
List<MenuButton> extra = IncariModules.system().menuButtons();
if (!extra.isEmpty()) {
int count = Math.min(3, extra.size());
int gap = 4;
int each = (right - left - (count - 1) * gap) / count;
int rowY = bottom + gap;
for (int i = 0; i < count; i++) {
MenuButton button = extra.get(i);
int buttonWidth = i == count - 1 ? right - left - (count - 1) * (each + gap) : each;
AbstractWidget widget = edited.add(Ui.menuButton(
Component.literal(button.label()),
MenuIcons.of(button.icon()),
buttonWidth,
button.action())
.centered());
widget.setPosition(left + i * (each + gap), rowY);
menu.add(widget);
bottom = Math.max(bottom, widget.getBottom());
}
}
int width = right - left + 2 * PADDING;
int height = HEADER + bottom - top + 2 * PADDING;
int x = (edited.width() - width) / 2;
int y = Math.max(6, (edited.height() - height) / 2);
int dx = x + PADDING - left;
int dy = y + PADDING + HEADER - top;
for (AbstractWidget widget : menu) {
widget.setPosition(widget.getX() + dx, widget.getY() + dy);
}
if (title != null) {
title.setPosition(x + PADDING, y + PADDING);
}
ScreenPanels.add(screen, x, y, width, height);
}
}
@@ -0,0 +1,73 @@
package incari.client.look;
import incari.client.ui.RoundRects;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.util.Util;
/**
* Snow falling over the menus in the Normal preset: a hundred or so soft flakes drifting down and
* swaying, larger ones nearer and faster. Positions are fractions of the screen, so a resize keeps
* the snow where it was.
*
* <p>Render thread. Hot path: fixed arrays, nothing allocates.
*/
public final class Snowfall {
private static final int FLAKES = 110;
private final float[] x = new float[FLAKES];
private final float[] y = new float[FLAKES];
private final float[] size = new float[FLAKES];
private final float[] speed = new float[FLAKES];
private final float[] phase = new float[FLAKES];
/** This frame's flakes for {@link RoundRects#dots}: x, y, size, color each. */
private final int[] dots = new int[FLAKES * 4];
private long last;
private int seed = 0x2F6E2B1;
public Snowfall() {
for (int i = 0; i < FLAKES; i++) {
x[i] = random();
y[i] = random();
size[i] = 0.25F + random() * 0.75F;
// A screen's height in 9 to 26 seconds; the nearest, largest flakes fastest.
speed[i] = 0.038F + size[i] * 0.07F;
phase[i] = random() * 6.28F;
}
}
/** Moves the flakes on by the time since the last frame and draws them over the screen. */
public void extract(GuiGraphicsExtractor graphics, int width, int height) {
long now = Util.getMillis();
float dt = last == 0 ? 0 : Math.min(0.1F, (now - last) / 1000.0F);
last = now;
float seconds = (now % 600_000L) / 1000.0F;
int scale = Math.max(1, Minecraft.getInstance().getWindow().getGuiScale());
float w = width * scale;
float h = height * scale;
for (int i = 0; i < FLAKES; i++) {
y[i] += speed[i] * dt;
if (y[i] > 1.02F) {
y[i] = -0.02F;
x[i] = random();
}
float sway = (float) Math.sin(seconds * (0.5F + size[i] * 0.4F) + phase[i]) * 0.008F;
int alpha = Math.round(90 + size[i] * 130);
dots[i * 4] = Math.round((x[i] + sway) * w);
dots[i * 4 + 1] = Math.round(y[i] * h);
dots[i * 4 + 2] = Math.max(2, Math.round((1.5F + size[i] * 3.5F) * scale / 2.0F));
dots[i * 4 + 3] = alpha << 24 | 0xFFFFFF;
}
// Every flake in one render state: the snow is a hundred quads, not a hundred states.
RoundRects.dots(graphics, dots, FLAKES);
}
private float random() {
seed ^= seed << 13;
seed ^= seed >>> 17;
seed ^= seed << 5;
return (seed >>> 8) / (float) (1 << 24);
}
}
@@ -0,0 +1,14 @@
package incari.client.look;
import net.minecraft.client.gui.GuiGraphicsExtractor;
/**
* What the title screen shows behind its menu: the menus' photo ({@link incari.client.ui.MenuBackdrop}) unless
* something else is set ({@link TitleLook#backdrop}).
*/
@FunctionalInterface
public interface TitleBackdrop {
/** Draws the backdrop over the whole screen, {@code width} by {@code height} GUI units. */
void extract(GuiGraphicsExtractor graphics, int width, int height, float a);
}
@@ -0,0 +1,465 @@
package incari.client.look;
import incari.client.IncariBuild;
import incari.client.cosmetics.Cosmetics;
import incari.client.cosmetics.WardrobeScreen;
import incari.client.modules.IncariModules;
import incari.client.online.AccountScreen;
import incari.client.online.IncariOnline;
import incari.client.online.UpdateNotice;
import incari.client.profile.PlayerName;
import incari.client.profile.TitleProfile;
import incari.client.settings.IncariSettingsScreen;
import incari.client.ui.Icons;
import incari.client.ui.Logo;
import incari.client.ui.Look;
import incari.client.ui.MenuBackdrop;
import incari.client.ui.Panels;
import incari.client.ui.RoundRects;
import incari.client.ui.Theme;
import incari.client.ui.Ui;
import incari.framework.MenuButton;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import net.minecraft.SharedConstants;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.gui.components.AbstractWidget;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.CommonButtons;
import net.minecraft.client.gui.components.PlainTextButton;
import net.minecraft.client.gui.components.SpriteIconButton;
import net.minecraft.client.gui.screens.CreditsAndAttributionScreen;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.gui.screens.multiplayer.JoinMultiplayerScreen;
import net.minecraft.client.gui.screens.multiplayer.SafetyScreen;
import net.minecraft.client.gui.screens.options.AccessibilityOptionsScreen;
import net.minecraft.client.gui.screens.options.LanguageSelectScreen;
import net.minecraft.client.gui.screens.options.OptionsScreen;
import net.minecraft.client.gui.screens.worldselection.SelectWorldScreen;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.FontDescription;
import net.minecraft.network.chat.Style;
import net.minecraft.resources.Identifier;
import net.minecraft.util.ARGB;
import net.minecraft.util.Util;
import org.jspecify.annotations.Nullable;
/**
* The title screen in the client's look: the backdrop under a cold tint that deepens toward
* the menu, Incari's wordmark over a column of menu buttons on the left, the player on a glass card
* on the right, and in Normal, falling snow and the menu rising in as the screen opens.
*
* <p>The game's {@code TitleScreen} stays the screen (the game checks for it by class): two hooks
* hand its layout ({@code init}) and its drawing ({@code extractRenderState}) over to this. Realms,
* the splash text and the Friends button are left out; Incari plays on its own servers and offline.
* Render thread.
*/
public final class TitleLook {
private static final Identifier WORDMARK_FONT = Identifier.fromNamespaceAndPath("incari", "wordmark");
private static final Style WORDMARK =
Style.EMPTY.withFont(new FontDescription.Resource(WORDMARK_FONT)).withoutShadow();
private static final String NAME = "INCARI";
private static final Component[] LETTERS = new Component[NAME.length()];
private static final Component SUBTITLE = Component.literal("CLIENT · " + IncariBuild.VERSION);
private static final Component CARD_LABEL = Component.literal("OFFLINE MODE");
private static final Component CARD_LABEL_MICROSOFT = Component.literal("MICROSOFT ACCOUNT");
private static final Component UPDATE_HINT = Component.literal("GitHub");
private static final Component NOTES_HINT = Component.literal("What's new");
private static final Component COPYRIGHT = Component.translatable("title.credits");
private static final String VERSION =
"Incari · Minecraft " + SharedConstants.getCurrentVersion().name();
private static final int WORDMARK_HEIGHT = 26;
private static final int LETTER_SPACING = 3;
private static final int ROW = Theme.CONTROL_HEIGHT;
private static final int ROW_GAP = 5;
/** How long the menu takes to rise in, in Normal. */
private static final float RISE_MILLIS = 550.0F;
private static final Snowfall SNOW = new Snowfall();
private static final List<AbstractWidget> RISING = new ArrayList<>();
private static TitleBackdrop backdrop =
(graphics, width, height, a) -> MenuBackdrop.extract(graphics, width, height);
private static @Nullable Screen laidOut;
private static long shownAt;
private static int columnX;
private static int wordmarkY;
private static int cardX;
private static int cardY;
private static int cardWidth;
private static int cardHeight;
private static int modelBottom;
/** Where the small screens' links in the top left corner end; 0 with the card. */
private static int linksRight;
/** The card's Incari Account button, named for the account once signed in. */
private static @Nullable Button account;
private static long accountRevision = -1;
/** The update notice at the top, hidden until the online service names a newer release. */
private static Ui.@Nullable MenuButton update;
private static long updateRevision = -1;
static {
for (int i = 0; i < NAME.length(); i++) {
LETTERS[i] = Component.literal(String.valueOf(NAME.charAt(i))).withStyle(WORDMARK);
}
}
private TitleLook() {}
/** Shows {@code next} behind the title screen from the next frame. */
public static void backdrop(TitleBackdrop next) {
backdrop = next;
}
/**
* {@code TitleScreen.init}: lays the title screen out in the client's look, adding its widgets
* with {@code add}. Returns false for the game to lay it out its own way.
*/
@SuppressWarnings("ReferenceEquality") // the title screen object, not an equal one
public static boolean init(Screen title, Consumer<AbstractWidget> add) {
Minecraft minecraft = Minecraft.getInstance();
Looks.start(minecraft);
if (laidOut != title) {
shownAt = Util.getMillis();
}
laidOut = title;
RISING.clear();
int width = title.width;
int height = title.height;
int columnWidth = Math.clamp(Math.round(width * 0.27F), 124, 168);
columnX = Math.max(14, Math.round(width * 0.07F));
// Incari Settings and modules' own buttons on a row under Multiplayer (the gallery is in there).
List<MenuButton> extra = new ArrayList<>();
extra.add(new MenuButton(
"incari",
IncariSettingsScreen.TITLE.getString(),
"incari",
() -> minecraft.gui.setScreen(new IncariSettingsScreen(minecraft.gui.screen()))));
extra.addAll(IncariModules.system().menuButtons());
int rows = 4;
int block = WORDMARK_HEIGHT + 18 + rows * ROW + (rows - 1) * ROW_GAP;
wordmarkY = Math.max(8, (height - block) / 2 - 6);
int y = wordmarkY + WORDMARK_HEIGHT + 24;
rise(
add,
place(
Ui.menuButton(
Component.translatable("menu.singleplayer"),
Icons.CUBE,
columnWidth,
() -> minecraft.gui.setScreen(new SelectWorldScreen(title))),
columnX,
y));
y += ROW + ROW_GAP;
Button multiplayer = Ui.menuButton(Component.translatable("menu.multiplayer"), Icons.GLOBE, columnWidth, () -> {
Screen next = minecraft.options.skipMultiplayerWarning
? new JoinMultiplayerScreen(title)
: new SafetyScreen(title);
minecraft.gui.setScreen(next);
});
multiplayer.active = minecraft.allowsMultiplayer();
rise(add, place(multiplayer, columnX, y));
y += ROW + ROW_GAP;
if (!extra.isEmpty()) {
int count = Math.min(3, extra.size());
int each = (columnWidth - (count - 1) * ROW_GAP) / count;
for (int i = 0; i < count; i++) {
MenuButton button = extra.get(i);
int buttonWidth = i == count - 1 ? columnWidth - (count - 1) * (each + ROW_GAP) : each;
rise(
add,
place(
Ui.menuButton(
Component.literal(button.label()),
MenuIcons.of(button.icon()),
buttonWidth,
button.action()),
columnX + i * (each + ROW_GAP),
y));
}
y += ROW + ROW_GAP;
}
rise(
add,
place(
Ui.menuButton(
Component.translatable("menu.options"),
Icons.GEAR,
columnWidth,
() -> minecraft.gui.setScreen(new OptionsScreen(title, minecraft.options))),
columnX,
y));
layOutCard(title, add, width, height);
// A newer Incari Client: shown once the online service says so (release builds only).
Ui.MenuButton notice =
Ui.menuButton(Component.empty(), Icons.ARROW, UPDATE_HINT, 0, () -> UpdateNotice.open(title));
notice.visible = false;
update = notice;
updateRevision = -1;
rise(add, notice);
// The game's language and accessibility buttons, small, in the top right corner.
SpriteIconButton language = CommonButtons.language(
ROW,
button -> minecraft.gui.setScreen(
new LanguageSelectScreen(title, minecraft.options, minecraft.getLanguageManager())),
true);
language.setPosition(width - 2 * ROW - 10, 6);
add.accept(language);
SpriteIconButton accessibility = CommonButtons.accessibility(
ROW, button -> minecraft.gui.setScreen(new AccessibilityOptionsScreen(title, minecraft.options)), true);
accessibility.setPosition(width - ROW - 6, 6);
add.accept(accessibility);
Font font = minecraft.font;
int copyrightWidth = font.width(COPYRIGHT);
add.accept(new PlainTextButton(
width - copyrightWidth - 6,
height - 12,
copyrightWidth,
10,
COPYRIGHT,
button -> minecraft.gui.setScreen(new CreditsAndAttributionScreen(title)),
font));
return true;
}
/** The player card on the right, or on a narrow screen, the profile link in its place. */
private static void layOutCard(Screen title, Consumer<AbstractWidget> add, int width, int height) {
cardWidth = Math.clamp(Math.round(width * 0.2F), 104, 132);
int modelHeight = Math.min(112, Math.round(height * 0.38F));
int modelWidth = modelHeight * 11 / 20;
cardHeight = 12 + 9 + 8 + modelHeight + 8 + 9 + 8 + 3 * ROW + 2 * ROW_GAP + 12;
cardX = width - columnX - cardWidth;
account = null;
linksRight = 0;
if (cardX < columnX + 168 + 24 || cardHeight > height - 40) {
cardWidth = 0;
AbstractWidget profile = TitleProfile.link(title);
AbstractWidget cosmeticsLink = TitleProfile.cosmeticsLink(title);
AbstractWidget accountLink = TitleProfile.accountLink(title);
add.accept(profile);
add.accept(cosmeticsLink);
add.accept(accountLink);
linksRight = Math.max(profile.getRight(), Math.max(cosmeticsLink.getRight(), accountLink.getRight()));
return;
}
cardY = (height - cardHeight) / 2;
int modelTop = cardY + 12 + 9 + 8;
modelBottom = modelTop + modelHeight;
rise(
add,
TitleProfile.playerView(
title, cardX + (cardWidth - modelWidth) / 2, modelTop, modelWidth, modelHeight, false));
rise(
add,
place(
Ui.button(
Component.literal("Edit Profile"),
cardWidth - 24,
() -> TitleProfile.openProfile(title)),
cardX + 12,
modelBottom + 8 + 9 + 8));
// Cosmetics (ADR 0061): what the player on this card wears.
rise(
add,
place(
Ui.button(
Component.literal("Cosmetics"), cardWidth - 24, () -> open(new WardrobeScreen(title))),
cardX + 12,
modelBottom + 8 + 9 + 8 + ROW + ROW_GAP));
// Incari accounts (ADR 0058): not a module, so here rather than in the module menu.
Button accountButton =
Ui.button(Component.literal("Incari Account"), cardWidth - 24, () -> open(new AccountScreen(title)));
account = accountButton;
accountRevision = -1;
rise(add, place(accountButton, cardX + 12, modelBottom + 8 + 9 + 8 + 2 * (ROW + ROW_GAP)));
}
private static void open(Screen screen) {
Minecraft.getInstance().gui.setScreen(screen);
}
/** The account button says who's signed in, kept current as the connection comes and goes. */
private static void refreshAccount() {
Button button = account;
if (button == null) {
return;
}
var online = IncariOnline.service();
long revision = online.revision();
if (revision == accountRevision) {
return;
}
accountRevision = revision;
String name = online.signedIn() ? online.accountName() : null;
button.setMessage(Component.literal(name == null ? "Incari Account" : "Incari: " + name));
}
/**
* The update notice follows what the service last said: centered at the top, between the small
* screens' links on the left and the language and accessibility buttons on the right.
*/
private static void refreshUpdate(int width) {
Ui.MenuButton button = update;
if (button == null) {
return;
}
var online = IncariOnline.service();
long revision = online.revision();
if (revision == updateRevision) {
return;
}
updateRevision = revision;
String newer = UpdateNotice.newer(online);
button.visible = newer != null;
if (newer == null) {
return;
}
Component label = Component.literal(
newer.isEmpty() ? "A new Incari Client is out" : "Incari Client " + newer + " is out");
// With a changelog, the notice opens it (and the tooltip shows it); without, the repository.
List<String> notes = UpdateNotice.notes(online);
Component hint = notes.isEmpty() ? UPDATE_HINT : NOTES_HINT;
button.setHint(hint);
button.setTooltip(Ui.tooltip(notes.isEmpty() ? "Open Incari Client on GitHub" : whatsNew(notes)));
Font font = Minecraft.getInstance().font;
// The menu button's insets: 8 and the icon (9 + 6) before the label, the hint's gap, 8 after.
int buttonWidth = 8 + 15 + font.width(label) + 14 + font.width(hint) + 8;
button.setMessage(label);
button.setWidth(buttonWidth);
int left = linksRight + 6;
int right = width - 2 * ROW - 16;
button.setPosition(Math.max(left, Math.min((width - buttonWidth) / 2, right - buttonWidth)), 6);
}
/** The tooltip's changelog: each change on its own line, then where pressing leads. */
private static String whatsNew(List<String> notes) {
StringBuilder text = new StringBuilder("What's new:");
for (String note : notes) {
text.append("\n\u2022 ").append(note);
}
return text.append("\n\nClick to get it").toString();
}
private static AbstractWidget place(AbstractWidget widget, int x, int y) {
widget.setPosition(x, y);
return widget;
}
private static void rise(Consumer<AbstractWidget> add, AbstractWidget widget) {
RISING.add(widget);
add.accept(widget);
}
/** Whether the title screen is laid out in the client's look, so drawn by {@link #extractBehind} and {@link #extractFront}. */
@SuppressWarnings("ReferenceEquality") // the title screen object, not an equal one
public static boolean active(Screen title) {
return title == laidOut;
}
/** {@code TitleScreen.extractRenderState}, before its widgets: the backdrop, snow, wordmark and card. */
public static void extractBehind(Screen title, GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
int width = title.width;
int height = title.height;
boolean normal = Look.normal();
backdrop.extract(graphics, width, height, a);
graphics.fill(0, 0, width, height, normal ? 0x1E101822 : 0x40101822);
RoundRects.fadeRight(graphics, 0, 0, Math.round(width * 0.6F), height, normal ? 0x8C0C131B : 0xB00C131B);
if (normal) {
SNOW.extract(graphics, width, height);
}
float shown = normal ? Math.min(1.0F, (Util.getMillis() - shownAt) / RISE_MILLIS) : 1.0F;
float eased = 1.0F - (1.0F - shown) * (1.0F - shown) * (1.0F - shown);
for (AbstractWidget widget : RISING) {
widget.setAlpha(eased);
}
graphics.pose().pushMatrix();
graphics.pose().translate(0, (1.0F - eased) * 8.0F);
extractWordmark(graphics, eased);
refreshUpdate(width);
if (cardWidth > 0) {
refreshAccount();
if (normal) {
// Normal's glass is light, made for a menu's dark tint; out here it would sit on the
// photo's bright cloud and its white text would wash out.
RoundRects.fill(
graphics,
cardX,
cardY,
cardWidth,
cardHeight,
Theme.PANEL_RADIUS,
ARGB.multiplyAlpha(0x800C131B, eased));
}
Panels.panel(graphics, cardX, cardY, cardWidth, cardHeight, eased);
Font font = Minecraft.getInstance().font;
graphics.centeredText(
font,
incari.client.account.MicrosoftAccounts.account() != null ? CARD_LABEL_MICROSOFT : CARD_LABEL,
cardX + cardWidth / 2,
cardY + 12,
ARGB.multiplyAlpha(Theme.MUTED, eased));
// In the player's name tag cosmetic, if they wear one (ADR 0061).
Component name = Cosmetics.ownName(PlayerName.name());
graphics.centeredText(
font, name, cardX + cardWidth / 2, modelBottom + 8, ARGB.multiplyAlpha(Theme.TEXT, eased));
}
graphics.pose().popMatrix();
}
/**
* {@code TitleScreen.extractRenderState}, after its widgets: the version in the bottom left
* corner, a line up where the screen is too narrow for it beside the copyright.
*/
public static void extractFront(Screen title, GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
Font font = Minecraft.getInstance().font;
int copyrightLeft = title.width - font.width(COPYRIGHT) - 6;
int y = 6 + font.width(VERSION) + Theme.GAP * 2 > copyrightLeft ? title.height - 24 : title.height - 12;
graphics.text(font, VERSION, 6, y, Theme.MUTED, false);
}
/** Incari's mark and INCARI, letter-spaced, and the line under them. */
private static void extractWordmark(GuiGraphicsExtractor graphics, float alpha) {
Font font = Minecraft.getInstance().font;
int color = ARGB.multiplyAlpha(Theme.TEXT, alpha);
if (Look.normal()) {
RoundRects.shadow(
graphics,
columnX + 4,
wordmarkY + 4,
WORDMARK_HEIGHT - 8,
WORDMARK_HEIGHT - 8,
(WORDMARK_HEIGHT - 8) / 2,
8,
ARGB.multiplyAlpha(Theme.ACCENT & 0x55FFFFFF, alpha));
}
Logo.draw(graphics, columnX, wordmarkY, WORDMARK_HEIGHT, alpha);
int x = columnX + WORDMARK_HEIGHT + 9;
// The wordmark font's baseline is 7 units down, as every font's is; its capitals stand 13.5 tall.
int letters = wordmarkY + 9;
for (Component letter : LETTERS) {
graphics.text(font, letter, x, letters, color, false);
x += font.width(letter) + LETTER_SPACING;
}
graphics.text(
font,
SUBTITLE,
columnX + WORDMARK_HEIGHT + 10,
wordmarkY + WORDMARK_HEIGHT - 3,
ARGB.multiplyAlpha(Theme.MUTED, alpha),
false);
}
}
@@ -0,0 +1,8 @@
/**
* The client's look on the game's own screens: the title screen, and what the screens players
* see most get besides the skin ({@link incari.client.ui.Skins}). Built from {@code incari.client.ui}.
*/
@NullMarked
package incari.client.look;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,115 @@
package incari.client.memory;
import java.util.Arrays;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.level.EmptyBlockGetter;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.SupportType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.shapes.VoxelShape;
import org.jspecify.annotations.Nullable;
/**
* Arrays every block state keeps a copy of, shared between the states whose copies are equal
* (block-state de-duplication, ADR 0025). The game's 26.x states already share their
* neighbour tables (what FerriteCore once added); what each still made for itself is the array of
* its occlusion shape's six faces, though states with the same shape have the same six faces, and
* the table of which faces are sturdy, of which there are a few hundred kinds among 35,000 states.
* Sharing them is safe because neither is ever written after the state's cache is built.
*
* <p>For the same reason it works out which faces are sturdy once per support shape rather than
* once per state: each of a state's 18 answers depends only on its support shape and the
* face, most states share their shape object with others, and the 630,000 answers were 60% of
* building the block states' caches at start-up. Whether a shape fills the block is asked once per
* shape too.
*
* <p>Built once, at bootstrap, on one thread; the interning maps are dropped with it.
*/
public final class BlockStateSharing {
// Keyed by the faces themselves: a shape's faces are the same objects every time it's asked
// (VoxelShape keeps them), and shapes compare by identity.
private static @Nullable Map<List<VoxelShape>, VoxelShape[]> faces = new HashMap<>();
private static @Nullable Map<BooleanKey, boolean[]> flags = new HashMap<>();
// Per support shape: bit i set if answer i is known, bit 32 + i its value (i = type, face).
private static @Nullable IdentityHashMap<VoxelShape, long[]> support = new IdentityHashMap<>();
private static @Nullable IdentityHashMap<VoxelShape, Boolean> fullBlocks = new IdentityHashMap<>();
private BlockStateSharing() {}
/** Hook: the array of faces equal to {@code shapes} that other states already use, or {@code shapes}. */
public static VoxelShape[] faces(VoxelShape[] shapes) {
Map<List<VoxelShape>, VoxelShape[]> known = faces;
return known == null ? shapes : known.computeIfAbsent(Arrays.asList(shapes.clone()), key -> shapes);
}
/** Hook: the table equal to {@code table} that other states already use, or {@code table}. */
public static boolean[] flags(boolean[] table) {
Map<BooleanKey, boolean[]> known = flags;
return known == null ? table : known.computeIfAbsent(new BooleanKey(table.clone()), key -> table);
}
/**
* Hook: whether {@code state}'s {@code direction} face is sturdy for {@code type}, as the
* game's cache asks it (of an empty level, at the origin): the answer for the state's support
* shape, worked out the first time any state with that shape asks.
*/
// The ordinals only number the answers kept in memory for the length of the bootstrap.
@SuppressWarnings("EnumOrdinal")
public static boolean isSupporting(SupportType type, BlockState state, Direction direction) {
IdentityHashMap<VoxelShape, long[]> known = support;
if (known == null) {
return type.isSupporting(state, EmptyBlockGetter.INSTANCE, BlockPos.ZERO, direction);
}
long[] answers = known.computeIfAbsent(
state.getBlockSupportShape(EmptyBlockGetter.INSTANCE, BlockPos.ZERO), shape -> new long[1]);
int bit = type.ordinal() * Direction.values().length + direction.ordinal();
if ((answers[0] & (1L << bit)) == 0) {
boolean value = type.isSupporting(state, EmptyBlockGetter.INSTANCE, BlockPos.ZERO, direction);
answers[0] |= (1L << bit) | (value ? 1L << (32 + bit) : 0);
}
return (answers[0] & (1L << (32 + bit))) != 0;
}
/**
* Hook: whether {@code shape} fills the block, as the game's {@code Block.isShapeFullBlock}
* answers it, asked once per shape while the states' caches are built (the game's own cache of
* the answer is a Guava cache, whose every lookup costs microseconds in the browser).
*/
public static boolean isFullBlock(VoxelShape shape) {
IdentityHashMap<VoxelShape, Boolean> known = fullBlocks;
return known == null ? Block.isShapeFullBlock(shape) : known.computeIfAbsent(shape, Block::isShapeFullBlock);
}
/** Hook: every state's cache is built; what's shared stays shared, and the maps go. */
public static void done() {
faces = null;
flags = null;
support = null;
fullBlocks = null;
}
/** An array of booleans compared by its contents. */
private static final class BooleanKey {
private final boolean[] values;
BooleanKey(boolean[] values) {
this.values = values;
}
@Override
public boolean equals(Object other) {
return other instanceof BooleanKey key && Arrays.equals(values, key.values);
}
@Override
public int hashCode() {
return Arrays.hashCode(values);
}
}
}
@@ -0,0 +1,112 @@
package incari.client.memory;
import incari.client.platform.ClientPlatform;
import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.longs.LongIterator;
import it.unimi.dsi.fastutil.longs.LongSet;
import net.minecraft.world.level.chunk.DataLayer;
import net.minecraft.world.level.lighting.DataLayerStorageMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The light engine's copies, where every thread is one (ADR 0032). The light engine keeps two maps
* of each loaded section's light: the one it updates, and a copy the rest of the game reads, so
* another thread never sees light half updated. After every round of light updates that changed
* anything (in a fly-through, most frames: light arrives with every chunk) the game copies the
* whole map over the visible one: for render distance 8 about 8,700 sections, two arrays of 16,384
* entries, for sky and block light each. In the desktop game's recordings those copies were most of
* what lived long enough to be collected late; in the page they're what its young collections
* spend their time on.
*
* <p>The copy's content is the updating map's at the swap, and between swaps the updating map only
* changes at sections the storage notes as changed (a section's light first written, added or
* removed). So the visible map is brought up to date at those sections only, in place, and is the
* same map the game's copy would be, layer for layer. The sky map's columns (the top section and
* lowest section of each) are copied whole, as the game's copy does: a few hundred entries. Only
* where the game's threads all run on one thread: elsewhere another thread may be reading the
* visible map while it changes, which is what the copy is for.
*
* <p>And light arriving from a server is kept as it arrives: the game copies each section's array
* out of the packet, which nothing else holds, except over the in-memory connection to the
* integrated server, where the packet is the server's own object.
*
* <p>{@code ?light=game} makes the game's copies, to compare; {@code ?light=verify} brings the map up
* to date in place and also makes the game's copy, and logs any section where they differ. Game
* thread.
*/
public final class LightCopies {
private static final Logger LOGGER = LoggerFactory.getLogger(LightCopies.class);
private static volatile boolean enabled = true;
private static boolean verify;
private static long swaps;
private static long differences;
private LightCopies() {}
public static void setEnabled(boolean on) {
enabled = on;
}
/** Checks every in-place update against the game's copy (development). */
public static void setVerify(boolean on) {
verify = on;
}
/**
* Hook ({@code LayerLightSectionStorage.swapSectionMap}): brings {@code visible} up to date with
* {@code updating} at the {@code changed} sections, in place of copying it; false if the game's
* copy is needed instead.
*/
public static boolean updateInPlace(
DataLayerStorageMap<?> visible, DataLayerStorageMap<?> updating, LongSet changed) {
if (!enabled || !ClientPlatform.oneThread()) {
return false;
}
Long2ObjectOpenHashMap<DataLayer> from = updating.incariLayers();
Long2ObjectOpenHashMap<DataLayer> to = visible.incariLayers();
for (LongIterator i = changed.iterator(); i.hasNext(); ) {
long section = i.nextLong();
DataLayer layer = from.get(section);
if (layer == null) {
to.remove(section);
} else {
to.put(section, layer);
}
}
visible.incariCopyColumnsFrom(updating);
if (verify) {
compare(to, updating.copy().incariLayers());
}
return true;
}
@SuppressWarnings("ReferenceEquality") // the same layer objects the game's copy would hold
private static void compare(Long2ObjectOpenHashMap<DataLayer> inPlace, Long2ObjectOpenHashMap<DataLayer> copied) {
swaps++;
boolean same = inPlace.size() == copied.size();
for (Long2ObjectMap.Entry<DataLayer> entry : copied.long2ObjectEntrySet()) {
if (inPlace.get(entry.getLongKey()) != entry.getValue()) {
same = false;
break;
}
}
if (!same && differences++ < 10) {
LOGGER.error("Light maps differ from the game's copy after {} swaps", swaps);
}
if (swaps % 1000 == 0) {
LOGGER.info("Light maps checked: {} swaps, {} different", swaps, differences);
}
}
/**
* Hook ({@code ClientPacketListener.readSectionList}): a section's light from a packet, for the
* client to keep: the packet's own array from a remote server, else a copy, as the game makes.
*/
public static byte[] received(byte[] packetData, boolean memoryConnection) {
return enabled && !memoryConnection && ClientPlatform.oneThread() ? packetData : packetData.clone();
}
}
@@ -0,0 +1,164 @@
package incari.client.memory;
import com.mojang.blaze3d.font.UnbakedGlyph;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
import java.util.Arrays;
import java.util.function.Function;
import java.util.function.ToIntFunction;
import net.minecraft.client.gui.font.CodepointMap;
import net.minecraft.client.gui.font.providers.UnihexProvider;
import org.jspecify.annotations.Nullable;
/**
* The Unicode font's glyphs packed into arrays, each made again as an object when the font asks
* for it. The game's unihex provider keeps a glyph as three objects (the glyph, its lines and their
* array) for each of about 271,000 codepoints: 27 MB of the page's heap in a heap snapshot, kept for
* the whole session, for glyphs a player mostly never sees. Here a glyph is its sixteen lines, each
* stored in as many bytes as the glyph is wide (one for 8 pixels, two for 16, three for 24, four for
* 32), and its left and right edges: about 9 MB in all. The font set asks for each glyph a few times
* while it loads and caches what it makes, so making one again is no hot path.
*
* <p>A line is read back exactly as the game's own contents give it: the stored bits shifted to the
* top of the int, as {@code ByteContents}, {@code ShortContents} and {@code IntContents} keep them.
*/
public final class PackedUnihex {
private static final int BLOCK_BITS = 8;
private static final int BLOCK_SIZE = 1 << BLOCK_BITS;
private static final int BLOCKS = 0x110000 >> BLOCK_BITS;
private static final int LINES = 16;
private static boolean enabled;
/** Per block of 256 codepoints, each glyph's first byte in {@link #bytes} (-1: none), or null. */
private final int[][] offsets = new int[BLOCKS][];
/** Per block, each glyph's width in bits (8, 16, 24 or 32), left edge and right edge. */
private final byte[][] widths = new byte[BLOCKS][];
private final byte[][] lefts = new byte[BLOCKS][];
private final byte[][] rights = new byte[BLOCKS][];
private byte[] bytes = new byte[1 << 20];
private int size;
private final IntSet codepoints = new IntOpenHashSet();
private PackedUnihex() {}
/** Off unless the page turns it on ({@code ?unihex=game} leaves it off, to compare). */
public static void setEnabled(boolean on) {
enabled = on;
}
public static boolean isEnabled() {
return enabled;
}
/** Makes a glyph from its lines and edges: the game's glyph record's constructor. */
@FunctionalInterface
public interface GlyphFactory<G extends UnbakedGlyph> {
G make(UnihexProvider.LineData lines, int left, int right);
}
/**
* Hook ({@code UnihexProvider.Definition.loadData}): the font's glyphs packed, read through the
* game's record's accessors.
*/
public static <G> PackedUnihex pack(
CodepointMap<G> glyphs,
Function<G, UnihexProvider.LineData> lines,
ToIntFunction<G> left,
ToIntFunction<G> right) {
PackedUnihex packed = new PackedUnihex();
glyphs.forEach((codepoint, glyph) ->
packed.add(codepoint, lines.apply(glyph), left.applyAsInt(glyph), right.applyAsInt(glyph)));
packed.bytes = Arrays.copyOf(packed.bytes, packed.size);
return packed;
}
private void add(int codepoint, UnihexProvider.LineData lines, int left, int right) {
int width = lines.bitWidth();
if (width != 8 && width != 16 && width != 24 && width != 32) {
throw new IllegalArgumentException("A unihex glyph " + width + " bits wide, at " + codepoint);
}
int block = codepoint >> BLOCK_BITS;
int[] blockOffsets = offsets[block];
if (blockOffsets == null) {
blockOffsets = new int[BLOCK_SIZE];
Arrays.fill(blockOffsets, -1);
offsets[block] = blockOffsets;
widths[block] = new byte[BLOCK_SIZE];
lefts[block] = new byte[BLOCK_SIZE];
rights[block] = new byte[BLOCK_SIZE];
}
int index = codepoint & (BLOCK_SIZE - 1);
int lineBytes = width / 8;
int need = LINES * lineBytes;
if (size + need > bytes.length) {
bytes = Arrays.copyOf(bytes, Math.max(bytes.length * 2, size + need));
}
blockOffsets[index] = size;
for (int i = 0; i < LINES; i++) {
// The line's bits sit at the top of the int; keep only those.
int bits = lines.line(i) >>> (32 - width);
for (int b = lineBytes - 1; b >= 0; b--) {
bytes[size++] = (byte) (bits >>> (8 * b));
}
}
widths[block][index] = (byte) width;
lefts[block][index] = (byte) left;
rights[block][index] = (byte) right;
codepoints.add(codepoint);
}
/** Hook ({@code UnihexProvider.getGlyph}): the glyph at {@code codepoint}, made anew, or null. */
public <G extends UnbakedGlyph> @Nullable G get(int codepoint, GlyphFactory<G> factory) {
if (codepoint < 0 || codepoint >= BLOCKS << BLOCK_BITS) {
return null;
}
int block = codepoint >> BLOCK_BITS;
int[] blockOffsets = offsets[block];
if (blockOffsets == null) {
return null;
}
int index = codepoint & (BLOCK_SIZE - 1);
int offset = blockOffsets[index];
if (offset < 0) {
return null;
}
return factory.make(new Lines(bytes, offset, widths[block][index]), lefts[block][index], rights[block][index]);
}
/** Hook ({@code UnihexProvider.getSupportedGlyphs}): every codepoint with a glyph. */
public IntSet codepoints() {
return codepoints;
}
/** A glyph's lines, read from the shared bytes. */
private static final class Lines implements UnihexProvider.LineData {
private final byte[] bytes;
private final int offset;
private final int width;
Lines(byte[] bytes, int offset, int width) {
this.bytes = bytes;
this.offset = offset;
this.width = width;
}
@Override
public int line(int index) {
int lineBytes = width / 8;
int at = offset + index * lineBytes;
int bits = 0;
for (int b = 0; b < lineBytes; b++) {
bits = bits << 8 | (bytes[at + b] & 0xFF);
}
return bits << (32 - width);
}
@Override
public int bitWidth() {
return width;
}
}
}
@@ -0,0 +1,5 @@
/** The memory diet (ADR 0025): data the game makes many equal copies of, shared. */
@NullMarked
package incari.client.memory;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,91 @@
package incari.client.modules;
import incari.features.armorpotionview.ArmorPotionView;
import incari.features.blockoutline.BlockOutline;
import incari.features.clearchat.ClearChat;
import incari.features.cooldownindicator.CooldownIndicator;
import incari.features.coordinates.Coordinates;
import incari.features.cps.Cps;
import incari.features.crosshair.CrosshairEditor;
import incari.features.customscoreboard.CustomScoreboard;
import incari.features.customsky.CustomSky;
import incari.features.fastcrystal.FastCrystal;
import incari.features.fpsdisplay.FpsDisplay;
import incari.features.freelook.Freelook;
import incari.features.fullbright.Fullbright;
import incari.features.glintcolor.EnchantGlint;
import incari.features.hitboxes.HitboxesModule;
import incari.features.hitcolor.HitColor;
import incari.features.hiteffects.HitEffects;
import incari.features.keystrokes.Keystrokes;
import incari.features.lowfire.LowFire;
import incari.features.lowshield.LowShield;
import incari.features.minimap.Minimap;
import incari.features.nohurtcam.NoHurtCam;
import incari.features.norender.NoRenderModule;
import incari.features.oldanimations.OldAnimations;
import incari.features.oldtextures.OldTextures;
import incari.features.reachdisplay.ReachDisplay;
import incari.features.saturation.Saturation;
import incari.features.schematics.SchematicsModule;
import incari.features.shieldtotem.ShieldTotem;
import incari.features.shortitems.ShortItems;
import incari.features.shulkertooltips.ShulkerTooltips;
import incari.features.theme.ThemeEditor;
import incari.features.togglesprint.ToggleSprint;
import incari.features.waypoints.WaypointsModule;
import incari.features.weatherchanger.WeatherChanger;
import incari.features.zoom.Zoom;
import incari.framework.Module;
import java.util.List;
/**
* Every feature module in the build, in the order the module menu lists them within a category. A
* new feature is a {@code features/<name>} project, a line in {@code :client}'s dependencies, and a
* line here: no reflection or service loading, which the browser build's closed world can't see.
*/
final class Features {
private Features() {}
/** A new instance of each. */
static List<Module> all() {
return List.of(
new ToggleSprint(),
new Keystrokes(),
new Cps(),
new FpsDisplay(),
new ReachDisplay(),
new Coordinates(),
new ArmorPotionView(),
new ShieldTotem(),
new Saturation(),
new CustomScoreboard(),
new Minimap(),
new CooldownIndicator(),
new HitEffects(),
new HitboxesModule(),
new FastCrystal(),
new OldAnimations(),
new Freelook(),
new Zoom(),
new CrosshairEditor(),
new LowShield(),
new ShortItems(),
new WeatherChanger(),
new Fullbright(),
new CustomSky(),
new BlockOutline(),
new HitColor(),
new EnchantGlint(),
new OldTextures(),
new ThemeEditor(),
new ClearChat(),
new LowFire(),
new NoHurtCam(),
new NoRenderModule(),
new WaypointsModule(),
new SchematicsModule(),
new ShulkerTooltips());
}
}
@@ -0,0 +1,224 @@
package incari.client.modules;
import com.mojang.logging.LogUtils;
import incari.client.platform.ClientPlatform;
import incari.client.ui.ControlList;
import incari.client.ui.ListScreen;
import incari.client.ui.Theme;
import incari.client.ui.Ui;
import incari.platform.api.PlatformShell;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.function.BiConsumer;
import java.util.stream.Stream;
import net.minecraft.ChatFormatting;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.layouts.LinearLayout;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.CommonComponents;
import net.minecraft.network.chat.Component;
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
/**
* A module's file chooser ({@code Game.chooseFile}): the files in one folder of the game directory,
* newest first, each with a button to choose it. The folder can be opened beside the game; in the
* browser that opens the file picker instead, and the files picked (or dropped on the window) are
* copied into the folder.
*/
final class FileChooserScreen extends ListScreen {
private static final Logger LOGGER = LogUtils.getLogger();
/** A file bigger than this isn't offered: it would only be refused after a long read. */
private static final long MAX_SIZE = 64L << 20;
/** Three side by side fit the narrowest screen, 320 GUI units. */
private static final int FOOTER_BUTTON = 90;
private final Path folder;
private final List<String> extensions;
private final BiConsumer<String, byte[]> chosen;
private final List<Path> files = new ArrayList<>();
private Component caption;
private long revision;
FileChooserScreen(
@Nullable Screen parent,
String title,
Path folder,
List<String> extensions,
BiConsumer<String, byte[]> chosen) {
super(Component.literal(title), parent);
this.folder = folder;
this.extensions = List.copyOf(extensions);
this.chosen = chosen;
this.caption = defaultCaption();
list();
}
private Component defaultCaption() {
String kinds = String.join(", ", extensions);
return Component.literal(
ClientPlatform.get().shell().showsFolders()
? "Put " + kinds + " files in the folder to see them here."
: "Add " + kinds + " files from your computer, or drop them here.");
}
/** Reads the folder's files again. */
private void list() {
files.clear();
if (Files.isDirectory(folder)) {
try (Stream<Path> listed = Files.list(folder)) {
listed.filter(path -> Files.isRegularFile(path)
&& accepted(path.getFileName().toString()))
.sorted(Comparator.comparingLong(FileChooserScreen::modified)
.reversed())
.forEach(files::add);
} catch (IOException e) {
LOGGER.warn("Couldn't list {}: {}", folder, e.toString());
}
}
revision++;
}
private boolean accepted(String name) {
String lower = name.toLowerCase(Locale.ROOT);
for (String extension : extensions) {
if (lower.endsWith(extension)) {
return true;
}
}
return false;
}
private static long modified(Path path) {
try {
return Files.getLastModifiedTime(path).toMillis();
} catch (IOException e) {
return 0;
}
}
private static long size(Path path) {
try {
return Files.size(path);
} catch (IOException e) {
return -1;
}
}
@Override
protected Component caption() {
return caption;
}
@Override
protected long revision() {
return revision;
}
@Override
protected Object shape() {
return List.copyOf(files);
}
@Override
protected List<ControlList.Row> rows(ControlList list) {
List<ControlList.Row> rows = new ArrayList<>();
if (files.isEmpty()) {
rows.add(list.heading(Component.literal("No files yet").withColor(Theme.MUTED)));
}
int labelWidth = list.getRowWidth() - Theme.SMALL_BUTTON_WIDTH - Theme.GAP * 4;
for (Path file : files) {
String name = file.getFileName().toString();
long bytes = size(file);
Button choose = Ui.button(Component.literal("Load"), Theme.SMALL_BUTTON_WIDTH, () -> choose(file));
choose.active = bytes >= 0 && bytes <= MAX_SIZE;
String label = Ui.fit(this.font, name, labelWidth);
rows.add(list.row(Component.literal(label), name + ", " + sizeText(bytes), List.of(choose), () -> {}));
}
return rows;
}
/** "2.4 MB", "830 KB". */
static String sizeText(long bytes) {
if (bytes < 0) {
return "unreadable";
}
if (bytes >= 1L << 20) {
return String.format(Locale.ROOT, "%.1f MB", bytes / (double) (1L << 20));
}
return Math.max(1, (bytes + 1023) / 1024) + " KB";
}
private void choose(Path file) {
byte[] bytes;
try {
bytes = Files.readAllBytes(file);
} catch (IOException e) {
LOGGER.warn("Couldn't read {}: {}", file, e.toString());
caption = Component.literal("Couldn't read " + file.getFileName()).withStyle(ChatFormatting.RED);
return;
}
this.minecraft.gui.setScreen(parent);
chosen.accept(file.getFileName().toString(), bytes);
}
@Override
protected void footer(LinearLayout footer) {
PlatformShell shell = ClientPlatform.get().shell();
footer.addChild(Ui.button(
Component.literal(shell.showsFolders() ? "Open folder" : "Add files"), FOOTER_BUTTON, () -> {
try {
Files.createDirectories(folder);
} catch (IOException e) {
LOGGER.warn("Couldn't make {}: {}", folder, e.toString());
}
shell.openPath(folder.toAbsolutePath().toString());
}));
footer.addChild(Ui.button(Component.literal("Refresh"), FOOTER_BUTTON, this::list));
footer.addChild(Ui.button(CommonComponents.GUI_CANCEL, FOOTER_BUTTON, this::onClose));
}
/** Files dropped on the window, or picked in the browser's file picker: copied into the folder. */
@Override
public void onFilesDrop(List<Path> dropped) {
int added = 0;
int skipped = 0;
for (Path file : dropped) {
Path name = file.getFileName();
if (name == null || !accepted(name.toString()) || !Files.isRegularFile(file)) {
skipped++;
continue;
}
try {
Files.createDirectories(folder);
Path target = folder.resolve(name.toString());
if (!target.toAbsolutePath()
.normalize()
.equals(file.toAbsolutePath().normalize())) {
// Read and written whole: the browser's in-memory files have no copy of their own.
Files.write(target, Files.readAllBytes(file));
}
added++;
} catch (IOException e) {
LOGGER.warn("Couldn't copy {} into {}: {}", file, folder, e.toString());
skipped++;
}
}
if (skipped > 0) {
caption = Component.literal(skipped + (skipped == 1 ? " file wasn't" : " files weren't") + " added: only "
+ String.join(", ", extensions))
.withStyle(ChatFormatting.GOLD);
} else if (added > 0) {
caption = defaultCaption();
}
list();
}
}
@@ -0,0 +1,143 @@
package incari.client.modules;
import com.mojang.blaze3d.platform.InputConstants;
import incari.client.ui.SettingControls;
import incari.framework.KeyInput;
import incari.framework.Module;
import incari.framework.ModuleSystem;
import incari.framework.setting.Key;
import incari.framework.setting.KeySetting;
import incari.framework.setting.Setting;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import net.minecraft.client.KeyMapping;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import org.jspecify.annotations.Nullable;
/**
* Module keybinds through the game's own key handling. Each {@link KeySetting} gets a key mapping
* of its own that isn't in the options' list: the game counts its presses and holds it down as it
* does for its own binds (none with a screen open, all released when one opens), but doesn't show
* it in Controls or save it to {@code options.txt}. The profile saves the bind; this keeps the
* mapping on the same key. Game thread.
*/
final class GameKeys implements KeyInput, SettingControls.KeyNames {
/** By the setting itself: settings don't define equality. */
private final IdentityHashMap<KeySetting, Mapping> mappings = new IdentityHashMap<>();
private final ModuleSystem system;
GameKeys(ModuleSystem system) {
this.system = system;
}
@Override
public int presses(KeySetting key) {
KeyMapping mapping = mapping(key);
if (mapping == null) {
return 0;
}
int presses = 0;
while (mapping.consumeClick()) {
presses++;
}
return presses;
}
@Override
public boolean isDown(KeySetting key) {
KeyMapping mapping = mapping(key);
return mapping != null && mapping.isDown();
}
@Override
public Component name(Key key) {
return toGame(key).getDisplayName();
}
@Override
public List<String> conflicts(KeySetting setting) {
List<String> names = new ArrayList<>();
Key key = setting.get();
if (!key.isBound()) {
return names;
}
InputConstants.Key gameKey = toGame(key);
for (KeyMapping other : Minecraft.getInstance().options.keyMappings) {
if (other.matches(gameKey)) {
names.add(Component.translatable(other.getName()).getString());
}
}
for (Module module : system.modules()) {
for (Setting<?> each : module.settings()) {
if (each instanceof KeySetting other
&& !other.equals(setting)
&& other.get().equals(key)) {
names.add(module.name() + ": " + other.name());
}
}
}
return names;
}
/** The game's key for one of the framework's. */
static InputConstants.Key toGame(Key key) {
return switch (key.device()) {
case KEYBOARD -> InputConstants.Type.KEYBOARD.getOrCreate(key.code());
case MOUSE -> InputConstants.Type.MOUSE.getOrCreate(key.code());
};
}
/** The framework's key for one of the game's. */
static Key fromGame(InputConstants.Key key) {
return key.getType() == InputConstants.Type.MOUSE ? Key.mouse(key.getValue()) : Key.keyboard(key.getValue());
}
/**
* The setting's mapping, made on first use; null while it's unbound. An unbound key would be
* the game's unknown key, which every key the platform can't name presses.
*/
private @Nullable KeyMapping mapping(KeySetting setting) {
Mapping mapping = mappings.get(setting);
if (mapping == null) {
Key key = setting.get();
if (!key.isBound()) {
return null;
}
// Unique, and not a translation key: the game never shows these names.
String name = "incari.modules.key." + mappings.size();
mapping = new Mapping(new KeyMapping(name, typeOf(key), key.code(), KeyMapping.Category.MISC), key);
mappings.put(setting, mapping);
} else if (!mapping.bound.equals(setting.get())) {
mapping.bound = setting.get();
mapping.mapping.setKey(toGame(mapping.bound));
// The game's key lookup is rebuilt from every mapping; only when a bind changed.
KeyMapping.resetMapping();
// Presses from before the change, or from the unknown key while it was unbound,
// aren't presses of the new bind.
mapping.mapping.setDown(false);
while (mapping.mapping.consumeClick()) {
// drained
}
}
return mapping.bound.isBound() ? mapping.mapping : null;
}
private static InputConstants.Type typeOf(Key key) {
return key.device() == Key.Device.MOUSE ? InputConstants.Type.MOUSE : InputConstants.Type.KEYBOARD;
}
private static final class Mapping {
final KeyMapping mapping;
Key bound;
Mapping(KeyMapping mapping, Key bound) {
this.mapping = mapping;
this.bound = bound;
}
}
}
@@ -0,0 +1,148 @@
package incari.client.modules;
import incari.client.look.HudLook;
import incari.framework.ModuleSystem;
import incari.framework.game.GamePart;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.network.chat.Component;
import net.minecraft.world.scores.Objective;
import net.minecraft.world.scores.ScoreHolder;
import net.minecraft.world.scores.Scoreboard;
import net.minecraft.world.scores.criteria.ObjectiveCriteria;
import org.jspecify.annotations.Nullable;
/**
* Parts of the game's HUD a module draws itself ({@code GamePartElement}, ADR 0050): the scoreboard
* sidebar. The game still draws the sidebar, with its own code and the client's look, but from the
* module's HUD element and at its place: {@link #takeSidebar} keeps the game from drawing it where
* it would, {@link #drawSidebar} has it drawn at the element's origin, and {@link #sidebarBox},
* inside the game's drawing, moves it there and measures it. Render thread.
*/
public final class GameParts {
/** The sidebar the game would have drawn this frame, if a module took it. */
private static @Nullable Objective sidebar;
/** Whether the game is drawing the sidebar for a module's element (move it to the origin). */
private static boolean placing;
/** The sidebar's size as last drawn, in GUI units. */
private static int sidebarWidth;
private static int sidebarHeight;
private static @Nullable Objective sample;
private GameParts() {}
/**
* Hook ({@code Hud.extractScoreboardSidebar}): the sidebar the game should draw in its place,
* or null when a module draws it.
*/
public static @Nullable Objective takeSidebar(@Nullable Objective objective) {
ModuleSystem system = IncariModules.current();
if (system == null || !system.holds(GamePart.SCOREBOARD)) {
sidebar = null;
return objective;
}
sidebar = objective;
return null;
}
/**
* Hook ({@code Hud.displayScoreboardSidebar}, before it draws): the sidebar's box as the game
* places it. When a module's element is drawing it, the box is moved to the element's origin.
*/
public static void sidebarBox(GuiGraphicsExtractor graphics, int left, int top, int right, int bottom) {
if (!placing) {
return;
}
// The card drawn around the box (HudLook) is what the element places and must fit.
int pad = HudLook.scoreboardPad();
sidebarWidth = right - left + 2 * pad;
sidebarHeight = bottom - top + 2 * pad;
graphics.pose().translate(pad - left, pad - top);
}
/** The player left the world: its sidebar goes with it. */
static void leave() {
sidebar = null;
sidebarWidth = 0;
sidebarHeight = 0;
}
/** Whether there's a sidebar to draw: the server's, or the editor's sample. */
static boolean hasSidebar(boolean editing) {
return sidebar != null || editing;
}
/** The sidebar's width as last drawn; 0 before the first. */
static int sidebarWidth(boolean editing) {
if (sidebarWidth == 0 && hasSidebar(editing)) {
measure(editing);
}
return hasSidebar(editing) ? sidebarWidth : 0;
}
/** The sidebar's height as last drawn. */
static int sidebarHeight(boolean editing) {
if (sidebarHeight == 0 && hasSidebar(editing)) {
measure(editing);
}
return hasSidebar(editing) ? sidebarHeight : 0;
}
/** Draws the sidebar with its top left at {@code x, y} (already in the element's frame). */
static void drawSidebar(GuiGraphicsExtractor graphics, int x, int y, boolean editing) {
Objective objective = sidebar;
if (objective == null) {
if (!editing) {
return;
}
objective = sample();
}
graphics.pose().pushMatrix().translate(x, y);
placing = true;
try {
Minecraft.getInstance().gui.hud.displayScoreboardSidebar(graphics, objective);
} finally {
placing = false;
graphics.pose().popMatrix();
}
}
/**
* A size before the first draw, which measures it: the element is placed by its size before
* it's drawn, so the first frame goes where a sidebar of the game's usual shape would.
*/
private static void measure(boolean editing) {
// A sidebar's lines are 9 units, the title's one more.
sidebarWidth = 80;
sidebarHeight = 9 * (editing && sidebar == null ? 4 : 6);
}
/** A sidebar for the HUD editor while the server sends none. */
private static Objective sample() {
Objective current = sample;
if (current == null) {
Scoreboard scoreboard = new Scoreboard();
current = scoreboard.addObjective(
"incari_sample",
ObjectiveCriteria.DUMMY,
Component.literal("Scoreboard"),
ObjectiveCriteria.RenderType.INTEGER,
false,
null);
String[] lines = {"Kills", "Deaths", "Coins"};
int[] scores = {12, 3, 250};
for (int i = 0; i < lines.length; i++) {
scoreboard
.getOrCreatePlayerScore(ScoreHolder.forNameOnly(lines[i]), current)
.set(scores[i]);
}
sample = current;
}
return current;
}
}
@@ -0,0 +1,867 @@
package incari.client.modules;
import com.mojang.blaze3d.platform.InputConstants;
import com.mojang.blaze3d.platform.cursor.CursorTypes;
import incari.client.gui.BackdropCache;
import incari.client.ui.Icons;
import incari.client.ui.Look;
import incari.client.ui.MenuBackdrop;
import incari.client.ui.Panels;
import incari.client.ui.RoundRects;
import incari.client.ui.Theme;
import incari.client.ui.Ui;
import incari.framework.Module;
import incari.framework.ModuleSystem;
import incari.framework.hud.Anchor;
import incari.framework.hud.HudCanvas;
import incari.framework.hud.HudElement;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.gui.components.AbstractButton;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.narration.NarrationElementOutput;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.input.InputWithModifiers;
import net.minecraft.client.input.KeyEvent;
import net.minecraft.client.input.MouseButtonEvent;
import net.minecraft.network.chat.CommonComponents;
import net.minecraft.network.chat.Component;
import net.minecraft.util.FormattedCharSequence;
import net.minecraft.util.Util;
import org.jspecify.annotations.Nullable;
/**
* The HUD editor: every enabled module's HUD elements, drawn as they are in play, over the
* world and the game's own HUD blurred behind them, so what can be moved stands out from what
* can't. Drag an element to move it; it snaps to the screen's sides and middle and to the other
* elements (Shift, or the Snap switch, places it freely), and takes the anchor of the third of the
* screen it's left in, so it keeps its place as the window changes. Scroll over it or drag its
* corner to resize it; right-click it for its module's settings; arrows nudge the chosen one; Ctrl+Z
* undoes. Opened from the module menu.
*
* <p>The blur is the editor's in either GUI preset. In Potato it's drawn a few times a second and
* kept in between ({@link BackdropCache}), while the elements and the toolbar keep the full frame
* rate. Placements are the elements' own settings, saved with the profile as any change is.
*/
final class HudEditorScreen extends Screen {
/** The margin the screen's sides snap at, in GUI units: the game's own HUD keeps about this much. */
private static final int EDGE = 2;
/** How close an edge must come to a line to snap to it. */
private static final int SNAP = 4;
/** The space kept between two elements snapped side by side. */
private static final int GAP = 2;
/** How far an element's frame stands out around it. */
private static final int FRAME = 2;
/** The resize handle's size, on the frame's bottom right corner. */
private static final int HANDLE = 6;
private static final int BAR_HEIGHT = 28;
private static final int BAR_PADDING = 9;
private static final int BUTTON_WIDTH = 54;
private static final int TAG_HEIGHT = 11;
private static final int ANCHOR_BAR = 14;
private static final int EMPTY_WIDTH = 224;
private static final int EMPTY_HEIGHT = 96;
/** Undo steps kept. */
private static final int UNDO_LIMIT = 64;
/** Scrolls or nudges of one element this close together undo as one step. */
private static final long MERGE_MILLIS = 700;
private static final int NO_GUIDE = Integer.MIN_VALUE;
private static final Component TITLE = Component.literal("HUD Layout");
private static final Component RESET_ONE = Component.literal("Reset");
private static final Component RESET_ALL = Component.literal("Reset all");
private static final String HINT =
"Drag to move · Scroll to resize · Shift places freely · Right-click for settings";
private static final String SHORT_HINT = "Drag to move · Scroll to resize";
/** Whether dragging snaps; kept between visits. */
private static boolean snapping = true;
private enum Drag {
NONE,
MOVE,
SCALE
}
/** An element's placement, to undo back to. */
private record Placement(HudElement element, Anchor anchor, int x, int y, float scale) {
static Placement of(HudElement element) {
return new Placement(
element,
element.anchor().get(),
element.offsetX().get(),
element.offsetY().get(),
element.scale().get());
}
void restore() {
element.anchor().set(anchor);
element.offsetX().set(x);
element.offsetY().set(y);
element.scale().set(scale);
}
}
private final @Nullable Screen parent;
private final ModuleSystem system;
private final List<HudElement> elements = new ArrayList<>();
private final List<Module> owners = new ArrayList<>();
private final ArrayDeque<List<Placement>> undo = new ArrayDeque<>();
private final int[] bounds = new int[4];
/** Each element's left, top, width and height as last drawn, scaled. */
private int[] rects = new int[0];
/** Each element's width and height unscaled. */
private int[] sizes = new int[0];
/** Whether each element was drawn (its module on, the element placeable). */
private boolean[] shown = new boolean[0];
private int selected = -1;
private int hovered = -1;
private Drag drag = Drag.NONE;
private double grabX;
private double grabY;
private int startX;
private int startY;
private int startWidth;
private int startHeight;
private int guideX = NO_GUIDE;
private int guideY = NO_GUIDE;
/** What the last undo step was for, so a run of scrolls or nudges is one step. */
private int mergeIndex = -1;
private @Nullable Drag mergeKind;
private long mergeAt;
private int barX;
private int barY;
private int barWidth;
private boolean empty;
private @Nullable Button reset;
private final List<AbstractButton> barWidgets = new ArrayList<>();
HudEditorScreen(@Nullable Screen parent, ModuleSystem system) {
super(TITLE);
this.parent = parent;
this.system = system;
}
@Override
protected void init() {
Look.frost(true);
BackdropCache.hold(true);
ModuleHud.hide(true);
elements.clear();
owners.clear();
for (Module module : system.modules()) {
for (HudElement element : module.hudElements()) {
elements.add(element);
owners.add(module);
}
}
rects = new int[elements.size() * 4];
sizes = new int[elements.size() * 2];
shown = new boolean[elements.size()];
if (selected >= elements.size()) {
selected = -1;
}
empty = true;
for (int i = 0; i < elements.size(); i++) {
if (owners.get(i).isEnabled() && elements.get(i).isPlaceable()) {
empty = false;
}
}
// The toolbar: the title, the snap switch, Reset and Done on one glass bar at the top.
barWidgets.clear();
SnapSwitch snap = new SnapSwitch();
snap.setTooltip(Ui.tooltip("Snap to the screen's sides and middle and to other elements. "
+ "Hold Shift while dragging to place freely."));
Button resetButton = Ui.button(RESET_ALL, BUTTON_WIDTH, this::reset);
Button done = Ui.button(CommonComponents.GUI_DONE, BUTTON_WIDTH, this::onClose);
int titleWidth = 12 + 5 + font.width(TITLE);
barWidth = BAR_PADDING + titleWidth + 14 + snap.getWidth() + 10 + BUTTON_WIDTH + Theme.GAP + BUTTON_WIDTH + 4;
barX = (width - barWidth) / 2;
barY = 6;
int controlY = barY + (BAR_HEIGHT - Theme.CONTROL_HEIGHT) / 2;
int x = barX + barWidth - 4 - BUTTON_WIDTH;
done.setPosition(x, controlY);
x -= Theme.GAP + BUTTON_WIDTH;
resetButton.setPosition(x, controlY);
x -= 10 + snap.getWidth();
snap.setPosition(x, controlY);
reset = resetButton;
for (AbstractButton widget : List.of(snap, resetButton, done)) {
barWidgets.add(widget);
addRenderableWidget(widget);
}
if (empty) {
Button modules = Ui.button(Component.literal("Modules"), 96, this::backToModules);
modules.setPosition(
(width - 96) / 2, (height - EMPTY_HEIGHT) / 2 + EMPTY_HEIGHT - 10 - Theme.CONTROL_HEIGHT);
addRenderableWidget(modules);
}
}
@Override
public void removed() {
Look.frost(false);
BackdropCache.hold(false);
ModuleHud.hide(false);
system.flush();
}
@Override
public void onClose() {
minecraft.gui.setScreen(parent);
}
@Override
public boolean isPauseScreen() {
// As the module menu: singleplayer pauses, and a still world is all the backdrop needs.
return true;
}
private void backToModules() {
if (parent instanceof ModuleListScreen) {
onClose();
} else {
IncariModules.openMenu(parent);
}
}
// Drawing.
@Override
public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
// The world (or the menus' photo) and the game's HUD, blurred in either preset: they're
// the backdrop the elements are placed against, not what's being placed.
if (minecraft.level == null && !BackdropCache.reusing()) {
MenuBackdrop.extract(graphics, width, height);
}
Panels.blurBehind(graphics);
graphics.fillGradient(0, 0, width, height, Theme.EDITOR_TINT_TOP, Theme.EDITOR_TINT_BOTTOM);
}
@Override
public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
HudCanvas canvas = ModuleHud.begin(graphics);
try {
measure(canvas);
hovered = drag == Drag.NONE ? elementAt(mouseX, mouseY) : selected;
extractGuides(graphics);
for (int i = 0; i < elements.size(); i++) {
if (shown[i]) {
extractFrame(graphics, i);
system.drawHud(canvas, owners.get(i), elements.get(i));
extractEdge(graphics, i, mouseX, mouseY);
}
}
} finally {
ModuleHud.end();
}
if (selected >= 0 && shown[selected]) {
extractAnchor(graphics, selected);
extractTag(graphics, selected, true);
}
if (hovered >= 0 && hovered != selected && shown[hovered]) {
extractTag(graphics, hovered, false);
}
// The toolbar fades away while an element is dragged across it.
float fade = drag != Drag.NONE && selected >= 0 && overBar(selected) ? 0.15F : 1.0F;
Panels.panel(graphics, barX, barY, barWidth, BAR_HEIGHT, fade);
int textY = barY + (BAR_HEIGHT - 7) / 2;
Icons.LAYOUT.draw(
graphics, barX + BAR_PADDING, barY + (BAR_HEIGHT - 12) / 2, 12, Panels.alpha(Theme.ACCENT, fade));
graphics.text(font, TITLE, barX + BAR_PADDING + 17, textY, Panels.alpha(Theme.TEXT, fade), false);
for (AbstractButton widget : barWidgets) {
widget.setAlpha(fade);
}
Button resetButton = reset;
if (resetButton != null) {
resetButton.setMessage(selected >= 0 ? RESET_ONE : RESET_ALL);
}
if (empty) {
extractEmpty(graphics);
}
super.extractRenderState(graphics, mouseX, mouseY, a);
extractCaption(graphics, fade);
if (drag != Drag.NONE || hovered >= 0) {
boolean handle = drag == Drag.SCALE
|| (drag == Drag.NONE && selected >= 0 && shown[selected] && overHandle(selected, mouseX, mouseY));
graphics.requestCursor(handle ? CursorTypes.POINTING_HAND : CursorTypes.RESIZE_ALL);
}
}
/** Where each element is this frame, and which are shown. */
private void measure(HudCanvas canvas) {
for (int i = 0; i < elements.size(); i++) {
HudElement element = elements.get(i);
shown[i] = owners.get(i).isEnabled() && element.isPlaceable();
if (!shown[i]) {
continue;
}
element.bounds(canvas, bounds);
System.arraycopy(bounds, 0, rects, i * 4, 4);
sizes[i * 2] = Math.max(1, element.width(canvas));
sizes[i * 2 + 1] = Math.max(1, element.height(canvas));
}
if (selected >= 0 && !shown[selected]) {
selected = -1;
drag = Drag.NONE;
}
}
/** The lines an element being dragged has snapped to, and the screen's middle, faintly. */
private void extractGuides(GuiGraphicsExtractor graphics) {
if (drag != Drag.MOVE) {
return;
}
int faint = 0x1FFFFFFF;
vertical(graphics, width / 2, faint);
horizontal(graphics, height / 2, faint);
int strong = Panels.alpha(Theme.ACCENT, 0.8F);
if (guideX != NO_GUIDE) {
vertical(graphics, guideX, strong);
}
if (guideY != NO_GUIDE) {
horizontal(graphics, guideY, strong);
}
// Where it was picked up from.
RoundRects.outline(
graphics,
startX - FRAME,
startY - FRAME,
startWidth + 2 * FRAME,
startHeight + 2 * FRAME,
Theme.RADIUS,
0x2EFFFFFF);
}
/** A line one screen pixel wide down the whole screen at GUI column {@code x}. */
private void vertical(GuiGraphicsExtractor graphics, int x, int argb) {
int scale = RoundRects.pixels(graphics);
int px = Math.min(x * scale, width * scale - 1);
graphics.fill(px, 0, px + 1, height * scale, argb);
graphics.pose().popMatrix();
}
/** A line one screen pixel high across the whole screen at GUI row {@code y}. */
private void horizontal(GuiGraphicsExtractor graphics, int y, int argb) {
int scale = RoundRects.pixels(graphics);
int py = Math.min(y * scale, height * scale - 1);
graphics.fill(0, py, width * scale, py + 1, argb);
graphics.pose().popMatrix();
}
/** The glass under an element: faint at rest, lit toward the accent when pointed at or chosen. */
private void extractFrame(GuiGraphicsExtractor graphics, int i) {
int x = rects[i * 4] - FRAME;
int y = rects[i * 4 + 1] - FRAME;
int w = rects[i * 4 + 2] + 2 * FRAME;
int h = rects[i * 4 + 3] + 2 * FRAME;
int fill;
int glow = 0;
if (i == selected) {
glow = Look.normal() ? Theme.GLOW : 0;
fill = Panels.alpha(Theme.ACCENT, 0.16F);
} else if (i == hovered) {
fill = Panels.alpha(Theme.ACCENT, 0.1F);
} else {
fill = 0x1FFFFFFF;
}
RoundRects.box(graphics, x, y, w, h, Theme.RADIUS, fill, 0, glow, 0, Panels.alpha(Theme.ACCENT, 0.3F));
}
/** The element's edge, over it, and the chosen one's resize handle. */
private void extractEdge(GuiGraphicsExtractor graphics, int i, int mouseX, int mouseY) {
int x = rects[i * 4] - FRAME;
int y = rects[i * 4 + 1] - FRAME;
int w = rects[i * 4 + 2] + 2 * FRAME;
int h = rects[i * 4 + 3] + 2 * FRAME;
int edge = i == selected ? Theme.ACCENT : i == hovered ? Panels.alpha(Theme.ACCENT, 0.6F) : 0x59FFFFFF;
RoundRects.outline(graphics, x, y, w, h, Theme.RADIUS, edge);
if (i == selected) {
int hx = handleX(i);
int hy = handleY(i);
boolean hot = drag == Drag.SCALE || (drag == Drag.NONE && overHandle(i, mouseX, mouseY));
RoundRects.box(
graphics,
hx,
hy,
HANDLE,
HANDLE,
HANDLE / 2,
hot ? Theme.ACCENT : Theme.TEXT,
hot ? Theme.TEXT : Theme.ACCENT);
}
}
/**
* Where the chosen element's anchor is, the corner, side or middle it keeps its place from: a
* short accent bar along that side (two at a corner), a dot in the middle.
*/
private void extractAnchor(GuiGraphicsExtractor graphics, int i) {
Anchor anchor = elements.get(i).anchor().get();
int column = anchor.column();
int row = anchor.row();
int color = Panels.alpha(Theme.ACCENT, 0.9F);
int length = ANCHOR_BAR;
if (column == 1 && row == 1) {
RoundRects.fill(graphics, width / 2 - 2, height / 2 - 2, 4, 4, 2, color);
return;
}
// Across: along the top or bottom; down: along the left or right.
int barX = column == 0 ? 0 : column == 1 ? (width - length) / 2 : width - length;
int barY = row == 0 ? 0 : row == 1 ? (height - length) / 2 : height - length;
if (row != 1) {
graphics.fill(barX, row == 0 ? 0 : height - 1, barX + length, row == 0 ? 1 : height, color);
}
if (column != 1) {
graphics.fill(column == 0 ? 0 : width - 1, barY, column == 0 ? 1 : width, barY + length, color);
}
}
/** The element's name on a pill above it (below, at the top of the screen): accent when chosen. */
private void extractTag(GuiGraphicsExtractor graphics, int i, boolean chosen) {
String name = tag(i);
int w = font.width(name) + 10;
int ex = rects[i * 4];
int ey = rects[i * 4 + 1];
int ew = rects[i * 4 + 2];
int eh = rects[i * 4 + 3];
int x = Math.max(2, Math.min(width - w - 2, ex + (ew - w) / 2));
int y = ey - FRAME - 3 - TAG_HEIGHT;
if (y < 2) {
y = ey + eh + FRAME + 3;
}
RoundRects.fill(graphics, x, y, w, TAG_HEIGHT, TAG_HEIGHT / 2, chosen ? Theme.ACCENT : Theme.FLOATING);
graphics.text(font, name, x + 5, y + 2, chosen ? Theme.ON_ACCENT : Theme.TEXT, false);
}
private String tag(int i) {
Module owner = owners.get(i);
HudElement element = elements.get(i);
String name = owner.hudElements().size() > 1 ? owner.name() + " · " + element.name() : owner.name();
float scale = element.scale().get();
return scale == 1.0F ? name : name + " " + element.scale().format(scale);
}
/** A line under the toolbar: how to use the editor, or where the element in hand is going. */
private void extractCaption(GuiGraphicsExtractor graphics, float fade) {
String text;
if (drag == Drag.MOVE && selected >= 0) {
HudElement element = elements.get(selected);
text = element.anchor().label() + " · " + element.offsetX().get() + ", "
+ element.offsetY().get();
} else if (drag == Drag.SCALE && selected >= 0) {
HudElement element = elements.get(selected);
text = "Size " + element.scale().format(element.scale().get());
} else if (selected >= 0) {
HudElement element = elements.get(selected);
text = tag(selected) + " · " + element.anchor().label() + " · Arrows nudge · Ctrl+Z undoes";
} else {
text = font.width(HINT) + 24 <= width ? HINT : SHORT_HINT;
}
int w = font.width(text) + 16;
int x = (width - w) / 2;
int y = barY + BAR_HEIGHT + 5;
RoundRects.fill(graphics, x, y, w, 14, 7, Panels.alpha(Theme.BACKGROUND, fade));
graphics.text(font, text, x + 8, y + 3, Panels.alpha(Theme.MUTED, fade), false);
}
/** With nothing to place: a card that says so, and a way back to turn something on. */
private void extractEmpty(GuiGraphicsExtractor graphics) {
int x = (width - EMPTY_WIDTH) / 2;
int y = (height - EMPTY_HEIGHT) / 2;
Panels.panel(graphics, x, y, EMPTY_WIDTH, EMPTY_HEIGHT, 1.0F);
Icons.LAYOUT.draw(graphics, x + 12, y + 11, 12, Theme.ACCENT);
graphics.text(font, "Nothing on the HUD yet", x + 30, y + 14, Theme.TEXT, false);
int lineY = y + 31;
for (FormattedCharSequence line : font.split(
Component.literal("Turn on a HUD module, like Toggle Sprint, to place it here."), EMPTY_WIDTH - 24)) {
graphics.text(font, line, x + 12, lineY, Theme.MUTED, false);
lineY += 10;
}
}
// Geometry.
/** The topmost element under the pointer, by its frame, or -1. */
private int elementAt(double mouseX, double mouseY) {
for (int i = elements.size() - 1; i >= 0; i--) {
if (shown[i]
&& mouseX >= rects[i * 4] - FRAME
&& mouseX < rects[i * 4] + rects[i * 4 + 2] + FRAME
&& mouseY >= rects[i * 4 + 1] - FRAME
&& mouseY < rects[i * 4 + 1] + rects[i * 4 + 3] + FRAME) {
return i;
}
}
return -1;
}
// On the frame's bottom right corner, kept on screen for an element against the side.
private int handleX(int i) {
return Math.min(width - HANDLE, rects[i * 4] + rects[i * 4 + 2] + FRAME - HANDLE / 2 - 1);
}
private int handleY(int i) {
return Math.min(height - HANDLE, rects[i * 4 + 1] + rects[i * 4 + 3] + FRAME - HANDLE / 2 - 1);
}
/** Whether the pointer is on element {@code i}'s resize handle, give or take a unit. */
private boolean overHandle(int i, double mouseX, double mouseY) {
int x = handleX(i);
int y = handleY(i);
return mouseX >= x - 1 && mouseX < x + HANDLE + 1 && mouseY >= y - 1 && mouseY < y + HANDLE + 1;
}
/** Whether element {@code i} is under the toolbar or its caption. */
private boolean overBar(int i) {
int bottom = barY + BAR_HEIGHT + 20;
return rects[i * 4] < barX + barWidth && rects[i * 4] + rects[i * 4 + 2] > barX && rects[i * 4 + 1] < bottom;
}
// Input.
@Override
public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) {
if (super.mouseClicked(event, doubleClick)) {
return true;
}
double mouseX = event.x();
double mouseY = event.y();
if (event.button() == InputConstants.MOUSE_BUTTON_LEFT
&& selected >= 0
&& shown[selected]
&& overHandle(selected, mouseX, mouseY)) {
pickUp(Drag.SCALE, selected, mouseX, mouseY);
return true;
}
int at = elementAt(mouseX, mouseY);
if (event.button() == InputConstants.MOUSE_BUTTON_RIGHT) {
if (at >= 0) {
IncariModules.openSettings(this, owners.get(at));
return true;
}
return false;
}
if (event.button() != InputConstants.MOUSE_BUTTON_LEFT) {
return false;
}
selected = at;
if (at >= 0) {
pickUp(Drag.MOVE, at, mouseX, mouseY);
}
return true;
}
private void pickUp(Drag kind, int i, double mouseX, double mouseY) {
drag = kind;
selected = i;
startX = rects[i * 4];
startY = rects[i * 4 + 1];
startWidth = rects[i * 4 + 2];
startHeight = rects[i * 4 + 3];
grabX = mouseX - startX;
grabY = mouseY - startY;
remember(i, null);
}
@Override
public boolean mouseDragged(MouseButtonEvent event, double dx, double dy) {
if (drag == Drag.NONE || selected < 0) {
return super.mouseDragged(event, dx, dy);
}
int i = selected;
if (drag == Drag.MOVE) {
moveTo(
i,
(int) Math.round(event.x() - grabX),
(int) Math.round(event.y() - grabY),
startWidth,
startHeight,
!snapping || event.hasShiftDown());
} else {
// The corner follows the pointer; the top left stays put.
HudElement element = elements.get(i);
float across = (float) (event.x() - startX) / sizes[i * 2];
float down = (float) (event.y() - startY) / sizes[i * 2 + 1];
element.scale().set(Math.max(across, down));
resized(i, startX, startY);
}
return true;
}
@Override
public boolean mouseReleased(MouseButtonEvent event) {
if (drag != Drag.NONE) {
drag = Drag.NONE;
guideX = NO_GUIDE;
guideY = NO_GUIDE;
return true;
}
return super.mouseReleased(event);
}
@Override
public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) {
int at = drag == Drag.NONE ? elementAt(mouseX, mouseY) : -1;
if (at < 0 || scrollY == 0) {
return super.mouseScrolled(mouseX, mouseY, scrollX, scrollY);
}
selected = at;
remember(at, Drag.SCALE);
HudElement element = elements.get(at);
element.scale()
.set(element.scale().get()
+ (scrollY > 0 ? 1 : -1) * element.scale().step());
// Grows and shrinks about its middle.
int centerX = rects[at * 4] + rects[at * 4 + 2] / 2;
int centerY = rects[at * 4 + 1] + rects[at * 4 + 3] / 2;
float scale = element.scale().get();
int w = Math.round(sizes[at * 2] * scale);
int h = Math.round(sizes[at * 2 + 1] * scale);
resized(at, centerX - w / 2, centerY - h / 2);
return true;
}
@Override
public boolean keyPressed(KeyEvent event) {
if (event.shortcutKey() == 'z' && event.hasControlDownWithQuirk()) {
undo();
return true;
}
if (selected >= 0 && shown[selected] && drag == Drag.NONE) {
int step = event.hasShiftDown() ? 10 : 1;
int dx = event.isLeft() ? -step : event.isRight() ? step : 0;
int dy = event.isUp() ? -step : event.isDown() ? step : 0;
if (dx != 0 || dy != 0) {
remember(selected, Drag.MOVE);
int i = selected;
moveTo(i, rects[i * 4] + dx, rects[i * 4 + 1] + dy, rects[i * 4 + 2], rects[i * 4 + 3], true);
return true;
}
}
if (event.isCycleFocus() && !empty) {
cycle(event.hasShiftDown() ? -1 : 1);
return true;
}
return super.keyPressed(event);
}
/** Chooses the next shown element, or the one before. */
private void cycle(int direction) {
int n = elements.size();
int i = selected < 0 ? (direction > 0 ? -1 : 0) : selected;
for (int k = 0; k < n; k++) {
i = Math.floorMod(i + direction, n);
if (shown[i]) {
selected = i;
return;
}
}
}
// Placing.
/**
* Puts element {@code i}, {@code w} by {@code h}, with its top left at {@code x, y} on the
* screen, snapped unless {@code free}.
*/
private void moveTo(int i, int x, int y, int w, int h, boolean free) {
x = Math.max(0, Math.min(x, width - w));
y = Math.max(0, Math.min(y, height - h));
guideX = NO_GUIDE;
guideY = NO_GUIDE;
if (!free) {
x = snap(i, x, w, width, true);
y = snap(i, y, h, height, false);
}
elements.get(i).place(x, y, w, h, width, height);
rects[i * 4] = x;
rects[i * 4 + 1] = y;
}
/** After a new scale: element {@code i} placed with its top left near {@code x, y}, kept on screen. */
private void resized(int i, int x, int y) {
HudElement element = elements.get(i);
float scale = element.scale().get();
int w = Math.round(sizes[i * 2] * scale);
int h = Math.round(sizes[i * 2 + 1] * scale);
x = Math.max(0, Math.min(x, width - w));
y = Math.max(0, Math.min(y, height - h));
element.place(x, y, w, h, width, height);
rects[i * 4] = x;
rects[i * 4 + 1] = y;
rects[i * 4 + 2] = w;
rects[i * 4 + 3] = h;
}
private int snapBest;
private int snapDistance;
private int snapGuide;
/**
* Element {@code i}'s start along one axis, snapped to the nearest line within {@link #SNAP}:
* the screen's sides (at {@link #EDGE}) and middle, the other elements' edges and middles, and
* {@link #GAP} beside them. The line it snapped to becomes that axis's guide.
*/
private int snap(int i, int start, int size, int screen, boolean across) {
snapBest = start;
snapDistance = SNAP + 1;
snapGuide = NO_GUIDE;
consider(start, EDGE, EDGE);
consider(start, screen - EDGE - size, screen - EDGE);
consider(start, (screen - size) / 2, screen / 2);
int offset = across ? 0 : 1;
for (int j = 0; j < elements.size(); j++) {
if (j == i || !shown[j]) {
continue;
}
int other = rects[j * 4 + offset];
int otherSize = rects[j * 4 + 2 + offset];
consider(start, other, other);
consider(start, other + otherSize - size, other + otherSize);
consider(start, other + (otherSize - size) / 2, other + otherSize / 2);
consider(start, other + otherSize + GAP, other + otherSize + GAP / 2);
consider(start, other - GAP - size, other - GAP / 2);
}
if (snapGuide != NO_GUIDE) {
if (across) {
guideX = snapGuide;
} else {
guideY = snapGuide;
}
}
return snapBest;
}
private void consider(int start, int candidate, int guide) {
int distance = Math.abs(candidate - start);
if (distance < snapDistance) {
snapDistance = distance;
snapBest = candidate;
snapGuide = guide;
}
}
/** Back to the defaults: the chosen element, or every shown one. */
private void reset() {
List<Placement> step = new ArrayList<>();
for (int i = 0; i < elements.size(); i++) {
if (shown[i] && (selected < 0 || i == selected)) {
step.add(Placement.of(elements.get(i)));
elements.get(i).resetPlacement();
}
}
push(step);
mergeKind = null;
}
/** Saves element {@code i}'s placement to undo to, unless it continues the last step. */
private void remember(int i, @Nullable Drag kind) {
long now = Util.getMillis();
boolean merges = kind != null && kind == mergeKind && i == mergeIndex && now - mergeAt < MERGE_MILLIS;
mergeKind = kind;
mergeIndex = i;
mergeAt = now;
if (!merges) {
push(List.of(Placement.of(elements.get(i))));
}
}
private void push(List<Placement> step) {
if (step.isEmpty()) {
return;
}
undo.push(step);
while (undo.size() > UNDO_LIMIT) {
undo.removeLast();
}
}
private void undo() {
List<Placement> step = undo.poll();
if (step != null) {
for (Placement placement : step) {
placement.restore();
}
}
mergeKind = null;
}
/** The toolbar's switch: whether dragging snaps. */
private static final class SnapSwitch extends AbstractButton {
private static final Component LABEL = Component.literal("Snap");
SnapSwitch() {
super(
0,
0,
net.minecraft.client.Minecraft.getInstance().font.width(LABEL) + 6 + Panels.SWITCH_WIDTH + 8,
Theme.CONTROL_HEIGHT,
LABEL);
}
@Override
public void onPress(InputWithModifiers input) {
snapping = !snapping;
}
@Override
protected void extractContents(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
var font = net.minecraft.client.Minecraft.getInstance().font;
if (isHoveredOrFocused()) {
RoundRects.fill(
graphics,
getX(),
getY(),
getWidth(),
getHeight(),
Theme.RADIUS,
Panels.alpha(Theme.BUTTON, alpha));
}
int textY = getY() + (getHeight() - 7) / 2;
graphics.text(
font,
getMessage(),
getX() + 4,
textY,
Panels.alpha(snapping ? Theme.TEXT : Theme.MUTED, alpha),
false);
Panels.toggle(
graphics,
getRight() - 4 - Panels.SWITCH_WIDTH,
getY() + (getHeight() - Panels.SWITCH_HEIGHT) / 2,
snapping,
alpha);
}
@Override
protected void updateWidgetNarration(NarrationElementOutput output) {
defaultButtonNarrationText(output);
}
}
}
@@ -0,0 +1,198 @@
package incari.client.modules;
import com.mojang.logging.LogUtils;
import incari.client.IncariKeys;
import incari.client.online.IncariOnline;
import incari.client.ui.SettingControls;
import incari.framework.Module;
import incari.framework.ModuleSystem;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.multiplayer.ClientPacketListener;
import net.minecraft.client.multiplayer.ServerData;
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
/**
* The client's module system (ADR 0046): made with the build's features on the first tick,
* its active profile loaded from the game directory. Runs the modules' tick and keybinds, fires
* join and leave as the player's connection comes and goes, and opens the module menu. Game thread.
*/
public final class IncariModules {
private static final Logger LOGGER = LogUtils.getLogger();
private static @Nullable ModuleSystem system;
private static @Nullable GameKeys keys;
/** The connection the player was in a world on, as of the last tick. */
private static @Nullable ClientPacketListener world;
/** The page's {@code ?modules=}: module ids turned on at start, or null to leave the profile's. */
private static @Nullable List<String> startOn;
private IncariModules() {}
/** The module system, or null before the first tick. */
public static @Nullable ModuleSystem current() {
return system;
}
/** The module system, made and loaded if this is the first time it's asked for. */
public static ModuleSystem system() {
ModuleSystem current = system;
if (current == null) {
current = new ModuleSystem(
Features.all(),
new ModuleStorage(Minecraft.getInstance().gameDirectory.toPath()),
(message, error) -> {
if (error == null) {
LOGGER.warn(message);
} else {
LOGGER.warn(message, error);
}
},
new ModuleGame(),
IncariOnline.service());
current.load();
List<String> on = startOn;
if (on != null) {
for (Module module : current.modules()) {
if (!module.isAlwaysOn() && (on.contains("all") || on.contains(module.id()))) {
module.setEnabled(true);
}
}
}
system = current;
keys = new GameKeys(current);
LOGGER.info("Modules: {} loaded, profile {}", current.modules().size(), current.activeProfile());
}
return current;
}
/**
* Development: modules to turn on when the system is made, the page's {@code ?modules=a,b} ("all"
* for every one), so the benchmark measures them. Before the first tick.
*/
public static void startWith(List<String> ids) {
startOn = List.copyOf(ids);
}
/** The game's names for module keys, for the settings screens. */
static GameKeys keys() {
system();
GameKeys current = keys;
if (current == null) {
throw new IllegalStateException("No module keys");
}
return current;
}
/** From {@code IncariTicks}, once a client tick before the game's keybinds. */
public static void tick(Minecraft minecraft) {
ModuleSystem modules = system();
ModuleGame.newTick();
trackWorld(minecraft, modules);
modules.tick(keys());
ModuleEffects.tick(minecraft, modules);
MapTerrain.tick(minecraft);
ModuleHands.tick(minecraft);
ModuleBreaks.tick(minecraft);
MapMemory.tick();
while (IncariKeys.MODULE_MENU.consumeClick()) {
if (minecraft.gui.screen() == null) {
openMenu(null);
}
}
}
/** Opens the module menu over {@code parent} (null for the game). */
public static void openMenu(@Nullable Screen parent) {
Minecraft.getInstance().gui.setScreen(new ModuleListScreen(parent, system()));
}
/** Opens {@code module}'s settings over {@code parent}. */
public static void openSettings(@Nullable Screen parent, Module module) {
Minecraft.getInstance().gui.setScreen(new ModuleSettingsScreen(parent, system(), module));
}
/** Opens the HUD editor over {@code parent}. */
public static void openHudEditor(@Nullable Screen parent) {
Minecraft.getInstance().gui.setScreen(new HudEditorScreen(parent, system()));
}
/**
* The game is stopping, or its page was hidden (the tab may be closed next, and nothing runs
* after): a change still waiting out its second is saved now.
*/
public static void saveNow() {
ModuleSystem current = system;
if (current != null) {
current.flush();
}
}
/**
* Hook ({@code LevelStorageAccess.deleteLevel}, once the world's folder is gone): its waypoints
* and explored map go too, so a new world made with the same folder name starts with none.
*/
public static void worldDeleted(String folder) {
String name = ModuleGame.localWorld(folder);
system().waypoints().delete(name);
MapMemory.delete(Minecraft.getInstance().gameDirectory.toPath(), name);
}
/** The keyboard layout's key names changed (the page learned them): the HUD's are made again. */
public static void keymapChanged() {
ModuleGame.keymapChanged();
}
/** Opens the profiles screen over {@code parent}. */
public static void openProfiles(@Nullable Screen parent) {
Minecraft.getInstance().gui.setScreen(new ProfilesScreen(parent, system()));
}
/**
* {@code KeyboardHandler.keyPress}: whether {@code screen} has a module keybind waiting for a key,
* so the game's own keys (F2's screenshot, F11's fullscreen, F1, F3) go to the bind instead, as
* they do for the game's Controls screen.
*/
public static boolean capturingKey(@Nullable Screen screen) {
return screen instanceof SettingControls.KeyCapture capture && capture.capturing() != null;
}
/**
* Join and leave follow the connection, not the level: a dimension change keeps the connection,
* a transfer to another server replaces it.
*/
@SuppressWarnings("ReferenceEquality") // The same connection object, not an equal one.
private static void trackWorld(Minecraft minecraft, ModuleSystem modules) {
ClientPacketListener connection = minecraft.level == null ? null : minecraft.getConnection();
ClientPacketListener last = world;
if (connection == last) {
return;
}
world = connection;
if (last != null) {
GameParts.leave();
modules.events().fireLeave();
// The last change before leaving shouldn't wait out its second: the tab may close next.
modules.flush();
modules.waypoints().close();
MapTerrain.leave();
MapMemory.close();
ModuleSky.leave();
ModuleEffects.leave();
ModuleBreaks.leave();
}
if (connection != null) {
// Before the join event: a module joining may read the world's waypoints.
String name = modules.game().world();
if (name != null) {
modules.waypoints().open(name);
MapMemory.open(minecraft.gameDirectory.toPath(), name);
}
ServerData server = minecraft.getCurrentServer();
modules.events().fireJoin(server == null || minecraft.isLocalServer() ? "" : server.ip);
}
}
}
@@ -0,0 +1,360 @@
package incari.client.modules;
import com.mojang.logging.LogUtils;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Stream;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
/**
* What the minimap has seen ({@link MapTerrain}), for the world map (ADR 0051): every chunk's 256
* colors as the map drew them, by region of 32 by 32 chunks, for each world and dimension. With the
* minimap's Remember explored map on, regions are kept in the game directory
* ({@code incari/map/<world>/<dimension>/<x>.<z>.map}) and read back when the world map or the
* minimap reaches them again; off, the map remembers only this visit, as many regions as it holds.
*
* <p>A region file: {@code IMAP}, a version, a bit for each of its 1024 chunks that's been seen, and
* each seen chunk's colors as RGB (0, 0, 0 for nothing there: black is stored a step lighter), all
* deflated at zlib's fastest level. A region seen whole is about 0.8 MB before and some 100-250 KB
* after. In the browser the game directory is in memory, stored behind (ADR 0011), so neither
* reading nor writing waits on a disk.
*
* <p>Render thread (the game's ticks run there too).
*/
public final class MapMemory {
private static final Logger LOGGER = LogUtils.getLogger();
/** Chunks a region's side. */
static final int REGION_CHUNKS = 32;
/** Blocks a region's side. */
static final int REGION_BLOCKS = REGION_CHUNKS * 16;
private static final int MAGIC = 0x494D4150;
private static final int VERSION = 1;
/** Regions kept in memory at most: some 1 MB each when seen whole. */
private static final int KEPT = 24;
/** Ticks between saves of what changed: half a minute. */
private static final int SAVE_TICKS = 600;
/** A region of one dimension. */
record Key(String dimension, int x, int z) {}
/** A region's chunks' colors, those seen; a number that goes up as more are. */
static final class Region {
final Key key;
final int[] @Nullable [] chunks = new int[REGION_CHUNKS * REGION_CHUNKS][];
int revision;
boolean dirty;
long usedAt;
Region(Key key) {
this.key = key;
}
/** Chunk {@code cx, cz} within the region (0 to 31 each), or null if unseen. */
int @Nullable [] chunk(int cx, int cz) {
return chunks[cx + cz * REGION_CHUNKS];
}
}
private static final Map<Key, Region> regions = new HashMap<>();
private static @Nullable Path folder;
private static boolean remember = true;
private static long uses;
private static int ticks;
/** Whether a half minute's saving is under way ({@link #tick}). */
private static boolean saving;
private MapMemory() {}
/** The minimap's Remember explored map. Turned on, what's been seen this visit is kept from now on. */
static void setRemember(boolean on) {
if (on && !remember) {
Path root = folder;
for (Region region : regions.values()) {
// A region made while the map wasn't remembered never read its file: what the file
// has and this visit hasn't seen joins it first, so saving it doesn't lose that.
Region saved = root == null ? null : read(root, region.key);
if (saved != null) {
merge(saved, region);
}
region.dirty = true;
}
}
remember = on;
}
/** Puts {@code from}'s chunks into {@code into} where {@code into} has none. */
static void merge(Region from, Region into) {
boolean added = false;
for (int i = 0; i < into.chunks.length; i++) {
if (into.chunks[i] == null && from.chunks[i] != null) {
into.chunks[i] = from.chunks[i];
added = true;
}
}
if (added) {
into.revision++;
}
}
/** The player joined {@code world} ({@code Game.world()}); its map is kept under its own folder. */
static void open(Path gameDirectory, String world) {
close();
folder = gameDirectory.resolve("incari").resolve("map").resolve(safe(world));
}
/**
* Deletes {@code world}'s explored map: the game deleted the world, and a new one with its name
* mustn't find it. Nothing for the world open now.
*/
static void delete(Path gameDirectory, String world) {
Path kept = gameDirectory.resolve("incari").resolve("map").resolve(safe(world));
if (kept.equals(folder) || !Files.isDirectory(kept)) {
return;
}
try (Stream<Path> files = Files.walk(kept)) {
// Deepest first: each folder is empty by the time it's deleted.
for (Path file : files.sorted(Comparator.reverseOrder()).toList()) {
Files.deleteIfExists(file);
}
} catch (IOException | RuntimeException e) {
LOGGER.warn("Couldn't delete the explored map {}", kept, e);
}
}
/** The player left: what changed is saved, and the regions let go. */
static void close() {
save();
regions.clear();
folder = null;
}
/**
* Once a client tick: what changed is saved every half minute, a region a tick. Each region is
* deflated on the render thread, and several at once would be one long frame.
*/
static void tick() {
if (++ticks % SAVE_TICKS == 0) {
saving = true;
}
if (saving) {
saving = writeOne();
}
}
/** Saves one region that changed; false if none had. */
private static boolean writeOne() {
if (!remember) {
return false;
}
for (Region region : regions.values()) {
if (region.dirty) {
write(region);
return true;
}
}
return false;
}
/** The map drew chunk {@code chunkX, chunkZ} of {@code dimension}: its 256 colors, row by row. */
static void record(String dimension, int chunkX, int chunkZ, int[] colors) {
if (folder == null) {
return;
}
Region region = region(dimension, chunkX >> 5, chunkZ >> 5, true);
if (region == null) {
return;
}
int index = (chunkX & 31) + (chunkZ & 31) * REGION_CHUNKS;
int[] kept = region.chunks[index];
if (kept == null) {
kept = new int[256];
region.chunks[index] = kept;
} else if (java.util.Arrays.equals(kept, colors)) {
return;
}
System.arraycopy(colors, 0, kept, 0, 256);
region.revision++;
region.dirty = true;
}
/**
* Region {@code x, z} of {@code dimension}, read from its file if it isn't in memory; null if
* there's no world open, or nothing seen there and {@code make} is false.
*/
static @Nullable Region region(String dimension, int x, int z, boolean make) {
Path root = folder;
if (root == null) {
return null;
}
Key key = new Key(dimension, x, z);
Region region = regions.get(key);
if (region == null) {
region = remember ? read(root, key) : null;
if (region == null) {
if (!make) {
return null;
}
region = new Region(key);
}
// Used now, before the eviction: else the region just read would be the one to go.
region.usedAt = ++uses;
regions.put(key, region);
evict();
}
region.usedAt = ++uses;
return region;
}
/** Whether a region of {@code dimension} at {@code x, z} has a file, without reading it. */
static boolean saved(String dimension, int x, int z) {
Path root = folder;
return root != null && remember && Files.isRegularFile(file(root, new Key(dimension, x, z)));
}
/** Over {@link #KEPT}: the least lately used goes, saved first if it's to be kept. */
private static void evict() {
while (regions.size() > KEPT) {
Region oldest = null;
for (Region region : regions.values()) {
if (oldest == null || region.usedAt < oldest.usedAt) {
oldest = region;
}
}
if (oldest == null) {
return;
}
write(oldest);
regions.remove(oldest.key);
}
}
/** Saves every region that changed, if the map is remembered (also the smoke test's, to check). */
public static void save() {
List<Region> all = new ArrayList<>(regions.values());
for (Region region : all) {
write(region);
}
}
private static void write(Region region) {
Path root = folder;
if (!remember || !region.dirty || root == null) {
return;
}
region.dirty = false;
Path file = file(root, region.key);
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream(64 * 1024);
Deflater deflater = new Deflater(Deflater.BEST_SPEED);
try (DataOutputStream out = new DataOutputStream(new DeflaterOutputStream(bytes, deflater))) {
out.writeInt(MAGIC);
out.writeInt(VERSION);
byte[] seen = new byte[region.chunks.length / 8];
for (int i = 0; i < region.chunks.length; i++) {
if (region.chunks[i] != null) {
seen[i >> 3] |= (byte) (1 << (i & 7));
}
}
out.write(seen);
byte[] rgb = new byte[256 * 3];
for (int[] chunk : region.chunks) {
if (chunk == null) {
continue;
}
for (int i = 0; i < 256; i++) {
int color = chunk[i];
// Clear is 0, 0, 0; a black block a step lighter, so it isn't read as clear.
int stored = (color >>> 24) == 0 ? 0 : (color & 0xFFFFFF) == 0 ? 0x010101 : color;
rgb[3 * i] = (byte) (stored >> 16);
rgb[3 * i + 1] = (byte) (stored >> 8);
rgb[3 * i + 2] = (byte) stored;
}
out.write(rgb);
}
} finally {
deflater.end();
}
Path parent = file.getParent();
if (parent != null) {
Files.createDirectories(parent);
}
Files.write(file, bytes.toByteArray());
} catch (IOException | RuntimeException e) {
LOGGER.warn("Couldn't save the map's region {}", file, e);
}
}
private static @Nullable Region read(Path root, Key key) {
Path file = file(root, key);
if (!Files.isRegularFile(file)) {
return null;
}
try (InputStream raw = Files.newInputStream(file);
DataInputStream in = new DataInputStream(new InflaterInputStream(raw))) {
if (in.readInt() != MAGIC || in.readInt() != VERSION) {
LOGGER.warn("Not a map region this build reads: {}", file);
return null;
}
byte[] seen = new byte[REGION_CHUNKS * REGION_CHUNKS / 8];
in.readFully(seen);
Region region = new Region(key);
byte[] rgb = new byte[256 * 3];
for (int i = 0; i < region.chunks.length; i++) {
if ((seen[i >> 3] & (1 << (i & 7))) == 0) {
continue;
}
in.readFully(rgb);
int[] chunk = new int[256];
for (int j = 0; j < 256; j++) {
int color = (rgb[3 * j] & 0xFF) << 16 | (rgb[3 * j + 1] & 0xFF) << 8 | (rgb[3 * j + 2] & 0xFF);
chunk[j] = color == 0 ? 0 : 0xFF000000 | color;
}
region.chunks[i] = chunk;
}
return region;
} catch (IOException | RuntimeException e) {
LOGGER.warn("Couldn't read the map's region {}", file, e);
return null;
}
}
private static Path file(Path root, Key key) {
return root.resolve(safe(key.dimension())).resolve(key.x() + "." + key.z() + ".map");
}
/** A name as a folder's: letters, digits, dots and dashes kept, the rest underscores, and a hash. */
static String safe(String name) {
StringBuilder safe = new StringBuilder(name.length() + 9);
for (int i = 0; i < name.length() && i < 64; i++) {
char c = name.charAt(i);
boolean plain =
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-';
safe.append(plain ? c : '_');
}
return safe.append('-')
.append(Integer.toHexString(name.hashCode()).toLowerCase(Locale.ROOT))
.toString();
}
}
@@ -0,0 +1,624 @@
package incari.client.modules;
import com.mojang.blaze3d.platform.NativeImage;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.VertexConsumer;
import com.mojang.renderpearl.api.GpuFormat;
import com.mojang.renderpearl.api.device.GpuDevice;
import com.mojang.renderpearl.api.pipeline.RenderPipeline;
import com.mojang.renderpearl.api.textures.FilterMode;
import com.mojang.renderpearl.api.textures.GpuSampler;
import com.mojang.renderpearl.api.textures.GpuTexture;
import com.mojang.renderpearl.api.textures.GpuTextureView;
import incari.client.ui.Circles;
import java.util.Arrays;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.gui.navigation.ScreenRectangle;
import net.minecraft.client.gui.render.TextureSetup;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.renderer.RenderPipelines;
import net.minecraft.client.renderer.state.gui.GuiElementRenderState;
import net.minecraft.core.BlockPos;
import net.minecraft.core.QuartPos;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.status.ChunkStatus;
import net.minecraft.world.level.levelgen.Heightmap;
import net.minecraft.world.level.material.MapColor;
import org.joml.Matrix3x2f;
import org.joml.Matrix3x2fc;
import org.joml.Vector4f;
import org.jspecify.annotations.Nullable;
/**
* The minimap's terrain ({@code HudCanvas.terrain}, ADR 0051): the loaded world seen from above, one
* texel a block, in a 512 by 512 texture that wraps. A block's texel is at its x and z modulo 512,
* so walking draws only the chunks coming into view, each into its own 16 by 16 square, and the
* map's coordinates run past the texture's edge (the sampler repeats). 512 blocks is more than any
* zoom shows, turned or not.
*
* <p>Each texel is the color of the block a map would show there: the top block's map color, grass,
* leaves and water in their biome's tint, shaded by the slope down from the north-west, and water
* darker the deeper it is. Where the world has a ceiling (the Nether), the map is a slice at the
* player's height instead: the floor of the space they're in, walls darkened.
*
* <p>Chunks are drawn in ticks, nearest first, at most 1.5 ms a tick, and only while a map is
* drawn. A drawn chunk is drawn again only once the game marks it changed ({@link #sectionChanged}):
* at most every half second near the player (so building and digging show), every second farther
* out. Render thread (the game's ticks run there too).
*/
public final class MapTerrain {
/** The texture's size in texels (blocks). */
static final int SIZE = 512;
/** Chunks across the texture. */
private static final int SLOTS = SIZE / 16;
/** How far from the middle, in chunks, the map can reach: 256 blocks across, turned. */
private static final int REACH = 13;
/** Ticks without a draw after which the map stops drawing chunks. */
private static final int IDLE_TICKS = 40;
/** The time a tick may spend drawing chunks. */
private static final long BUDGET_NANOS = 1_500_000;
/** A changed chunk within one of the player's is drawn again at most this often, in ticks. */
private static final int NEAR_REFRESH = 10;
/** A changed chunk farther out, in ticks. */
private static final int FAR_REFRESH = 20;
/** How much lighter or darker a block's color gets per block of slope, up to four. */
private static final float SLOPE_SHADE = 0.075F;
/**
* Every color a little darker: the map sits on a dark glass frame, and snow and sand at full
* white glare beside it.
*/
private static final float TONE = 0.9F;
/** A slot that holds no chunk. */
private static final long NONE = Long.MIN_VALUE;
/** A slot whose chunk isn't loaded: drawn clear, looked for again each tick. */
private static final byte MISSING = 1;
/** A slot whose chunk is drawn. */
private static final byte DRAWN = 2;
/** Offsets from the middle chunk within {@link #REACH}, nearest first, as dx, dz pairs. */
private static final int[] SPIRAL = spiral();
private static final long[] slotChunk = new long[SLOTS * SLOTS];
private static final byte[] slotState = new byte[SLOTS * SLOTS];
private static final int[] slotDrawnAt = new int[SLOTS * SLOTS];
/** Each drawn slot's colors' hash: a chunk drawn again the same isn't uploaded or recorded again. */
private static final int[] slotHash = new int[SLOTS * SLOTS];
/** Whether each drawn slot's chunk has changed since ({@link #sectionChanged}). */
private static final boolean[] slotChanged = new boolean[SLOTS * SLOTS];
private static @Nullable GpuTexture texture;
private static @Nullable GpuTextureView view;
private static @Nullable NativeImage staging;
private static @Nullable ClientLevel level;
/** {@link #level}'s dimension's id, made once. */
private static String dimension = "";
private static int ticks;
private static int drawnAt = -IDLE_TICKS;
private static int centerX;
private static int centerZ;
private static int reach = REACH;
/** In a world with a ceiling, the height the map is sliced at, and where the slice was last drawn. */
private static int sliceY;
private static int slicedAt = Integer.MIN_VALUE;
private static int refreshCursor;
/** One column's height and the height of each block's north and west neighbours, while drawing a chunk. */
private static final int[] heights = new int[18 * 18];
private static final BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos();
static {
Arrays.fill(slotChunk, NONE);
}
private MapTerrain() {}
/** From {@code IncariModules}, once a client tick: draws chunks while the map is shown. */
@SuppressWarnings("ReferenceEquality") // Another level object is another dimension or world.
static void tick(Minecraft minecraft) {
ticks++;
ClientLevel current = minecraft.level;
if (current == null || ticks - drawnAt > IDLE_TICKS || texture == null) {
return;
}
if (current != level) {
// Another dimension (or world): what's drawn is of the last one.
forget();
level = current;
dimension = current.dimension().identifier().toString();
}
if (current.dimensionType().hasCeiling() && minecraft.player != null) {
sliceY = minecraft.player.getBlockY() + 1;
if (Math.abs(sliceY - slicedAt) >= 3) {
// Up or down a floor: every chunk's slice is of the wrong floor.
slicedAt = sliceY;
for (int i = 0; i < slotState.length; i++) {
if (slotState[i] == DRAWN) {
slotChanged[i] = true;
slotDrawnAt[i] = Integer.MIN_VALUE / 2;
}
}
}
}
long deadline = System.nanoTime() + BUDGET_NANOS;
// New chunks, nearest first.
int limit = SPIRAL.length / 2;
for (int i = 0; i < limit; i++) {
int dx = SPIRAL[2 * i];
int dz = SPIRAL[2 * i + 1];
if (Math.max(Math.abs(dx), Math.abs(dz)) > reach) {
continue;
}
int chunkX = centerX + dx;
int chunkZ = centerZ + dz;
int slot = slot(chunkX, chunkZ);
long key = ChunkPos.pack(chunkX, chunkZ);
boolean stale = slotChunk[slot] != key;
if (!stale && slotState[slot] == DRAWN) {
continue;
}
LevelChunk chunk = current.getChunkSource().getChunk(chunkX, chunkZ, ChunkStatus.FULL, false);
if (chunk == null) {
if (stale || slotState[slot] != MISSING) {
clear(slot, chunkX, chunkZ, key);
}
continue;
}
draw(current, chunk, slot, key);
if (System.nanoTime() > deadline) {
return;
}
}
// Changed chunks, from where the last tick stopped: those by the player sooner. The clock
// only after a redraw: in the browser each reading is a call out to the page.
for (int step = 0; step < limit; step++) {
refreshCursor = (refreshCursor + 1) % limit;
int dx = SPIRAL[2 * refreshCursor];
int dz = SPIRAL[2 * refreshCursor + 1];
int ring = Math.max(Math.abs(dx), Math.abs(dz));
if (ring <= reach
&& refresh(current, centerX + dx, centerZ + dz, ring <= 1 ? NEAR_REFRESH : FAR_REFRESH)
&& System.nanoTime() > deadline) {
return;
}
}
}
/**
* Hook ({@code LevelExtractor.setSectionDirty}): a section of chunk {@code sectionX, sectionZ}
* changed (a block, its light, the chunk loaded), so its column may look different from above.
* Called for every section a block change touches: a lookup and a flag.
*/
public static void sectionChanged(int sectionX, int sectionZ) {
int slot = slot(sectionX, sectionZ);
if (slotChunk[slot] == ChunkPos.pack(sectionX, sectionZ)) {
slotChanged[slot] = true;
}
}
/**
* Draws the chunk again if it changed and was drawn more than {@code age} ticks ago; true if
* it was.
*/
private static boolean refresh(ClientLevel current, int chunkX, int chunkZ, int age) {
int slot = slot(chunkX, chunkZ);
long key = ChunkPos.pack(chunkX, chunkZ);
if (!slotChanged[slot]
|| slotChunk[slot] != key
|| slotState[slot] != DRAWN
|| ticks - slotDrawnAt[slot] < age) {
return false;
}
LevelChunk chunk = current.getChunkSource().getChunk(chunkX, chunkZ, ChunkStatus.FULL, false);
if (chunk == null) {
clear(slot, chunkX, chunkZ, key);
} else {
draw(current, chunk, slot, key);
}
return true;
}
/**
* The world map's, each tick it's open: keeps chunks around {@code x, z} being drawn (and so
* remembered) as if the minimap were, out as far as the map reaches.
*/
static void keepDrawing(double x, double z) {
view();
drawnAt = ticks;
centerX = (int) Math.floor(x) >> 4;
centerZ = (int) Math.floor(z) >> 4;
reach = REACH;
}
/** The player left the world: nothing drawn is theirs any more. */
static void leave() {
forget();
level = null;
}
private static void forget() {
Arrays.fill(slotChunk, NONE);
Arrays.fill(slotState, (byte) 0);
Arrays.fill(slotChanged, false);
slicedAt = Integer.MIN_VALUE;
GpuTexture current = texture;
if (current != null) {
RenderSystem.getDevice().createCommandEncoder().clearColorTexture(current, new Vector4f(0.0F));
}
}
/**
* Draws the terrain around {@code centerX, centerZ} into the square {@code size} GUI units at
* {@code x, y} ({@code HudCanvas.terrain}), and keeps the chunks around it drawn.
*/
static void draw(
GuiGraphicsExtractor graphics,
int x,
int y,
int size,
boolean round,
double centerX,
double centerZ,
float blocksAcross,
float rotation) {
GpuTextureView current = view();
drawnAt = ticks;
MapTerrain.centerX = (int) Math.floor(centerX) >> 4;
MapTerrain.centerZ = (int) Math.floor(centerZ) >> 4;
// The chunks the map's corners reach, turned, and one more.
reach = Math.min(REACH, (int) Math.ceil(blocksAcross * 0.71F / 16.0F) + 1);
Matrix3x2f pose = new Matrix3x2f(graphics.pose());
GpuSampler sampler = RenderSystem.getSamplerCache().getRepeat(FilterMode.NEAREST);
ScreenRectangle bounds = new ScreenRectangle(x, y, size, size).transformMaxBounds(pose);
float scale = Math.max(1, Minecraft.getInstance().getWindow().getGuiScale());
float poseScale = (float) Math.sqrt(pose.m00() * pose.m00() + pose.m01() * pose.m01());
Minecraft.getInstance()
.gameRenderer
.gameRenderState()
.guiRenderState
.addGuiElement(new Mesh(
pose,
TextureSetup.singleTexture(current, sampler),
x + size / 2.0F,
y + size / 2.0F,
size / 2.0F,
round,
// Where the middle is in the texture, from the world's coordinates modulo its size:
// a float holds that exactly, where it would lose blocks at the world's edges.
(float) (floorMod(centerX, SIZE) / SIZE),
(float) (floorMod(centerZ, SIZE) / SIZE),
blocksAcross / size / SIZE,
(float) Math.toRadians(rotation),
Circles.sides(size / 2.0F * scale * poseScale),
bounds));
}
private static double floorMod(double value, int modulus) {
double result = value % modulus;
return result < 0 ? result + modulus : result;
}
private static GpuTextureView view() {
GpuTextureView current = view;
if (current == null) {
GpuDevice device = RenderSystem.getDevice();
GpuTexture made = device.createTexture(
() -> "Incari minimap",
GpuTexture.USAGE_COPY_DST | GpuTexture.USAGE_TEXTURE_BINDING | GpuTexture.USAGE_RENDER_ATTACHMENT,
GpuFormat.RGBA8_UNORM,
SIZE,
SIZE,
1,
1);
device.createCommandEncoder().clearColorTexture(made, new Vector4f(0.0F));
texture = made;
current = device.createTextureView(made);
view = current;
}
return current;
}
private static int slot(int chunkX, int chunkZ) {
return (chunkX & (SLOTS - 1)) + (chunkZ & (SLOTS - 1)) * SLOTS;
}
private static NativeImage staging() {
NativeImage current = staging;
if (current == null) {
current = new NativeImage(16, 16, true);
staging = current;
}
return current;
}
/** Clears a slot's square: its chunk isn't loaded. */
private static void clear(int slot, int chunkX, int chunkZ, long key) {
NativeImage image = staging();
image.fillRect(0, 0, 16, 16, 0);
upload(image, chunkX, chunkZ);
slotChunk[slot] = key;
slotState[slot] = MISSING;
slotChanged[slot] = false;
}
private static void upload(NativeImage image, int chunkX, int chunkZ) {
GpuTexture current = texture;
if (current != null) {
RenderSystem.getDevice()
.createCommandEncoder()
.writeToTexture(current, image, 0, 0, (chunkX & (SLOTS - 1)) * 16, (chunkZ & (SLOTS - 1)) * 16);
}
}
/** Draws a chunk's 256 columns into its slot. */
private static void draw(ClientLevel current, LevelChunk chunk, int slot, long key) {
ChunkPos chunkPos = chunk.getPos();
int baseX = chunkPos.getMinBlockX();
int baseZ = chunkPos.getMinBlockZ();
boolean ceiling = current.dimensionType().hasCeiling();
int minY = current.getMinY();
NativeImage image = staging();
// Heights of the chunk's columns and of the row north and column west of it (from the
// neighbours where they're loaded, else the chunk's own edge), for the slopes' shading.
LevelChunk north = current.getChunkSource().getChunk(chunkPos.x(), chunkPos.z() - 1, ChunkStatus.FULL, false);
LevelChunk west = current.getChunkSource().getChunk(chunkPos.x() - 1, chunkPos.z(), ChunkStatus.FULL, false);
for (int lz = 0; lz < 16; lz++) {
for (int lx = 0; lx < 16; lx++) {
COLORS[lx + lz * 16] = column(chunk, baseX + lx, baseZ + lz, ceiling, minY);
FLAT[lx + lz * 16] = columnFlat;
heights[(lx + 1) + (lz + 1) * 18] = columnY;
}
}
for (int i = 0; i < 16; i++) {
heights[(i + 1)] = north == null ? heights[(i + 1) + 18] : surface(north, i, 15, ceiling, minY);
heights[(i + 1) * 18] = west == null ? heights[1 + (i + 1) * 18] : surface(west, 15, i, ceiling, minY);
}
int hash = 1;
for (int lz = 0; lz < 16; lz++) {
for (int lx = 0; lx < 16; lx++) {
int color = COLORS[lx + lz * 16];
if (color != 0 && !FLAT[lx + lz * 16]) {
int h = heights[(lx + 1) + (lz + 1) * 18];
int slope = (h - heights[(lx + 1) + lz * 18]) + (h - heights[lx + (lz + 1) * 18]);
color = shade(color, 1.0F + Math.max(-4, Math.min(4, slope)) * SLOPE_SHADE);
}
COLORS[lx + lz * 16] = color;
hash = 31 * hash + color;
}
}
slotDrawnAt[slot] = ticks;
slotChanged[slot] = false;
// Most redraws (the player's own chunks every half second) find nothing changed: then the
// texture and the world map already have it.
if (slotChunk[slot] == key && slotState[slot] == DRAWN && slotHash[slot] == hash) {
return;
}
for (int i = 0; i < 256; i++) {
image.setPixel(i & 15, i >> 4, COLORS[i]);
}
upload(image, chunkPos.x(), chunkPos.z());
// And kept, for the world map.
MapMemory.record(dimension, chunkPos.x(), chunkPos.z(), COLORS);
slotChunk[slot] = key;
slotState[slot] = DRAWN;
slotHash[slot] = hash;
}
/** A chunk's columns' colors while it's drawn, and whether each is shaded already (water, walls). */
private static final int[] COLORS = new int[256];
private static final boolean[] FLAT = new boolean[256];
/** The height of the last column {@link #column} looked at, and whether it's shaded already. */
private static int columnY;
private static boolean columnFlat;
/**
* A column's color at {@code x, z}, opaque, or 0 (clear) for nothing; its height is left in
* {@link #columnY}.
*/
private static int column(LevelChunk chunk, int x, int z, boolean ceiling, int minY) {
int y = ceiling ? sliceTop(chunk, x, z, minY) : chunk.getHeight(Heightmap.Types.WORLD_SURFACE, x, z);
boolean wall = false;
if (y == Integer.MIN_VALUE) {
// Solid all the way down from the slice: a wall.
wall = true;
y = sliceY;
}
columnY = y;
columnFlat = wall;
if (y < minY) {
return 0;
}
BlockState state = chunk.getBlockState(pos.set(x, y, z));
MapColor mapColor = state.getMapColor(chunk, pos);
// Down through what a map shows nothing of: glass, torches, air in a slice.
for (int steps = 0; mapColor.id == MapColor.NONE.id && y > minY && steps < 64; steps++) {
y--;
state = chunk.getBlockState(pos.set(x, y, z));
mapColor = state.getMapColor(chunk, pos);
}
columnY = y;
if (mapColor.id == MapColor.NONE.id) {
return 0;
}
if (wall) {
return shade(0xFF000000 | mapColor.col, 0.45F);
}
if (mapColor.id == MapColor.WATER.id) {
int depth = 1;
for (; depth < 12 && y - depth > minY; depth++) {
if (chunk.getBlockState(pos.set(x, y - depth, z)).getMapColor(chunk, pos).id != MapColor.WATER.id) {
break;
}
}
int water = 0xFF000000 | biome(chunk, x, y, z).getWaterColor();
// Shallows lighter, the deep darker; flat, so not shaded by slope.
columnFlat = true;
return shade(water, (1.08F - depth * 0.045F) * TONE);
}
int color;
if (mapColor.id == MapColor.GRASS.id) {
color = biome(chunk, x, y, z).getGrassColor(x, z);
} else if (mapColor.id == MapColor.PLANT.id) {
color = biome(chunk, x, y, z).getFoliageColor();
} else {
color = mapColor.col;
}
return shade(0xFF000000 | color, TONE);
}
/** The column's surface height only, for a neighbour's edge. */
private static int surface(LevelChunk chunk, int lx, int lz, boolean ceiling, int minY) {
ChunkPos chunkPos = chunk.getPos();
int x = chunkPos.getMinBlockX() + lx;
int z = chunkPos.getMinBlockZ() + lz;
int y = ceiling ? sliceTop(chunk, x, z, minY) : chunk.getHeight(Heightmap.Types.WORLD_SURFACE, x, z);
return y == Integer.MIN_VALUE ? sliceY : y;
}
/**
* Under a ceiling: the top of the floor below the slice's height. From the slice down to the
* first open block, then down through it; {@code Integer.MIN_VALUE} if solid all the way (a wall).
*/
private static int sliceTop(LevelChunk chunk, int x, int z, int minY) {
int y = sliceY;
int open = Integer.MIN_VALUE;
for (int steps = 0; steps < 24 && y > minY; steps++, y--) {
if (chunk.getBlockState(pos.set(x, y, z)).isAir()) {
open = y;
break;
}
}
if (open == Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
for (int steps = 0; steps < 64 && y > minY; steps++, y--) {
if (!chunk.getBlockState(pos.set(x, y, z)).isAir()) {
return y;
}
}
return minY - 1;
}
private static Biome biome(LevelChunk chunk, int x, int y, int z) {
return chunk.getNoiseBiome(QuartPos.fromBlock(x), QuartPos.fromBlock(y), QuartPos.fromBlock(z))
.value();
}
/** {@code argb} with each color brighter or darker by {@code factor}, alpha kept. */
private static int shade(int argb, float factor) {
int r = Math.min(255, Math.round((argb >> 16 & 0xFF) * factor));
int g = Math.min(255, Math.round((argb >> 8 & 0xFF) * factor));
int b = Math.min(255, Math.round((argb & 0xFF) * factor));
return (argb & 0xFF000000) | r << 16 | g << 8 | b;
}
/** Offsets within {@link #REACH} chunks, nearest first. */
private static int[] spiral() {
int side = 2 * REACH + 1;
Integer[] order = new Integer[side * side];
for (int i = 0; i < order.length; i++) {
order[i] = i;
}
Arrays.sort(order, (a, b) -> Integer.compare(distance(a, side), distance(b, side)));
int[] offsets = new int[order.length * 2];
for (int i = 0; i < order.length; i++) {
offsets[2 * i] = order[i] % side - REACH;
offsets[2 * i + 1] = order[i] / side - REACH;
}
return offsets;
}
private static int distance(int index, int side) {
int dx = index % side - REACH;
int dz = index / side - REACH;
return dx * dx + dz * dz;
}
/**
* The map: a fan of triangles around the middle for a round one, a quad for a square, each
* corner's texture coordinates the world's position there, turned ({@code texelsPer}: texture
* units a GUI unit).
*/
private record Mesh(
Matrix3x2fc pose,
TextureSetup textureSetup,
float centerX,
float centerY,
float half,
boolean round,
float u,
float v,
float texelsPer,
float rotation,
int sides,
ScreenRectangle bounds)
implements GuiElementRenderState {
@Override
public void buildVertices(VertexConsumer consumer) {
float cos = (float) Math.cos(rotation);
float sin = (float) Math.sin(rotation);
if (!round) {
vertex(consumer, -half, -half, cos, sin);
vertex(consumer, -half, half, cos, sin);
vertex(consumer, half, half, cos, sin);
vertex(consumer, half, -half, cos, sin);
return;
}
float[] corners = Circles.corners(sides);
float x0 = half;
float y0 = 0;
for (int i = 1; i <= sides; i++) {
float x1 = corners[2 * i] * half;
float y1 = corners[2 * i + 1] * half;
// Wound as the game's GUI quads are: its pipeline culls the other way round.
vertex(consumer, 0, 0, cos, sin);
vertex(consumer, x1, y1, cos, sin);
vertex(consumer, x0, y0, cos, sin);
vertex(consumer, 0, 0, cos, sin);
x0 = x1;
y0 = y1;
}
}
/** A corner {@code sx, sy} from the middle: the world there is the map's turn undone. */
private void vertex(VertexConsumer consumer, float sx, float sy, float cos, float sin) {
float east = sx * cos - sy * sin;
float south = sx * sin + sy * cos;
consumer.addVertexWith2DPose(pose, centerX + sx, centerY + sy)
.setUv(u + east * texelsPer, v + south * texelsPer)
.setColor(0xFFFFFFFF);
}
@Override
public RenderPipeline pipeline() {
return RenderPipelines.GUI_TEXTURED;
}
@Override
public @Nullable ScreenRectangle scissorArea() {
return null;
}
}
}

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