// 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"; // 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 { 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(); 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}`; } const game_canvas = document.getElementById("game") as HTMLCanvasElement; if (!game_canvas) { throw Error("Canvas was not found"); } try { await init_window(game_canvas); } catch (e) { show_fatal_error(e instanceof Error ? e.message : String(e)); throw e; } InputManager.initialize(game_canvas); self.addEventListener("resize", resize_canvas); resize_canvas(); 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();