Start maybe working on a native app
This commit is contained in:
+12
-12
@@ -2,6 +2,8 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import { load_texture, Texture } from "./renderer/mod.ts";
|
||||
import { decode_png } from "./png.ts";
|
||||
import { platform } from "./platform.ts";
|
||||
|
||||
type Asset = Texture | string | Record<string, unknown>;
|
||||
|
||||
@@ -18,26 +20,24 @@ export class AssetManager {
|
||||
return;
|
||||
}
|
||||
|
||||
// the client's own files are next to the page, see platform.page
|
||||
const url = new URL(src, platform.page);
|
||||
if (src.endsWith(".png")) {
|
||||
const img = new Image();
|
||||
const promise = new Promise<void>((resolve, reject) => {
|
||||
img.onload = () => {
|
||||
this.assets[key] = load_texture(img);
|
||||
resolve();
|
||||
};
|
||||
img.onerror = () => reject(new Error(`Failed to load image: ${src}`));
|
||||
});
|
||||
img.src = src;
|
||||
this.loading_promises.push(promise);
|
||||
const promise = async () => {
|
||||
const resp = await fetch(url);
|
||||
if (!resp.ok) throw new Error(`Failed to load image: ${src}`);
|
||||
this.assets[key] = load_texture(decode_png(new Uint8Array(await resp.arrayBuffer())));
|
||||
};
|
||||
this.loading_promises.push(promise());
|
||||
} else if (src.endsWith(".txt") || src.endsWith(".md") || src.endsWith(".fnt")) {
|
||||
const promise = async () => {
|
||||
const resp = await fetch(src);
|
||||
const resp = await fetch(url);
|
||||
this.assets[key] = await resp.text();
|
||||
};
|
||||
this.loading_promises.push(promise());
|
||||
} else if (src.endsWith(".json")) {
|
||||
const promise = async () => {
|
||||
const resp = await fetch(src);
|
||||
const resp = await fetch(url);
|
||||
this.assets[key] = await resp.json();
|
||||
};
|
||||
this.loading_promises.push(promise());
|
||||
|
||||
+46
-41
@@ -7,6 +7,8 @@ import { TEXTURE_SIZE } from "@/common/constants.ts";
|
||||
import type { SpriteRegion } from "@/common/constants.ts";
|
||||
import { type Animation, texture_animation, type TextureJson } from "@/common/texture_animation.ts";
|
||||
import { AnimatedTexture } from "./texture_animations.ts";
|
||||
import { decode_png, type Pixels } from "./png.ts";
|
||||
import { platform } from "./platform.ts";
|
||||
|
||||
export interface AtlasLayout {
|
||||
// in pixels, a power of two
|
||||
@@ -67,17 +69,16 @@ function pack_shelves(entries: [string, TextureSize][], size: number) {
|
||||
// textures are png bytes by id, texture_json the .json of the ones that have one. ones that don't decode show as
|
||||
// missing. an animated texture takes one frame's room, its first frame, and plays from animated (see
|
||||
// texture_animations.ts)
|
||||
export async function build_atlas(textures: Map<string, Uint8Array>, texture_json = new Map<string, TextureJson>()) {
|
||||
const images = new Map<string, ImageBitmap>();
|
||||
await Promise.all([...textures].map(async ([id, png]) => {
|
||||
export function build_atlas(textures: Map<string, Uint8Array>, texture_json = new Map<string, TextureJson>()) {
|
||||
const images = new Map<string, Pixels>();
|
||||
for (const [id, png] of textures) {
|
||||
if (id === "cubi:missing") continue;
|
||||
try {
|
||||
images.set(id, await createImageBitmap(new Blob([png as Uint8Array<ArrayBuffer>], { type: "image/png" })));
|
||||
images.set(id, decode_png(png));
|
||||
} catch {
|
||||
console.warn(`Texture ${id} isn't a png that can be shown, it will show as missing`);
|
||||
}
|
||||
}));
|
||||
images.get("cubi:missing")?.close();
|
||||
images.delete("cubi:missing");
|
||||
}
|
||||
|
||||
const animations = new Map<string, Animation>();
|
||||
for (const [id, image] of images) {
|
||||
@@ -91,43 +92,36 @@ export async function build_atlas(textures: Map<string, Uint8Array>, texture_jso
|
||||
}));
|
||||
|
||||
const { size, regions } = atlas_layout(sizes);
|
||||
const canvas = new OffscreenCanvas(size, size);
|
||||
const ctx = canvas.getContext("2d")!;
|
||||
const pixels = new Uint8ClampedArray(size * size * 4);
|
||||
const atlas = { width: size, height: size, data: pixels };
|
||||
|
||||
// magenta and black checker
|
||||
const missing = regions["cubi:missing"];
|
||||
const half = TEXTURE_SIZE / 2;
|
||||
ctx.fillStyle = "magenta";
|
||||
ctx.fillRect(missing.x, missing.y, half, half);
|
||||
ctx.fillRect(missing.x + half, missing.y + half, half, half);
|
||||
ctx.fillStyle = "black";
|
||||
ctx.fillRect(missing.x + half, missing.y, half, half);
|
||||
ctx.fillRect(missing.x, missing.y + half, half, half);
|
||||
for (let py = 0; py < TEXTURE_SIZE; py++) {
|
||||
for (let px = 0; px < TEXTURE_SIZE; px++) {
|
||||
const i = ((missing.y + py) * size + missing.x + px) * 4;
|
||||
const magenta = (px < half) === (py < half);
|
||||
pixels.set(magenta ? [255, 0, 255, 255] : [0, 0, 0, 255], i);
|
||||
}
|
||||
}
|
||||
|
||||
const animated: AnimatedTexture[] = [];
|
||||
for (const [id, image] of images) {
|
||||
const animation = animations.get(id);
|
||||
const { x, y, width, height } = regions[id];
|
||||
if (animation) {
|
||||
const first = animation.frames[0];
|
||||
ctx.drawImage(image, first.x, first.y, width, height, x, y, width, height);
|
||||
animated.push(new AnimatedTexture(regions[id], animation, image_pixels(image), image.width));
|
||||
} else {
|
||||
ctx.drawImage(image, x, y);
|
||||
}
|
||||
image.close();
|
||||
const first = animation?.frames[0] ?? { x: 0, y: 0 };
|
||||
copy_pixels(image, first.x, first.y, width, height, atlas, x, y);
|
||||
if (animation) animated.push(new AnimatedTexture(regions[id], animation, image.data, image.width));
|
||||
}
|
||||
for (const id of textures.keys()) {
|
||||
regions[id] ??= missing;
|
||||
}
|
||||
|
||||
const image_data = ctx.getImageData(0, 0, size, size);
|
||||
const pixels = image_data.data;
|
||||
extrude_borders(pixels, size, regions);
|
||||
ctx.putImageData(image_data, 0, 0);
|
||||
|
||||
// which pixels of each texture can be seen, for the 3d models of dropped items (see item_model.ts)
|
||||
built_atlas = image_data;
|
||||
built_atlas = atlas;
|
||||
opaque.clear();
|
||||
for (const [id, region] of Object.entries(regions)) {
|
||||
const mask = new Uint8Array(region.width * region.height);
|
||||
@@ -140,7 +134,24 @@ export async function build_atlas(textures: Map<string, Uint8Array>, texture_jso
|
||||
opaque.set(id, { width: region.width, height: region.height, mask });
|
||||
}
|
||||
|
||||
return { image: canvas.transferToImageBitmap(), regions, animated };
|
||||
return { image: atlas, regions, animated };
|
||||
}
|
||||
|
||||
// a width × height part of from, starting at from_x from_y, into to at to_x to_y
|
||||
function copy_pixels(
|
||||
from: Pixels,
|
||||
from_x: number,
|
||||
from_y: number,
|
||||
width: number,
|
||||
height: number,
|
||||
to: Pixels,
|
||||
to_x: number,
|
||||
to_y: number,
|
||||
) {
|
||||
for (let row = 0; row < height; row++) {
|
||||
const start = ((from_y + row) * from.width + from_x) * 4;
|
||||
to.data.set(from.data.subarray(start, start + width * 4), ((to_y + row) * to.width + to_x) * 4);
|
||||
}
|
||||
}
|
||||
|
||||
// fills each region's border with copies of its edge pixels, the corners with its corners. pixels is a size × size
|
||||
@@ -169,13 +180,6 @@ export function extrude_borders(pixels: Uint8ClampedArray, size: number, regions
|
||||
}
|
||||
}
|
||||
|
||||
// every frame of an animated texture stays in memory, to copy into the atlas when it's that frame's turn
|
||||
function image_pixels(image: ImageBitmap) {
|
||||
const ctx = new OffscreenCanvas(image.width, image.height).getContext("2d")!;
|
||||
ctx.drawImage(image, 0, 0);
|
||||
return ctx.getImageData(0, 0, image.width, image.height).data;
|
||||
}
|
||||
|
||||
// a texture's pixels, 1 (can be seen) or 0, row by row from the top
|
||||
export interface OpaqueMask {
|
||||
width: number;
|
||||
@@ -192,22 +196,23 @@ export function opaque_pixels(texture_id: string): OpaqueMask | undefined {
|
||||
}
|
||||
|
||||
// the last atlas built, before any animated texture moved on from its first frame
|
||||
let built_atlas: ImageData | undefined;
|
||||
let built_atlas: Pixels | undefined;
|
||||
|
||||
// the atlas as a png, undefined before one is built. for the f3 screen's copy button
|
||||
// the atlas as a png, undefined before one is built or where there's no canvas to encode it (the desktop app). for
|
||||
// the f3 screen's copy button
|
||||
export function atlas_png(): Promise<Blob> | undefined {
|
||||
if (!built_atlas) return undefined;
|
||||
if (!built_atlas || typeof document === "undefined") return undefined;
|
||||
const canvas = new OffscreenCanvas(built_atlas.width, built_atlas.height);
|
||||
canvas.getContext("2d")!.putImageData(built_atlas, 0, 0);
|
||||
canvas.getContext("2d")!.putImageData(new ImageData(built_atlas.data, built_atlas.width), 0, 0);
|
||||
return canvas.convertToBlob({ type: "image/png" });
|
||||
}
|
||||
|
||||
// the engine's own textures, which come with the client instead of a mod. see build_engine_textures in build.ts
|
||||
export async function engine_textures(): Promise<Map<string, Uint8Array>> {
|
||||
const names: string[] = await (await fetch("/assets/textures/index.json")).json();
|
||||
const names: string[] = await (await fetch(new URL("/assets/textures/index.json", platform.page))).json();
|
||||
const textures = new Map<string, Uint8Array>();
|
||||
await Promise.all(names.map(async (name) => {
|
||||
const response = await fetch(`/assets/textures/${name}.png`);
|
||||
const response = await fetch(new URL(`/assets/textures/${name}.png`, platform.page));
|
||||
textures.set(`cubi:${name}`, new Uint8Array(await response.arrayBuffer()));
|
||||
}));
|
||||
return textures;
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// the page's keys and mouse for InputManager, and grabbing the mouse with the browser's pointer lock
|
||||
import { InputManager } from "./input_manager.ts";
|
||||
|
||||
// the keys the game keeps in fullscreen, see "fullscreenchange". not every key: with all of them locked, chromium
|
||||
// can keep alt+tab and the windows key from the os too
|
||||
const FULLSCREEN_LOCKED_KEYS = ["Escape", "KeyW"];
|
||||
|
||||
// chromium's keyboard lock api, typescript's dom types don't have it yet
|
||||
interface KeyboardLock {
|
||||
lock(codes?: string[]): Promise<void>;
|
||||
unlock(): void;
|
||||
}
|
||||
|
||||
let canvas: HTMLCanvasElement;
|
||||
|
||||
let pointer_lock_flag = false;
|
||||
let mouse_ungrab_timer = 0;
|
||||
let mouse_ungrab_timeout = -1;
|
||||
let pointer_lock_waiting = false;
|
||||
// chrome sometimes sends a huge movement with the first mouse event after the lock starts
|
||||
let skip_look_event = false;
|
||||
// the browser let go of the mouse while the game wanted it, like escape or switching windows
|
||||
let lost_pointer_lock = false;
|
||||
// the canvas had the pointer lock at the last pointerlockchange
|
||||
let was_locked = false;
|
||||
// the desktop app moving the cursor after the mouse was let go, see center_desktop_mouse. grabbing it again waits
|
||||
// for that, or the move would come while it's locked and turn the camera
|
||||
let centering = Promise.resolve();
|
||||
let awaiting_centering = false;
|
||||
// the locked mouse doesn't turn the camera until then, the move can still reach chromium after the app answered,
|
||||
// or the mouse was locked again before chromium said it let go
|
||||
let ignore_look_until = 0;
|
||||
// what the game last asked for, it can change while grabbing waits
|
||||
let want_grab = false;
|
||||
|
||||
export function listen_to_page(page_canvas: HTMLCanvasElement) {
|
||||
canvas = page_canvas;
|
||||
|
||||
self.addEventListener("keydown", (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
InputManager.key_down(e.code, e.key, is_shortcut(e));
|
||||
});
|
||||
|
||||
self.addEventListener("blur", () => InputManager.release_all());
|
||||
|
||||
self.addEventListener("keyup", (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
InputManager.key_up(e.code);
|
||||
});
|
||||
|
||||
self.addEventListener("mousedown", (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (!document.hasFocus() && document.pointerLockElement !== canvas) {
|
||||
set_mouse_grabbed(true);
|
||||
return;
|
||||
}
|
||||
InputManager.mouse_down(e.button);
|
||||
});
|
||||
|
||||
self.addEventListener("mouseup", (e) => {
|
||||
e.preventDefault();
|
||||
InputManager.mouse_up(e.button);
|
||||
});
|
||||
|
||||
// ctrl+scroll (and pinching a trackpad, which browsers send as that) would zoom the page. only a listener that
|
||||
// isn't passive can stop it, and on the window they're passive unless told otherwise
|
||||
self.addEventListener("wheel", (e) => {
|
||||
if (e.ctrlKey) {
|
||||
e.preventDefault();
|
||||
}
|
||||
InputManager.scroll(e.deltaY);
|
||||
}, { passive: false });
|
||||
|
||||
document.addEventListener("mousemove", (e) => {
|
||||
e.preventDefault();
|
||||
if (document.pointerLockElement === canvas) {
|
||||
if (skip_look_event) {
|
||||
skip_look_event = false;
|
||||
return;
|
||||
}
|
||||
if (performance.now() < ignore_look_until) return;
|
||||
InputManager.look(e.movementX, e.movementY);
|
||||
} else {
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
InputManager.move_cursor(e.clientX - rect.left, e.clientY - rect.top);
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener("pointerlockchange", () => {
|
||||
const locked = document.pointerLockElement === canvas;
|
||||
if (was_locked && !locked) {
|
||||
ignore_look_until = Infinity;
|
||||
centering = center_desktop_mouse().then(() => {
|
||||
ignore_look_until = performance.now() + CENTERING_SETTLE_MS;
|
||||
});
|
||||
}
|
||||
was_locked = locked;
|
||||
skip_look_event = locked;
|
||||
self.setTimeout(() => {
|
||||
const grab = document.pointerLockElement === canvas;
|
||||
if (!grab) {
|
||||
if (pointer_lock_flag) {
|
||||
mouse_ungrab_timer = performance.now();
|
||||
lost_pointer_lock = true;
|
||||
}
|
||||
}
|
||||
pointer_lock_flag = grab;
|
||||
}, 60);
|
||||
pointer_lock_waiting = false;
|
||||
});
|
||||
|
||||
// in fullscreen, chromium's keyboard lock gives the game escape (holding it still leaves fullscreen) and ctrl+w,
|
||||
// instead of the browser leaving fullscreen or closing the tab. other browsers don't have it and work as before
|
||||
document.addEventListener("fullscreenchange", () => {
|
||||
const keyboard = (navigator as Navigator & { keyboard?: KeyboardLock }).keyboard;
|
||||
if (!keyboard?.lock) return;
|
||||
if (document.fullscreenElement) {
|
||||
keyboard.lock(FULLSCREEN_LOCKED_KEYS).catch(() => {});
|
||||
} else {
|
||||
keyboard.unlock();
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener("pointerlockerror", () => {
|
||||
pointer_lock_waiting = false;
|
||||
});
|
||||
}
|
||||
|
||||
// ctrl (cmd on macs) held for a shortcut. altgr types characters like @ and comes as ctrl+alt on windows, so it
|
||||
// isn't one. getModifierState("AltGraph") isn't used, some linux layouts report it along with plain ctrl
|
||||
function is_shortcut(e: KeyboardEvent) {
|
||||
return e.metaKey || (e.ctrlKey && !e.altKey);
|
||||
}
|
||||
|
||||
export async function set_mouse_grabbed(grab: boolean) {
|
||||
pointer_lock_flag = grab;
|
||||
want_grab = grab;
|
||||
// a retry to grab it again mustn't happen once it shouldn't be grabbed
|
||||
if (!grab && mouse_ungrab_timeout !== -1) {
|
||||
self.clearTimeout(mouse_ungrab_timeout);
|
||||
mouse_ungrab_timeout = -1;
|
||||
}
|
||||
// already how it should be, the game calls this every frame
|
||||
const locked = document.pointerLockElement === canvas;
|
||||
if (grab ? locked : !locked && !pointer_lock_waiting) {
|
||||
return;
|
||||
}
|
||||
if (grab) {
|
||||
// called every frame, once is enough
|
||||
if (awaiting_centering) return;
|
||||
awaiting_centering = true;
|
||||
await centering;
|
||||
awaiting_centering = false;
|
||||
// a gui opened again meanwhile
|
||||
if (!want_grab || document.pointerLockElement === canvas) return;
|
||||
}
|
||||
const t = performance.now();
|
||||
if (grab) {
|
||||
InputManager.mouse_x = -1;
|
||||
InputManager.mouse_y = -1;
|
||||
pointer_lock_waiting = true;
|
||||
try {
|
||||
await canvas.requestPointerLock();
|
||||
} catch (_) { /* */ }
|
||||
if (mouse_ungrab_timeout !== -1) {
|
||||
self.clearTimeout(mouse_ungrab_timeout);
|
||||
}
|
||||
mouse_ungrab_timeout = -1;
|
||||
if (t - mouse_ungrab_timer < 3000) {
|
||||
mouse_ungrab_timeout = self.setTimeout(async () => {
|
||||
try {
|
||||
await canvas.requestPointerLock();
|
||||
} catch (_) { /* */ }
|
||||
}, 3100 - (t - mouse_ungrab_timer));
|
||||
}
|
||||
} else {
|
||||
if (!pointer_lock_waiting) {
|
||||
document.exitPointerLock();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// whether the browser took the mouse away since the last call, it eats the escape that does it
|
||||
export function take_lost_pointer_lock() {
|
||||
const lost = lost_pointer_lock;
|
||||
lost_pointer_lock = false;
|
||||
return lost;
|
||||
}
|
||||
|
||||
export function is_mouse_grabbed() {
|
||||
return document.hasFocus() && document.pointerLockElement === canvas;
|
||||
}
|
||||
|
||||
export function toggle_fullscreen() {
|
||||
if (!document.fullscreenElement) {
|
||||
canvas.requestFullscreen();
|
||||
} else {
|
||||
document.exitFullscreen();
|
||||
}
|
||||
}
|
||||
|
||||
const CENTERING_TIMEOUT_MS = 250;
|
||||
const CENTERING_SETTLE_MS = 100;
|
||||
|
||||
// the desktop app (the page has ?singleplayer there, see desktop/main.ts) moves the cursor to the middle of the
|
||||
// window when the mouse is let go to open a gui, like minecraft. chromium would put it back where it was grabbed.
|
||||
// resolves once the cursor was moved, or after CENTERING_TIMEOUT_MS if the app is slow, so grabbing isn't held up
|
||||
function center_desktop_mouse(): Promise<void> {
|
||||
if (!new URL(location.href).searchParams.has("singleplayer")) return Promise.resolve();
|
||||
const moved = fetch("/desktop/center_mouse", { method: "POST" }).then(() => {}, () => {});
|
||||
return Promise.race([moved, new Promise<void>((resolve) => self.setTimeout(resolve, CENTERING_TIMEOUT_MS))]);
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// the client in a browser page, see platform.ts
|
||||
import type { Platform } from "./platform.ts";
|
||||
import { render_debug } from "./renderer/mod.ts";
|
||||
import { confirm_mods } from "./confirm_mods.ts";
|
||||
import { CreditsScreen } from "./gui/credits_screen.ts";
|
||||
import { is_mouse_grabbed, set_mouse_grabbed, take_lost_pointer_lock, toggle_fullscreen } from "./browser_input.ts";
|
||||
|
||||
// with render_debug.uncapped, the most frames between two of the display's refreshes. it's the highest fps that shows,
|
||||
// 960 on a 60 hz display, and what the gpu can be behind by
|
||||
const UNCAPPED_FRAMES_PER_REFRESH = 16;
|
||||
|
||||
// with render_debug.uncapped: frames since the display last refreshed, and the frame waiting for the next one
|
||||
let frames_this_refresh = 0;
|
||||
let waiting_for_refresh: ((time: number) => void) | undefined;
|
||||
let refresh_requested = false;
|
||||
let next_task: MessageChannel | undefined;
|
||||
let next_task_frame: ((time: number) => void) | undefined;
|
||||
|
||||
// with the display's refresh, or with render_debug.uncapped right away, so frames aren't held to vsync and show what
|
||||
// they cost. up to UNCAPPED_FRAMES_PER_REFRESH, then it waits for the next refresh, which the browser holds back
|
||||
// while the gpu is behind, so frames the gpu can't keep up with don't pile up. the browser saying a frame is done
|
||||
// can't be waited on instead, firefox only says so every 100 ms when nothing else is sent to the gpu
|
||||
function request_frame(frame: (time: number) => void) {
|
||||
if (!render_debug.uncapped) {
|
||||
requestAnimationFrame(frame);
|
||||
return;
|
||||
}
|
||||
if (!refresh_requested) {
|
||||
refresh_requested = true;
|
||||
requestAnimationFrame(() => {
|
||||
refresh_requested = false;
|
||||
frames_this_refresh = 0;
|
||||
const waiting = waiting_for_refresh;
|
||||
waiting_for_refresh = undefined;
|
||||
waiting?.(performance.now());
|
||||
});
|
||||
}
|
||||
frames_this_refresh += 1;
|
||||
if (frames_this_refresh < UNCAPPED_FRAMES_PER_REFRESH) {
|
||||
// a task of its own, so input and the workers' messages get handled in between
|
||||
if (!next_task) {
|
||||
next_task = new MessageChannel();
|
||||
next_task.port1.onmessage = () => next_task_frame?.(performance.now());
|
||||
}
|
||||
next_task_frame = frame;
|
||||
next_task.port2.postMessage(null);
|
||||
} else {
|
||||
waiting_for_refresh = frame;
|
||||
}
|
||||
}
|
||||
|
||||
// pages that aren't https or localhost have no clipboard api, like a server on another computer, but the old way
|
||||
// still copies from a click
|
||||
function write_clipboard(text: string): Promise<void> {
|
||||
if (navigator.clipboard) return navigator.clipboard.writeText(text);
|
||||
const area = document.createElement("textarea");
|
||||
area.value = text;
|
||||
document.body.append(area);
|
||||
area.select();
|
||||
const copied = document.execCommand("copy");
|
||||
area.remove();
|
||||
return copied ? Promise.resolve() : Promise.reject(new Error("Couldn't copy"));
|
||||
}
|
||||
|
||||
function show_fatal_error(message: string) {
|
||||
document.exitPointerLock?.();
|
||||
|
||||
const overlay = document.createElement("div");
|
||||
overlay.style.cssText =
|
||||
"position:fixed;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;" +
|
||||
"gap:12px;background:rgba(0,0,0,0.85);color:white;font:20px system-ui,sans-serif;text-align:center;";
|
||||
const text = document.createElement("div");
|
||||
text.textContent = message;
|
||||
const hint = document.createElement("div");
|
||||
hint.textContent = "Reload the page to try again.";
|
||||
hint.style.cssText = "font-size:14px;opacity:0.7;";
|
||||
overlay.append(text, hint);
|
||||
document.body.append(overlay);
|
||||
}
|
||||
|
||||
export const browser_platform: Platform = {
|
||||
get page() {
|
||||
return new URL(location.href);
|
||||
},
|
||||
restart(url) {
|
||||
location.href = url.href;
|
||||
},
|
||||
request_frame,
|
||||
get storage() {
|
||||
return localStorage;
|
||||
},
|
||||
on_shown(shown) {
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (!document.hidden) shown();
|
||||
});
|
||||
},
|
||||
// sprinting is ctrl and walking is w, and ctrl+w closes the tab without the page getting a say. in fullscreen
|
||||
// the keyboard lock catches it instead (see browser_input.ts)
|
||||
confirm_leaving(confirm) {
|
||||
self.onbeforeunload = confirm ? (event) => event.preventDefault() : null;
|
||||
},
|
||||
show_fatal_error,
|
||||
confirm_mods,
|
||||
credits_screen: (on_back) => new CreditsScreen(on_back),
|
||||
read_clipboard: () =>
|
||||
navigator.clipboard ? navigator.clipboard.readText() : Promise.reject(new Error("No clipboard")),
|
||||
write_clipboard,
|
||||
set_mouse_grabbed,
|
||||
is_mouse_grabbed,
|
||||
take_lost_mouse: take_lost_pointer_lock,
|
||||
toggle_fullscreen,
|
||||
};
|
||||
@@ -0,0 +1,197 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import { AssetManager } from "./assets.ts";
|
||||
import { Client } from "./client.ts";
|
||||
import { InputManager } from "./input_manager.ts";
|
||||
import { Connection } from "./network.ts";
|
||||
import { Options } from "./options.ts";
|
||||
import { connect, HandshakeError, is_trusted, join, remember_trust, ServerAddress } from "./handshake.ts";
|
||||
import { build_atlas, engine_textures } from "./atlas.ts";
|
||||
import { set_texture_animations } from "./texture_animations.ts";
|
||||
import type { TextureJson } from "@/common/texture_animation.ts";
|
||||
import { ModLoadError } from "@/common/mod_loader.ts";
|
||||
import { begin_drawing, clear_background, device, end_drawing, init_font, load_texture } from "./renderer/mod.ts";
|
||||
import { is_stopped } from "./fatal.ts";
|
||||
import { download_mods, load_client_mods, set_mods_client } from "./mods.ts";
|
||||
import type { GuiScreen } from "./gui/gui_screen.ts";
|
||||
import { in_desktop_app, type JoinServer, TitleScreen } from "./gui/title_screen.ts";
|
||||
import { MainMenuScreen } from "./gui/main_menu.ts";
|
||||
import { DisconnectedScreen } from "./gui/disconnected_screen.ts";
|
||||
import { profiler } from "./profiler.ts";
|
||||
import { platform } from "./platform.ts";
|
||||
|
||||
// runs whatever is showing every frame: a menu screen before joining (and after leaving), or the game
|
||||
class ClientLoop {
|
||||
running = false;
|
||||
last_time = 0;
|
||||
client: Client | undefined;
|
||||
screen: GuiScreen | undefined;
|
||||
|
||||
frame_count = 0;
|
||||
last_fps_time = 0;
|
||||
|
||||
start() {
|
||||
platform.on_shown(() => {
|
||||
this.last_time = performance.now();
|
||||
});
|
||||
|
||||
this.running = true;
|
||||
const now = performance.now();
|
||||
this.last_time = now;
|
||||
this.frame_count = 0;
|
||||
this.last_fps_time = this.last_time;
|
||||
platform.request_frame((time) => this.loop(time));
|
||||
}
|
||||
|
||||
stop() {
|
||||
this.running = false;
|
||||
}
|
||||
|
||||
show_screen(screen: GuiScreen) {
|
||||
this.screen?.on_close();
|
||||
this.client = undefined;
|
||||
platform.confirm_leaving(false);
|
||||
this.screen = screen;
|
||||
InputManager.set_mouse_grabbed(false);
|
||||
}
|
||||
|
||||
play(connection: Connection) {
|
||||
const client = new Client(connection, (message) => this.show_screen(new DisconnectedScreen(message)));
|
||||
set_mods_client(client);
|
||||
client.chat.add("Connected to the server");
|
||||
this.screen?.on_close();
|
||||
this.screen = undefined;
|
||||
this.client = client;
|
||||
platform.confirm_leaving(true);
|
||||
console.log("Game started");
|
||||
}
|
||||
|
||||
loop(time: number) {
|
||||
if (!this.running || is_stopped()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const delta = (time - this.last_time) / 1000;
|
||||
|
||||
profiler.begin_frame();
|
||||
profiler.section("begin frame", begin_drawing);
|
||||
clear_background(0.69, 0.8, 1, 1.0);
|
||||
if (this.client) {
|
||||
this.client.run_frame(delta);
|
||||
} else if (this.screen) {
|
||||
this.screen.on_tick(delta);
|
||||
this.screen.on_render();
|
||||
}
|
||||
profiler.section("submit", end_drawing);
|
||||
profiler.end_frame();
|
||||
|
||||
this.frame_count += 1;
|
||||
const now = performance.now();
|
||||
if (now - this.last_fps_time >= 1000) {
|
||||
const fps = (this.frame_count * 1000) / (now - this.last_fps_time);
|
||||
console.log(`FPS: ${fps.toFixed(2)}`);
|
||||
this.frame_count = 0;
|
||||
this.last_fps_time = now;
|
||||
}
|
||||
|
||||
InputManager.update();
|
||||
|
||||
this.last_time = time;
|
||||
platform.request_frame((time) => this.loop(time));
|
||||
}
|
||||
}
|
||||
|
||||
// a server's blocks, items and scripts can't be taken back out once loaded, so a failure after that point
|
||||
// can't go back to the title screen to try again, the page has to start over
|
||||
class FailedAfterLoadingMods extends Error {}
|
||||
|
||||
// the game only runs against a server, it owns the world and everything in it. see docs/modding/networking/index.md
|
||||
async function join_server(address: ServerAddress, name: string, status: (text: string) => void): Promise<Connection> {
|
||||
const { socket, welcome } = await connect(address, name);
|
||||
console.log(`Connected to ${address.ws_url}`);
|
||||
|
||||
let loaded_mods = false;
|
||||
try {
|
||||
if (address.cross_origin && !is_trusted(address, welcome)) {
|
||||
status("Waiting for you to accept the server's mods...");
|
||||
if (!await platform.confirm_mods(address, welcome)) {
|
||||
throw new HandshakeError(`You didn't join ${address.base.host}`);
|
||||
}
|
||||
remember_trust(address, welcome);
|
||||
}
|
||||
|
||||
// textures, blocks and items all come from the server's mods, so this happens before anything else
|
||||
status("Downloading the server's mods...");
|
||||
const mods = await download_mods(welcome.mods, address.base);
|
||||
const textures = await engine_textures();
|
||||
const texture_json = new Map<string, TextureJson>();
|
||||
for (const mod of mods) {
|
||||
for (const [id, png] of mod.textures) textures.set(id, png);
|
||||
for (const [id, json] of mod.texture_json ?? []) texture_json.set(id, json);
|
||||
}
|
||||
const atlas = build_atlas(textures, texture_json);
|
||||
loaded_mods = true;
|
||||
const atlas_texture = load_texture(atlas.image);
|
||||
set_texture_animations(atlas_texture.tex, device.queue, atlas.animated);
|
||||
AssetManager.instance.assets["cubi:textures"] = atlas_texture;
|
||||
AssetManager.instance.assets["cubi:textures_info"] = atlas.regions;
|
||||
await load_client_mods(welcome.mods, mods);
|
||||
console.log(`Mods: ${welcome.mods.map((mod) => `${mod.id} ${mod.version}`).join(", ") || "none"}`);
|
||||
|
||||
status("Joining...");
|
||||
const joined = await join(socket, new Options().render_distance);
|
||||
return new Connection(socket, welcome, joined);
|
||||
} catch (e) {
|
||||
socket.close();
|
||||
const message = error_message(e);
|
||||
throw loaded_mods ? new FailedAfterLoadingMods(message) : new HandshakeError(message);
|
||||
}
|
||||
}
|
||||
|
||||
function error_message(e: unknown) {
|
||||
if (e instanceof HandshakeError) {
|
||||
return e.message;
|
||||
}
|
||||
if (e instanceof ModLoadError) {
|
||||
return `Couldn't load the server's mods: ${e.message}`;
|
||||
}
|
||||
return `Something went wrong joining the server: ${e instanceof Error ? e.message : e}`;
|
||||
}
|
||||
|
||||
// the title screen (the main menu in the desktop app), and the game once it joins a server. the platform is set, the
|
||||
// window was set up with init_window, and input comes in
|
||||
export async function start_client() {
|
||||
AssetManager.instance.load("cubi:assets_text", "/assets/ASSETS.md");
|
||||
|
||||
AssetManager.instance.load("cubi:skin", "/assets/sprites/skin_template.png");
|
||||
AssetManager.instance.load("cubi:gui", "/assets/sprites/gui.png");
|
||||
|
||||
AssetManager.instance.load("cubi:m6x11", "/assets/fonts/m6x11.png");
|
||||
AssetManager.instance.load("cubi:m6x11_fnt", "/assets/fonts/m6x11.fnt");
|
||||
|
||||
await AssetManager.instance.load_all();
|
||||
|
||||
init_font();
|
||||
|
||||
const loop = new ClientLoop();
|
||||
const join_game: JoinServer = async (address, name, status) => {
|
||||
let connection: Connection;
|
||||
try {
|
||||
connection = await join_server(address, name, status);
|
||||
} catch (e) {
|
||||
if (e instanceof FailedAfterLoadingMods) {
|
||||
loop.show_screen(new DisconnectedScreen(e.message));
|
||||
return;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
loop.play(connection);
|
||||
};
|
||||
loop.show_screen(
|
||||
in_desktop_app()
|
||||
? new MainMenuScreen((screen) => loop.show_screen(screen), join_game)
|
||||
: new TitleScreen(join_game),
|
||||
);
|
||||
loop.start();
|
||||
}
|
||||
+3
-10
@@ -36,7 +36,6 @@ export abstract class Player extends Entity {
|
||||
// which way the body lies while swimming, radians up from flat: the way they're going, or looking when still
|
||||
swim_pitch = 0;
|
||||
prev_swim_pitch = 0;
|
||||
#skin_version = 0;
|
||||
|
||||
constructor(level: ClientLevel, id: string, name: string) {
|
||||
super(level, id, PLAYER_WIDTH, PLAYER_HEIGHT, PLAYER_EYE_HEIGHT);
|
||||
@@ -72,15 +71,9 @@ export abstract class Player extends Entity {
|
||||
};
|
||||
}
|
||||
|
||||
// a base64 png from the server, or undefined for the default. the old skin stays until the new one is decoded
|
||||
async set_skin(skin: string | undefined, slim = false) {
|
||||
const version = ++this.#skin_version;
|
||||
const texture = skin ? await decode_skin(skin) : undefined;
|
||||
if (version !== this.#skin_version) {
|
||||
// a newer skin came while this one was decoding
|
||||
texture?.tex.destroy();
|
||||
return;
|
||||
}
|
||||
// a base64 png from the server, or undefined for the default
|
||||
set_skin(skin: string | undefined, slim = false) {
|
||||
const texture = skin ? decode_skin(skin) : undefined;
|
||||
this.skin?.tex.destroy();
|
||||
this.skin = texture;
|
||||
this.slim = slim;
|
||||
|
||||
+3
-13
@@ -1,6 +1,8 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import { platform } from "./platform.ts";
|
||||
|
||||
let stopped = false;
|
||||
|
||||
// replaces the game with a message, for when it can't go on (no server, lost connection)
|
||||
@@ -9,19 +11,7 @@ export function show_fatal_error(message: string) {
|
||||
return;
|
||||
}
|
||||
stopped = true;
|
||||
document.exitPointerLock?.();
|
||||
|
||||
const overlay = document.createElement("div");
|
||||
overlay.style.cssText =
|
||||
"position:fixed;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;" +
|
||||
"gap:12px;background:rgba(0,0,0,0.85);color:white;font:20px system-ui,sans-serif;text-align:center;";
|
||||
const text = document.createElement("div");
|
||||
text.textContent = message;
|
||||
const hint = document.createElement("div");
|
||||
hint.textContent = "Reload the page to try again.";
|
||||
hint.style.cssText = "font-size:14px;opacity:0.7;";
|
||||
overlay.append(text, hint);
|
||||
document.body.append(overlay);
|
||||
platform.show_fatal_error(message);
|
||||
}
|
||||
|
||||
export function is_stopped() {
|
||||
|
||||
@@ -55,7 +55,7 @@ export class CreditsScreen extends GuiScreen {
|
||||
|
||||
const content = document.createElement("div");
|
||||
content.style.cssText = "overflow-y:auto;flex:1;min-height:0;padding-right:8px;";
|
||||
content.innerHTML = this.#sections().map(({ heading, text }) =>
|
||||
content.innerHTML = credit_sections().map(({ heading, text }) =>
|
||||
`<section><h2 style="border-bottom:1px solid #374151;padding-bottom:4px">${escape_html(heading)}</h2>` +
|
||||
`${markdown.parse(text, { async: false })}</section>`
|
||||
).join("");
|
||||
@@ -72,14 +72,6 @@ export class CreditsScreen extends GuiScreen {
|
||||
document.body.append(this.#overlay);
|
||||
}
|
||||
|
||||
#sections() {
|
||||
const sections = [{ heading: "cubi", text: AssetManager.instance.get<string>("cubi:assets_text") ?? "" }];
|
||||
for (const mod of mod_credits) {
|
||||
sections.push({ heading: `${mod.name} ${mod.version}`, text: mod.text });
|
||||
}
|
||||
return sections;
|
||||
}
|
||||
|
||||
on_tick(_delta: number): void {}
|
||||
|
||||
on_render(): void {
|
||||
@@ -91,6 +83,15 @@ export class CreditsScreen extends GuiScreen {
|
||||
}
|
||||
}
|
||||
|
||||
// the engine's assets/ASSETS.md, then each loaded mod's credits file, as markdown
|
||||
export function credit_sections(): { heading: string; text: string }[] {
|
||||
const sections = [{ heading: "cubi", text: AssetManager.instance.get<string>("cubi:assets_text") ?? "" }];
|
||||
for (const mod of mod_credits) {
|
||||
sections.push({ heading: `${mod.name} ${mod.version}`, text: mod.text });
|
||||
}
|
||||
return sections;
|
||||
}
|
||||
|
||||
function escape_html(text: string) {
|
||||
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import { RENDER_LAYERS } from "@/common/everything_registry.ts";
|
||||
import { atlas_png } from "@/client/atlas.ts";
|
||||
import { RenderBenchmark } from "@/client/benchmark/benchmark.ts";
|
||||
import { format_report } from "@/client/benchmark/report.ts";
|
||||
import { platform } from "@/client/platform.ts";
|
||||
|
||||
// how often the totals that go through every chunk are worked out again, so the overlay doesn't slow the frames it's
|
||||
// measuring
|
||||
@@ -113,7 +114,7 @@ export class DebugOverlay {
|
||||
if (copy) {
|
||||
const switches = { ...render_debug, ...level_renderer.draw };
|
||||
lines.push(Object.entries(switches).map(([key, on]) => ` ${key}: ${on}`).join("\n"));
|
||||
copy_text(lines.join("\n")).catch(() => {});
|
||||
platform.write_clipboard(lines.join("\n")).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,7 +138,7 @@ export class DebugOverlay {
|
||||
|
||||
// right after the benchmark, firefox and safari only let the page copy from a click
|
||||
#copy_benchmark() {
|
||||
copy_text(this.#benchmark_report!).then(
|
||||
platform.write_clipboard(this.#benchmark_report!).then(
|
||||
() => this.#benchmark_status = "The benchmark's results are on the clipboard",
|
||||
() => this.#benchmark_status = "Click above to copy the benchmark's results",
|
||||
);
|
||||
@@ -187,16 +188,3 @@ export class DebugOverlay {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// pages that aren't https or localhost have no clipboard api, like a server on another computer, but the old way
|
||||
// still copies from a click
|
||||
function copy_text(text: string): Promise<void> {
|
||||
if (navigator.clipboard) return navigator.clipboard.writeText(text);
|
||||
const area = document.createElement("textarea");
|
||||
area.value = text;
|
||||
document.body.append(area);
|
||||
area.select();
|
||||
const copied = document.execCommand("copy");
|
||||
area.remove();
|
||||
return copied ? Promise.resolve() : Promise.reject(new Error("Couldn't copy"));
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import { InputManager } from "@/client/input_manager.ts";
|
||||
import { canvas, draw_rect, draw_text, measure_text } from "@/client/renderer/mod.ts";
|
||||
import { server_address } from "@/client/handshake.ts";
|
||||
import { GuiScreen } from "./gui_screen.ts";
|
||||
import { CreditsScreen } from "./credits_screen.ts";
|
||||
import { platform } from "../platform.ts";
|
||||
import type { JoinServer } from "./title_screen.ts";
|
||||
import { Button, EditBox, ListBox, TEXT_HEIGHT, TEXT_SCALE, TextInput } from "./widgets.ts";
|
||||
|
||||
@@ -37,7 +37,7 @@ export class MainMenuScreen extends GuiScreen {
|
||||
new Button("Singleplayer", WIDTH, ROW_HEIGHT, () => show(new WorldListScreen(show, join))),
|
||||
multiplayer,
|
||||
mods,
|
||||
new Button("Credits", WIDTH, ROW_HEIGHT, () => show(new CreditsScreen(back))),
|
||||
new Button("Credits", WIDTH, ROW_HEIGHT, () => show(platform.credits_screen(back))),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -145,7 +145,7 @@ class WorldListScreen extends GuiScreen {
|
||||
this.#status.set(`Starting ${world.name}...`);
|
||||
try {
|
||||
await desktop("play", { world: world.name });
|
||||
await this.#join(server_address(location.host), SINGLEPLAYER_NAME, (text) => this.#status.set(text));
|
||||
await this.#join(server_address(platform.page.host), SINGLEPLAYER_NAME, (text) => this.#status.set(text));
|
||||
} catch (e) {
|
||||
this.#status.fail(e);
|
||||
this.#busy = false;
|
||||
@@ -294,7 +294,10 @@ function draw_centered(text: string, y: number, scale: number) {
|
||||
|
||||
// asks the desktop app, see desktop/main.ts. throws with what the app said went wrong
|
||||
async function desktop(path: string, body: unknown = {}): Promise<Response> {
|
||||
const response = await fetch(`/desktop/${path}`, { method: "POST", body: JSON.stringify(body) });
|
||||
const response = await fetch(new URL(`/desktop/${path}`, platform.page), {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!response.ok) throw new Error(await response.text());
|
||||
return response;
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { Client } from "@/client/client.ts";
|
||||
import { canvas, draw_rect, draw_text, measure_text } from "@/client/renderer/mod.ts";
|
||||
import { GuiScreen } from "./gui_screen.ts";
|
||||
import { Button, TEXT_HEIGHT } from "./widgets.ts";
|
||||
import { CreditsScreen } from "./credits_screen.ts";
|
||||
import { platform } from "../platform.ts";
|
||||
|
||||
const BUTTON_WIDTH = 440;
|
||||
const BUTTON_HEIGHT = 48;
|
||||
@@ -20,7 +20,7 @@ export class PauseScreen extends GuiScreen {
|
||||
this.buttons = [
|
||||
new Button("Back to game", BUTTON_WIDTH, BUTTON_HEIGHT, () => client.pop_screen()),
|
||||
new Button("Credits", BUTTON_WIDTH, BUTTON_HEIGHT, () => {
|
||||
client.push_screen(new CreditsScreen(() => client.pop_screen()));
|
||||
client.push_screen(platform.credits_screen(() => client.pop_screen()));
|
||||
}),
|
||||
new Button("Disconnect", BUTTON_WIDTH, BUTTON_HEIGHT, () => client.disconnect()),
|
||||
];
|
||||
|
||||
+11
-11
@@ -7,7 +7,7 @@ import { canvas, draw_rect, draw_text, measure_text } from "@/client/renderer/mo
|
||||
import { default_server, HandshakeError, server_address, ServerAddress } from "@/client/handshake.ts";
|
||||
import { default_player_name } from "@/client/network.ts";
|
||||
import { GuiScreen } from "./gui_screen.ts";
|
||||
import { CreditsScreen } from "./credits_screen.ts";
|
||||
import { platform } from "../platform.ts";
|
||||
import { Button, EditBox, TEXT_HEIGHT, TEXT_SCALE, TextInput } from "./widgets.ts";
|
||||
|
||||
const LAST_SERVER_KEY = "cubi:last_server";
|
||||
@@ -40,7 +40,7 @@ export class TitleScreen extends GuiScreen {
|
||||
// the desktop app for this computer's os
|
||||
download_button = new Button(`Download for ${download_os().name}`, WIDTH, ROW_HEIGHT, download_desktop_app);
|
||||
// open over the title screen, it gets the input while it's there
|
||||
#credits: CreditsScreen | undefined;
|
||||
#credits: GuiScreen | undefined;
|
||||
|
||||
status = "";
|
||||
status_is_error = false;
|
||||
@@ -118,7 +118,7 @@ export class TitleScreen extends GuiScreen {
|
||||
}
|
||||
|
||||
#open_credits() {
|
||||
this.#credits ??= new CreditsScreen(() => this.#close_credits());
|
||||
this.#credits ??= platform.credits_screen(() => this.#close_credits());
|
||||
}
|
||||
|
||||
#close_credits() {
|
||||
@@ -188,18 +188,18 @@ export class TitleScreen extends GuiScreen {
|
||||
|
||||
// what was typed last time, unless the page was opened with ?server= or ?name=
|
||||
function initial_server() {
|
||||
const page = new URL(location.href);
|
||||
const page = platform.page;
|
||||
return page.searchParams.has("server") ? default_server(page) : recall(LAST_SERVER_KEY) ?? default_server(page);
|
||||
}
|
||||
|
||||
function initial_name() {
|
||||
const page = new URL(location.href);
|
||||
const page = platform.page;
|
||||
return page.searchParams.has("name") ? default_player_name() : recall(LAST_NAME_KEY) ?? "";
|
||||
}
|
||||
|
||||
function recall(key: string): string | undefined {
|
||||
try {
|
||||
return localStorage.getItem(key) ?? undefined;
|
||||
return platform.storage.getItem(key) ?? undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
@@ -207,7 +207,7 @@ function recall(key: string): string | undefined {
|
||||
|
||||
function remember(key: string, value: string) {
|
||||
try {
|
||||
localStorage.setItem(key, value);
|
||||
platform.storage.setItem(key, value);
|
||||
} catch {
|
||||
// private windows and blocked storage just start empty next time
|
||||
}
|
||||
@@ -215,7 +215,7 @@ function remember(key: string, value: string) {
|
||||
|
||||
// the page is the desktop app's, see desktop/main.ts
|
||||
export function in_desktop_app() {
|
||||
return new URL(location.href).searchParams.has("singleplayer");
|
||||
return platform.page.searchParams.has("singleplayer");
|
||||
}
|
||||
|
||||
// the desktop app's build for the os the browser is on, which the server has in /dist/, see DESKTOP_DOWNLOADS. everything that isn't windows
|
||||
@@ -237,11 +237,11 @@ function download_desktop_app() {
|
||||
// or ?name=, so the fields show what was used last. the desktop app keeps its ?singleplayer and ?server=, for its
|
||||
// main menu
|
||||
export function back_to_title() {
|
||||
const page = new URL(location.href);
|
||||
const next = new URL(location.pathname, location.href);
|
||||
const page = platform.page;
|
||||
const next = new URL(page.pathname, page);
|
||||
if (in_desktop_app()) {
|
||||
next.searchParams.set("server", page.searchParams.get("server") ?? "");
|
||||
next.searchParams.set("singleplayer", "");
|
||||
}
|
||||
location.href = next.href;
|
||||
platform.restart(next);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { point_inside_rec } from "@/common/utils.ts";
|
||||
import { InputManager, type KeyCode } from "@/client/input_manager.ts";
|
||||
import { draw_rect, draw_rect_stroke, draw_text, measure_text } from "@/client/renderer/mod.ts";
|
||||
import { draw_gui_sprite } from "./gui_sprites.ts";
|
||||
import { platform } from "@/client/platform.ts";
|
||||
|
||||
export const TEXT_SCALE = 2;
|
||||
// how tall the font is at scale 1
|
||||
@@ -124,14 +125,14 @@ export class TextInput {
|
||||
const copy = InputManager.is_shortcut_pressed("c");
|
||||
const cut = InputManager.is_shortcut_pressed("x");
|
||||
if ((copy || cut) && this.anchor !== this.caret) {
|
||||
navigator.clipboard?.writeText(this.selected_text()).catch(() => {});
|
||||
platform.write_clipboard(this.selected_text()).catch(() => {});
|
||||
if (cut) {
|
||||
this.delete_to(this.caret);
|
||||
}
|
||||
}
|
||||
if (InputManager.is_shortcut_pressed("v")) {
|
||||
// the browser may ask first, it's put in once it answers
|
||||
navigator.clipboard?.readText().then((text) => this.insert(text), () => {});
|
||||
platform.read_clipboard().then((text) => this.insert(text), () => {});
|
||||
}
|
||||
for (const char of InputManager.get_typed_characters()) {
|
||||
this.insert(char);
|
||||
|
||||
+5
-4
@@ -4,6 +4,7 @@
|
||||
// connecting to a server and getting what it needs before joining, see docs/modding/networking/index.md:
|
||||
// hello -> welcome, download and check everything, ready -> join
|
||||
import { ClientMessage, PROTOCOL_VERSION, ServerMessage } from "@/common/protocol.ts";
|
||||
import { platform } from "./platform.ts";
|
||||
|
||||
const CONNECT_TIMEOUT_MS = 5000;
|
||||
const TRUST_KEY_PREFIX = "cubi:trusted:";
|
||||
@@ -23,12 +24,12 @@ export interface ServerAddress {
|
||||
export class HandshakeError extends Error {}
|
||||
|
||||
// what the server field starts as: ?server=host:port, otherwise the server that served the page
|
||||
export function default_server(page = new URL(location.href)): string {
|
||||
export function default_server(page = platform.page): string {
|
||||
return page.searchParams.get("server") ?? page.host;
|
||||
}
|
||||
|
||||
// what a player typed as the server: host:port, or a full http(s) or ws(s) url to pick the scheme
|
||||
export function server_address(input: string, page = new URL(location.href)): ServerAddress {
|
||||
export function server_address(input: string, page = platform.page): ServerAddress {
|
||||
const text = input.trim();
|
||||
let host = text;
|
||||
let secure: boolean;
|
||||
@@ -209,7 +210,7 @@ function mod_versions(welcome: Welcome) {
|
||||
|
||||
export function is_trusted(address: ServerAddress, welcome: Welcome): boolean {
|
||||
try {
|
||||
return localStorage.getItem(trust_key(address)) === mod_versions(welcome);
|
||||
return platform.storage.getItem(trust_key(address)) === mod_versions(welcome);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
@@ -217,7 +218,7 @@ export function is_trusted(address: ServerAddress, welcome: Welcome): boolean {
|
||||
|
||||
export function remember_trust(address: ServerAddress, welcome: Welcome) {
|
||||
try {
|
||||
localStorage.setItem(trust_key(address), mod_versions(welcome));
|
||||
platform.storage.setItem(trust_key(address), mod_versions(welcome));
|
||||
} catch {
|
||||
// private windows and blocked storage just ask again next time
|
||||
}
|
||||
|
||||
+70
-224
@@ -1,7 +1,7 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import { canvas } from "./renderer/core.ts";
|
||||
import { platform } from "./platform.ts";
|
||||
|
||||
export type KeyCode =
|
||||
// letters
|
||||
@@ -79,16 +79,8 @@ export type KeyCode =
|
||||
| "F11"
|
||||
| "F12";
|
||||
|
||||
// the keys the game keeps in fullscreen, see "fullscreenchange". not every key: with all of them locked, chromium
|
||||
// can keep alt+tab and the windows key from the os too
|
||||
const FULLSCREEN_LOCKED_KEYS = ["Escape", "KeyW"];
|
||||
|
||||
// chromium's keyboard lock api, typescript's dom types don't have it yet
|
||||
interface KeyboardLock {
|
||||
lock(codes?: string[]): Promise<void>;
|
||||
unlock(): void;
|
||||
}
|
||||
|
||||
// what the player presses and how the mouse moves, kept for the frame. where it runs feeds it events: the page's
|
||||
// (browser_input.ts) or the desktop app's window (native/), and grabs the mouse for it (see platform.ts)
|
||||
export class InputManager {
|
||||
static keys_down = new Set<string>();
|
||||
static keys_pressed = new Set<string>();
|
||||
@@ -108,8 +100,6 @@ export class InputManager {
|
||||
// around a screen can never turn it
|
||||
static look_delta_x = 0;
|
||||
static look_delta_y = 0;
|
||||
// chrome sometimes sends a huge movement with the first mouse event after the lock starts
|
||||
static #skip_look_event = false;
|
||||
static wheel_delta = 0;
|
||||
|
||||
// in the order they were typed. a list, since the same letter can be typed twice in one frame
|
||||
@@ -117,147 +107,71 @@ export class InputManager {
|
||||
// letters pressed with ctrl (cmd on macs) held, like "a" for select all
|
||||
static shortcuts: string[] = [];
|
||||
|
||||
static pointer_lock_flag = false;
|
||||
static mouse_grab_timer = 0;
|
||||
static mouse_ungrab_timer = 0;
|
||||
static mouse_ungrab_timeout = -1;
|
||||
static pointer_lock_waiting = false;
|
||||
// the browser let go of the mouse while the game wanted it, like escape or switching windows
|
||||
static #lost_pointer_lock = false;
|
||||
// the canvas had the pointer lock at the last pointerlockchange
|
||||
static #was_locked = false;
|
||||
// the desktop app moving the cursor after the mouse was let go, see center_desktop_mouse. grabbing it again waits
|
||||
// for that, or the move would come while it's locked and turn the camera
|
||||
static #centering = Promise.resolve();
|
||||
static #awaiting_centering = false;
|
||||
// the locked mouse doesn't turn the camera until then, the move can still reach chromium after the app answered,
|
||||
// or the mouse was locked again before chromium said it let go
|
||||
static #ignore_look_until = 0;
|
||||
// what the game last asked for, it can change while grabbing waits
|
||||
static #want_grab = false;
|
||||
|
||||
static initialize(canvas: HTMLCanvasElement) {
|
||||
self.addEventListener("keydown", (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (!this.keys_down.has(e.code)) {
|
||||
this.keys_pressed.add(e.code);
|
||||
}
|
||||
this.keys_down.add(e.code);
|
||||
if (e.key.length === 1) {
|
||||
if (this.#is_shortcut(e)) {
|
||||
this.shortcuts.push(e.key.toLowerCase());
|
||||
} else {
|
||||
this.typed_characters.push(e.key);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// keys let go while the window isn't focused never send keyup, so they'd stay held
|
||||
self.addEventListener("blur", () => {
|
||||
this.keys_down.clear();
|
||||
this.mouse_buttons_down.clear();
|
||||
});
|
||||
|
||||
self.addEventListener("keyup", (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
this.keys_down.delete(e.code);
|
||||
this.keys_released.add(e.code);
|
||||
});
|
||||
|
||||
self.addEventListener("mousedown", (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (!document.hasFocus() && document.pointerLockElement !== canvas) {
|
||||
this.set_mouse_grabbed(true);
|
||||
return;
|
||||
}
|
||||
if (!this.mouse_buttons_down.has(e.button)) {
|
||||
this.mouse_buttons_pressed.add(e.button);
|
||||
}
|
||||
this.mouse_buttons_down.add(e.button);
|
||||
});
|
||||
|
||||
self.addEventListener("mouseup", (e) => {
|
||||
e.preventDefault();
|
||||
this.mouse_buttons_down.delete(e.button);
|
||||
this.mouse_buttons_released.add(e.button);
|
||||
});
|
||||
|
||||
// ctrl+scroll (and pinching a trackpad, which browsers send as that) would zoom the page. only a listener that
|
||||
// isn't passive can stop it, and on the window they're passive unless told otherwise
|
||||
self.addEventListener("wheel", (e) => {
|
||||
if (e.ctrlKey) {
|
||||
e.preventDefault();
|
||||
}
|
||||
this.wheel_delta += e.deltaY;
|
||||
}, { passive: false });
|
||||
|
||||
document.addEventListener("mousemove", (e) => {
|
||||
e.preventDefault();
|
||||
if (document.pointerLockElement === canvas) {
|
||||
if (this.#skip_look_event) {
|
||||
this.#skip_look_event = false;
|
||||
return;
|
||||
}
|
||||
if (performance.now() < this.#ignore_look_until) return;
|
||||
this.look_delta_x += e.movementX;
|
||||
this.look_delta_y += e.movementY;
|
||||
// code is a KeyCode, key what it types: a character, or a name like "Enter". shortcut is whether ctrl (cmd on
|
||||
// macs) is held for one, then a letter is a shortcut instead of being typed
|
||||
static key_down(code: string, key: string, shortcut: boolean) {
|
||||
if (!this.keys_down.has(code)) {
|
||||
this.keys_pressed.add(code);
|
||||
}
|
||||
this.keys_down.add(code);
|
||||
if (key.length === 1) {
|
||||
if (shortcut) {
|
||||
this.shortcuts.push(key.toLowerCase());
|
||||
} else {
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const new_x = e.clientX - rect.left;
|
||||
const new_y = e.clientY - rect.top;
|
||||
|
||||
// not from where it was before the mouse was grabbed, that's -1
|
||||
if (this.mouse_x >= 0 && this.mouse_y >= 0) {
|
||||
this.mouse_delta_x += new_x - this.mouse_x;
|
||||
this.mouse_delta_y += new_y - this.mouse_y;
|
||||
}
|
||||
|
||||
this.mouse_x = new_x;
|
||||
this.mouse_y = new_y;
|
||||
this.typed_characters.push(key);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener("pointerlockchange", () => {
|
||||
const locked = document.pointerLockElement === canvas;
|
||||
if (this.#was_locked && !locked) {
|
||||
this.#ignore_look_until = Infinity;
|
||||
this.#centering = center_desktop_mouse().then(() => {
|
||||
this.#ignore_look_until = performance.now() + CENTERING_SETTLE_MS;
|
||||
});
|
||||
}
|
||||
this.#was_locked = locked;
|
||||
this.#skip_look_event = locked;
|
||||
self.setTimeout(() => {
|
||||
const grab = document.pointerLockElement === canvas;
|
||||
if (!grab) {
|
||||
if (this.pointer_lock_flag) {
|
||||
this.mouse_ungrab_timer = performance.now();
|
||||
this.#lost_pointer_lock = true;
|
||||
}
|
||||
}
|
||||
this.pointer_lock_flag = grab;
|
||||
}, 60);
|
||||
this.pointer_lock_waiting = false;
|
||||
});
|
||||
// for where typing comes apart from keys, the desktop app's window
|
||||
static type_text(text: string) {
|
||||
this.typed_characters.push(...text);
|
||||
}
|
||||
|
||||
// in fullscreen, chromium's keyboard lock gives the game escape (holding it still leaves fullscreen) and ctrl+w,
|
||||
// instead of the browser leaving fullscreen or closing the tab. other browsers don't have it and work as before
|
||||
document.addEventListener("fullscreenchange", () => {
|
||||
const keyboard = (navigator as Navigator & { keyboard?: KeyboardLock }).keyboard;
|
||||
if (!keyboard?.lock) return;
|
||||
if (document.fullscreenElement) {
|
||||
keyboard.lock(FULLSCREEN_LOCKED_KEYS).catch(() => {});
|
||||
} else {
|
||||
keyboard.unlock();
|
||||
}
|
||||
});
|
||||
static key_up(code: string) {
|
||||
this.keys_down.delete(code);
|
||||
this.keys_released.add(code);
|
||||
}
|
||||
|
||||
document.addEventListener("pointerlockerror", () => {
|
||||
this.pointer_lock_waiting = false;
|
||||
});
|
||||
// buttons are numbered like the dom's: 0 left, 1 middle, 2 right
|
||||
static mouse_down(button: number) {
|
||||
if (!this.mouse_buttons_down.has(button)) {
|
||||
this.mouse_buttons_pressed.add(button);
|
||||
}
|
||||
this.mouse_buttons_down.add(button);
|
||||
}
|
||||
|
||||
static mouse_up(button: number) {
|
||||
this.mouse_buttons_down.delete(button);
|
||||
this.mouse_buttons_released.add(button);
|
||||
}
|
||||
|
||||
// the cursor at x y, in the canvas's pixels
|
||||
static move_cursor(x: number, y: number) {
|
||||
// not from where it was before the mouse was grabbed, that's -1
|
||||
if (this.mouse_x >= 0 && this.mouse_y >= 0) {
|
||||
this.mouse_delta_x += x - this.mouse_x;
|
||||
this.mouse_delta_y += y - this.mouse_y;
|
||||
}
|
||||
this.mouse_x = x;
|
||||
this.mouse_y = y;
|
||||
}
|
||||
|
||||
// the grabbed mouse moved
|
||||
static look(x: number, y: number) {
|
||||
this.look_delta_x += x;
|
||||
this.look_delta_y += y;
|
||||
}
|
||||
|
||||
// down is positive, about 100 for a notch of a wheel
|
||||
static scroll(amount: number) {
|
||||
this.wheel_delta += amount;
|
||||
}
|
||||
|
||||
// keys and buttons let go while the game didn't have focus never come up, so they'd stay held
|
||||
static release_all() {
|
||||
this.keys_down.clear();
|
||||
this.mouse_buttons_down.clear();
|
||||
}
|
||||
|
||||
static is_key_down(code: KeyCode): boolean {
|
||||
@@ -306,12 +220,6 @@ export class InputManager {
|
||||
this.mouse_buttons_consumed.add(button);
|
||||
}
|
||||
|
||||
// ctrl (cmd on macs) held for a shortcut. altgr types characters like @ and comes as ctrl+alt on windows, so it
|
||||
// isn't one. getModifierState("AltGraph") isn't used, some linux layouts report it along with plain ctrl
|
||||
static #is_shortcut(e: KeyboardEvent) {
|
||||
return e.metaKey || (e.ctrlKey && !e.altKey);
|
||||
}
|
||||
|
||||
static is_shortcut_pressed(letter: string): boolean {
|
||||
return this.shortcuts.includes(letter);
|
||||
}
|
||||
@@ -337,83 +245,21 @@ export class InputManager {
|
||||
this.mouse_buttons_consumed.clear();
|
||||
}
|
||||
|
||||
static async set_mouse_grabbed(grab: boolean) {
|
||||
this.pointer_lock_flag = grab;
|
||||
this.#want_grab = grab;
|
||||
// a retry to grab it again mustn't happen once it shouldn't be grabbed
|
||||
if (!grab && this.mouse_ungrab_timeout !== -1) {
|
||||
self.clearTimeout(this.mouse_ungrab_timeout);
|
||||
this.mouse_ungrab_timeout = -1;
|
||||
}
|
||||
// already how it should be, the game calls this every frame
|
||||
const locked = document.pointerLockElement === canvas;
|
||||
if (grab ? locked : !locked && !this.pointer_lock_waiting) {
|
||||
return;
|
||||
}
|
||||
if (grab) {
|
||||
// called every frame, once is enough
|
||||
if (this.#awaiting_centering) return;
|
||||
this.#awaiting_centering = true;
|
||||
await this.#centering;
|
||||
this.#awaiting_centering = false;
|
||||
// a gui opened again meanwhile
|
||||
if (!this.#want_grab || document.pointerLockElement === canvas) return;
|
||||
}
|
||||
const t = performance.now();
|
||||
this.mouse_grab_timer = t;
|
||||
if (grab) {
|
||||
this.mouse_x = -1;
|
||||
this.mouse_y = -1;
|
||||
this.pointer_lock_waiting = true;
|
||||
try {
|
||||
await canvas.requestPointerLock();
|
||||
} catch (_) { /* */ }
|
||||
if (this.mouse_ungrab_timeout !== -1) {
|
||||
self.clearTimeout(this.mouse_ungrab_timeout);
|
||||
}
|
||||
this.mouse_ungrab_timeout = -1;
|
||||
if (t - this.mouse_ungrab_timer < 3000) {
|
||||
this.mouse_ungrab_timeout = self.setTimeout(async () => {
|
||||
try {
|
||||
await canvas.requestPointerLock();
|
||||
} catch (_) { /* */ }
|
||||
}, 3100 - (t - this.mouse_ungrab_timer));
|
||||
}
|
||||
} else {
|
||||
if (!this.pointer_lock_waiting) {
|
||||
document.exitPointerLock();
|
||||
}
|
||||
}
|
||||
// the game calls this every frame
|
||||
static set_mouse_grabbed(grab: boolean) {
|
||||
platform.set_mouse_grabbed(grab);
|
||||
}
|
||||
|
||||
// whether the mouse was taken away since the last call, browsers eat the escape that does it
|
||||
// whether the mouse was taken away since the last call, like browsers do with escape
|
||||
static take_lost_pointer_lock() {
|
||||
const lost = this.#lost_pointer_lock;
|
||||
this.#lost_pointer_lock = false;
|
||||
return lost;
|
||||
return platform.take_lost_mouse();
|
||||
}
|
||||
|
||||
static is_mouse_grabbed() {
|
||||
return document.hasFocus() && document.pointerLockElement === canvas;
|
||||
return platform.is_mouse_grabbed();
|
||||
}
|
||||
|
||||
static toggle_fullscreen() {
|
||||
if (!document.fullscreenElement) {
|
||||
canvas.requestFullscreen();
|
||||
} else {
|
||||
document.exitFullscreen();
|
||||
}
|
||||
platform.toggle_fullscreen();
|
||||
}
|
||||
}
|
||||
|
||||
const CENTERING_TIMEOUT_MS = 250;
|
||||
const CENTERING_SETTLE_MS = 100;
|
||||
|
||||
// the desktop app (the page has ?singleplayer there, see desktop/main.ts) moves the cursor to the middle of the
|
||||
// window when the mouse is let go to open a gui, like minecraft. chromium would put it back where it was grabbed.
|
||||
// resolves once the cursor was moved, or after CENTERING_TIMEOUT_MS if the app is slow, so grabbing isn't held up
|
||||
function center_desktop_mouse(): Promise<void> {
|
||||
if (!new URL(location.href).searchParams.has("singleplayer")) return Promise.resolve();
|
||||
const moved = fetch("/desktop/center_mouse", { method: "POST" }).then(() => {}, () => {});
|
||||
return Promise.race([moved, new Promise<void>((resolve) => self.setTimeout(resolve, CENTERING_TIMEOUT_MS))]);
|
||||
}
|
||||
|
||||
+14
-249
@@ -1,224 +1,17 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import { AssetManager } from "./assets.ts";
|
||||
import { Client } from "./client.ts";
|
||||
import { InputManager } from "./input_manager.ts";
|
||||
import { Connection } from "./network.ts";
|
||||
import { Options } from "./options.ts";
|
||||
import { connect, HandshakeError, is_trusted, join, remember_trust, ServerAddress } from "./handshake.ts";
|
||||
import { build_atlas, engine_textures } from "./atlas.ts";
|
||||
import { confirm_mods } from "./confirm_mods.ts";
|
||||
import { set_texture_animations } from "./texture_animations.ts";
|
||||
import type { TextureJson } from "@/common/texture_animation.ts";
|
||||
import { ModLoadError } from "@/common/mod_loader.ts";
|
||||
import {
|
||||
begin_drawing,
|
||||
canvas,
|
||||
clear_background,
|
||||
device,
|
||||
end_drawing,
|
||||
init_font,
|
||||
init_window,
|
||||
load_texture,
|
||||
render_debug,
|
||||
resize_canvas,
|
||||
} from "./renderer/mod.ts";
|
||||
import { is_stopped, show_fatal_error } from "./fatal.ts";
|
||||
import { download_mods, load_client_mods, set_mods_client } from "./mods.ts";
|
||||
import type { GuiScreen } from "./gui/gui_screen.ts";
|
||||
import { in_desktop_app, type JoinServer, TitleScreen } from "./gui/title_screen.ts";
|
||||
import { MainMenuScreen } from "./gui/main_menu.ts";
|
||||
import { DisconnectedScreen } from "./gui/disconnected_screen.ts";
|
||||
import { profiler } from "./profiler.ts";
|
||||
// the client in a browser page, drawing on index.html's canvas. the desktop app's starts at native/main.ts
|
||||
import { set_platform } from "./platform.ts";
|
||||
import { browser_platform } from "./browser_platform.ts";
|
||||
import { listen_to_page } from "./browser_input.ts";
|
||||
import { init_window, resize_canvas } from "./renderer/mod.ts";
|
||||
import { show_fatal_error } from "./fatal.ts";
|
||||
import { sounds } from "./sounds.ts";
|
||||
import { WebAudioOutput } from "./audio_output.ts";
|
||||
import { start_client } from "./client_loop.ts";
|
||||
|
||||
// runs whatever is showing every frame: a menu screen before joining (and after leaving), or the game
|
||||
export // while playing, the browser asks before leaving the page. sprinting is ctrl and walking is w, and ctrl+w closes the
|
||||
// tab without the page getting a say. in fullscreen the keyboard lock catches it instead (see input_manager.ts)
|
||||
function confirm_leaving(confirm: boolean) {
|
||||
self.onbeforeunload = confirm ? (event) => event.preventDefault() : null;
|
||||
}
|
||||
|
||||
// with render_debug.uncapped, the most frames between two of the display's refreshes. it's the highest fps that shows,
|
||||
// 960 on a 60 hz display, and what the gpu can be behind by
|
||||
const UNCAPPED_FRAMES_PER_REFRESH = 16;
|
||||
|
||||
class ClientLoop {
|
||||
running = false;
|
||||
last_time = 0;
|
||||
client: Client | undefined;
|
||||
screen: GuiScreen | undefined;
|
||||
|
||||
frame_count = 0;
|
||||
last_fps_time = 0;
|
||||
|
||||
start() {
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (!document.hidden) {
|
||||
this.last_time = performance.now();
|
||||
}
|
||||
});
|
||||
|
||||
this.#next_task.port1.onmessage = () => this.loop(performance.now());
|
||||
this.running = true;
|
||||
const now = performance.now();
|
||||
this.last_time = now;
|
||||
this.frame_count = 0;
|
||||
this.last_fps_time = this.last_time;
|
||||
requestAnimationFrame((time) => this.loop(time));
|
||||
}
|
||||
|
||||
stop() {
|
||||
this.running = false;
|
||||
}
|
||||
|
||||
show_screen(screen: GuiScreen) {
|
||||
this.screen?.on_close();
|
||||
this.client = undefined;
|
||||
confirm_leaving(false);
|
||||
this.screen = screen;
|
||||
InputManager.set_mouse_grabbed(false);
|
||||
}
|
||||
|
||||
play(connection: Connection) {
|
||||
const client = new Client(connection, (message) => this.show_screen(new DisconnectedScreen(message)));
|
||||
set_mods_client(client);
|
||||
client.chat.add("Connected to the server");
|
||||
this.screen?.on_close();
|
||||
this.screen = undefined;
|
||||
this.client = client;
|
||||
confirm_leaving(true);
|
||||
console.log("Game started");
|
||||
}
|
||||
|
||||
// with render_debug.uncapped: frames since the display last refreshed, and whether the next one waits for it
|
||||
#frames_this_refresh = 0;
|
||||
#waiting_for_refresh = false;
|
||||
#refresh_requested = false;
|
||||
#next_task = new MessageChannel();
|
||||
|
||||
// with the display's refresh, or with render_debug.uncapped right away, so frames aren't held to vsync and show what
|
||||
// they cost. up to UNCAPPED_FRAMES_PER_REFRESH, then it waits for the next refresh, which the browser holds back
|
||||
// while the gpu is behind, so frames the gpu can't keep up with don't pile up. the browser saying a frame is done
|
||||
// can't be waited on instead, firefox only says so every 100 ms when nothing else is sent to the gpu
|
||||
#next_frame() {
|
||||
if (!render_debug.uncapped) {
|
||||
requestAnimationFrame((time) => this.loop(time));
|
||||
return;
|
||||
}
|
||||
if (!this.#refresh_requested) {
|
||||
this.#refresh_requested = true;
|
||||
requestAnimationFrame(() => {
|
||||
this.#refresh_requested = false;
|
||||
this.#frames_this_refresh = 0;
|
||||
if (this.#waiting_for_refresh) {
|
||||
this.#waiting_for_refresh = false;
|
||||
this.loop(performance.now());
|
||||
}
|
||||
});
|
||||
}
|
||||
this.#frames_this_refresh += 1;
|
||||
if (this.#frames_this_refresh < UNCAPPED_FRAMES_PER_REFRESH) {
|
||||
// a task of its own, so input and the workers' messages get handled in between
|
||||
this.#next_task.port2.postMessage(null);
|
||||
} else {
|
||||
this.#waiting_for_refresh = true;
|
||||
}
|
||||
}
|
||||
|
||||
loop(time: number) {
|
||||
if (!this.running || is_stopped()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const delta = (time - this.last_time) / 1000;
|
||||
|
||||
profiler.begin_frame();
|
||||
profiler.section("begin frame", begin_drawing);
|
||||
clear_background(0.69, 0.8, 1, 1.0);
|
||||
if (this.client) {
|
||||
this.client.run_frame(delta);
|
||||
} else if (this.screen) {
|
||||
this.screen.on_tick(delta);
|
||||
this.screen.on_render();
|
||||
}
|
||||
profiler.section("submit", end_drawing);
|
||||
profiler.end_frame();
|
||||
|
||||
this.frame_count += 1;
|
||||
const now = performance.now();
|
||||
if (now - this.last_fps_time >= 1000) {
|
||||
const fps = (this.frame_count * 1000) / (now - this.last_fps_time);
|
||||
console.log(`FPS: ${fps.toFixed(2)}`);
|
||||
this.frame_count = 0;
|
||||
this.last_fps_time = now;
|
||||
}
|
||||
|
||||
InputManager.update();
|
||||
|
||||
this.last_time = time;
|
||||
this.#next_frame();
|
||||
}
|
||||
}
|
||||
|
||||
// a server's blocks, items and scripts can't be taken back out once loaded, so a failure after that point
|
||||
// can't go back to the title screen to try again, the page has to start over
|
||||
class FailedAfterLoadingMods extends Error {}
|
||||
|
||||
// the game only runs against a server, it owns the world and everything in it. see docs/modding/networking/index.md
|
||||
async function join_server(address: ServerAddress, name: string, status: (text: string) => void): Promise<Connection> {
|
||||
const { socket, welcome } = await connect(address, name);
|
||||
console.log(`Connected to ${address.ws_url}`);
|
||||
|
||||
let loaded_mods = false;
|
||||
try {
|
||||
if (address.cross_origin && !is_trusted(address, welcome)) {
|
||||
status("Waiting for you to accept the server's mods...");
|
||||
if (!await confirm_mods(address, welcome)) {
|
||||
throw new HandshakeError(`You didn't join ${address.base.host}`);
|
||||
}
|
||||
remember_trust(address, welcome);
|
||||
}
|
||||
|
||||
// textures, blocks and items all come from the server's mods, so this happens before anything else
|
||||
status("Downloading the server's mods...");
|
||||
const mods = await download_mods(welcome.mods, address.base);
|
||||
const textures = await engine_textures();
|
||||
const texture_json = new Map<string, TextureJson>();
|
||||
for (const mod of mods) {
|
||||
for (const [id, png] of mod.textures) textures.set(id, png);
|
||||
for (const [id, json] of mod.texture_json ?? []) texture_json.set(id, json);
|
||||
}
|
||||
const atlas = await build_atlas(textures, texture_json);
|
||||
loaded_mods = true;
|
||||
const atlas_texture = load_texture(atlas.image);
|
||||
set_texture_animations(atlas_texture.tex, device.queue, atlas.animated);
|
||||
AssetManager.instance.assets["cubi:textures"] = atlas_texture;
|
||||
AssetManager.instance.assets["cubi:textures_info"] = atlas.regions;
|
||||
await load_client_mods(welcome.mods, mods);
|
||||
console.log(`Mods: ${welcome.mods.map((mod) => `${mod.id} ${mod.version}`).join(", ") || "none"}`);
|
||||
|
||||
status("Joining...");
|
||||
const joined = await join(socket, new Options().render_distance);
|
||||
return new Connection(socket, welcome, joined);
|
||||
} catch (e) {
|
||||
socket.close();
|
||||
const message = error_message(e);
|
||||
throw loaded_mods ? new FailedAfterLoadingMods(message) : new HandshakeError(message);
|
||||
}
|
||||
}
|
||||
|
||||
function error_message(e: unknown) {
|
||||
if (e instanceof HandshakeError) {
|
||||
return e.message;
|
||||
}
|
||||
if (e instanceof ModLoadError) {
|
||||
return `Couldn't load the server's mods: ${e.message}`;
|
||||
}
|
||||
return `Something went wrong joining the server: ${e instanceof Error ? e.message : e}`;
|
||||
}
|
||||
set_platform(browser_platform);
|
||||
|
||||
const game_canvas = document.getElementById("game") as HTMLCanvasElement;
|
||||
if (!game_canvas) {
|
||||
@@ -232,40 +25,12 @@ try {
|
||||
throw e;
|
||||
}
|
||||
|
||||
InputManager.initialize(game_canvas);
|
||||
listen_to_page(game_canvas);
|
||||
// waits for the first click or key, which the title screen gets
|
||||
sounds.set_output(new WebAudioOutput());
|
||||
self.addEventListener("resize", resize_canvas);
|
||||
resize_canvas();
|
||||
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
|
||||
const fit_page = () => resize_canvas(self.innerWidth, self.innerHeight);
|
||||
self.addEventListener("resize", fit_page);
|
||||
fit_page();
|
||||
game_canvas.addEventListener("contextmenu", (event) => event.preventDefault());
|
||||
|
||||
AssetManager.instance.load("cubi:assets_text", "/assets/ASSETS.md");
|
||||
|
||||
AssetManager.instance.load("cubi:skin", "/assets/sprites/skin_template.png");
|
||||
AssetManager.instance.load("cubi:gui", "/assets/sprites/gui.png");
|
||||
|
||||
AssetManager.instance.load("cubi:m6x11", "/assets/fonts/m6x11.png");
|
||||
AssetManager.instance.load("cubi:m6x11_fnt", "/assets/fonts/m6x11.fnt");
|
||||
|
||||
await AssetManager.instance.load_all();
|
||||
|
||||
init_font();
|
||||
|
||||
const loop = new ClientLoop();
|
||||
const join_game: JoinServer = async (address, name, status) => {
|
||||
let connection: Connection;
|
||||
try {
|
||||
connection = await join_server(address, name, status);
|
||||
} catch (e) {
|
||||
if (e instanceof FailedAfterLoadingMods) {
|
||||
loop.show_screen(new DisconnectedScreen(e.message));
|
||||
return;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
loop.play(connection);
|
||||
};
|
||||
loop.show_screen(
|
||||
in_desktop_app() ? new MainMenuScreen((screen) => loop.show_screen(screen), join_game) : new TitleScreen(join_game),
|
||||
);
|
||||
loop.start();
|
||||
await start_client();
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import { canvas, draw_rect, draw_text, measure_text } from "../renderer/mod.ts";
|
||||
import { GuiScreen } from "../gui/gui_screen.ts";
|
||||
import { credit_sections } from "../gui/credits_screen.ts";
|
||||
import { Button, ListBox, TEXT_SCALE } from "../gui/widgets.ts";
|
||||
|
||||
const MAX_WIDTH = 1200;
|
||||
const MARGIN = 32;
|
||||
const TOP = 90;
|
||||
const BUTTON_WIDTH = 200;
|
||||
const BUTTON_HEIGHT = 48;
|
||||
// the list's own padding around its text
|
||||
const TEXT_PADDING = 24;
|
||||
|
||||
// the credits in the desktop app, drawn in the window with the markdown as it's written, since there's no browser to
|
||||
// show it as a page
|
||||
export class TextCreditsScreen extends GuiScreen {
|
||||
#list = new ListBox(0, 0, () => {});
|
||||
#back: Button;
|
||||
// what the lines were wrapped for
|
||||
#wrapped_width = 0;
|
||||
|
||||
constructor(on_back: () => void) {
|
||||
super();
|
||||
this.#back = new Button("Back", BUTTON_WIDTH, BUTTON_HEIGHT, on_back);
|
||||
}
|
||||
|
||||
on_tick(_delta: number): void {
|
||||
const list = this.#list;
|
||||
list.width = Math.min(MAX_WIDTH, canvas.width - MARGIN * 2);
|
||||
list.height = Math.max(BUTTON_HEIGHT, canvas.height - TOP - BUTTON_HEIGHT - MARGIN * 2);
|
||||
list.x = (canvas.width - list.width) / 2;
|
||||
list.y = TOP;
|
||||
if (list.width !== this.#wrapped_width) {
|
||||
this.#wrapped_width = list.width;
|
||||
list.rows = credit_lines(list.width - TEXT_PADDING).map((text) => ({ text }));
|
||||
}
|
||||
this.#back.x = (canvas.width - BUTTON_WIDTH) / 2;
|
||||
this.#back.y = list.y + list.height + MARGIN;
|
||||
list.handle_input();
|
||||
this.#back.handle_input();
|
||||
}
|
||||
|
||||
on_render(): void {
|
||||
draw_rect(0, 0, canvas.width, canvas.height, [0, 0, 0, 0.6]);
|
||||
const scale = TEXT_SCALE * 2;
|
||||
draw_text("Credits", (canvas.width - measure_text("Credits", scale)) / 2, TOP / 2 - 12, scale);
|
||||
this.#list.render();
|
||||
this.#back.render();
|
||||
}
|
||||
|
||||
on_close(): void {}
|
||||
}
|
||||
|
||||
// every section's heading and text, wrapped at spaces to width pixels
|
||||
function credit_lines(width: number): string[] {
|
||||
const lines: string[] = [];
|
||||
for (const { heading, text } of credit_sections()) {
|
||||
lines.push(heading, "");
|
||||
for (const line of text.split("\n")) {
|
||||
let current = "";
|
||||
for (const word of line.split(" ")) {
|
||||
const next = current ? `${current} ${word}` : word;
|
||||
if (current && measure_text(next, TEXT_SCALE) > width) {
|
||||
lines.push(current);
|
||||
current = word;
|
||||
} else {
|
||||
current = next;
|
||||
}
|
||||
}
|
||||
lines.push(current);
|
||||
}
|
||||
lines.push("");
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// the desktop app's client: a deno worker drawing into the app's window with webgpu, see desktop/native.ts. the
|
||||
// window sends what the player does (messages.ts), and does what needs the os, like grabbing the mouse. the browser's
|
||||
// client starts at ../main.ts
|
||||
import { type Platform, set_platform } from "../platform.ts";
|
||||
import { InputManager } from "../input_manager.ts";
|
||||
import { init_window, resize_canvas } from "../renderer/mod.ts";
|
||||
import { show_fatal_error } from "../fatal.ts";
|
||||
import { start_client } from "../client_loop.ts";
|
||||
import { TextCreditsScreen } from "./credits_screen.ts";
|
||||
import type { ClientMessage, WindowMessage } from "./messages.ts";
|
||||
|
||||
const post = (message: ClientMessage) => self.postMessage(message);
|
||||
|
||||
// what the game asked for, the window does it
|
||||
let grabbed = false;
|
||||
let focused = true;
|
||||
// the window let go of the mouse while the game had it, see Platform.take_lost_mouse
|
||||
let lost_mouse = false;
|
||||
|
||||
// frames are each a task of their own, so input, the network and the workers' messages get handled in between.
|
||||
// waiting for the display's refresh happens while drawing, the window's surface holds back frames the display can't
|
||||
// show yet. a timer, not a MessageChannel like the browser's: deno handles a channel's messages before timers,
|
||||
// fetches and the gpu's callbacks, so frames one after another through one would hold those back
|
||||
let shown = true;
|
||||
let next_frame: ((time: number) => void) | undefined;
|
||||
let frame_waiting = false;
|
||||
const shown_listeners: (() => void)[] = [];
|
||||
|
||||
function run_frame() {
|
||||
frame_waiting = false;
|
||||
const frame = next_frame;
|
||||
next_frame = undefined;
|
||||
frame?.(performance.now());
|
||||
}
|
||||
|
||||
function request_frame(frame: (time: number) => void) {
|
||||
next_frame = frame;
|
||||
// a hidden window gets no frames, drawing to it could wait until it's shown again
|
||||
if (shown) wait_for_frame();
|
||||
}
|
||||
|
||||
function wait_for_frame() {
|
||||
if (frame_waiting) return;
|
||||
frame_waiting = true;
|
||||
setTimeout(run_frame, 0);
|
||||
}
|
||||
|
||||
function set_shown(now_shown: boolean) {
|
||||
if (shown === now_shown) return;
|
||||
shown = now_shown;
|
||||
if (!shown) return;
|
||||
for (const listener of shown_listeners) listener();
|
||||
if (next_frame) wait_for_frame();
|
||||
}
|
||||
|
||||
// what was asked of the window, by id, waiting for its answer
|
||||
let next_id = 0;
|
||||
const asking = new Map<number, (answer: string | boolean) => void>();
|
||||
|
||||
function ask<T extends string | boolean>(question: (id: number) => ClientMessage): Promise<T> {
|
||||
const id = next_id++;
|
||||
post(question(id));
|
||||
return new Promise((resolve) => asking.set(id, resolve as (answer: string | boolean) => void));
|
||||
}
|
||||
|
||||
function native_platform(page: URL, stored: Record<string, string>): Platform {
|
||||
const storage = new Map(Object.entries(stored));
|
||||
return {
|
||||
page,
|
||||
restart(url) {
|
||||
post({ type: "restart", page: url.href });
|
||||
},
|
||||
request_frame,
|
||||
on_shown(listener) {
|
||||
shown_listeners.push(listener);
|
||||
},
|
||||
// kept by the window, which saves it with the app's data
|
||||
storage: {
|
||||
getItem: (key) => storage.get(key) ?? null,
|
||||
setItem(key, value) {
|
||||
storage.set(key, value);
|
||||
post({ type: "store", key, value });
|
||||
},
|
||||
},
|
||||
// the window saves the world when it closes
|
||||
confirm_leaving() {},
|
||||
show_fatal_error(message) {
|
||||
post({ type: "fatal", message });
|
||||
},
|
||||
confirm_mods(address, welcome) {
|
||||
const mods = welcome.mods.map((mod) => {
|
||||
// it can change anything about the game, not just add to it
|
||||
const access = mod.engine_access ? ", changes the engine" : "";
|
||||
return `• ${mod.name} ${mod.version} (${mod.id}${access})`;
|
||||
});
|
||||
const text = "This server runs these mods in the game. They can do anything the game can, including " +
|
||||
`reading what it saved. Only join servers you trust.\n\n${mods.join("\n")}`;
|
||||
const title = `Join ${address.base.host}?`;
|
||||
return ask((id) => ({ type: "ask", id, title, text, yes: "Join", no: "Cancel" }));
|
||||
},
|
||||
credits_screen: (on_back) => new TextCreditsScreen(on_back),
|
||||
read_clipboard: () => ask((id) => ({ type: "read_clipboard", id })),
|
||||
write_clipboard(text) {
|
||||
post({ type: "write_clipboard", text });
|
||||
return Promise.resolve();
|
||||
},
|
||||
set_mouse_grabbed(grab) {
|
||||
if (grab === grabbed) return;
|
||||
grabbed = grab;
|
||||
// it's no longer where it was, see InputManager.move_cursor
|
||||
if (grab) {
|
||||
InputManager.mouse_x = -1;
|
||||
InputManager.mouse_y = -1;
|
||||
}
|
||||
post({ type: "grab", grab });
|
||||
},
|
||||
is_mouse_grabbed: () => grabbed && focused,
|
||||
take_lost_mouse() {
|
||||
const lost = lost_mouse;
|
||||
lost_mouse = false;
|
||||
return lost;
|
||||
},
|
||||
toggle_fullscreen() {
|
||||
post({ type: "fullscreen" });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function start(message: Extract<WindowMessage, { type: "start" }>) {
|
||||
set_platform(native_platform(new URL(message.page), message.storage));
|
||||
const { surface: handles, width, height } = message;
|
||||
const surface = new Deno.UnsafeWindowSurface({
|
||||
system: handles.system,
|
||||
windowHandle: Deno.UnsafePointer.create(handles.window),
|
||||
displayHandle: Deno.UnsafePointer.create(handles.display),
|
||||
width,
|
||||
height,
|
||||
});
|
||||
// pointers to the window were all that needed ffi. mods run in here too, they don't get it
|
||||
await Deno.permissions.revoke({ name: "ffi" });
|
||||
try {
|
||||
await init_window(surface);
|
||||
} catch (e) {
|
||||
show_fatal_error(e instanceof Error ? e.message : String(e));
|
||||
throw e;
|
||||
}
|
||||
resize_canvas(width, height);
|
||||
await start_client();
|
||||
}
|
||||
|
||||
self.onmessage = (event: MessageEvent<WindowMessage>) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "start":
|
||||
start(message);
|
||||
break;
|
||||
case "resize":
|
||||
resize_canvas(message.width, message.height);
|
||||
break;
|
||||
case "key":
|
||||
if (message.down) InputManager.key_down(message.code, message.key, message.shortcut);
|
||||
else InputManager.key_up(message.code);
|
||||
break;
|
||||
case "text":
|
||||
InputManager.type_text(message.text);
|
||||
break;
|
||||
case "button":
|
||||
if (message.down) InputManager.mouse_down(message.button);
|
||||
else InputManager.mouse_up(message.button);
|
||||
break;
|
||||
case "cursor":
|
||||
InputManager.move_cursor(message.x, message.y);
|
||||
break;
|
||||
case "look":
|
||||
if (grabbed) InputManager.look(message.x, message.y);
|
||||
break;
|
||||
case "scroll":
|
||||
InputManager.scroll(message.amount);
|
||||
break;
|
||||
case "focus":
|
||||
focused = message.focused;
|
||||
if (focused) break;
|
||||
InputManager.release_all();
|
||||
// the window let go of it, the game asks again once it wants it
|
||||
if (grabbed) {
|
||||
lost_mouse = true;
|
||||
grabbed = false;
|
||||
post({ type: "grab", grab: false });
|
||||
}
|
||||
break;
|
||||
case "shown":
|
||||
set_shown(message.shown);
|
||||
break;
|
||||
case "clipboard":
|
||||
asking.get(message.id)?.(message.text);
|
||||
asking.delete(message.id);
|
||||
break;
|
||||
case "answer":
|
||||
asking.get(message.id)?.(message.yes);
|
||||
asking.delete(message.id);
|
||||
break;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,55 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// what the desktop app's window (desktop/native.ts, on deno's main thread) and the client running in a worker (see
|
||||
// main.ts here) tell each other. the window has the os's events and the client draws into it
|
||||
|
||||
// the window's surface, for deno's UnsafeWindowSurface. handles are pointers' addresses, pointers can't be posted
|
||||
export interface SurfaceHandles {
|
||||
system: "cocoa" | "win32" | "x11" | "wayland";
|
||||
window: bigint;
|
||||
display: bigint;
|
||||
}
|
||||
|
||||
export type WindowMessage =
|
||||
| {
|
||||
type: "start";
|
||||
page: string;
|
||||
surface: SurfaceHandles;
|
||||
width: number;
|
||||
height: number;
|
||||
// what the client saved, see NativePlatform's storage
|
||||
storage: Record<string, string>;
|
||||
}
|
||||
// in pixels, what's drawn to is this big now
|
||||
| { type: "resize"; width: number; height: number }
|
||||
// code like a KeyboardEvent's, key the letter for a shortcut (see InputManager.key_down), "" otherwise
|
||||
| { type: "key"; down: boolean; code: string; key: string; shortcut: boolean }
|
||||
| { type: "text"; text: string }
|
||||
// buttons numbered like the dom's
|
||||
| { type: "button"; down: boolean; button: number }
|
||||
// the cursor, in pixels from the window's top left
|
||||
| { type: "cursor"; x: number; y: number }
|
||||
// the grabbed mouse moved
|
||||
| { type: "look"; x: number; y: number }
|
||||
// down is positive, about 100 for a notch, like the dom's
|
||||
| { type: "scroll"; amount: number }
|
||||
// the window lost or got focus, losing it lets go of the mouse
|
||||
| { type: "focus"; focused: boolean }
|
||||
// whether the window can be seen
|
||||
| { type: "shown"; shown: boolean }
|
||||
// answers, by the id they were asked with
|
||||
| { type: "clipboard"; id: number; text: string }
|
||||
| { type: "answer"; id: number; yes: boolean };
|
||||
|
||||
export type ClientMessage =
|
||||
| { type: "grab"; grab: boolean }
|
||||
| { type: "fullscreen" }
|
||||
// start the client over at page, see Platform.restart
|
||||
| { type: "restart"; page: string }
|
||||
| { type: "fatal"; message: string }
|
||||
// a question with a yes and a no, answered with "answer"
|
||||
| { type: "ask"; id: number; title: string; text: string; yes: string; no: string }
|
||||
| { type: "read_clipboard"; id: number }
|
||||
| { type: "write_clipboard"; text: string }
|
||||
| { type: "store"; key: string; value: string };
|
||||
+2
-1
@@ -5,6 +5,7 @@ import { ClientMessage, EntityInfo, MenuSlotInfo, PlayerInfo, ServerMessage } fr
|
||||
import type { ModListing } from "@/common/mod_loader.ts";
|
||||
import { WorldShape } from "@/common/world_shape.ts";
|
||||
import type { Join, ServerSocket, Welcome } from "./handshake.ts";
|
||||
import { platform } from "./platform.ts";
|
||||
|
||||
export class Connection {
|
||||
#server: ServerSocket;
|
||||
@@ -59,5 +60,5 @@ export class Connection {
|
||||
|
||||
// what the name field starts as, from ?name=
|
||||
export function default_player_name(): string {
|
||||
return new URLSearchParams(location.search).get("name") ?? "";
|
||||
return platform.page.searchParams.get("name") ?? "";
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// what the client needs from where it runs: a browser page (browser_platform.ts), or the desktop app's window, where
|
||||
// it runs in deno with no browser (native/). the entry point sets it before anything else runs
|
||||
import type { ServerAddress, Welcome } from "./handshake.ts";
|
||||
import type { GuiScreen } from "./gui/gui_screen.ts";
|
||||
|
||||
export interface Platform {
|
||||
// the page's address. its query has the options (?server=, ?name=, ?singleplayer), and the client's own files
|
||||
// (/assets/) and the desktop app's requests (/desktop/) are relative to it
|
||||
page: URL;
|
||||
// starts the client over at url, like loading the page again. a server's mods can't be taken back out once
|
||||
// they're loaded, so leaving a server does this
|
||||
restart(url: URL): void;
|
||||
// calls frame once it's time for the next frame, with the time like performance.now()
|
||||
request_frame(frame: (time: number) => void): void;
|
||||
// calls shown when the game can be seen again after being hidden, there are no frames meanwhile
|
||||
on_shown(shown: () => void): void;
|
||||
// what's remembered from one time to the next, like the servers whose mods the player trusts. it can throw, like a
|
||||
// browser's in a private window
|
||||
storage: Pick<Storage, "getItem" | "setItem">;
|
||||
// while playing, leaving asks first
|
||||
confirm_leaving(confirm: boolean): void;
|
||||
// replaces the game with a message, for when it can't go on
|
||||
show_fatal_error(message: string): void;
|
||||
// asks before running the mods of a server that isn't the page's own, see docs/modding/concepts/security.md.
|
||||
// resolves with whether the player wants to join
|
||||
confirm_mods(address: ServerAddress, welcome: Welcome): Promise<boolean>;
|
||||
// who made what: the engine's assets/ASSETS.md, then each loaded mod's credits file
|
||||
credits_screen(on_back: () => void): GuiScreen;
|
||||
read_clipboard(): Promise<string>;
|
||||
write_clipboard(text: string): Promise<void>;
|
||||
// while the mouse is grabbed it turns the camera and there's no cursor
|
||||
set_mouse_grabbed(grab: boolean): void;
|
||||
is_mouse_grabbed(): boolean;
|
||||
// whether the mouse was let go by something other than the game since the last call, like switching windows
|
||||
take_lost_mouse(): boolean;
|
||||
toggle_fullscreen(): void;
|
||||
}
|
||||
|
||||
export let platform: Platform;
|
||||
|
||||
export function set_platform(chosen: Platform) {
|
||||
platform = chosen;
|
||||
}
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// png decoding, for textures, skins and the gui. the desktop app's client runs without a browser, so it has no image
|
||||
// decoding of its own, and both clients decoding the same way keeps them alike. pixels come out as stored: no color
|
||||
// profile or gamma is applied, like an editor that ignores them
|
||||
import { unzlibSync } from "fflate";
|
||||
|
||||
// rgba, 8 bits a channel, not premultiplied, row by row from the top
|
||||
export interface Pixels {
|
||||
width: number;
|
||||
height: number;
|
||||
data: Uint8ClampedArray<ArrayBuffer>;
|
||||
}
|
||||
|
||||
const SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10];
|
||||
|
||||
// by color type: gray, rgb, palette, gray and alpha, rgba
|
||||
const CHANNELS: Record<number, number> = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 };
|
||||
|
||||
// the 7 passes of an interlaced image: the first pixel's x and y, and the steps between pixels
|
||||
const ADAM7 = [
|
||||
[0, 0, 8, 8],
|
||||
[4, 0, 8, 8],
|
||||
[0, 4, 4, 8],
|
||||
[2, 0, 4, 4],
|
||||
[0, 2, 2, 4],
|
||||
[1, 0, 2, 2],
|
||||
[0, 1, 1, 2],
|
||||
];
|
||||
|
||||
// throws for anything that isn't a png
|
||||
export function decode_png(bytes: Uint8Array): Pixels {
|
||||
if (bytes.length < 8 || SIGNATURE.some((byte, i) => bytes[i] !== byte)) throw new Error("Not a png");
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
|
||||
let width = 0;
|
||||
let height = 0;
|
||||
let depth = 0;
|
||||
let color_type = -1;
|
||||
let interlaced = false;
|
||||
let palette: Uint8Array | undefined;
|
||||
// the alpha of each palette entry, or the one gray or rgb value that's see-through
|
||||
let transparency: Uint8Array | undefined;
|
||||
const compressed: Uint8Array[] = [];
|
||||
|
||||
let pos = 8;
|
||||
while (pos + 8 <= bytes.length) {
|
||||
const length = view.getUint32(pos);
|
||||
const type = String.fromCharCode(...bytes.subarray(pos + 4, pos + 8));
|
||||
const start = pos + 8;
|
||||
const data = bytes.subarray(start, start + length);
|
||||
pos = start + length + 4;
|
||||
if (type === "IHDR") {
|
||||
width = view.getUint32(start);
|
||||
height = view.getUint32(start + 4);
|
||||
depth = data[8];
|
||||
color_type = data[9];
|
||||
interlaced = data[12] === 1;
|
||||
} else if (type === "PLTE") {
|
||||
palette = data;
|
||||
} else if (type === "tRNS") {
|
||||
transparency = data;
|
||||
} else if (type === "IDAT") {
|
||||
compressed.push(data);
|
||||
} else if (type === "IEND") {
|
||||
break;
|
||||
}
|
||||
}
|
||||
const channels = CHANNELS[color_type];
|
||||
if (!channels || !width || !height || ![1, 2, 4, 8, 16].includes(depth)) throw new Error("Not a png");
|
||||
if (color_type === 3 && !palette) throw new Error("A palette png without a palette");
|
||||
|
||||
const raw = unzlibSync(concat(compressed));
|
||||
const pixels = new Uint8ClampedArray(width * height * 4);
|
||||
const bits_per_pixel = channels * depth;
|
||||
// filters work on whole bytes, a pixel's or 1 for pixels smaller than a byte
|
||||
const filter_step = Math.max(1, bits_per_pixel >> 3);
|
||||
// a sample at depth, scaled to 0-255
|
||||
const max = (1 << depth) - 1;
|
||||
const sample = (line: Uint8Array, index: number) => {
|
||||
if (depth === 8) return line[index];
|
||||
if (depth === 16) return (line[index * 2] << 8) | line[index * 2 + 1];
|
||||
const bit = index * depth;
|
||||
return (line[bit >> 3] >> (8 - depth - (bit & 7))) & max;
|
||||
};
|
||||
const to_byte = (value: number) => depth === 16 ? value >> 8 : depth === 8 ? value : Math.round(value * 255 / max);
|
||||
const see_through = (value: number, channel: number) =>
|
||||
(transparency![channel * 2] << 8 | transparency![channel * 2 + 1]) === value;
|
||||
|
||||
let offset = 0;
|
||||
for (const [first_x, first_y, step_x, step_y] of interlaced ? ADAM7 : [[0, 0, 1, 1]]) {
|
||||
const pass_width = Math.ceil((width - first_x) / step_x);
|
||||
const pass_height = Math.ceil((height - first_y) / step_y);
|
||||
if (pass_width <= 0 || pass_height <= 0) continue;
|
||||
const stride = Math.ceil(pass_width * bits_per_pixel / 8);
|
||||
let previous = new Uint8Array(stride);
|
||||
for (let y = 0; y < pass_height; y++) {
|
||||
if (offset + 1 + stride > raw.length) throw new Error("A png with too little image data");
|
||||
const line = raw.slice(offset + 1, offset + 1 + stride);
|
||||
unfilter(raw[offset], line, previous, filter_step);
|
||||
offset += 1 + stride;
|
||||
previous = line;
|
||||
|
||||
for (let x = 0; x < pass_width; x++) {
|
||||
const out = ((first_y + y * step_y) * width + first_x + x * step_x) * 4;
|
||||
const s = x * channels;
|
||||
if (color_type === 3) {
|
||||
const entry = sample(line, x);
|
||||
pixels[out] = palette![entry * 3];
|
||||
pixels[out + 1] = palette![entry * 3 + 1];
|
||||
pixels[out + 2] = palette![entry * 3 + 2];
|
||||
pixels[out + 3] = transparency && entry < transparency.length ? transparency[entry] : 255;
|
||||
} else if (color_type === 0 || color_type === 4) {
|
||||
const gray = sample(line, s);
|
||||
pixels[out] = pixels[out + 1] = pixels[out + 2] = to_byte(gray);
|
||||
pixels[out + 3] = color_type === 4
|
||||
? to_byte(sample(line, s + 1))
|
||||
: transparency && see_through(gray, 0)
|
||||
? 0
|
||||
: 255;
|
||||
} else {
|
||||
const [r, g, b] = [sample(line, s), sample(line, s + 1), sample(line, s + 2)];
|
||||
pixels[out] = to_byte(r);
|
||||
pixels[out + 1] = to_byte(g);
|
||||
pixels[out + 2] = to_byte(b);
|
||||
pixels[out + 3] = color_type === 6
|
||||
? to_byte(sample(line, s + 3))
|
||||
: transparency && see_through(r, 0) && see_through(g, 1) && see_through(b, 2)
|
||||
? 0
|
||||
: 255;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return { width, height, data: pixels };
|
||||
}
|
||||
|
||||
// undoes a line's filter in place, previous is the line above it, already undone
|
||||
function unfilter(filter: number, line: Uint8Array, previous: Uint8Array, step: number) {
|
||||
switch (filter) {
|
||||
case 0:
|
||||
return;
|
||||
case 1:
|
||||
for (let i = step; i < line.length; i++) line[i] += line[i - step];
|
||||
return;
|
||||
case 2:
|
||||
for (let i = 0; i < line.length; i++) line[i] += previous[i];
|
||||
return;
|
||||
case 3:
|
||||
for (let i = 0; i < line.length; i++) line[i] += ((i >= step ? line[i - step] : 0) + previous[i]) >> 1;
|
||||
return;
|
||||
case 4:
|
||||
for (let i = 0; i < line.length; i++) {
|
||||
const left = i >= step ? line[i - step] : 0;
|
||||
const up = previous[i];
|
||||
const up_left = i >= step ? previous[i - step] : 0;
|
||||
const p = left + up - up_left;
|
||||
const [pa, pb, pc] = [Math.abs(p - left), Math.abs(p - up), Math.abs(p - up_left)];
|
||||
line[i] += pa <= pb && pa <= pc ? left : pb <= pc ? up : up_left;
|
||||
}
|
||||
return;
|
||||
default:
|
||||
throw new Error("A png with an unknown filter");
|
||||
}
|
||||
}
|
||||
|
||||
function concat(parts: Uint8Array[]) {
|
||||
const all = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
|
||||
let at = 0;
|
||||
for (const part of parts) {
|
||||
all.set(part, at);
|
||||
at += part.length;
|
||||
}
|
||||
return all;
|
||||
}
|
||||
+30
-11
@@ -7,8 +7,20 @@ import type { RenderLayer } from "@/common/everything_registry.ts";
|
||||
import { TERRAIN_VERTEX_BYTES } from "../workers/chunk_messages.ts";
|
||||
import { GpuTimer } from "./gpu_timing.ts";
|
||||
|
||||
// what frames are drawn on: the page's canvas, or the desktop app's window (deno's UnsafeWindowSurface). setting
|
||||
// width and height resizes it, like a canvas
|
||||
export interface DrawSurface {
|
||||
width: number;
|
||||
height: number;
|
||||
getContext(id: "webgpu"): unknown;
|
||||
// shows what was drawn, the window's needs it after every frame, a canvas does it by itself
|
||||
present?(): void;
|
||||
// a canvas is shown scaled when its size is fixed, see set_canvas_size
|
||||
style?: { width: string; height: string };
|
||||
}
|
||||
|
||||
export let device: GPUDevice;
|
||||
export let canvas: HTMLCanvasElement;
|
||||
export let canvas: DrawSurface;
|
||||
|
||||
const MAX_SPRITES = 100000;
|
||||
const VERTS_PER_SPRITE = 6;
|
||||
@@ -120,6 +132,8 @@ export let gpu_timer: GpuTimer | undefined;
|
||||
export let adapter_info: GPUAdapterInfo | undefined;
|
||||
// see set_canvas_size
|
||||
let fixed_canvas_size: { width: number; height: number } | undefined;
|
||||
// the space frames are shown in, the page's or the window's, see resize_canvas
|
||||
let view_size = { width: 1800, height: 900 };
|
||||
let resize_pending = false;
|
||||
// what the passes starting now are timed as
|
||||
let gpu_label = "other";
|
||||
@@ -287,10 +301,10 @@ fn fs_translucent(in: VertexOut) -> @location(0) vec4<f32> {
|
||||
}
|
||||
`;
|
||||
|
||||
export async function init_window(canvas_element: HTMLCanvasElement) {
|
||||
canvas = canvas_element;
|
||||
canvas.width = 1800;
|
||||
canvas.height = 900;
|
||||
export async function init_window(surface: DrawSurface) {
|
||||
canvas = surface;
|
||||
canvas.width = view_size.width;
|
||||
canvas.height = view_size.height;
|
||||
|
||||
if (!navigator.gpu) {
|
||||
throw new Error("WebGPU not supported");
|
||||
@@ -413,6 +427,7 @@ export function end_drawing() {
|
||||
gpu_timer?.resolve(encoder!);
|
||||
device.queue.submit([encoder!.finish()]);
|
||||
encoder = undefined;
|
||||
canvas.present?.();
|
||||
gpu_timer?.read();
|
||||
|
||||
for (const buffer of pending_destroy) {
|
||||
@@ -695,19 +710,23 @@ export function destroy_buffer(buffer: GPUBuffer) {
|
||||
}
|
||||
}
|
||||
|
||||
export function resize_canvas() {
|
||||
const width = fixed_canvas_size?.width ?? self.innerWidth;
|
||||
const height = fixed_canvas_size?.height ?? self.innerHeight;
|
||||
// the space frames are shown in changed to view_width × view_height, or the fixed size did
|
||||
export function resize_canvas(view_width = view_size.width, view_height = view_size.height) {
|
||||
view_size = { width: view_width, height: view_height };
|
||||
const width = fixed_canvas_size?.width ?? view_width;
|
||||
const height = fixed_canvas_size?.height ?? view_height;
|
||||
// a fixed size is shown as big as it fits in the window
|
||||
const scale = Math.min(self.innerWidth / width, self.innerHeight / height);
|
||||
const scale = Math.min(view_width / width, view_height / height);
|
||||
|
||||
if (canvas.width !== width || canvas.height !== height) {
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
// render targets get recreated at the start of the next frame
|
||||
}
|
||||
canvas.style.width = width * scale + "px";
|
||||
canvas.style.height = height * scale + "px";
|
||||
if (canvas.style) {
|
||||
canvas.style.width = width * scale + "px";
|
||||
canvas.style.height = height * scale + "px";
|
||||
}
|
||||
}
|
||||
|
||||
// frames are drawn at this size whatever the window's, like the benchmark's, or at the window's again when it's
|
||||
|
||||
@@ -3,10 +3,11 @@
|
||||
|
||||
import { create_texture, device, push_quad, push_quad_vertices, use_texture } from "./core.ts";
|
||||
import { Texture } from "./types.ts";
|
||||
import type { Pixels } from "../png.ts";
|
||||
|
||||
export function load_texture(image: HTMLImageElement | ImageBitmap): Texture {
|
||||
export function load_texture(image: Pixels): Texture {
|
||||
const texture = create_texture(image.width, image.height);
|
||||
device.queue.copyExternalImageToTexture({ source: image }, { texture }, [image.width, image.height]);
|
||||
device.queue.writeTexture({ texture }, image.data, { bytesPerRow: image.width * 4 }, [image.width, image.height]);
|
||||
|
||||
return {
|
||||
tex: texture,
|
||||
|
||||
+6
-11
@@ -2,19 +2,14 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import { load_texture, type Texture } from "./renderer/mod.ts";
|
||||
import { decode_png } from "./png.ts";
|
||||
|
||||
// a player's skin as the server sends it (a base64 64x64 png), undefined when it can't be decoded
|
||||
export async function decode_skin(skin: string): Promise<Texture | undefined> {
|
||||
// a player's skin as the server sends it (a base64 64x64 png), undefined when it can't be decoded. pixels are as
|
||||
// stored, so pngs with a color profile look the same as in an editor that ignores it
|
||||
export function decode_skin(skin: string): Texture | undefined {
|
||||
try {
|
||||
const bytes = Uint8Array.from(atob(skin), (char) => char.charCodeAt(0));
|
||||
// as stored, so pngs with a color profile look the same as in an editor that ignores it, like minecraft
|
||||
const image = await createImageBitmap(new Blob([bytes], { type: "image/png" }), {
|
||||
colorSpaceConversion: "none",
|
||||
premultiplyAlpha: "none",
|
||||
});
|
||||
const texture = image.width === 64 && image.height === 64 ? load_texture(image) : undefined;
|
||||
image.close();
|
||||
return texture;
|
||||
const image = decode_png(Uint8Array.from(atob(skin), (char) => char.charCodeAt(0)));
|
||||
return image.width === 64 && image.height === 64 ? load_texture(image) : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user