Move away from browser as a main plataform

This commit is contained in:
2026-11-22 21:38:12 -03:00
parent cbd662dc2a
commit 90dd86b336
12 changed files with 166 additions and 150 deletions
+22 -1
View File
@@ -16,7 +16,8 @@ Always ask before making even the simplest models, unless it's coming from ports
## Layout ## Layout
- `server/`: the game server, world, saves and server-side game logic - `server/`: the game server, world, saves and server-side game logic
- `client/`: the browser client: rendering, meshing and lighting workers, UI - `client/`: the client: rendering, meshing and lighting workers, UI. `client/native/` runs it in the desktop app
- `desktop/`: the desktop app: its window, sound, singleplayer and client updates (see "Desktop first")
- `common/`: code shared by both, including world generation, the protocol and the modding API (`common/mod_api/`) - `common/`: code shared by both, including world generation, the protocol and the modding API (`common/mod_api/`)
- `mods/`: mods, with JSON data (blocks, items, recipes, worldgen, tags), textures and TypeScript scripts - `mods/`: mods, with JSON data (blocks, items, recipes, worldgen, tags), textures and TypeScript scripts
- `docs/`: modding docs and `docs/modding_plan.md` - `docs/`: modding docs and `docs/modding_plan.md`
@@ -33,6 +34,8 @@ deno test -A tests/door_test.ts # one test file, prefer this while working
deno task check-mods # validate and typecheck every mod in mods/ deno task check-mods # validate and typecheck every mod in mods/
deno task build # pack mods and build the client, then keeps rebuilding on changes deno task build # pack mods and build the client, then keeps rebuilding on changes
deno task server # start a server with the mods from the last build deno task server # start a server with the mods from the last build
deno task desktop # run the desktop app with what the last build made
deno task compile [linux] [windows] # build the desktop app's executables into dist/
deno fmt # format (tabs, 120 columns), applies to JSON too deno fmt # format (tabs, 120 columns), applies to JSON too
deno task import KIND IN --output OUT # convert a java mod's resources, see tools/importer.ts deno task import KIND IN --output OUT # convert a java mod's resources, see tools/importer.ts
``` ```
@@ -50,6 +53,24 @@ engine, since other mods would hit the same wall. See "The Engine and the Base G
When changing the modding API, update the docs that cover it: `MODS.md` and `docs/modding/`, which follows the layout of When changing the modding API, update the docs that cover it: `MODS.md` and `docs/modding/`, which follows the layout of
`ports/neoforge-docs`. `ports/neoforge-docs`.
## Desktop first
The desktop app is the main target and the browser a secondary one, so build and try new features in the desktop app
first. The app (`desktop/`) is an SDL3 window that the client draws into with Deno's WebGPU, running in a Deno worker
(`client/native/`), with sound through OpenAL Soft and a singleplayer server of its own.
- The client keeps using web APIs: WebGPU, Web Audio, fetch, WebSocket. Where Deno doesn't have one, polyfill the part
the game uses, like `client/native/web_audio.ts` does over OpenAL, instead of writing engine code only the desktop app
can run.
- What has to differ between the two goes through `Platform` (`client/platform.ts`), which `client/browser_platform.ts`
and `client/native/main.ts` implement, rather than checks for the DOM in shared code.
- Keep the browser working, but a browser limitation doesn't block a feature: it can be missing or simpler there.
- The client worker runs servers' mods, so it only gets the network and reading its own files, and gives up FFI once the
window's surface exists. Don't widen its permissions.
- The Windows build ships SDL3 and OpenAL Soft from `desktop/windows/`: unmodified files from their tagged releases,
with their licenses and where they came from in `credits.txt` there, which the app shows in its credits. Update it
along with the DLLs.
## Conventions ## Conventions
- Classes are PascalCase, everything else is snake_case: functions, variables, fields, files and ids. - Classes are PascalCase, everything else is snake_case: functions, variables, fields, files and ids.
-2
View File
@@ -4,7 +4,6 @@
// the client in a browser page, see platform.ts // the client in a browser page, see platform.ts
import type { Platform } from "./platform.ts"; import type { Platform } from "./platform.ts";
import { render_debug } from "./renderer/mod.ts"; import { render_debug } from "./renderer/mod.ts";
import { confirm_mods } from "./confirm_mods.ts";
import { CreditsScreen } from "./gui/credits_screen.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"; import { is_mouse_grabbed, set_mouse_grabbed, take_lost_pointer_lock, toggle_fullscreen } from "./browser_input.ts";
@@ -103,7 +102,6 @@ export const browser_platform: Platform = {
self.onbeforeunload = confirm ? (event) => event.preventDefault() : null; self.onbeforeunload = confirm ? (event) => event.preventDefault() : null;
}, },
show_fatal_error, show_fatal_error,
confirm_mods,
credits_screen: (on_back) => new CreditsScreen(on_back), credits_screen: (on_back) => new CreditsScreen(on_back),
read_clipboard: () => read_clipboard: () =>
navigator.clipboard ? navigator.clipboard.readText() : Promise.reject(new Error("No clipboard")), navigator.clipboard ? navigator.clipboard.readText() : Promise.reject(new Error("No clipboard")),
+29 -5
View File
@@ -6,7 +6,7 @@ import { Client } from "./client.ts";
import { InputManager } from "./input_manager.ts"; import { InputManager } from "./input_manager.ts";
import { Connection } from "./network.ts"; import { Connection } from "./network.ts";
import { Options } from "./options.ts"; import { Options } from "./options.ts";
import { connect, HandshakeError, is_trusted, join, remember_trust, ServerAddress } from "./handshake.ts"; import { connect, HandshakeError, is_trusted, join, remember_trust, ServerAddress, type Welcome } from "./handshake.ts";
import { build_atlas, engine_textures } from "./atlas.ts"; import { build_atlas, engine_textures } from "./atlas.ts";
import { set_texture_animations } from "./texture_animations.ts"; import { set_texture_animations } from "./texture_animations.ts";
import type { TextureJson } from "@/common/texture_animation.ts"; import type { TextureJson } from "@/common/texture_animation.ts";
@@ -18,6 +18,7 @@ import type { GuiScreen } from "./gui/gui_screen.ts";
import { in_desktop_app, type JoinServer, TitleScreen } from "./gui/title_screen.ts"; import { in_desktop_app, type JoinServer, TitleScreen } from "./gui/title_screen.ts";
import { MainMenuScreen } from "./gui/main_menu.ts"; import { MainMenuScreen } from "./gui/main_menu.ts";
import { DisconnectedScreen } from "./gui/disconnected_screen.ts"; import { DisconnectedScreen } from "./gui/disconnected_screen.ts";
import { ConfirmModsScreen } from "./gui/confirm_mods_screen.ts";
import { profiler } from "./profiler.ts"; import { profiler } from "./profiler.ts";
import { platform } from "./platform.ts"; import { platform } from "./platform.ts";
@@ -27,6 +28,8 @@ class ClientLoop {
last_time = 0; last_time = 0;
client: Client | undefined; client: Client | undefined;
screen: GuiScreen | undefined; screen: GuiScreen | undefined;
// over the screen, it gets the input while it's there
overlay: GuiScreen | undefined;
frame_count = 0; frame_count = 0;
last_fps_time = 0; last_fps_time = 0;
@@ -56,6 +59,16 @@ class ClientLoop {
InputManager.set_mouse_grabbed(false); InputManager.set_mouse_grabbed(false);
} }
// shown over whatever screen is joining, see ConfirmModsScreen
confirm_mods(address: ServerAddress, welcome: Welcome): Promise<boolean> {
return new Promise((resolve) => {
this.overlay = new ConfirmModsScreen(address, welcome, (join) => {
this.overlay = undefined;
resolve(join);
});
});
}
play(connection: Connection) { play(connection: Connection) {
const client = new Client(connection, (message) => this.show_screen(new DisconnectedScreen(message))); const client = new Client(connection, (message) => this.show_screen(new DisconnectedScreen(message)));
set_mods_client(client); set_mods_client(client);
@@ -80,8 +93,9 @@ class ClientLoop {
if (this.client) { if (this.client) {
this.client.run_frame(delta); this.client.run_frame(delta);
} else if (this.screen) { } else if (this.screen) {
this.screen.on_tick(delta); (this.overlay ?? this.screen).on_tick(delta);
this.screen.on_render(); this.screen.on_render();
this.overlay?.on_render();
} }
profiler.section("submit", end_drawing); profiler.section("submit", end_drawing);
profiler.end_frame(); profiler.end_frame();
@@ -107,7 +121,12 @@ class ClientLoop {
class FailedAfterLoadingMods extends Error {} 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 // 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> { async function join_server(
address: ServerAddress,
name: string,
status: (text: string) => void,
confirm_mods: (address: ServerAddress, welcome: Welcome) => Promise<boolean>,
): Promise<Connection> {
const { socket, welcome } = await connect(address, name); const { socket, welcome } = await connect(address, name);
console.log(`Connected to ${address.ws_url}`); console.log(`Connected to ${address.ws_url}`);
@@ -115,7 +134,7 @@ async function join_server(address: ServerAddress, name: string, status: (text:
try { try {
if (address.cross_origin && !is_trusted(address, welcome)) { if (address.cross_origin && !is_trusted(address, welcome)) {
status("Waiting for you to accept the server's mods..."); status("Waiting for you to accept the server's mods...");
if (!await platform.confirm_mods(address, welcome)) { if (!await confirm_mods(address, welcome)) {
throw new HandshakeError(`You didn't join ${address.base.host}`); throw new HandshakeError(`You didn't join ${address.base.host}`);
} }
remember_trust(address, welcome); remember_trust(address, welcome);
@@ -178,7 +197,12 @@ export async function start_client() {
const join_game: JoinServer = async (address, name, status) => { const join_game: JoinServer = async (address, name, status) => {
let connection: Connection; let connection: Connection;
try { try {
connection = await join_server(address, name, status); connection = await join_server(
address,
name,
status,
(address, welcome) => loop.confirm_mods(address, welcome),
);
} catch (e) { } catch (e) {
if (e instanceof FailedAfterLoadingMods) { if (e instanceof FailedAfterLoadingMods) {
loop.show_screen(new DisconnectedScreen(e.message)); loop.show_screen(new DisconnectedScreen(e.message));
-55
View File
@@ -1,55 +0,0 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
import type { ServerAddress, Welcome } from "./handshake.ts";
// asks before running a server's mods when the page came from somewhere else, see docs/modding/concepts/security.md.
// resolves with whether the player wants to join
export function confirm_mods(address: ServerAddress, welcome: Welcome): Promise<boolean> {
return new Promise((resolve) => {
const overlay = document.createElement("div");
overlay.style.cssText =
"position:fixed;inset:0;display:flex;align-items:center;justify-content:center;padding:16px;" +
"background:rgba(0,0,0,0.85);color:white;font:16px system-ui,sans-serif;";
const panel = document.createElement("div");
panel.style.cssText = "max-width:480px;display:flex;flex-direction:column;gap:12px;";
const title = document.createElement("div");
title.style.cssText = "font-size:20px;";
title.textContent = `Join ${address.base.host}?`;
const warning = document.createElement("div");
warning.style.cssText = "opacity:0.8;";
warning.textContent = "This server runs these mods in your browser. They can do anything this page can, " +
"including reading what it saved. Only join servers you trust.";
const list = document.createElement("ul");
list.style.cssText = "margin:0;padding-left:20px;";
for (const mod of welcome.mods) {
const item = document.createElement("li");
// it can change anything about the game, not just add to it
const access = mod.engine_access ? ", changes the engine" : "";
item.textContent = `${mod.name} ${mod.version} (${mod.id}${access})`;
list.append(item);
}
const buttons = document.createElement("div");
buttons.style.cssText = "display:flex;gap:8px;justify-content:flex-end;";
const button = (label: string, answer: boolean) => {
const element = document.createElement("button");
element.textContent = label;
element.style.cssText = "font:inherit;padding:6px 16px;cursor:pointer;";
element.addEventListener("click", () => {
overlay.remove();
resolve(answer);
});
return element;
};
buttons.append(button("Cancel", false), button("Join", true));
panel.append(title, warning, list, buttons);
overlay.append(panel);
document.body.append(overlay);
});
}
+89
View File
@@ -0,0 +1,89 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
import { InputManager } from "@/client/input_manager.ts";
import { canvas, draw_rect, draw_text, measure_text } from "@/client/renderer/mod.ts";
import type { ServerAddress, Welcome } from "@/client/handshake.ts";
import { GuiScreen } from "./gui_screen.ts";
import { Button, LIST_ROW_HEIGHT, ListBox, TEXT_HEIGHT, TEXT_SCALE, wrap_text } from "./widgets.ts";
const MAX_WIDTH = 720;
const MARGIN = 32;
const GAP = 20;
const BUTTON_HEIGHT = 48;
const TITLE_SCALE = 4;
const LINE_HEIGHT = TEXT_HEIGHT * TEXT_SCALE + 6;
const WARNING = "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.";
// asks before running the mods of a server that isn't the page's own, see docs/modding/concepts/security.md. it's
// shown over the screen that's joining, and answer gets whether the player wants to join
export class ConfirmModsScreen extends GuiScreen {
#title: string;
#warning: string[] = [];
// what the warning was wrapped for
#wrapped_width = 0;
#list = new ListBox(0, 0, () => {});
#cancel: Button;
#join: Button;
constructor(address: ServerAddress, welcome: Welcome, answer: (join: boolean) => void) {
super();
this.#title = `Join ${address.base.host}?`;
this.#list.rows = 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 { text: `${mod.name} ${mod.version} (${mod.id}${access})` };
});
this.#cancel = new Button("Cancel", 0, BUTTON_HEIGHT, () => answer(false));
this.#join = new Button("Join", 0, BUTTON_HEIGHT, () => answer(true));
}
on_tick(_delta: number): void {
const width = Math.min(MAX_WIDTH, canvas.width - MARGIN * 2);
if (width !== this.#wrapped_width) {
this.#wrapped_width = width;
this.#warning = wrap_text(WARNING, width);
}
// the list gets what room the title, the warning and the buttons leave
const above = this.#warning_y + this.#warning.length * LINE_HEIGHT + GAP;
const room = canvas.height - MARGIN * 2 - above - GAP - BUTTON_HEIGHT;
const list = this.#list;
list.width = width;
list.height = Math.max(LIST_ROW_HEIGHT, Math.min(list.rows.length * LIST_ROW_HEIGHT, room));
this.x = (canvas.width - width) / 2;
this.y = Math.max(MARGIN, (canvas.height - above - list.height - GAP - BUTTON_HEIGHT) / 2);
list.x = this.x;
list.y = this.y + above;
const half = (width - GAP) / 2;
for (const [i, button] of [this.#cancel, this.#join].entries()) {
button.width = half;
button.x = this.x + i * (half + GAP);
button.y = list.y + list.height + GAP;
}
// only a click joins, never a key pressed for something else, like the enter that joined the server
if (InputManager.is_key_pressed("Escape")) return this.#cancel.on_press();
list.handle_input();
this.#cancel.handle_input();
this.#join.handle_input();
}
on_render(): void {
draw_rect(0, 0, canvas.width, canvas.height, [0, 0, 0, 0.85]);
draw_text(this.#title, (canvas.width - measure_text(this.#title, TITLE_SCALE)) / 2, this.y, TITLE_SCALE);
for (const [i, line] of this.#warning.entries()) {
draw_text(line, this.x, this.y + this.#warning_y + i * LINE_HEIGHT, TEXT_SCALE, [0.85, 0.85, 0.85, 1]);
}
this.#list.render();
this.#cancel.render();
this.#join.render();
}
on_close(): void {}
// below the title, from the screen's top
get #warning_y() {
return TEXT_HEIGHT * TITLE_SCALE + GAP;
}
}
+20 -1
View File
@@ -347,7 +347,7 @@ export class EditBox {
} }
} }
const LIST_ROW_HEIGHT = 40; export const LIST_ROW_HEIGHT = 40;
const CHECK_SIZE = 20; const CHECK_SIZE = 20;
// rows of text that scroll with the mouse wheel, like minecraft's selection lists. a row can have a box ticked or not // rows of text that scroll with the mouse wheel, like minecraft's selection lists. a row can have a box ticked or not
@@ -421,3 +421,22 @@ export class ListBox {
} }
} }
} }
// text split into lines no wider than width pixels at TEXT_SCALE, at spaces and at its own line breaks
export function wrap_text(text: string, width: number): string[] {
const lines: string[] = [];
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);
}
return lines;
}
+2 -20
View File
@@ -4,7 +4,7 @@
import { canvas, draw_rect, draw_text, measure_text } from "../renderer/mod.ts"; import { canvas, draw_rect, draw_text, measure_text } from "../renderer/mod.ts";
import { GuiScreen } from "../gui/gui_screen.ts"; import { GuiScreen } from "../gui/gui_screen.ts";
import { credit_sections } from "../gui/credits_screen.ts"; import { credit_sections } from "../gui/credits_screen.ts";
import { Button, ListBox, TEXT_SCALE } from "../gui/widgets.ts"; import { Button, ListBox, TEXT_SCALE, wrap_text } from "../gui/widgets.ts";
const MAX_WIDTH = 1200; const MAX_WIDTH = 1200;
const MARGIN = 32; const MARGIN = 32;
@@ -58,23 +58,5 @@ export class TextCreditsScreen extends GuiScreen {
// every section's heading and text, wrapped at spaces to width pixels // every section's heading and text, wrapped at spaces to width pixels
function credit_lines(sections: { heading: string; text: string }[], width: number): string[] { function credit_lines(sections: { heading: string; text: string }[], width: number): string[] {
const lines: string[] = []; return sections.flatMap(({ heading, text }) => [heading, "", ...wrap_text(text, width), ""]);
for (const { heading, text } of 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;
} }
+3 -18
View File
@@ -61,12 +61,12 @@ function set_shown(now_shown: boolean) {
// what was asked of the window, by id, waiting for its answer // what was asked of the window, by id, waiting for its answer
let next_id = 0; let next_id = 0;
const asking = new Map<number, (answer: string | boolean) => void>(); const asking = new Map<number, (answer: string) => void>();
function ask<T extends string | boolean>(question: (id: number) => ClientMessage): Promise<T> { function ask(question: (id: number) => ClientMessage): Promise<string> {
const id = next_id++; const id = next_id++;
post(question(id)); post(question(id));
return new Promise((resolve) => asking.set(id, resolve as (answer: string | boolean) => void)); return new Promise((resolve) => asking.set(id, resolve));
} }
function native_platform(page: URL, stored: Record<string, string>, credits: string | undefined): Platform { function native_platform(page: URL, stored: Record<string, string>, credits: string | undefined): Platform {
@@ -93,17 +93,6 @@ function native_platform(page: URL, stored: Record<string, string>, credits: str
show_fatal_error(message) { show_fatal_error(message) {
post({ type: "fatal", 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, credits), credits_screen: (on_back) => new TextCreditsScreen(on_back, credits),
read_clipboard: () => ask((id) => ({ type: "read_clipboard", id })), read_clipboard: () => ask((id) => ({ type: "read_clipboard", id })),
write_clipboard(text) { write_clipboard(text) {
@@ -205,10 +194,6 @@ self.onmessage = (event: MessageEvent<WindowMessage>) => {
asking.get(message.id)?.(message.text); asking.get(message.id)?.(message.text);
asking.delete(message.id); asking.delete(message.id);
break; break;
case "answer":
asking.get(message.id)?.(message.yes);
asking.delete(message.id);
break;
case "audio_ended": case "audio_ended":
sources_ended(message.sources); sources_ended(message.sources);
break; break;
+1 -4
View File
@@ -43,9 +43,8 @@ export type WindowMessage =
| { type: "focus"; focused: boolean } | { type: "focus"; focused: boolean }
// whether the window can be seen // whether the window can be seen
| { type: "shown"; shown: boolean } | { type: "shown"; shown: boolean }
// answers, by the id they were asked with // the answer to read_clipboard, by the id it was asked with
| { type: "clipboard"; id: number; text: string } | { type: "clipboard"; id: number; text: string }
| { type: "answer"; id: number; yes: boolean }
// sources that played to their end, see web_audio.ts // sources that played to their end, see web_audio.ts
| { type: "audio_ended"; sources: number[] }; | { type: "audio_ended"; sources: number[] };
@@ -55,8 +54,6 @@ export type ClientMessage =
// start the client over at page, see Platform.restart // start the client over at page, see Platform.restart
| { type: "restart"; page: string } | { type: "restart"; page: string }
| { type: "fatal"; message: 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: "read_clipboard"; id: number }
| { type: "write_clipboard"; text: string } | { type: "write_clipboard"; text: string }
| { type: "store"; key: string; value: string } | { type: "store"; key: string; value: string }
-4
View File
@@ -3,7 +3,6 @@
// what the client needs from where it runs: a browser page (browser_platform.ts), or the desktop app's window, where // 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 // 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"; import type { GuiScreen } from "./gui/gui_screen.ts";
export interface Platform { export interface Platform {
@@ -24,9 +23,6 @@ export interface Platform {
confirm_leaving(confirm: boolean): void; confirm_leaving(confirm: boolean): void;
// replaces the game with a message, for when it can't go on // replaces the game with a message, for when it can't go on
show_fatal_error(message: string): void; 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 // who made what: the engine's assets/ASSETS.md, then each loaded mod's credits file
credits_screen(on_back: () => void): GuiScreen; credits_screen(on_back: () => void): GuiScreen;
read_clipboard(): Promise<string>; read_clipboard(): Promise<string>;
-8
View File
@@ -124,14 +124,6 @@ function handle(message: ClientMessage) {
game_window.show_error("bworld", message.message); game_window.show_error("bworld", message.message);
close(); close();
break; break;
case "ask":
game_window.set_grabbed(false);
send({
type: "answer",
id: message.id,
yes: game_window.ask(message.title, message.text, message.yes, message.no),
});
break;
case "read_clipboard": case "read_clipboard":
send({ type: "clipboard", id: message.id, text: game_window.read_clipboard() }); send({ type: "clipboard", id: message.id, text: game_window.read_clipboard() });
break; break;
-32
View File
@@ -31,16 +31,12 @@ const SYMBOLS = {
SDL_GetClipboardText: { parameters: [], result: "pointer" }, SDL_GetClipboardText: { parameters: [], result: "pointer" },
SDL_SetClipboardText: { parameters: ["buffer"], result: "bool" }, SDL_SetClipboardText: { parameters: ["buffer"], result: "bool" },
SDL_ShowSimpleMessageBox: { parameters: ["u32", "buffer", "buffer", "pointer"], result: "bool" }, SDL_ShowSimpleMessageBox: { parameters: ["u32", "buffer", "buffer", "pointer"], result: "bool" },
SDL_ShowMessageBox: { parameters: ["buffer", "buffer"], result: "bool" },
} as const; } as const;
const INIT_VIDEO = 0x20; const INIT_VIDEO = 0x20;
const WINDOW_FULLSCREEN = 0x1n; const WINDOW_FULLSCREEN = 0x1n;
const WINDOW_RESIZABLE = 0x20n; const WINDOW_RESIZABLE = 0x20n;
const MESSAGEBOX_ERROR = 0x10; const MESSAGEBOX_ERROR = 0x10;
const MESSAGEBOX_WARNING = 0x20;
const BUTTON_RETURNKEY_DEFAULT = 0x1;
const BUTTON_ESCAPEKEY_DEFAULT = 0x2;
const EVENT_QUIT = 0x100; const EVENT_QUIT = 0x100;
const EVENT_WINDOW_SHOWN = 0x202; const EVENT_WINDOW_SHOWN = 0x202;
@@ -227,34 +223,6 @@ export class SdlWindow {
this.#sdl.SDL_ShowSimpleMessageBox(MESSAGEBOX_ERROR, c_string(title), c_string(text), this.#window); this.#sdl.SDL_ShowSimpleMessageBox(MESSAGEBOX_ERROR, c_string(title), c_string(text), this.#window);
} }
// waits for the player to pick yes or no, no if the box can't be shown
ask(title: string, text: string, yes: string, no: string): boolean {
const [title_text, message, yes_text, no_text] = [title, text, yes, no].map(c_string);
const ptr = (buffer: Uint8Array<ArrayBuffer>) =>
BigInt(Deno.UnsafePointer.value(Deno.UnsafePointer.of(buffer)));
// SDL_MessageBoxButtonData: flags, id, text
const buttons = new ArrayBuffer(32);
const button_view = new DataView(buttons);
button_view.setUint32(0, BUTTON_ESCAPEKEY_DEFAULT, true);
button_view.setInt32(4, 0, true);
button_view.setBigUint64(8, ptr(no_text), true);
button_view.setUint32(16, BUTTON_RETURNKEY_DEFAULT, true);
button_view.setInt32(20, 1, true);
button_view.setBigUint64(24, ptr(yes_text), true);
// SDL_MessageBoxData: flags, window, title, message, button count, buttons, colors
const data = new ArrayBuffer(56);
const data_view = new DataView(data);
data_view.setUint32(0, MESSAGEBOX_WARNING, true);
data_view.setBigUint64(8, BigInt(Deno.UnsafePointer.value(this.#window)), true);
data_view.setBigUint64(16, ptr(title_text), true);
data_view.setBigUint64(24, ptr(message), true);
data_view.setInt32(32, 2, true);
data_view.setBigUint64(40, ptr(new Uint8Array(buttons)), true);
const picked = new Int32Array([0]);
const shown = this.#sdl.SDL_ShowMessageBox(new Uint8Array(data), picked);
return shown && picked[0] === 1;
}
// everything that happened since the last call, as the client's messages. on_close is for the window being closed // everything that happened since the last call, as the client's messages. on_close is for the window being closed
poll(send: (message: WindowMessage) => void, on_close: () => void) { poll(send: (message: WindowMessage) => void, on_close: () => void) {
const sdl = this.#sdl; const sdl = this.#sdl;