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
@@ -0,0 +1,9 @@
# platform-api
- Only `java.*` and `org.jspecify.*` imports. No game types, no LWJGL, no TeaVM: this module is
compiled into every build. `BoundaryTest` fails otherwise.
- Only JDK APIs TeaVM's class library has. When unsure, check `docs/port-backlog.md`.
- Every public type and method gets Javadoc that states its threading and ownership rules.
- Changing an interface changes both platforms: update `platform-desktop` and `platform-web` in
the same change.
- Test: `./gradlew :platform-api:check`.
@@ -0,0 +1,35 @@
# platform-api: the platform interfaces
Everything the game needs from the machine it runs on, as Java interfaces with no game or library
types: the window and its events, input, audio, the graphics surface, files, clipboard, threads.
`platform-desktop` and `platform-web` implement it; the game reaches it through `client`'s hooks.
## Code map
- `Platform` (package `incari.platform.api`): lifecycle, the clock, event polling, and access to
everything below. `Platforms` holds the one installed platform.
- `window`: `PlatformWindow`, `PlatformDisplays`, `PlatformEventListener` (window and input
events), display modes, cursors, icons.
- `input`: keyboard state and key names; `Scancodes` and `KeyModifiers` define the values, which
are SDL3's (USB HID usage ids, `SDL_Keymod` bits), the format the game's key handling reads.
- `audio`: output devices, sources, PCM buffers, the listener.
- `net`: `PlatformNetwork`, a byte stream (TCP) or a message stream (WebSocket) to a server, and a
blocking, size-capped HTTP GET (`fetch`) for public files such as skins and server packs.
- `rtc`: `PlatformRtc`, WebRTC peer connections with voice and data channels, and the
microphone, for Eagler voice chat and shared worlds; only the browser has it (ADR 0019).
- `storage`, `threads`, and `PlatformShell` (clipboard, links, message boxes).
[ADR 0005](../docs/adr/0005-platform-layer.md) explains the design.
## Invariants
- **Depends on nothing** but the JDK subset TeaVM supports and JSpecify
(`gradle/module-boundaries.txt`, `BoundaryTest`).
- **Every public type has Javadoc**, including its threading and ownership rules.
- **Null-marked**: unannotated types are non-null; `@Nullable` marks the exceptions.
## How to test
```sh
./gradlew :platform-api:check
```
@@ -0,0 +1,15 @@
plugins {
`java-library`
}
// No dependencies but the JDK subset TeaVM supports, and JSpecify for nullness in signatures:
// both platforms and the game compile against this module (gradle/module-boundaries.txt).
dependencies {
api(libs.jspecify)
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
testImplementation(libs.assertj)
testImplementation(libs.archunit)
testRuntimeOnly(libs.junit.launcher)
}
@@ -0,0 +1,13 @@
package incari.platform.api;
/**
* What the platform needs to know about the application: names for the window manager, the
* audio mixer and crash dialogs.
*
* @param name the product name, for example "Minecraft"
* @param version the game version, for example "26.3"
* @param identifier a reverse-DNS application id, for example "com.mojang.minecraft"
* @param creator who made it, for the platform's "about" metadata
* @param url the product's web page
*/
public record AppInfo(String name, String version, String identifier, String creator, String url) {}
@@ -0,0 +1,24 @@
package incari.platform.api;
import org.jspecify.annotations.Nullable;
/**
* Creates the native window a graphics backend draws into. Mojang's backends own this step
* ({@code GpuBackend.createWindow}) because each needs its own window flags: OpenGL a GL-capable
* window, Vulkan a Vulkan one. The platform calls it from {@link Platform#createWindow}.
*/
@FunctionalInterface
public interface NativeSurfaceFactory {
/**
* Creates the window.
*
* @param title the window title, or null for none
* @param width the width in screen coordinates
* @param height the height in screen coordinates
* @param flags platform window flags (on the desktop, SDL window flags) the platform needs
* on every window, for example resizable and high-density
* @return the native window handle, or 0 if creation failed
*/
long create(@Nullable String title, int width, int height, long flags);
}
@@ -0,0 +1,150 @@
package incari.platform.api;
import incari.platform.api.audio.PlatformAudio;
import incari.platform.api.fonts.PlatformFonts;
import incari.platform.api.input.PlatformInput;
import incari.platform.api.net.PlatformNetwork;
import incari.platform.api.profile.PlatformProfiling;
import incari.platform.api.rtc.PlatformRtc;
import incari.platform.api.storage.PlatformStorage;
import incari.platform.api.threads.PlatformThreads;
import incari.platform.api.window.PlatformDisplays;
import incari.platform.api.window.PlatformEventListener;
import incari.platform.api.window.PlatformWindow;
import incari.platform.api.window.WindowSpec;
/**
* Everything the game needs from the machine it runs on. One implementation per platform:
* {@code platform-desktop} (LWJGL, for development) and {@code platform-web} (the browser).
*
* <p>The game reaches the platform only through this interface and the ones it returns, never
* through a platform library directly. The running platform is installed once at startup with
* {@link Platforms#install} and read with {@link Platforms#current}.
*
* <p><b>Threading.</b> Unless a method says otherwise, call it from the thread that called
* {@link #initialize}: the game's render thread. In the browser that's the page's only thread,
* so no method here blocks.
*/
public interface Platform {
/** A short description for logs and crash reports, for example "SDL 3.4 on linux (wayland)". */
String description();
/**
* Which build this is, for the usage counts (ADR 0062): {@code fast}, {@code compatible} or
* {@code html} in the browser, {@code desktop} here by default.
*/
default String buildKind() {
return "desktop";
}
/**
* Starts the platform: native libraries, the windowing and input systems, application
* metadata. Called once, before any other method but {@link #description}.
*
* @throws PlatformException if the platform can't run here (no display, missing libraries)
*/
void initialize(AppInfo app);
/** Stops the platform. The window must be closed first. Nothing may be called after this. */
void shutdown();
/**
* A monotonic clock in nanoseconds, from an arbitrary origin. The game's frame timing is
* built on it, so it must be cheap: it's read several times per frame.
*/
long nanoTime();
/** The monitors, and notifications when they change. */
PlatformDisplays displays();
/**
* Creates the game's one window.
*
* @param surface creates the native surface the graphics backend draws to. The desktop
* calls it to make the window itself (the OpenGL and Vulkan backends each need their
* own window flags); the browser, whose surface is a canvas, may ignore it.
* @throws PlatformException if no window can be created
*/
PlatformWindow createWindow(WindowSpec spec, NativeSurfaceFactory surface);
/**
* Delivers every pending window and input event to {@code listener}, then returns. Called
* once per frame. Events are delivered on the calling thread, in the order they happened.
*/
void pollEvents(PlatformEventListener listener);
/**
* Called once per frame, after the frame is presented. The browser suspends the game here
* until the next animation frame, which is when the page gets to handle input and draw; the
* desktop, whose swap already paces the loop, returns at once.
*/
void endFrame();
/**
* Asks the platform to hold the game to at most {@code framesPerSecond} frames a second (the
* game's frame limit, or its throttling in menus and when idle) by delaying the next frames at
* {@link #endFrame}. Returns false if it doesn't pace frames itself, and the game should sleep
* the rest of the frame out as it does on the desktop. The browser paces frames by skipping
* animation frames: a sleep there would hold the page's frame, not just the game's.
*/
default boolean limitFrameRate(int framesPerSecond) {
return false;
}
/**
* Discards pending input events (keys, text, mouse). Used after a long stall, so input
* queued during a load isn't replayed into the game.
*/
void flushInputEvents();
/** Keyboard and mouse state, and key names in the user's keyboard layout. */
PlatformInput input();
/** The clipboard, opening links and folders, and native message boxes. */
PlatformShell shell();
/** Sound output. */
PlatformAudio audio();
/** Connections to game servers. */
PlatformNetwork network();
/**
* WebRTC: voice chat and shared worlds. Only the browser has it; the default says there
* is none.
*/
default PlatformRtc rtc() {
return PlatformRtc.UNSUPPORTED;
}
/**
* Crashes the process the way a native bug would, for testing crash handling (the game's
* "debug crash" key). Never returns. A platform that can't crash natively throws an error.
*/
void crashNatively();
/** Where the game keeps its files. */
PlatformStorage storage();
/** Worker pools for background work. */
PlatformThreads threads();
/** Screen recording (ADR 0062). The default records nothing: only the browser has it. */
default PlatformRecorder recorder() {
return PlatformRecorder.NONE;
}
/** Smooth fonts' glyphs. The default draws none: the game keeps its bitmap fonts. */
default PlatformFonts fonts() {
return PlatformFonts.UNSUPPORTED;
}
/**
* Memory figures and a place for the game's frame measurements. The default measures
* nothing and keeps nothing.
*/
default PlatformProfiling profiling() {
return PlatformProfiling.NONE;
}
}
@@ -0,0 +1,17 @@
package incari.platform.api;
import org.jspecify.annotations.Nullable;
/** The platform couldn't do something the game can't continue without (a window, a display). */
public class PlatformException extends RuntimeException {
private static final long serialVersionUID = 1L;
public PlatformException(String message) {
super(message);
}
public PlatformException(String message, @Nullable Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,41 @@
package incari.platform.api;
import org.jspecify.annotations.Nullable;
/**
* Where a platform reports what it's doing: the window it created, a device that failed. The entry
* point passes one in that forwards to the game's logging, so platform modules need no logging
* library of their own. May be called from any thread.
*/
@FunctionalInterface
public interface PlatformLog {
/** Severity, from routine detail to failure. */
enum Level {
DEBUG,
INFO,
WARN,
ERROR
}
/** Discards everything. For tests. */
PlatformLog NONE = (level, message, error) -> {};
void log(Level level, String message, @Nullable Throwable error);
default void debug(String message) {
log(Level.DEBUG, message, null);
}
default void info(String message) {
log(Level.INFO, message, null);
}
default void warn(String message) {
log(Level.WARN, message, null);
}
default void error(String message, @Nullable Throwable error) {
log(Level.ERROR, message, error);
}
}
@@ -0,0 +1,21 @@
package incari.platform.api;
/**
* Something the platform found that the player must hear about, because it changes what happens to
* their game: chiefly, that what they do won't be saved. Delivered through
* {@code PlatformEventListener.notice} on the polling thread; the game words it for the player.
*/
public enum PlatformNotice {
/** The game is open in another tab or window, which keeps the files: nothing here is saved. */
SAVES_HELD_ELSEWHERE,
/** The browser gives the page no storage (a private window, storage blocked): nothing is saved. */
SAVES_UNAVAILABLE,
/**
* Saving failed (the disk is full, or storage refused the write). What failed is tried again a
* few seconds later; reported once until saving works again.
*/
SAVE_FAILED
}
@@ -0,0 +1,87 @@
package incari.platform.api;
import org.jspecify.annotations.Nullable;
/**
* Screen recording (ADR 0062), as Eaglercraft's browser builds have it: the game's picture and
* sound, and the microphone if asked, recorded to a video the player downloads when it stops. Only
* the browser has it; the default says there's none.
*
* <p>Render thread. Starting may wait on the page (the microphone's permission): {@link #state()}
* says when it's recording.
*/
public interface PlatformRecorder {
/** No recorder: the desktop, which has its own screen recorders. */
PlatformRecorder NONE = new PlatformRecorder() {
@Override
public boolean supported() {
return false;
}
@Override
public void start(Options options, String fileName) {}
@Override
public void stop() {}
@Override
public State state() {
return State.IDLE;
}
@Override
public @Nullable String error() {
return null;
}
@Override
public long elapsedMillis() {
return 0;
}
};
/**
* How to record.
*
* @param framesPerSecond the video's frame rate
* @param videoKilobits the video's bit rate, in kilobits a second
* @param gameVolume the game's sound in the recording, 0 to 1 (as the player hears it, times this)
* @param microphone whether to record the microphone too
* @param microphoneVolume the microphone's level in the recording, 0 to 1
*/
record Options(
int framesPerSecond, int videoKilobits, float gameVolume, boolean microphone, float microphoneVolume) {}
/** Where a recording is. */
enum State {
/** Not recording. */
IDLE,
/** Asked to start: waiting on the page (the microphone's permission). */
STARTING,
/** Recording. */
RECORDING
}
/** Whether this platform can record. */
boolean supported();
/**
* Starts recording. When it stops, the video downloads as {@code fileName} with the format's
* extension ({@code .mp4} or {@code .webm}, whichever the browser records).
*/
void start(Options options, String fileName);
/** Stops recording and downloads what was recorded. */
void stop();
/** Where the recording is now. */
State state();
/** Why the last recording failed or went without the microphone; null if it didn't. */
@Nullable
String error();
/** How long the recording has run, in milliseconds; 0 when not recording. */
long elapsedMillis();
}
@@ -0,0 +1,77 @@
package incari.platform.api;
import java.io.File;
import java.net.URI;
import org.jspecify.annotations.Nullable;
/** The parts of the operating system around the window: clipboard, links, files, message boxes. */
public interface PlatformShell {
/**
* The clipboard's text.
*
* @return the text, empty if the clipboard holds none, or null if it couldn't be read. In the
* browser this is the text of the last paste event: pages can't read the clipboard at will.
*/
@Nullable
String clipboardText();
/** Replaces the clipboard's contents with {@code text}. Returns false if that failed. */
boolean setClipboardText(String text);
/**
* Puts a PNG image on the clipboard, without waiting (a screenshot).
*
* @return false if this platform can't put images on the clipboard; true if it's on its way
*/
default boolean setClipboardImage(byte[] png) {
return false;
}
/**
* Opens a link or a local folder in the user's default application, without waiting for it.
* May be called from any thread. Failures are logged by the platform, never thrown: the game
* never depends on the result.
*/
void open(URI uri);
/**
* Shows the player one of the game's files or folders (a screenshot, the resource pack
* folder), without waiting. The desktop opens it in the system's file manager. A page can't
* show the player its files: the browser downloads a file, and for a folder opens the file
* picker, whose files reach the game as if dropped on its window. Failures are logged, never
* thrown.
*
* @param path an absolute path in the platform's file system
*/
default void openPath(String path) {
open(new File(path).toURI());
}
/**
* Whether {@link #openPath} shows the player a folder's contents (a file manager). A page can't:
* a folder the player wants to see, a world, is better handed over as a {@link #download}.
*/
default boolean showsFolders() {
return true;
}
/**
* Hands the player a file to keep, without waiting: the browser downloads it under {@code
* fileName}. A platform that shows folders ({@link #showsFolders}) has no need for it and
* logs that it was asked.
*/
default void download(String fileName, byte[] bytes) {
System.err.println("[Incari] This platform shows folders; not downloading " + fileName);
}
/**
* Shows a blocking error dialog, for failures the game reports before or instead of its own
* UI (a crash at startup).
*
* @param askToContinue whether to offer "Continue"/"Quit" instead of just "OK"
* @return true if the player chose to continue; false if they didn't, if there was no choice
* to make, or if no dialog could be shown
*/
boolean showErrorDialog(String title, String message, boolean askToContinue);
}
@@ -0,0 +1,55 @@
package incari.platform.api;
import org.jspecify.annotations.Nullable;
/**
* Holds the running {@link Platform}. The entry point ({@code app-desktop} or {@code app-web})
* installs it before the game starts; the game reads it through {@link #current}.
*
* <p>A static holder rather than dependency injection because the game's own code reaches the
* platform from static contexts (Mojang's {@code Blaze3D}, {@code InputConstants}), and there is
* exactly one platform per process.
*/
public final class Platforms {
private static volatile @Nullable Platform current;
private Platforms() {}
/**
* Installs the platform. Call once, before the game starts.
*
* @throws IllegalStateException if a platform is already installed
*/
public static synchronized void install(Platform platform) {
if (current != null) {
throw new IllegalStateException("A platform is already installed: " + current.description());
}
current = platform;
}
/**
* The installed platform.
*
* @throws IllegalStateException if none is installed yet, which means the game was started
* without going through an Incari entry point
*/
public static Platform current() {
Platform platform = current;
if (platform == null) {
throw new IllegalStateException(
"No platform installed. Start the game through app-desktop or app-web, not its own Main.");
}
return platform;
}
/** Whether a platform is installed. */
public static boolean isInstalled() {
return current != null;
}
/** Removes the installed platform. For tests only: a real run never changes platform. */
public static synchronized void uninstallForTests() {
current = null;
}
}
@@ -0,0 +1,15 @@
package incari.platform.api.audio;
/** PCM samples uploaded to the device, playable by any number of sources. */
public interface AudioBuffer extends AutoCloseable {
/** The format the samples were uploaded in. */
PcmFormat format();
/** The size of the samples in bytes. */
int sizeInBytes();
/** Frees the buffer. A source still using it must be stopped or given another buffer first. */
@Override
void close();
}
@@ -0,0 +1,21 @@
package incari.platform.api.audio;
/**
* Decodes compressed sound files the platform can decode better than the game's own Java decoder:
* in the browser, natively and off the page's thread. A platform without one ({@link
* PlatformAudio#decoder} is null) leaves decoding to the game.
*/
public interface AudioDecoder {
/**
* Decodes a whole Ogg Vorbis file into samples any of this platform's devices can play
* ({@link AudioDevice#createBuffer(DecodedAudio)}).
*
* <p>Waits until the file is decoded: never call it from the game's main thread or its sound
* thread. In the browser the wait suspends only the calling coroutine; the page keeps running.
*
* @param file the complete file
* @throws AudioException if it isn't a file this decoder can read
*/
DecodedAudio decodeOggVorbis(byte[] file);
}
@@ -0,0 +1,57 @@
package incari.platform.api.audio;
import java.nio.ByteBuffer;
import org.jspecify.annotations.Nullable;
/**
* An open output device and its mixer. Everything it creates belongs to it and becomes invalid
* when it's closed. Call it from the game's sound thread.
*/
public interface AudioDevice extends AutoCloseable {
/** The device's name, as {@link AudioDeviceList} lists it. */
String name();
/** Whether the device was unplugged or otherwise lost since it was opened. */
boolean isDisconnected();
/** How many sources can play at once, at least 1. */
int maxSources();
/** The listener: the player's ears. */
AudioListener listener();
/** Creates a source, or returns null if {@link #maxSources} are already in use. */
@Nullable
AudioSource createSource();
/**
* Uploads PCM samples into a buffer sources can play.
*
* @param samples interleaved PCM, little-endian for 16-bit; read from its position to its limit
* @throws AudioException if the format isn't supported or the upload failed
*/
AudioBuffer createBuffer(ByteBuffer samples, PcmFormat format);
/**
* A buffer over samples the platform's {@link AudioDecoder} produced. Only platforms with a
* decoder support it.
*
* @throws AudioException if this device can't play them
*/
default AudioBuffer createBuffer(DecodedAudio audio) {
throw new AudioException("This device only plays PCM it's given");
}
/**
* Whether its sources can play an Ogg Vorbis file as a stream, decoding it as they play
* ({@link AudioSource#streamOggVorbis}), rather than being queued decoded chunks.
*/
default boolean streamsOggVorbis() {
return false;
}
/** Closes the device and everything it created. */
@Override
void close();
}
@@ -0,0 +1,19 @@
package incari.platform.api.audio;
import java.util.List;
import org.jspecify.annotations.Nullable;
/**
* The output devices available.
*
* @param defaultDevice the system default's name, or null if there is no device at all
* @param all every device's name, the default included
*/
public record AudioDeviceList(@Nullable String defaultDevice, List<String> all) {
public static final AudioDeviceList EMPTY = new AudioDeviceList(null, List.of());
public AudioDeviceList {
all = List.copyOf(all);
}
}
@@ -0,0 +1,17 @@
package incari.platform.api.audio;
import org.jspecify.annotations.Nullable;
/** Sound output failed: a device couldn't be opened, or it lacks what the game needs. */
public class AudioException extends RuntimeException {
private static final long serialVersionUID = 1L;
public AudioException(String message) {
super(message);
}
public AudioException(String message, @Nullable Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,13 @@
package incari.platform.api.audio;
/**
* Where the player hears from. Positions are in the game's world coordinates (blocks); sources
* are placed in the same space.
*/
public interface AudioListener {
void setPosition(double x, double y, double z);
/** Which way the listener faces, as a forward and an up vector (need not be normalized). */
void setOrientation(double forwardX, double forwardY, double forwardZ, double upX, double upY, double upZ);
}
@@ -0,0 +1,79 @@
package incari.platform.api.audio;
/**
* One playing sound. It plays either a single buffer ({@link #setBuffer}) or a stream of buffers
* queued one after another ({@link #queue}), never both.
*/
public interface AudioSource extends AutoCloseable {
/** Where a source is in its life. */
enum State {
/** Created or rewound, never played. */
INITIAL,
PLAYING,
PAUSED,
/** Played to the end, or stopped. */
STOPPED
}
void play();
void pause();
/** Stops and rewinds. */
void stop();
State state();
void setPosition(double x, double y, double z);
/** Playback speed and pitch, 1 for normal. */
void setPitch(float pitch);
void setLooping(boolean looping);
/** Volume, 0 to 1. */
void setGain(float gain);
/**
* Whether the position is relative to the listener rather than the world. Relative sources at
* the origin sound the same wherever the player is: music, UI sounds.
*/
void setRelative(boolean relative);
/** Plays at full volume at any distance. */
void disableAttenuation();
/** Fades linearly from full volume at the source to silence at {@code maxDistance} blocks. */
void setLinearAttenuation(float maxDistance);
/** Plays this buffer, replacing whatever was attached. */
void setBuffer(AudioBuffer buffer);
/** Appends a buffer to the stream; it plays after the ones already queued. */
void queue(AudioBuffer buffer);
/**
* Removes the queued buffers that finished playing and closes them.
*
* @return how many were removed
*/
int releaseProcessedBuffers();
/**
* Plays a whole Ogg Vorbis file as a stream, decoded as it plays, instead of queued buffers
* (music, records). Only on devices that {@link AudioDevice#streamsOggVorbis}; then
* {@link #releaseProcessedBuffers} has nothing to release.
*
* @param file the complete file; the source keeps its own copy
* @param looping whether to start over at the end, without a gap
* @throws AudioException if the device can't
*/
default void streamOggVorbis(byte[] file, boolean looping) {
throw new AudioException("This device doesn't stream compressed files");
}
/** Stops the source and frees it. Queued buffers are closed with it. */
@Override
void close();
}
@@ -0,0 +1,21 @@
package incari.platform.api.audio;
/**
* A sound an {@link AudioDecoder} decoded, held by the platform in whatever form its devices play
* (in the browser, a Web Audio buffer of 32-bit float samples). It isn't tied to a device: it can
* be decoded before one opens and given to the next one after it closes.
*/
public interface DecodedAudio {
/** Samples per second per channel. */
int sampleRate();
/** 1 (mono, the only kind that can be positioned) or 2 (stereo). */
int channels();
/** How many samples each channel has. */
int frames();
/** How much memory the samples take, in bytes. */
int sizeInBytes();
}
@@ -0,0 +1,23 @@
package incari.platform.api.audio;
/**
* The layout of uncompressed audio samples.
*
* @param sampleRate samples per second per channel, for example 44100
* @param channels 1 (mono, the only kind that can be positioned) or 2 (stereo)
* @param bitsPerSample 8 (unsigned) or 16 (signed, little-endian)
*/
public record PcmFormat(int sampleRate, int channels, int bitsPerSample) {
public PcmFormat {
if (sampleRate <= 0 || (channels != 1 && channels != 2) || (bitsPerSample != 8 && bitsPerSample != 16)) {
throw new AudioException("Unsupported PCM format: " + sampleRate + " Hz, " + channels + " channels, "
+ bitsPerSample + "-bit");
}
}
/** The size of one frame (a sample for every channel) in bytes. */
public int frameSize() {
return channels * bitsPerSample / 8;
}
}
@@ -0,0 +1,42 @@
package incari.platform.api.audio;
import org.jspecify.annotations.Nullable;
/**
* Sound output. The game opens one {@link AudioDevice} at a time and plays positional sources
* through it. On the desktop this is OpenAL; in the browser, Web Audio.
*/
public interface PlatformAudio {
/** The output devices the player could choose, as of now. */
AudioDeviceList devices();
/**
* Whether {@link #setDeviceChangeListener} will report device changes. When not, the game
* polls {@link #devices} instead.
*/
boolean reportsDeviceChanges();
/**
* Called, on an arbitrary thread, when devices are added or removed. Replaces any previous
* listener; null removes it. Ignored when {@link #reportsDeviceChanges} is false.
*/
void setDeviceChangeListener(@Nullable Runnable listener);
/**
* Opens an output device.
*
* @param deviceName a name from {@link #devices}, or null for the system default
* @param spatialize whether to use head-related spatialization (HRTF) if the device has it
* @throws AudioException if the device can't be opened or lacks what the game needs
*/
AudioDevice open(@Nullable String deviceName, boolean spatialize);
/**
* The platform's own decoder for compressed sound files, or null if the game should decode
* them itself and hand devices PCM (the desktop, where the game's decoder is the reference).
*/
default @Nullable AudioDecoder decoder() {
return null;
}
}
@@ -0,0 +1,5 @@
/** Sound output: devices, sources, buffers and the listener. */
@NullMarked
package incari.platform.api.audio;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,67 @@
package incari.platform.api.fonts;
import org.jspecify.annotations.Nullable;
/** A font opened at one size. Not thread-safe: one thread draws at a time. */
public interface FontFace extends AutoCloseable {
/**
* Draws {@code codepoint}, or returns null if the font has no glyph for it (a platform that
* can't tell answers with the font's fallback glyph; callers ask only for the font's own).
*/
@Nullable
Glyph glyph(int codepoint);
@Override
void close();
/**
* A drawn glyph, in pixels, as FreeType gives it: {@code left} from the pen to the bitmap's left
* edge, {@code top} from the baseline up to its top edge, and the pen's advance. An empty glyph
* (a space) has no pixels. Its coverage is {@code width * height} bytes, row by row from the
* top, 0 transparent to 255 opaque.
*/
final class Glyph {
private final float advance;
private final int left;
private final int top;
private final int width;
private final int height;
private final byte[] coverage;
public Glyph(float advance, int left, int top, int width, int height, byte[] coverage) {
this.advance = advance;
this.left = left;
this.top = top;
this.width = width;
this.height = height;
this.coverage = coverage;
}
public float advance() {
return advance;
}
public int left() {
return left;
}
public int top() {
return top;
}
public int width() {
return width;
}
public int height() {
return height;
}
/** The pixels' coverage, the glyph's own array: don't change it. */
@SuppressWarnings("EffectivelyPrivate")
public byte[] coverage() {
return coverage;
}
}
}
@@ -0,0 +1,24 @@
package incari.platform.api.fonts;
import org.jspecify.annotations.Nullable;
/**
* Draws a font's glyphs from its TrueType or OpenType file, at a size in pixels. The game's own
* TrueType provider needs FreeType, which the browser doesn't have; the browser draws text natively,
* so each platform rasterizes with what it has, and the client's fonts look the same on both.
*/
public interface PlatformFonts {
/** No font drawing: callers fall back to the game's bitmap fonts. */
PlatformFonts UNSUPPORTED = (data, name, pixelsPerEm) -> null;
/**
* Opens the font in {@code data} for glyphs {@code pixelsPerEm} pixels to the em, or returns
* null if this platform can't. May suspend while the font loads (the browser): call it from a
* background thread, never the game's main thread.
*
* @param name a name for the font, the same for the same file (the browser registers it by name)
*/
@Nullable
FontFace open(byte[] data, String name, float pixelsPerEm);
}
@@ -0,0 +1,5 @@
/** Smooth fonts drawn by the platform: FreeType on the desktop, the browser's own text in the page. */
@NullMarked
package incari.platform.api.fonts;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,9 @@
package incari.platform.api.input;
/** What happened to a key. */
public enum KeyAction {
PRESS,
RELEASE,
/** The key is held and the system's auto-repeat fired. */
REPEAT
}
@@ -0,0 +1,29 @@
package incari.platform.api.input;
/**
* Modifier key bits, as reported with key, mouse button and wheel events and by
* {@link PlatformInput#modifiers}. The values are SDL3's {@code SDL_Keymod} values, which is the
* format the game's key handling reads; the browser maps its own modifier flags onto them.
*/
public final class KeyModifiers {
public static final int LEFT_SHIFT = 0x0001;
public static final int RIGHT_SHIFT = 0x0002;
public static final int LEFT_CTRL = 0x0040;
public static final int RIGHT_CTRL = 0x0080;
public static final int LEFT_ALT = 0x0100;
public static final int RIGHT_ALT = 0x0200;
/** The Windows key, Command on macOS. */
public static final int LEFT_SUPER = 0x0400;
public static final int RIGHT_SUPER = 0x0800;
public static final int NUM_LOCK = 0x1000;
public static final int CAPS_LOCK = 0x2000;
public static final int SHIFT = LEFT_SHIFT | RIGHT_SHIFT;
public static final int CTRL = LEFT_CTRL | RIGHT_CTRL;
public static final int ALT = LEFT_ALT | RIGHT_ALT;
public static final int SUPER = LEFT_SUPER | RIGHT_SUPER;
private KeyModifiers() {}
}
@@ -0,0 +1,26 @@
package incari.platform.api.input;
import org.jspecify.annotations.Nullable;
/** Keyboard state and key names. Events are delivered through {@code Platform.pollEvents}. */
public interface PlatformInput {
/**
* Whether the key is held right now, as of the last {@code pollEvents}.
*
* @param scancode a {@link Scancodes} value; out-of-range values are simply not down
*/
boolean isKeyDown(int scancode);
/** The modifiers held right now, as {@link KeyModifiers} bits. */
int modifiers();
/**
* What the key is labelled in the player's current keyboard layout, for key binding screens:
* "Z" for the key at {@link Scancodes#W} on a French keyboard.
*
* @return the label, or null if the platform has none for this key
*/
@Nullable
String keyName(int scancode);
}
@@ -0,0 +1,50 @@
package incari.platform.api.input;
/**
* Physical key codes. A scancode names a key by where it is, not what it types: the key right of
* Tab is {@link #Q} on every layout. The values are USB HID keyboard usage ids (HID usage table,
* page 0x07), which is also what SDL3's scancodes and the game's key bindings use. The browser
* maps {@code KeyboardEvent.code} onto them.
*
* <p>Only the codes Incari's own code needs are named here; every HID usage id is a valid
* scancode.
*/
public final class Scancodes {
public static final int UNKNOWN = 0;
public static final int A = 4;
/** Letters run contiguously from A (4) to Z (29). */
public static final int Z = 29;
/** Digits run from 1 (30) to 9 (38), then 0 (39). */
public static final int DIGIT_1 = 30;
public static final int DIGIT_0 = 39;
public static final int Q = 20;
public static final int W = 26;
public static final int RETURN = 40;
public static final int ESCAPE = 41;
public static final int BACKSPACE = 42;
public static final int TAB = 43;
public static final int SPACE = 44;
public static final int F1 = 58;
/** Function keys run contiguously from F1 (58) to F12 (69). */
public static final int F12 = 69;
public static final int RIGHT = 79;
public static final int LEFT = 80;
public static final int DOWN = 81;
public static final int UP = 82;
public static final int LEFT_CTRL = 224;
public static final int LEFT_SHIFT = 225;
public static final int LEFT_ALT = 226;
public static final int LEFT_SUPER = 227;
public static final int RIGHT_CTRL = 228;
public static final int RIGHT_SHIFT = 229;
public static final int RIGHT_ALT = 230;
public static final int RIGHT_SUPER = 231;
/** One past the largest scancode: the size of a table indexed by scancode. */
public static final int COUNT = 512;
private Scancodes() {}
}
@@ -0,0 +1,5 @@
/** Keyboard and mouse input: key codes, modifiers and keyboard state. */
@NullMarked
package incari.platform.api.input;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,84 @@
package incari.platform.api.net;
import java.nio.ByteBuffer;
import java.util.Map;
import org.jspecify.annotations.Nullable;
/**
* One connection to a server, carrying bytes in order both ways. Methods may be called from any
* thread.
*/
public interface NetConnection {
/**
* Sends bytes, from the buffer's position to its limit: over a WebSocket, as one binary
* message. Queues them if the connection is still opening; does nothing once it's closed. The
* caller must not change the buffer afterwards.
*/
void send(ByteBuffer data);
/**
* Sends one text message over a WebSocket, queued like {@link #send}. Only Eagler's server
* queries (the server list's MOTD) use text; the game's packets are always binary.
*
* @throws UnsupportedOperationException on a TCP connection, which has no messages
*/
default void sendText(String text) {
throw new UnsupportedOperationException("Text messages need a WebSocket: " + remoteDescription());
}
/**
* The end of a batch of {@link #send} calls (the game's network channel was flushed): a
* connection that gathers what it sends may send it now (singleplayer's link to its server in a
* worker, ADR 0041). Connections that send each call at once ignore it.
*/
default void flush() {}
/** Closes the connection. The listener hears {@link Listener#closed} once, if it hasn't already. */
void close();
/** Whether the connection is established and not yet closed. */
boolean isOpen();
/** A description of the far end for logs, for example "mc.example.com/203.0.113.7:25565". */
String remoteDescription();
/**
* What the platform alone knows about how the connection went (a WebSocket's close code, how
* long the game left its messages waiting), for the disconnect screen's details: label to
* value, in order, in plain words. Empty when it has nothing to add. Called on the game's
* thread, usually after the connection closed.
*/
default Map<String, String> details() {
return Map.of();
}
/**
* Hears what happens on a connection. Callbacks come on a platform thread (the desktop's
* reader thread, the browser's main thread), one at a time and in order.
*/
interface Listener {
/** The connection is established; {@link NetConnection#send} now writes to the wire. */
void connected();
/**
* Bytes arrived: a piece of the stream over TCP, one whole message over a WebSocket. The
* buffer is the listener's to keep; it's never reused by the platform.
*/
void received(ByteBuffer data);
/**
* One whole text message arrived over a WebSocket. Ignored unless the listener asks for
* text: game connections are binary, and Eagler servers answer queries in text.
*/
default void receivedText(String text) {}
/**
* The connection closed or failed to open. Called exactly once, and last.
*
* @param cause why, or null for an orderly close by either side
*/
void closed(@Nullable Throwable cause);
}
}
@@ -0,0 +1,69 @@
package incari.platform.api.net;
import java.io.IOException;
/**
* Connections to game servers. Two kinds: a TCP byte stream (the desktop only), and a WebSocket
* carrying one packet per binary message (every platform; the only kind a browser has). The game's
* own protocol code (compression, packets) runs on top of either. Small files come by HTTP GET
* ({@link #fetch}).
*/
public interface PlatformNetwork {
/**
* Starts a TCP connection and returns at once. The listener hears {@link
* NetConnection.Listener#connected} or {@link NetConnection.Listener#closed} with the reason it
* failed. Bytes arrive as the stream delivers them, with no message boundaries.
*
* <p>A platform without raw sockets (the browser) fails the connection through the listener.
*
* @param host a host name or IP address literal
* @param port the TCP port
*/
NetConnection connect(String host, int port, NetConnection.Listener listener);
/**
* Starts a WebSocket connection and returns at once. Messages are binary: each {@link
* NetConnection#send} is one whole message, and each {@link NetConnection.Listener#received}
* buffer is one whole message as the server sent it. Text messages go both ways too ({@link
* NetConnection#sendText}, {@link NetConnection.Listener#receivedText}), for Eagler's queries.
*
* @param url a {@code ws://} or {@code wss://} URL, already checked for syntax by the caller
*/
NetConnection openWebSocket(String url, NetConnection.Listener listener);
/**
* The body of an HTTP GET of {@code url}: public files such as player skins and server
* resource packs. Blocks the calling thread until the whole body has arrived, so call it from a
* background thread, never the render thread. The bytes are the caller's. No headers beyond
* the platform's own are sent.
*
* <p>In a browser the server must allow the page's origin (CORS), and an {@code https} page
* can't fetch {@code http} URLs.
*
* @param url an absolute {@code http} or {@code https} URL
* @param maxBytes the largest body accepted; a bigger one fails, before it's all downloaded
* when the server gives its length
* @throws IOException if it can't be fetched, the answer isn't a 2xx, or the body is too big
*/
default byte[] fetch(String url, int maxBytes) throws IOException {
throw new IOException("This platform can't fetch " + url);
}
/**
* Whether other machines can connect to this one: the game's "Open to LAN" listens on a TCP
* port. A page can't listen for connections; its worlds are shared through an Eagler relay
* instead.
*/
default boolean canAcceptConnections() {
return true;
}
/**
* Whether {@link #connect} opens real TCP connections. A page can't: what needs TCP there goes
* through a Wisp proxy instead (Java servers, ADR 0065; Microsoft sign-in, ADR 0070).
*/
default boolean canOpenSockets() {
return true;
}
}
@@ -0,0 +1,5 @@
/** Connections to game servers: TCP byte streams and WebSocket message streams. */
@NullMarked
package incari.platform.api.net;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,5 @@
/** The platform interfaces: everything the game needs from the machine it runs on. */
@NullMarked
package incari.platform.api;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,25 @@
package incari.platform.api.profile;
/**
* One frame, measured by the game. Times are milliseconds of the render thread's CPU time
* spent in each part of the frame, or {@code NaN} where nothing measured it.
*
* @param tickMillis the client's ticks and the packets and tasks queued for them
* @param extractMillis preparing the frame: updating the camera and HUD, extracting render state
* @param renderMillis issuing the frame to the graphics backend ("render submit")
* @param gpuMillis how long the GPU took for a recent frame, where the backend can time it; a
* frame or two behind, since GPU timers answer late
* @param drawCalls draw calls issued to the graphics API this frame
* @param terrainDrawCalls those of them that drew terrain; a multi-draw counts once
* @param terrainSections terrain sections drawn (each layer of each section once)
* @param meshQueue sections waiting to be meshed
*/
public record FrameSample(
double tickMillis,
double extractMillis,
double renderMillis,
double gpuMillis,
int drawCalls,
int terrainDrawCalls,
int terrainSections,
int meshQueue) {}
@@ -0,0 +1,18 @@
package incari.platform.api.profile;
/**
* Memory in use, as the platform can see it. A value the platform can't measure is -1.
*
* @param heapUsed bytes in use on the managed heap (the JVM's heap; in the browser, the page's
* JavaScript heap, which holds the WebAssembly GC objects too)
* @param heapLimit the most the managed heap may grow to
* @param nativeBytes memory outside the managed heap that the game owns: in the browser, the
* WebAssembly linear memory that holds its off-heap buffers (ADR 0008)
* @param collections garbage collections so far; in the browser an estimate (drops in the heap
* between frames), since a page can't observe collections
*/
public record MemoryUsage(long heapUsed, long heapLimit, long nativeBytes, long collections) {
/** Nothing known. */
public static final MemoryUsage UNKNOWN = new MemoryUsage(-1, -1, -1, -1);
}
@@ -0,0 +1,55 @@
package incari.platform.api.profile;
/**
* The platform's side of profiling (ADR 0021). The game measures its frames itself and hands
* each one here; the browser keeps them where the benchmark runner reads them.
*/
public interface PlatformProfiling {
/** Memory in use now. Cheap enough to read once a frame. */
MemoryUsage memory();
/**
* Records a frame the game just finished, before the platform's {@code endFrame}. Only called
* while the game's profiler is collecting.
*/
void frameProfiled(FrameSample sample);
/**
* Records that the game reached a point of its start-up ({@code "title"}: the title screen
* shown; {@code "world"}: the first frame of a world), with the platform's clock.
*/
void mark(String name);
/**
* Records one tick of singleplayer's server where it runs apart from the game's frames (the
* browser's server worker, ADR 0039), for the singleplayer benchmark to read.
*
* @param millis how long the tick took
* @param paused whether the server was paused (only its connection ticked)
* @param loadedChunks the overworld's loaded chunks after the tick
*/
default void serverTickProfiled(double millis, boolean paused, int loadedChunks) {}
/**
* Whether a measuring tool (the benchmark runner) has asked the game for {@code name}, such as
* leaving the world; a request is answered once. Platforms without such a tool never ask.
*/
default boolean takeRequest(String name) {
return false;
}
/** Profiling on a platform that records nothing and can't see its memory. */
PlatformProfiling NONE = new PlatformProfiling() {
@Override
public MemoryUsage memory() {
return MemoryUsage.UNKNOWN;
}
@Override
public void frameProfiled(FrameSample sample) {}
@Override
public void mark(String name) {}
};
}
@@ -0,0 +1,9 @@
/**
* Profiling (ADR 0021): what the platform knows about a frame that the game doesn't (memory,
* garbage collections), and where the game's own per-frame measurements go so tools outside the
* game can read them (the browser page, for the benchmark runner).
*/
@NullMarked
package incari.platform.api.profile;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,29 @@
package incari.platform.api.rtc;
import org.jspecify.annotations.Nullable;
/**
* A STUN or TURN server a peer connection may use to reach the other side.
*
* @param url a {@code stun:} or {@code turn:} URL
* @param username a TURN server's user name, or null
* @param credential a TURN server's password, or null
*/
public record IceServer(
String url, @Nullable String username, @Nullable String credential) {
/**
* Parses Eagler's form: a URL, or {@code url;username;password} for a TURN server. Returns
* null for anything else.
*/
public static @Nullable IceServer parseEagler(String text) {
String[] parts = text.split(";", -1);
if (parts.length == 1 && !parts[0].isBlank()) {
return new IceServer(parts[0].trim(), null, null);
}
if (parts.length == 3) {
return new IceServer(parts[0].trim(), parts[1], parts[2]);
}
return null;
}
}
@@ -0,0 +1,43 @@
package incari.platform.api.rtc;
/**
* The microphone, for voice chat. Opening it asks the user for permission, which takes a while
* and may be refused; {@link #state} says how it went. It stays silent until {@link
* #setTransmitting} (push to talk).
*/
public interface Microphone {
/** Where the microphone stands. */
enum State {
/** Not asked for yet. */
CLOSED,
/** Waiting for the user's permission. */
OPENING,
/** Open, and sent to every peer that asked for it. */
OPEN,
/** The user refused, or there's no microphone. */
UNAVAILABLE
}
State state();
/** Asks for the microphone, if it isn't open or being opened. Returns at once. */
void open();
/**
* Lets the microphone go: the device stops recording (the browser's recording indicator goes
* out), peers it was sent to get silence, and {@link #state} is {@link State#CLOSED} again, so
* {@link #open} asks anew. One still waiting for permission is let go as soon as it opens.
* Returns at once; game thread.
*/
void close();
/** Whether what the microphone hears is sent now. Starts false. */
void setTransmitting(boolean transmitting);
/** The microphone's gain, 1 for as heard. */
void setVolume(float volume);
/** How loud the microphone is now, from 0 to 1, for a talking indicator. */
float level();
}
@@ -0,0 +1,37 @@
package incari.platform.api.rtc;
import java.util.List;
/**
* WebRTC, where the platform has it (ADR 0019): the browser. A platform without it says so
* with {@link #supported}; the rest of the interface then throws.
*/
public interface PlatformRtc {
/** Whether peer connections work here. */
boolean supported();
/** The microphone. */
Microphone microphone();
/** Starts a peer connection that reaches the other side through {@code iceServers}. */
RtcPeer createPeer(List<IceServer> iceServers, RtcPeer.Listener listener);
/** WebRTC for a platform that has none. */
PlatformRtc UNSUPPORTED = new PlatformRtc() {
@Override
public boolean supported() {
return false;
}
@Override
public Microphone microphone() {
throw new UnsupportedOperationException("No WebRTC on this platform");
}
@Override
public RtcPeer createPeer(List<IceServer> iceServers, RtcPeer.Listener listener) {
throw new UnsupportedOperationException("No WebRTC on this platform");
}
};
}
@@ -0,0 +1,17 @@
package incari.platform.api.rtc;
/**
* How a peer's voice plays: its volume and its place left to right. The caller works out both from
* where the peer stands (proximity chat) or keeps them fixed (global chat).
*/
public interface RemoteVoice {
/** The voice's gain, 0 for silent, 1 for as sent. */
void setVolume(float volume);
/** Where the voice sits between the ears, from -1 (left) to 1 (right). */
void setPan(float pan);
/** How loud the peer is now, from 0 to 1: whether they're talking. */
float level();
}
@@ -0,0 +1,70 @@
package incari.platform.api.rtc;
import incari.platform.api.net.NetConnection;
/**
* One WebRTC peer connection. Descriptions (offers and answers) are JSON objects with {@code type}
* and {@code sdp}, as the browser writes them; the signalling that carries them (a game server, a
* relay) is the caller's. Events reach the {@link Listener} on the game's thread, once a frame.
*/
public interface RtcPeer {
/** Sends the microphone's audio to this peer (voice chat). Call before {@link #createOffer}. */
void sendMicrophone();
/**
* Opens a data channel to the peer, carrying binary messages in order. Call before {@link
* #createOffer}. The listener hears {@link NetConnection.Listener#connected} when it opens.
*/
NetConnection openDataChannel(String label, NetConnection.Listener listener);
/** Makes an offer; {@link Listener#localDescription} hears it. */
void createOffer();
/** The peer's description. An offer is answered at once ({@link Listener#localDescription}). */
void setRemoteDescription(String json);
/** One of the peer's ICE candidates. */
void addIceCandidate(String candidate, int sdpMLineIndex);
/** The peer's voice, once {@link Listener#remoteAudio} has come; silent before. */
RemoteVoice voice();
/** Closes the connection; the listener hears nothing more. */
void close();
/** Hears a peer connection's events, on the game's thread. */
interface Listener {
/** This side's offer or answer, for the peer. */
void localDescription(String json);
/** One of this side's ICE candidates, for the peer. */
void iceCandidate(String candidate, int sdpMLineIndex);
/** This side has no more ICE candidates. */
default void iceGatheringComplete() {}
/** The peer's audio arrived; {@link RtcPeer#voice} plays it. */
default void remoteAudio() {}
/** The connection's state changed: "connecting", "connected", "disconnected", "failed", "closed". */
default void stateChanged(String state) {}
/**
* The peer opened a data channel called {@code label} (a shared world's guest, ADR 0062):
* {@link IncomingChannel#accept} takes it. One not accepted here is closed.
*/
default void dataChannel(String label, IncomingChannel channel) {}
}
/** A data channel the peer opened, waiting to be taken. */
interface IncomingChannel {
/**
* Takes the channel: {@code listener} hears it as {@link #openDataChannel}'s listener would,
* its opening (at once, if it's open already) and its messages, none lost before this.
*/
NetConnection accept(NetConnection.Listener listener);
}
}
@@ -0,0 +1,9 @@
/**
* WebRTC: peer connections with voice and data channels, for Eagler's voice chat and for joining
* worlds shared through a relay (ADR 0019). The browser has it; the desktop doesn't, and says
* so ({@link incari.platform.api.rtc.PlatformRtc#supported}).
*/
@NullMarked
package incari.platform.api.rtc;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,47 @@
package incari.platform.api.storage;
import org.jspecify.annotations.Nullable;
/**
* Where the game keeps its files. Paths are strings in the platform's file system: on the desktop
* real directories, in the browser folders of the page's file system, which OPFS or IndexedDB
* keeps across reloads (ADR 0011).
*/
public interface PlatformStorage {
/** The game directory: options, saves, resource packs, screenshots, logs. */
String gameDirectory();
/** The directory holding the game's asset index and objects (sounds, languages). */
String assetsDirectory();
/** The asset index to load from {@link #assetsDirectory}, or null if assets come bundled. */
@Nullable
String assetIndex();
/**
* The files under {@code directory}, encoded for another copy of the game's program
* (ADR 0039), and dropped from this one without telling the store: they're the other copy's
* until it hands them back ({@link #takeOver}). Files the store keeps in place (a world's region
* files in the browser, ADR 0041) go as their sizes, once the store has every write to them; the
* other copy opens them where they are. May wait for the store. Null where the platform's files
* are its operating system's, shared by every thread (the desktop).
*/
default byte @Nullable [] handOver(String directory) {
return null;
}
/** Takes back files {@link #handOver} encoded (here or in the other copy), as the store had them. */
default void takeOver(byte[] files) {}
/**
* In a copy of the program: what changed in its files since it was last asked, encoded; null
* if nothing did, or if the copy sends its changes to the store itself (ADR 0041).
*/
default byte @Nullable [] takeChanges() {
return null;
}
/** Passes changes another copy of the program made ({@link #takeChanges}) to this one's store. */
default void storeChanges(byte[] changes) {}
}
@@ -0,0 +1,5 @@
/** Where the game keeps its files. */
@NullMarked
package incari.platform.api.storage;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,68 @@
package incari.platform.api.threads;
import org.jspecify.annotations.Nullable;
/**
* Messages between the game's program and a second copy of it running apart, in a worker
* ({@link PlatformThreads#startGameWorker}): the page and singleplayer's server (ADR 0039). Each
* message is a kind (a number the two sides agree on) and bytes. Messages arrive in the order they
* were sent.
*
* <p>Both ends belong to one thread each at a time: {@link #receive} waits, so it runs on a thread
* that may (never the render thread).
*/
public interface PlatformChannel {
/** A message: its kind and its bytes, which the receiver owns. */
final class Message {
private final int kind;
private final byte[] bytes;
public Message(int kind, byte[] bytes) {
this.kind = kind;
this.bytes = bytes;
}
public int kind() {
return kind;
}
/** The message's bytes, the receiver's to keep or change. */
public byte[] bytes() {
return bytes;
}
}
/**
* Sends a message without waiting. The bytes are copied (or handed over) before this returns,
* so the caller may reuse the array.
*/
void send(int kind, byte[] bytes, int offset, int length);
/** Sends a message with no bytes. */
default void send(int kind) {
send(kind, new byte[0], 0, 0);
}
/**
* Waits for the next message, or returns null once the channel is closed (by either end, or
* because the other program stopped).
*/
@Nullable
Message receive();
/** The next message if one has arrived, without waiting; null if none has. */
@Nullable
Message poll();
/**
* Asks the platform to send an empty message of {@code kind} on its own whenever the page is
* about to be hidden, reloaded or closed: when the game's thread may never run again, so it
* can't send it itself (singleplayer's server saves on it). From the side that started the
* worker; the desktop, which has no page, ignores it. Once per channel; ends with it.
*/
default void sendWhenLeaving(int kind) {}
/** Closes the channel; the other end's {@link #receive} returns null. Ends the worker it started. */
void close();
}
@@ -0,0 +1,84 @@
package incari.platform.api.threads;
import java.util.concurrent.ExecutorService;
import org.jspecify.annotations.Nullable;
/**
* How the game's background work runs. On a normal JVM the game keeps its own thread pools. In
* the browser, TeaVM runs every Java thread as a coroutine on the page's one thread, so extra
* pool threads only add switching cost; real parallelism comes from Web Workers.
*/
public interface PlatformThreads {
/**
* How many threads the game's main background pool gets, when the platform doesn't run the
* pool itself ({@link #backgroundExecutor}).
*
* @param suggested what the game would choose on a normal JVM (usually cores - 1)
* @return the thread count; 0 runs background tasks directly on the thread that submits them
*/
int backgroundThreads(int suggested);
/**
* The platform's own executor for the game's background pool, or null to let the game build
* the pool from {@link #backgroundThreads} threads. The browser runs the pool's tasks in the
* time left over after each frame, so a burst of work (terrain meshes as the camera turns)
* spreads across frames instead of stalling one.
*
* @param name the pool's name, for its threads' names ("Main" for the game's worker pool)
*/
default @Nullable ExecutorService backgroundExecutor(String name) {
return null;
}
/**
* Starts workers running {@code program} beside the game: {@code "mesher"}, Incari's
* terrain mesher. Returns null where the platform has none; the game then does the work on its
* own threads (the desktop, whose background pool is already parallel).
*/
default @Nullable WorkerPool workers(String program) {
return null;
}
/**
* Called now and then by a long background task (a section's snapshot). Where the pool runs
* between frames and the task's time is up, waits for the pool's next turn, so the task spreads
* over frames instead of holding up the next one; otherwise returns at once. The task must not
* hold anything the frame needs meanwhile.
*/
default void pauseIfLate() {}
/**
* Whether all the game's threads share one real thread, switching only where they wait (the
* browser's coroutines). The game's checks for two threads writing one chunk can then never
* fire, and are skipped (ADR 0030).
*/
default boolean oneThread() {
return false;
}
/**
* How many tasks wait in the platform's background pools ({@link #backgroundExecutor}) for
* their turn: work that can wait for a quiet moment (ADR 0041) asks first. 0 where the platform
* can't say, or has no pools of its own.
*/
default int backgroundQueued() {
return 0;
}
/**
* Starts another copy of the game (a Web Worker in the browser) in the given role and returns
* the channel to it; null where the platform can't (the desktop runs singleplayer's server on
* its own thread). ADR 0039.
*
* @param role what the copy is for ({@code "server"}); its entry point picks what to run by it
*/
default @Nullable PlatformChannel startGameWorker(String role) {
return null;
}
/** In a copy started by {@link #startGameWorker}, the channel to the program that started it; null elsewhere. */
default @Nullable PlatformChannel parentChannel() {
return null;
}
}
@@ -0,0 +1,11 @@
package incari.platform.api.threads;
/** A worker failed a job, or stopped. */
public final class WorkerException extends RuntimeException {
private static final long serialVersionUID = 1L;
public WorkerException(String message) {
super(message);
}
}
@@ -0,0 +1,23 @@
package incari.platform.api.threads;
import java.nio.ByteBuffer;
/** A job sent to a {@link WorkerPool}, and its answer. */
public interface WorkerJob {
/**
* Waits for the answer and returns its bytes, from position 0 to the limit, little-endian; valid
* until {@link #release}. On a thread of the platform's background executor (its
* {@link PlatformThreads#backgroundExecutor}), the pool goes on with its other tasks while this
* one waits, and this one goes on in a later slot.
*
* @throws WorkerException if the worker failed or is gone
*/
ByteBuffer await();
/** Whether the answer is in: {@link #await} won't wait. */
boolean done();
/** Gives the answer's memory back. The job can't be used after this. */
void release();
}
@@ -0,0 +1,32 @@
package incari.platform.api.threads;
import java.nio.ByteBuffer;
/**
* Workers running a program of their own beside the game, each with its own memory: the page's Web
* Workers running the mesher's WebAssembly module (ADR 0023). They share nothing with the
* game; everything they get and give back is bytes.
*
* <p>Call from the game's threads; in the browser, from the page's only thread.
*/
public interface WorkerPool {
/** How many workers there are. */
int size();
/**
* Sends {@code message} (its bytes from position to limit) to every worker, ahead of any job
* submitted after it: the tables every later job reads, say. The bytes are copied before this
* returns.
*/
void broadcast(ByteBuffer message);
/**
* Sends a job to a worker (the one with the fewest in hand). The bytes, from position to limit,
* are copied before this returns.
*/
WorkerJob submit(ByteBuffer message);
/** How many jobs have been submitted and not yet answered. */
int inFlight();
}
@@ -0,0 +1,5 @@
/** How the game's background work runs. */
@NullMarked
package incari.platform.api.threads;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,30 @@
package incari.platform.api.window;
import java.util.List;
/**
* One monitor.
*
* @param id the platform's id for it; stable while it stays connected, never 0
* @param name a human-readable name, for example "DELL U2720Q"
* @param x the left edge on the virtual desktop, in screen coordinates
* @param y the top edge on the virtual desktop
* @param width the width in screen coordinates
* @param height the height in screen coordinates
* @param desktopMode the mode the desktop runs at
* @param fullscreenModes every mode exclusive fullscreen can switch to, best first; may be empty
*/
public record DisplayInfo(
int id,
String name,
int x,
int y,
int width,
int height,
DisplayMode desktopMode,
List<DisplayMode> fullscreenModes) {
public DisplayInfo {
fullscreenModes = List.copyOf(fullscreenModes);
}
}
@@ -0,0 +1,13 @@
package incari.platform.api.window;
/**
* A resolution and refresh rate a display can run at.
*
* @param width the width in pixels
* @param height the height in pixels
* @param redBits bits per pixel of red; 8 on anything the game supports
* @param greenBits bits per pixel of green
* @param blueBits bits per pixel of blue
* @param refreshRate the refresh rate in hertz, for example 59.94; 0 if unknown
*/
public record DisplayMode(int width, int height, int redBits, int greenBits, int blueBits, float refreshRate) {}
@@ -0,0 +1,36 @@
package incari.platform.api.window;
/** One size of the window icon: RGBA pixels, row by row from the top. */
public final class IconImage {
private final int width;
private final int height;
private final byte[] rgba;
/**
* @param rgba four bytes per pixel in R, G, B, A order; the icon takes ownership, so the
* caller must not change the array afterwards
*/
public IconImage(int width, int height, byte[] rgba) {
if (width <= 0 || height <= 0 || rgba.length != width * height * 4) {
throw new IllegalArgumentException(
"A " + width + "x" + height + " icon needs " + width * height * 4 + " bytes, got " + rgba.length);
}
this.width = width;
this.height = height;
this.rgba = rgba;
}
public int width() {
return width;
}
public int height() {
return height;
}
/** The pixels. Shared, not copied: read them, never change them. */
public byte[] rgba() {
return rgba;
}
}
@@ -0,0 +1,23 @@
package incari.platform.api.window;
import java.util.List;
import org.jspecify.annotations.Nullable;
/**
* The connected monitors. Changes are reported as events ({@link PlatformEventListener#displayAdded}
* and friends); these methods always answer with the current state.
*
* <p>The browser reports one display, the screen the page is on.
*/
public interface PlatformDisplays {
/** Every connected display, primary first. */
List<DisplayInfo> all();
/** The display with this id, or null if it's disconnected or can't be queried. */
@Nullable
DisplayInfo get(int id);
/** The id of the primary display, or 0 if there is none. */
int primaryId();
}
@@ -0,0 +1,113 @@
package incari.platform.api.window;
import incari.platform.api.PlatformNotice;
import incari.platform.api.input.KeyAction;
import incari.platform.api.input.KeyModifiers;
import incari.platform.api.input.Scancodes;
import java.util.List;
/**
* Receives window and input events from {@code Platform.pollEvents}. Every method has a no-op
* default, so a listener implements only what it handles. Events arrive on the thread that polls,
* in the order they happened.
*
* <p>Units: window positions and sizes are in screen coordinates, framebuffer sizes in pixels
* (they differ on high-density displays); mouse positions are in window coordinates with the
* origin at the top left. Key and modifier values are described in {@link Scancodes} and
* {@link KeyModifiers}.
*/
public interface PlatformEventListener {
/** The player asked to close the window: the close button, or the system's quit shortcut. */
default void closeRequested() {}
/** The system is ending the application; it must shut down now. */
default void terminating() {}
default void windowMoved(int x, int y) {}
default void windowResized(int width, int height) {}
/**
* The drawable size changed, for example after a resize or a move to a denser display. The size
* is the whole surface, as {@link PlatformWindow#framebufferWidth} reports it.
*/
default void framebufferResized(int width, int height) {}
default void minimizedChanged(boolean minimized) {}
default void focusChanged(boolean focused) {}
/** The mouse entered or left the window. */
default void cursorEnteredOrLeft() {}
/** The window moved to another display, or its display's scale changed. */
default void displayChanged() {}
/** The window entered or left fullscreen, whoever asked for it. */
default void fullscreenChanged(boolean fullscreen) {}
default void displayAdded(int displayId) {}
default void displayRemoved(int displayId) {}
default void displayModeChanged(int displayId) {}
/**
* A key was pressed, released or auto-repeated.
*
* @param scancode the physical key, as a USB HID usage id ({@link Scancodes})
* @param keyCode the key's meaning in the current layout: its Unicode code point when it types
* a character, otherwise {@code scancode | 0x40000000} (SDL's keycode convention)
* @param modifiers the modifiers held, as {@link KeyModifiers} bits
*/
default void key(int scancode, int keyCode, int modifiers, KeyAction action) {}
/** The keyboard layout changed, so key names may have too. */
default void keymapChanged() {}
/** Text was typed, after any input method composed it. */
default void textInput(String text) {}
/**
* An input method is composing text that isn't committed yet.
*
* @param start the cursor position within {@code text}, in characters
* @param length the length of the selection within {@code text}, in characters
*/
default void textEditing(String text, int start, int length) {}
/**
* The mouse moved.
*
* @param x the new position in window coordinates
* @param dx the relative motion; in relative mouse mode this is the only meaningful part
*/
default void mouseMoved(double x, double y, double dx, double dy) {}
/**
* A mouse button changed state.
*
* @param button 1 left, 2 middle, 3 right, 4 and up for extra buttons
* @param modifiers the keyboard modifiers held, as {@link KeyModifiers} bits
*/
default void mouseButton(int button, boolean pressed, int modifiers) {}
/**
* The wheel or a trackpad scrolled.
*
* @param dx horizontal scroll, positive to the right
* @param dy vertical scroll, positive away from the user
* @param modifiers the keyboard modifiers held, as {@link KeyModifiers} bits
*/
default void mouseWheel(double dx, double dy, int modifiers) {}
/** Files were dropped onto the window, as platform paths or URLs. */
default void filesDropped(List<String> paths) {}
/**
* Something the player must be told: that their game isn't being saved, for one. Each notice
* comes once when it starts to apply, not every frame.
*/
default void notice(PlatformNotice notice) {}
}
@@ -0,0 +1,131 @@
package incari.platform.api.window;
import java.util.List;
import org.jspecify.annotations.Nullable;
/**
* The game's window: a desktop window, or the page's canvas in the browser.
*
* <p>State queries answer from the platform's current state; changes are also reported as
* {@link PlatformEventListener} events. Call everything from the render thread.
*/
public interface PlatformWindow extends AutoCloseable {
/**
* The handle the graphics backend and the game use to identify this window: on the desktop,
* the SDL window pointer; in the browser, a constant non-zero id. Never 0.
*/
long nativeHandle();
/** The left edge on the virtual desktop, in screen coordinates. */
int x();
int y();
/** The width in screen coordinates. */
int width();
int height();
/** The drawable surface's width in pixels, at least 1: what the graphics surface is sized to. */
int framebufferWidth();
int framebufferHeight();
/**
* Pixels at the right edge of the framebuffer the game shouldn't lay its UI out in, usually 0.
* The desktop's borderless fullscreen makes the window one pixel wider than the display, so
* drivers don't mistake it for exclusive fullscreen; that extra column is off screen.
*/
int unusedWidth();
/** Pixels per screen coordinate: 1 on normal displays, 2 on most high-density ones. */
float pixelDensity();
/** The id of the display the window is mostly on, or 0 if unknown. */
int displayId();
void setTitle(String title);
/** Sets the window icon from one or more sizes, largest first. Ignored where there is none. */
void setIcon(List<IconImage> sizes);
/** Limits how large the player can make the window; 0 for no limit. */
void setMaximumSize(int width, int height);
/**
* Leaves fullscreen, if in it, and places the window.
*
* @return false if the platform refused; the window is then unchanged
*/
boolean setWindowed(int x, int y, int width, int height);
/**
* Enters fullscreen on the window's display.
*
* @param exclusiveMode the mode to switch the display to, or null for borderless fullscreen
* at the desktop's own mode. When the display has no mode close to it, the platform falls
* back to borderless and logs why.
* @return false if the platform refused; the window is then unchanged
*/
boolean setFullscreen(@Nullable DisplayMode exclusiveMode);
boolean isFullscreen();
/** Whether the window is fullscreen with the display switched to a mode of its own. */
boolean isExclusiveFullscreen();
/**
* Turns a system behavior the player controls on or off. Platforms without it ignore the call.
*/
void setSystemBehavior(SystemBehavior behavior, boolean enabled);
/** The mode of the display the window is on, or null if it can't be determined. */
@Nullable
DisplayMode currentDisplayMode();
/**
* Relative mouse mode: the cursor is hidden and locked, and motion is reported as deltas
* (the browser's Pointer Lock). Used while the player looks around.
*/
void setRelativeMouseMode(boolean enabled);
/**
* Whether closing the window now would lose the player's game (they're in a world): a browser
* then asks before the page is closed or reloaded, as it already does while the mouse is held.
* Cheap to call every frame with the same value. The desktop ignores it.
*/
default void setLeaveWarning(boolean warn) {}
/** Moves the cursor to a position in window coordinates. Ignored where not allowed. */
void warpMouse(double x, double y);
/** The cursor position in window coordinates, even when it's outside the window. */
CursorPosition cursorPosition();
void setCursor(SystemCursor cursor);
/** Starts delivering {@link PlatformEventListener#textInput} and composition events. */
void startTextInput();
void stopTextInput();
/**
* Where the text being typed is, in window coordinates, so an input method can place its
* candidate list next to it.
*/
void setTextInputArea(int x, int y, int width, int height);
/**
* Whether the system's close shortcut (Alt+F4 on Windows) closes the window. The game turns
* it off while a key binding might use it.
*/
void setQuitShortcutEnabled(boolean enabled);
/** Destroys the window. */
@Override
void close();
/** A cursor position in window coordinates. */
record CursorPosition(double x, double y) {}
}
@@ -0,0 +1,9 @@
package incari.platform.api.window;
/** Desktop behaviors the game lets the player toggle in its options. */
public enum SystemBehavior {
/** macOS: a Control-click acts as a right click, as on a one-button mouse. */
CTRL_CLICK_IS_RIGHT_CLICK,
/** macOS: the menu bar slides down in fullscreen when the pointer reaches the top. */
MENU_BAR_IN_FULLSCREEN
}
@@ -0,0 +1,14 @@
package incari.platform.api.window;
/** The mouse cursor shapes the game uses, drawn by the platform. */
public enum SystemCursor {
DEFAULT,
ARROW,
TEXT,
CROSSHAIR,
POINTING_HAND,
RESIZE_NS,
RESIZE_EW,
RESIZE_ALL,
NOT_ALLOWED
}
@@ -0,0 +1,24 @@
package incari.platform.api.window;
/**
* How to create the window.
*
* @param title the initial title
* @param width the initial width in screen coordinates, at least {@link #MIN_WIDTH}
* @param height the initial height in screen coordinates, at least {@link #MIN_HEIGHT}
* @param maximumSize the largest the window may be in either dimension, or 0 for no limit
*/
public record WindowSpec(String title, int width, int height, int maximumSize) {
/** The smallest window the game's UI fits in. */
public static final int MIN_WIDTH = 320;
public static final int MIN_HEIGHT = 240;
public WindowSpec {
if (width < MIN_WIDTH || height < MIN_HEIGHT) {
throw new IllegalArgumentException(
"Window " + width + "x" + height + " is smaller than the minimum " + MIN_WIDTH + "x" + MIN_HEIGHT);
}
}
}
@@ -0,0 +1,5 @@
/** The window, the displays, and the events they report. */
@NullMarked
package incari.platform.api.window;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,23 @@
package incari.platform.api;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
import com.tngtech.archunit.core.importer.ImportOption;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;
/**
* platform-api is compiled into every build, the browser one included: it may use only the JDK
* (the subset TeaVM supports) and JSpecify. No game, library or platform types.
*/
@AnalyzeClasses(packages = "incari.platform.api", importOptions = ImportOption.DoNotIncludeTests.class)
class BoundaryTest {
@ArchTest
static final ArchRule onlyJdkAndJspecify = classes()
.should()
.onlyDependOnClassesThat()
.resideInAnyPackage("java..", "org.jspecify..", "incari.platform.api..")
.allowEmptyShould(true);
}
@@ -0,0 +1,61 @@
package incari.platform.api;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import incari.platform.api.audio.AudioException;
import incari.platform.api.audio.PcmFormat;
import incari.platform.api.window.DisplayInfo;
import incari.platform.api.window.DisplayMode;
import incari.platform.api.window.IconImage;
import incari.platform.api.window.WindowSpec;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
class ValueTypesTest {
@AfterEach
void uninstall() {
Platforms.uninstallForTests();
}
@Test
void windowsCantBeSmallerThanTheGuiNeeds() {
assertThat(new WindowSpec("t", 320, 240, 0).width()).isEqualTo(320);
assertThatThrownBy(() -> new WindowSpec("t", 319, 240, 0)).isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> new WindowSpec("t", 320, 239, 0)).isInstanceOf(IllegalArgumentException.class);
}
@Test
void pcmFormatsAreLimitedToWhatEveryBackendPlays() {
assertThat(new PcmFormat(44_100, 2, 16).frameSize()).isEqualTo(4);
assertThat(new PcmFormat(22_050, 1, 8).frameSize()).isEqualTo(1);
assertThatThrownBy(() -> new PcmFormat(44_100, 6, 16)).isInstanceOf(AudioException.class);
assertThatThrownBy(() -> new PcmFormat(44_100, 2, 24)).isInstanceOf(AudioException.class);
assertThatThrownBy(() -> new PcmFormat(0, 2, 16)).isInstanceOf(AudioException.class);
}
@Test
void iconsNeedExactlyFourBytesPerPixel() {
assertThat(new IconImage(2, 2, new byte[16]).width()).isEqualTo(2);
assertThatThrownBy(() -> new IconImage(2, 2, new byte[15])).isInstanceOf(IllegalArgumentException.class);
}
@Test
void displayModeListsAreCopied() {
List<DisplayMode> modes = new ArrayList<>(List.of(new DisplayMode(1920, 1080, 8, 8, 8, 60.0F)));
DisplayInfo display = new DisplayInfo(1, "d", 0, 0, 1920, 1080, modes.getFirst(), modes);
modes.clear();
assertThat(display.fullscreenModes()).hasSize(1);
}
@Test
void onePlatformPerProcess() {
assertThatThrownBy(Platforms::current)
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("app-desktop or app-web");
assertThat(Platforms.isInstalled()).isFalse();
}
}