diff --git a/build.ts b/build.ts index 65d1058..4941915 100644 --- a/build.ts +++ b/build.ts @@ -4,7 +4,8 @@ import { copy, walk } from "@std/fs"; import { relative } from "@std/path"; import { PROTOCOL_VERSION } from "./common/protocol.ts"; -import { CLIENT_MANIFEST, client_manifest, sha256 } from "./desktop/client_updates.ts"; +import { CLIENT_MANIFEST, client_manifest } from "./desktop/client_updates.ts"; +import { sha256 } from "./common/utils.ts"; import { createCanvas, loadImage } from "@gfx/canvas-wasm"; import { ENGINE_TEXTURE_DIR, load_and_check, load_order, LoadedMod } from "./tools/check_mods.ts"; import { pack_mod } from "./tools/pack_mod.ts"; diff --git a/client/debug_ui.ts b/client/debug_ui.ts index addf00d..5959386 100644 --- a/client/debug_ui.ts +++ b/client/debug_ui.ts @@ -3,7 +3,8 @@ import { point_inside_rec } from "$/common/utils.ts"; import { InputManager } from "$/client/input_manager.ts"; -import { begin_clip, draw_rect, draw_rect_stroke, draw_text, end_clip, measure_text } from "./renderer/mod.ts"; +import { TextInput } from "$/client/gui/widgets.ts"; +import { begin_clip, draw_rect, draw_rect_stroke, draw_text, end_clip } from "./renderer/mod.ts"; const HEADER_HEIGHT = 24; const RESIZE_SIZE = 12; @@ -21,20 +22,11 @@ interface WindowState { content_height: number; } -interface TextInputState { - value: string; - caret: number; - focused: boolean; - last_blink: number; - show_caret: boolean; - key_repeat_timer: number; -} - export class DebugUI { static windows = new Map(); static current_window: WindowState | undefined = undefined; - static text_inputs = new Map(); + static text_inputs = new Map(); static active_text_input: string | undefined = undefined; static open_sections = new Map(); @@ -324,15 +316,7 @@ export class DebugUI { let state = this.text_inputs.get(id); if (!state) { - // initial state - state = { - value, - caret: value.length, - focused: false, - last_blink: performance.now(), - show_caret: true, - key_repeat_timer: 0, - }; + state = new TextInput(value, Infinity); this.text_inputs.set(id, state); } // update on every call @@ -350,11 +334,9 @@ export class DebugUI { if (hovered && InputManager.is_mouse_pressed(0)) { InputManager.consume_mouse(0); this.active_text_input = id; - state.focused = true; - state.caret = value.length; + state.move_caret(value.length); } else if (InputManager.is_mouse_pressed(0) && !hovered) { if (this.active_text_input === id) { - state.focused = false; this.active_text_input = undefined; } } @@ -362,18 +344,7 @@ export class DebugUI { const is_active = this.active_text_input === id; if (is_active) { - this.#handle_text_editing(state); - } - - // overkill? - if (is_active) { - const now = performance.now(); - if (now - state.last_blink > 500) { - state.show_caret = !state.show_caret; - state.last_blink = now; - } - } else { - state.show_caret = false; + state.handle_keys(); } // draw box @@ -396,14 +367,14 @@ export class DebugUI { const text_x = x + 6; - draw_text(state.value, x + 6, y + 4); + if (is_active) { + state.draw_selection(text_x, y + 4, height - 8, 1); + } + draw_text(state.value, text_x, y + 4); // caret ! - if (is_active && state.show_caret) { - const before_text = state.value.substring(0, state.caret); - const caret_x = text_x + measure_text(before_text); - - draw_rect(caret_x, y + 4, 1, height - 4); + if (is_active && TextInput.caret_visible()) { + draw_rect(state.caret_x(text_x, 1), y + 4, 1, height - 4); } this.cursor_y += height + PADDING; @@ -459,60 +430,4 @@ export class DebugUI { // thumb draw_rect(x, thumb_y, scrollbar_width, thumb_height, [0x88 / 255, 0x88 / 255, 0x88 / 255, 1]); } - - static #handle_text_editing(state: TextInputState) { - const now = performance.now(); - const repeat_delay = 400; - const repeat_rate = 40; - - function allow_repeat(): boolean { - if (InputManager.is_key_pressed("Backspace")) { - state.key_repeat_timer = now; - return true; - } - - if (InputManager.is_key_down("Backspace")) { - if (now - state.key_repeat_timer > repeat_delay) { - state.key_repeat_timer = now - (repeat_delay - repeat_rate); - return true; - } - } - - return false; - } - - if (allow_repeat()) { - if (state.caret > 0) { - state.value = state.value.slice(0, state.caret - 1) + state.value.slice(state.caret); - state.caret -= 1; - } - } - - if (InputManager.is_key_pressed("Delete")) { - state.value = state.value.slice(0, state.caret) + state.value.slice(state.caret + 1); - } - - if (InputManager.is_key_pressed("ArrowLeft")) { - state.caret = Math.max(0, state.caret - 1); - } - - if (InputManager.is_key_pressed("ArrowRight")) { - state.caret = Math.min(state.value.length, state.caret + 1); - } - - if (InputManager.is_key_pressed("Home")) { - state.caret = 0; - } - - if (InputManager.is_key_pressed("End")) { - state.caret = state.value.length; - } - - const typed = InputManager.get_typed_characters(); - - for (const char of typed) { - state.value = state.value.slice(0, state.caret) + char + state.value.slice(state.caret); - state.caret += 1; - } - } } diff --git a/client/entity/remote_entity.ts b/client/entity/remote_entity.ts index 5f0bdb4..9a576cd 100644 --- a/client/entity/remote_entity.ts +++ b/client/entity/remote_entity.ts @@ -4,6 +4,7 @@ import type { EntityData, EntityEvent, EntityInfo } from "$/common/protocol.ts"; import type { EntityJson } from "$/common/mod_data.ts"; import { EverythingRegistry } from "$/common/everything_registry.ts"; +import { wrap_angle } from "$/common/utils.ts"; import type { ClientLevel } from "../level/client_level.ts"; import { Entity } from "./entity.ts"; @@ -88,10 +89,3 @@ export class RemoteEntity extends Entity { return this.swing_ticks === undefined ? 0 : Math.min(1, (this.swing_ticks + partial_tick) / SWING_TICKS); } } - -function wrap_angle(angle: number) { - angle %= Math.PI * 2; - if (angle >= Math.PI) angle -= Math.PI * 2; - if (angle < -Math.PI) angle += Math.PI * 2; - return angle; -} diff --git a/client/gui/mod_graphics.ts b/client/gui/mod_graphics.ts index f33216f..456fbc2 100644 --- a/client/gui/mod_graphics.ts +++ b/client/gui/mod_graphics.ts @@ -137,6 +137,26 @@ export class ModGraphics implements Graphics { ); } + progress( + empty: string, + full: string, + x: number, + y: number, + w: number, + h: number, + filled: number, + direction: "right" | "up" = "right", + ) { + // nothing filled for NaN too, like progress / max before there's a max + const done = filled > 0 ? Math.min(1, filled) : 0; + this.texture(empty, x, y, w, h); + if (direction === "right") { + this.texture(full, x, y, w * done, h, [0, 0, done, 1]); + } else { + this.texture(full, x, y + h * (1 - done), w, h * done, [0, 1 - done, 1, done]); + } + } + item(id: string, x: number, y: number, count = 1) { if (!EverythingRegistry.get("items", id)) throw new Error(`unknown item ${id}`); const stack = new ItemStack(id, count); diff --git a/client/renderer/core.ts b/client/renderer/core.ts index 39e792f..fbf9b69 100644 --- a/client/renderer/core.ts +++ b/client/renderer/core.ts @@ -567,6 +567,14 @@ export function set_current_texture(texture: GPUTexture) { current_texture = texture; } +// draws with texture from now on, flushing what was batched with another one first +export function use_texture(texture: GPUTexture) { + if (current_texture !== texture) { + flush_batch(); + current_texture = texture; + } +} + export function create_texture(width: number, height: number): GPUTexture { return device.createTexture({ size: [width, height], diff --git a/client/renderer/mod.ts b/client/renderer/mod.ts index 4256144..5aa2dd9 100644 --- a/client/renderer/mod.ts +++ b/client/renderer/mod.ts @@ -5,5 +5,4 @@ export * from "./core.ts"; export * from "./shapes.ts"; export * from "./textures.ts"; export * from "./text.ts"; -export * from "./models.ts"; export * from "./types.ts"; diff --git a/client/renderer/models.ts b/client/renderer/models.ts deleted file mode 100644 index c99ac92..0000000 --- a/client/renderer/models.ts +++ /dev/null @@ -1,262 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Paula Wisnievski -// SPDX-License-Identifier: AGPL-3.0-or-later - -import { push_vertex } from "./core.ts"; -import type { Texture } from "./types.ts"; - -const pad = 0.5; - -export function push_front_face( - texture: Texture, - x: number, - y: number, - z: number, - sx: number, - sy: number, - sw: number, - sh: number, - r = 1, - g = 1, - b = 1, - a = 1, -) { - const x2 = x + 1; - const y2 = y + 1; - const z2 = z + 1; - - const u0 = (sx + pad) / texture.width; - const v0 = (sy + pad) / texture.height; - const u1 = (sx + sw - pad) / texture.width; - const v1 = (sy + sh - pad) / texture.height; - - push_vertex(x, y, z2, u0, v1, r, g, b, a); - push_vertex(x2, y, z2, u1, v1, r, g, b, a); - push_vertex(x2, y2, z2, u1, v0, r, g, b, a); - - push_vertex(x, y, z2, u0, v1, r, g, b, a); - push_vertex(x2, y2, z2, u1, v0, r, g, b, a); - push_vertex(x, y2, z2, u0, v0, r, g, b, a); -} - -export function push_back_face( - texture: Texture, - x: number, - y: number, - z: number, - sx: number, - sy: number, - sw: number, - sh: number, - r = 1, - g = 1, - b = 1, - a = 1, -) { - const x2 = x + 1; - const y2 = y + 1; - - const u0 = (sx + pad) / texture.width; - const v0 = (sy + pad) / texture.height; - const u1 = (sx + sw - pad) / texture.width; - const v1 = (sy + sh - pad) / texture.height; - - push_vertex(x2, y, z, u0, v1, r, g, b, a); - push_vertex(x, y, z, u1, v1, r, g, b, a); - push_vertex(x, y2, z, u1, v0, r, g, b, a); - - push_vertex(x2, y, z, u0, v1, r, g, b, a); - push_vertex(x, y2, z, u1, v0, r, g, b, a); - push_vertex(x2, y2, z, u0, v0, r, g, b, a); -} - -export function push_left_face( - texture: Texture, - x: number, - y: number, - z: number, - sx: number, - sy: number, - sw: number, - sh: number, - r = 1, - g = 1, - b = 1, - a = 1, -) { - const y2 = y + 1; - const z2 = z + 1; - - const u0 = (sx + pad) / texture.width; - const v0 = (sy + pad) / texture.height; - const u1 = (sx + sw - pad) / texture.width; - const v1 = (sy + sh - pad) / texture.height; - - push_vertex(x, y, z, u0, v1, r, g, b, a); - push_vertex(x, y, z2, u1, v1, r, g, b, a); - push_vertex(x, y2, z2, u1, v0, r, g, b, a); - - push_vertex(x, y, z, u0, v1, r, g, b, a); - push_vertex(x, y2, z2, u1, v0, r, g, b, a); - push_vertex(x, y2, z, u0, v0, r, g, b, a); -} - -export function push_right_face( - texture: Texture, - x: number, - y: number, - z: number, - sx: number, - sy: number, - sw: number, - sh: number, - r = 1, - g = 1, - b = 1, - a = 1, -) { - const x2 = x + 1; - const y2 = y + 1; - const z2 = z + 1; - - const u0 = (sx + pad) / texture.width; - const v0 = (sy + pad) / texture.height; - const u1 = (sx + sw - pad) / texture.width; - const v1 = (sy + sh - pad) / texture.height; - - push_vertex(x2, y, z2, u0, v1, r, g, b, a); - push_vertex(x2, y, z, u1, v1, r, g, b, a); - push_vertex(x2, y2, z, u1, v0, r, g, b, a); - - push_vertex(x2, y, z2, u0, v1, r, g, b, a); - push_vertex(x2, y2, z, u1, v0, r, g, b, a); - push_vertex(x2, y2, z2, u0, v0, r, g, b, a); -} - -export function push_top_face( - texture: Texture, - x: number, - y: number, - z: number, - sx: number, - sy: number, - sw: number, - sh: number, - r = 1, - g = 1, - b = 1, - a = 1, -) { - const x2 = x + 1; - const z2 = z + 1; - const y2 = y + 1; - - const u0 = (sx + pad) / texture.width; - const v0 = (sy + pad) / texture.height; - const u1 = (sx + sw - pad) / texture.width; - const v1 = (sy + sh - pad) / texture.height; - - push_vertex(x, y2, z2, u0, v1, r, g, b, a); - push_vertex(x2, y2, z2, u1, v1, r, g, b, a); - push_vertex(x2, y2, z, u1, v0, r, g, b, a); - - push_vertex(x, y2, z2, u0, v1, r, g, b, a); - push_vertex(x2, y2, z, u1, v0, r, g, b, a); - push_vertex(x, y2, z, u0, v0, r, g, b, a); -} - -export function push_bottom_face( - texture: Texture, - x: number, - y: number, - z: number, - sx: number, - sy: number, - sw: number, - sh: number, - r = 1, - g = 1, - b = 1, - a = 1, -) { - const x2 = x + 1; - const z2 = z + 1; - - const u0 = (sx + pad) / texture.width; - const v0 = (sy + pad) / texture.height; - const u1 = (sx + sw - pad) / texture.width; - const v1 = (sy + sh - pad) / texture.height; - - push_vertex(x, y, z, u0, v1, r, g, b, a); - push_vertex(x2, y, z, u1, v1, r, g, b, a); - push_vertex(x2, y, z2, u1, v0, r, g, b, a); - - push_vertex(x, y, z, u0, v1, r, g, b, a); - push_vertex(x2, y, z2, u1, v0, r, g, b, a); - push_vertex(x, y, z2, u0, v0, r, g, b, a); -} - -// solid colored box, draw it with white_tex as the current texture -export function push_box( - x: number, - y: number, - z: number, - width: number, - height: number, - depth: number, - r = 1, - g = 1, - b = 1, - a = 1, -) { - const x2 = x + width; - const y2 = y + height; - const z2 = z + depth; - - // front - push_vertex(x, y, z2, 0, 1, r, g, b, a); - push_vertex(x2, y, z2, 1, 1, r, g, b, a); - push_vertex(x2, y2, z2, 1, 0, r, g, b, a); - push_vertex(x, y, z2, 0, 1, r, g, b, a); - push_vertex(x2, y2, z2, 1, 0, r, g, b, a); - push_vertex(x, y2, z2, 0, 0, r, g, b, a); - - // back - push_vertex(x2, y, z, 0, 1, r * 0.8, g * 0.8, b * 0.8, a); - push_vertex(x, y, z, 1, 1, r * 0.8, g * 0.8, b * 0.8, a); - push_vertex(x, y2, z, 1, 0, r * 0.8, g * 0.8, b * 0.8, a); - push_vertex(x2, y, z, 0, 1, r * 0.8, g * 0.8, b * 0.8, a); - push_vertex(x, y2, z, 1, 0, r * 0.8, g * 0.8, b * 0.8, a); - push_vertex(x2, y2, z, 0, 0, r * 0.8, g * 0.8, b * 0.8, a); - - // left - push_vertex(x, y, z, 0, 1, r * 0.9, g * 0.9, b * 0.9, a); - push_vertex(x, y, z2, 1, 1, r * 0.9, g * 0.9, b * 0.9, a); - push_vertex(x, y2, z2, 1, 0, r * 0.9, g * 0.9, b * 0.9, a); - push_vertex(x, y, z, 0, 1, r * 0.9, g * 0.9, b * 0.9, a); - push_vertex(x, y2, z2, 1, 0, r * 0.9, g * 0.9, b * 0.9, a); - push_vertex(x, y2, z, 0, 0, r * 0.9, g * 0.9, b * 0.9, a); - - // right - push_vertex(x2, y, z2, 0, 1, r * 0.9, g * 0.9, b * 0.9, a); - push_vertex(x2, y, z, 1, 1, r * 0.9, g * 0.9, b * 0.9, a); - push_vertex(x2, y2, z, 1, 0, r * 0.9, g * 0.9, b * 0.9, a); - push_vertex(x2, y, z2, 0, 1, r * 0.9, g * 0.9, b * 0.9, a); - push_vertex(x2, y2, z, 1, 0, r * 0.9, g * 0.9, b * 0.9, a); - push_vertex(x2, y2, z2, 0, 0, r * 0.9, g * 0.9, b * 0.9, a); - - // top - push_vertex(x, y2, z2, 0, 1, r, g, b, a); - push_vertex(x2, y2, z2, 1, 1, r, g, b, a); - push_vertex(x2, y2, z, 1, 0, r, g, b, a); - push_vertex(x, y2, z2, 0, 1, r, g, b, a); - push_vertex(x2, y2, z, 1, 0, r, g, b, a); - push_vertex(x, y2, z, 0, 0, r, g, b, a); - - // bottom - push_vertex(x, y, z, 0, 1, r * 0.6, g * 0.6, b * 0.6, a); - push_vertex(x2, y, z, 1, 1, r * 0.6, g * 0.6, b * 0.6, a); - push_vertex(x2, y, z2, 1, 0, r * 0.6, g * 0.6, b * 0.6, a); - push_vertex(x, y, z, 0, 1, r * 0.6, g * 0.6, b * 0.6, a); - push_vertex(x2, y, z2, 1, 0, r * 0.6, g * 0.6, b * 0.6, a); - push_vertex(x, y, z2, 0, 0, r * 0.6, g * 0.6, b * 0.6, a); -} diff --git a/client/renderer/shapes.ts b/client/renderer/shapes.ts index d041ffb..79a3486 100644 --- a/client/renderer/shapes.ts +++ b/client/renderer/shapes.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -import { flush_batch, get_current_texture, push_quad, push_vertex, set_current_texture, white_tex } from "./core.ts"; +import { push_quad, push_vertex, use_texture, white_tex } from "./core.ts"; export function draw_rect( x: number, @@ -10,10 +10,7 @@ export function draw_rect( h: number, color: [number, number, number, number] = [1, 1, 1, 1], ) { - if (get_current_texture() !== white_tex) { - flush_batch(); - set_current_texture(white_tex!); - } + use_texture(white_tex!); push_quad(x, y, w, h, 0, 0, 1, 1, color[0], color[1], color[2], color[3]); } @@ -89,9 +86,6 @@ export function draw_rect_3d( h: number, color: readonly number[] = [1, 1, 1, 1], ) { - if (get_current_texture() !== white_tex) { - flush_batch(); - set_current_texture(white_tex!); - } + use_texture(white_tex!); push_plane_quad(plane, x, y, w, h, 0, 0, 1, 1, color); } diff --git a/client/renderer/text.ts b/client/renderer/text.ts index 637be86..633323f 100644 --- a/client/renderer/text.ts +++ b/client/renderer/text.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later import { AssetManager } from "../assets.ts"; -import { flush_batch, get_current_texture, push_quad, set_current_texture } from "./core.ts"; +import { push_quad, use_texture } from "./core.ts"; import { type Plane3d, push_plane_quad } from "./shapes.ts"; import { FntChar, FntFont, Texture } from "./types.ts"; @@ -79,10 +79,7 @@ export function draw_text(str: string, x: number, y: number, scale: number = 1, return; } - if (get_current_texture() !== font_texture.tex) { - flush_batch(); - set_current_texture(font_texture.tex); - } + use_texture(font_texture.tex); for (const ch of str) { const glyph = font_fnt.chars[ch.charCodeAt(0)]; @@ -120,10 +117,7 @@ export function draw_text_3d( return; } - if (get_current_texture() !== font_texture.tex) { - flush_batch(); - set_current_texture(font_texture.tex); - } + use_texture(font_texture.tex); for (const ch of str) { const glyph = font_fnt.chars[ch.charCodeAt(0)]; diff --git a/client/renderer/textures.ts b/client/renderer/textures.ts index 1e1f4d8..a1bdd0a 100644 --- a/client/renderer/textures.ts +++ b/client/renderer/textures.ts @@ -1,15 +1,7 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -import { - create_texture, - device, - flush_batch, - get_current_texture, - push_quad, - push_quad_vertices, - set_current_texture, -} from "./core.ts"; +import { create_texture, device, push_quad, push_quad_vertices, use_texture } from "./core.ts"; import { Texture } from "./types.ts"; export function load_texture(image: HTMLImageElement | ImageBitmap): Texture { @@ -32,21 +24,7 @@ export function draw_texture( flip_x = false, flip_y = false, ) { - if (get_current_texture() !== texture.tex) { - flush_batch(); - set_current_texture(texture.tex); - } - - let u0 = 0, v0 = 0, u1 = 1, v1 = 1; - - if (flip_x) { - [u0, u1] = [u1, u0]; - } - if (flip_y) { - [v0, v1] = [v1, v0]; - } - - push_quad(x, y, w, h, u0, v0, u1, v1); + draw_texture_region(texture, 0, 0, texture.width, texture.height, x, y, w, h, flip_x, flip_y); } export function draw_texture_region( @@ -66,23 +44,8 @@ export function draw_texture_region( b = 1, a = 1, ) { - if (get_current_texture() !== texture.tex) { - flush_batch(); - set_current_texture(texture.tex); - } - - let u0 = sx / texture.width; - let v0 = sy / texture.height; - let u1 = (sx + sw) / texture.width; - let v1 = (sy + sh) / texture.height; - - if (flip_x) { - [u0, u1] = [u1, u0]; - } - if (flip_y) { - [v0, v1] = [v1, v0]; - } - + use_texture(texture.tex); + const [u0, v0, u1, v1] = region_uvs(texture, sx, sy, sw, sh, flip_x, flip_y); push_quad(dx, dy, dw, dh, u0, v0, u1, v1, r, g, b, a); } @@ -105,22 +68,8 @@ export function draw_texture_region_skewed( flip_x = false, flip_y = false, ) { - if (get_current_texture() !== texture.tex) { - flush_batch(); - set_current_texture(texture.tex); - } - - let u0 = sx / texture.width; - let v0 = sy / texture.height; - let u1 = (sx + sw) / texture.width; - let v1 = (sy + sh) / texture.height; - - if (flip_x) { - [u0, u1] = [u1, u0]; - } - if (flip_y) { - [v0, v1] = [v1, v0]; - } + use_texture(texture.tex); + const [u0, v0, u1, v1] = region_uvs(texture, sx, sy, sw, sh, flip_x, flip_y); const p0 = points[0]; const p1 = points[1]; @@ -146,3 +95,20 @@ export function draw_texture_region_skewed( a, ); } + +// the uvs of a region of texture given in pixels, swapped to flip it +function region_uvs( + texture: Texture, + sx: number, + sy: number, + sw: number, + sh: number, + flip_x: boolean, + flip_y: boolean, +) { + const u = [sx / texture.width, (sx + sw) / texture.width]; + const v = [sy / texture.height, (sy + sh) / texture.height]; + if (flip_x) u.reverse(); + if (flip_y) v.reverse(); + return [u[0], v[0], u[1], v[1]]; +} diff --git a/client/rendering/gui_player.ts b/client/rendering/gui_player.ts index 3f45c7a..ebaaa49 100644 --- a/client/rendering/gui_player.ts +++ b/client/rendering/gui_player.ts @@ -5,7 +5,7 @@ // facing out of the screen, the body turned a little toward the mouse and the head turned and tilted more, with what // they wear, like their curios. the gui has no depth buffer, so the faces are drawn back to front with the ones facing // away left out, like 3d items in slots -import { flush_batch, get_current_texture, push_vertex, set_current_texture, type Texture } from "../renderer/mod.ts"; +import { push_vertex, type Texture, use_texture } from "../renderer/mod.ts"; import type { ItemStack } from "$/common/inventory.ts"; import { AssetManager } from "../assets.ts"; import { rotation_around } from "./model_math.ts"; @@ -102,10 +102,7 @@ export function draw_gui_player( // blocks to skin pixels to the screen, y down const scale = 16 * pixel; for (const { vertices, texture } of faces) { - if (get_current_texture() !== texture.tex) { - flush_batch(); - set_current_texture(texture.tex); - } + use_texture(texture.tex); for (const [vx, vy, , u, v, r, g, b] of vertices) { push_vertex(x + vx * scale, feet_y - vy * scale, 0, u, v, r, g, b, 1); } diff --git a/client/rendering/hand_renderer.ts b/client/rendering/hand_renderer.ts index 7883aa9..d49ab6a 100644 --- a/client/rendering/hand_renderer.ts +++ b/client/rendering/hand_renderer.ts @@ -8,7 +8,14 @@ import { mat4, vec3 } from "gl-matrix"; import type { ItemStack } from "$/common/inventory.ts"; import { AssetManager } from "$/client/assets.ts"; import type { LocalPlayer } from "$/client/entity/local_player.ts"; -import { begin_view_model, end_mode_3d, flush_batch, set_current_texture, Texture } from "$/client/renderer/mod.ts"; +import { + begin_view_model, + end_mode_3d, + flush_batch, + set_current_texture, + Texture, + use_texture, +} from "$/client/renderer/mod.ts"; import { item_block, push_item } from "./item_renderer.ts"; import { push_cube, type Vec3 } from "./player_renderer.ts"; import { right_arm } from "./player_model.ts"; @@ -69,8 +76,7 @@ export class HandRenderer { push_cube(skin, arm, arm.overlay, arm.inflate, transform, tint); // what's worn on it goes over it, from the atlas if (player.worn.length > 0) { - flush_batch(); - set_current_texture(AssetManager.instance.get("bworld:textures").tex); + use_texture(AssetManager.instance.get("bworld:textures").tex); render_worn_arm(player, transform, tint); } } diff --git a/client/rendering/level_renderer.ts b/client/rendering/level_renderer.ts index 0058c6a..d34274d 100644 --- a/client/rendering/level_renderer.ts +++ b/client/rendering/level_renderer.ts @@ -25,6 +25,7 @@ import { push_vertex, set_current_texture, Texture, + use_texture, view_projection, white_tex, } from "$/client/renderer/mod.ts"; @@ -123,10 +124,7 @@ export class LevelRenderer { for (const entity of level.entities.values()) { if (entity !== camera_entity && entity instanceof RemotePlayer) { const skin = entity.skin ?? default_skin; - if (get_current_texture() !== skin.tex) { - flush_batch(); - set_current_texture(skin.tex); - } + use_texture(skin.tex); const tint = entity_tint(entity, partial_tick, entity.hurt_time > 0 ? HURT_TINT : undefined); const pose = player_pose(entity, partial_tick); render_player(skin, pose, tint); diff --git a/client/rendering/render_utils.ts b/client/rendering/render_utils.ts index 61e4d8e..c53ab5c 100644 --- a/client/rendering/render_utils.ts +++ b/client/rendering/render_utils.ts @@ -21,11 +21,9 @@ import { draw_text, draw_texture_region, draw_texture_region_skewed, - flush_batch, - get_current_texture, push_vertex, - set_current_texture, Texture, + use_texture, } from "$/client/renderer/mod.ts"; // the corners keep their size (times scale), the edges stretch along and the middle fills the rest, like minecraft's @@ -163,10 +161,7 @@ const ICON_VIEW = [-1, 1, -1]; // a block's item_model in a slot: its faces that face the viewer, back to front function draw_item_model(block_info: BlockRegistry, quads: BakedQuad[], x: number, y: number) { const atlas = AssetManager.instance.get("bworld:textures"); - if (get_current_texture() !== atlas.tex) { - flush_batch(); - set_current_texture(atlas.tex); - } + use_texture(atlas.tex); const project = item_projection(x, y); const toward_viewer = (p: number[]) => p[0] * ICON_VIEW[0] + p[1] * ICON_VIEW[1] + p[2] * ICON_VIEW[2]; const visible = quads diff --git a/common/loot.ts b/common/loot.ts index ca90219..b60d169 100644 --- a/common/loot.ts +++ b/common/loot.ts @@ -8,7 +8,7 @@ // see docs/modding/resources/loot_tables.md import { EverythingRegistry, type ItemRegistry } from "./everything_registry.ts"; import { list_matches, Tags } from "./tags.ts"; -import { TAG_ID_PATTERN } from "./mod_data.ts"; +import { is_object, TAG_ID_PATTERN } from "./mod_data.ts"; // a whole number, a random one from min to max, or the number of n tries at chance p that succeed, like minecraft's // constant, uniform and binomial number providers @@ -450,7 +450,3 @@ export function loot_references(table: LootTableJson) { } return refs; } - -function is_object(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value); -} diff --git a/common/mod_api/client.ts b/common/mod_api/client.ts index 61818b3..787d611 100644 --- a/common/mod_api/client.ts +++ b/common/mod_api/client.ts @@ -148,6 +148,17 @@ export interface Graphics { measure_text(text: string, scale?: number): number; // part is the part of the texture to draw, [u, v, width, height] from 0 to 1, like a progress bar's filled part texture(id: Id, x: number, y: number, w: number, h: number, part?: [number, number, number, number]): void; + // a progress bar: filled (0 to 1) of full drawn over empty, from the left, or from the bottom going "up" + progress( + empty: Id, + full: Id, + x: number, + y: number, + w: number, + h: number, + filled: number, + direction?: "right" | "up", + ): void; item(id: Id, x: number, y: number, count?: number): void; clip(x: number, y: number, w: number, h: number, draw: () => void): void; button(label: string, x: number, y: number, w: number, h: number): boolean; diff --git a/common/mod_check.ts b/common/mod_check.ts index d63575f..56bb64f 100644 --- a/common/mod_check.ts +++ b/common/mod_check.ts @@ -36,6 +36,7 @@ import { type WorldgenRefs, } from "./worldgen/data.ts"; import { feature_refs, type FeatureJson } from "./worldgen/features.ts"; +import type { ModData } from "./mod_loader.ts"; export interface ModReport { id: string; @@ -73,6 +74,29 @@ export interface LoadedMod { texture_json: Map; } +// what a mod's data files hold, as packed into its .bmod +export function mod_data(mod: LoadedMod): ModData { + return { + blocks: mod.blocks.map((b) => b.json), + models: mod.models.map((m) => m.json), + items: mod.items.map((i) => i.json), + recipes: mod.recipes.map((r) => r.json), + ores: mod.ores.map((o) => o.json), + spawns: mod.spawns.map((s) => s.json), + entities: mod.entities.map((e) => e.json), + entity_models: mod.entity_models.map((m) => m.json), + effects: mod.effects.map((e) => e.json), + tags: mod.tags.map((t) => t.json), + loot_tables: mod.loot_tables.map((t) => t.json), + biomes: mod.biomes.map((b) => b.json), + noises: mod.noises.map((n) => n.json), + density_functions: mod.density_functions.map((d) => d.json), + noise_settings: mod.noise_settings.map((n) => n.json), + biome_sources: mod.biome_sources.map((b) => b.json), + features: mod.features.map((f) => f.json), + }; +} + // dependencies before the mods that need them, otherwise alphabetical export function load_order(mods: LoadedMod[]): LoadedMod[] { const by_id = new Map(mods.map((mod) => [mod.id, mod])); diff --git a/common/mod_data.ts b/common/mod_data.ts index 0573526..99177ab 100644 --- a/common/mod_data.ts +++ b/common/mod_data.ts @@ -1236,6 +1236,7 @@ function validate_stack(value: unknown, field: string): Problems { return problems; } -function is_object(value: unknown): value is Record { +// a json object, not null or an array +export function is_object(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } diff --git a/common/texture_animation.ts b/common/texture_animation.ts index 4fc6540..718ce30 100644 --- a/common/texture_animation.ts +++ b/common/texture_animation.ts @@ -3,6 +3,8 @@ // animated textures, like minecraft's .png.mcmeta and in the same format: textures/.json next to // textures/.png says how to cut the png into frames and how long each one shows. see docs/modding/resources/textures.md +import { is_object } from "./mod_data.ts"; + export interface TextureJson { animation?: AnimationJson; } @@ -101,7 +103,3 @@ function frame_size(animation: AnimationJson, size: { width: number; height: num const side = Math.min(size.width, size.height); return { frame_width: animation.width ?? side, frame_height: animation.height ?? side }; } - -function is_object(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value); -} diff --git a/common/utils.ts b/common/utils.ts index c1ed172..37f4c28 100644 --- a/common/utils.ts +++ b/common/utils.ts @@ -38,6 +38,20 @@ export function distance_point_rectangle(px: number, py: number, sqx: number, sq return Math.sqrt(dx * dx + dy * dy); } +// -pi to pi +export function wrap_angle(angle: number) { + angle %= Math.PI * 2; + if (angle >= Math.PI) angle -= Math.PI * 2; + if (angle < -Math.PI) angle += Math.PI * 2; + return angle; +} + +// the hex sha-256 of bytes +export async function sha256(bytes: Uint8Array): Promise { + const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)); + return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join(""); +} + export function distance_point_point(ax: number, ay: number, az: number, bx: number, by: number, bz: number) { const dx = ax - bx; const dy = ay - by; diff --git a/common/worldgen/biomes.ts b/common/worldgen/biomes.ts index 43fe6f8..8c86b2a 100644 --- a/common/worldgen/biomes.ts +++ b/common/worldgen/biomes.ts @@ -4,7 +4,7 @@ // biomes as data: worldgen/biomes/.json in a mod, see docs/modding/worldgen/biomes.md. which biome a column // gets is the generator's biome rules (worldgen/biome_source), these say what a biome looks like once it's picked import { EverythingRegistry } from "../everything_registry.ts"; -import { ID_PATTERN } from "../mod_data.ts"; +import { ID_PATTERN, is_object } from "../mod_data.ts"; import { farming_day } from "../time.ts"; export const SEASONS = ["spring", "summer", "autumn", "winter"] as const; @@ -164,7 +164,3 @@ export function validate_biome(json: unknown): string[] { } return problems; } - -function is_object(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value); -} diff --git a/common/worldgen/data.ts b/common/worldgen/data.ts index 55bc536..1453a30 100644 --- a/common/worldgen/data.ts +++ b/common/worldgen/data.ts @@ -4,7 +4,7 @@ // world generation as data: noises, density functions, noise settings (a generator) and biome sources, see // docs/modding/worldgen/terrain.md. checked here, compiled by density.ts and generator.ts. the names follow // minecraft's (density functions, the noise router, surface rules) where the idea is the same -import { ID_PATTERN, TAG_ID_PATTERN } from "../mod_data.ts"; +import { ID_PATTERN, is_object, TAG_ID_PATTERN } from "../mod_data.ts"; // ids of worldgen data can have folders, like "bworld:overworld/erosion" export const WORLDGEN_ID_PATTERN = TAG_ID_PATTERN; @@ -540,7 +540,3 @@ function block_id(value: unknown, field: string, refs: WorldgenRefs, problems: s if (typeof value === "string" && ID_PATTERN.test(value)) refs.blocks.add(value); else problems.push(`${field} must be a block's id`); } - -function is_object(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value); -} diff --git a/common/worldgen/features.ts b/common/worldgen/features.ts index ec4e471..1ee1e42 100644 --- a/common/worldgen/features.ts +++ b/common/worldgen/features.ts @@ -7,7 +7,7 @@ import { EverythingRegistry } from "../everything_registry.ts"; import type { BlockRegistry } from "../everything_registry.ts"; import { CHUNK_HEIGHT, CHUNK_SIZE } from "../constants.ts"; -import { ID_PATTERN, TAG_ID_PATTERN } from "../mod_data.ts"; +import { ID_PATTERN, is_object, TAG_ID_PATTERN } from "../mod_data.ts"; import { list_matches } from "../tags.ts"; import { can_stand_on } from "../utils.ts"; import { AIR_ID } from "../protocol.ts"; @@ -598,7 +598,3 @@ function height_provider(json: unknown): IntProvider { const span = anchor(object.max_inclusive) - min + 1; return (chunk) => min + Math.floor(chunk.rng.next() * span); } - -function is_object(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value); -} diff --git a/desktop/client_updates.ts b/desktop/client_updates.ts index 72e35de..753ba04 100644 --- a/desktop/client_updates.ts +++ b/desktop/client_updates.ts @@ -6,6 +6,7 @@ // copy from its data folder. the singleplayer server is part of the app and can't update this way, so a client for // a different protocol is never used. anything that goes wrong leaves the app on the client it has import { join } from "@std/path"; +import { sha256 } from "../common/utils.ts"; // where the manifest is, in a build folder and on the site export const CLIENT_MANIFEST = "client/manifest.json"; @@ -19,11 +20,6 @@ export interface ClientManifest { files: Record; } -export async function sha256(bytes: Uint8Array): Promise { - const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)); - return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join(""); -} - export async function client_manifest(files: Record, protocol: number): Promise { const sorted = Object.fromEntries(Object.entries(files).sort(([a], [b]) => a.localeCompare(b))); const listing = Object.entries(sorted).map(([path, hash]) => `${path} ${hash}`).join("\n"); diff --git a/docs/modding/gui/index.md b/docs/modding/gui/index.md index a1c118c..de2bc7f 100644 --- a/docs/modding/gui/index.md +++ b/docs/modding/gui/index.md @@ -115,6 +115,17 @@ interface Graphics { measure_text(text: string, scale?: number): number; // any texture. part is [u, v, width, height] from 0 to 1, the part of it to draw, like a progress bar's filled part texture(id: string, x: number, y: number, w: number, h: number, part?: [u, v, w, h]): void; + // full drawn over empty, filled from 0 to 1 of the way from the left, or from the bottom when direction is "up" + progress( + empty: string, + full: string, + x: number, + y: number, + w: number, + h: number, + filled: number, + direction?: "right" | "up", + ): void; item(id: string, x: number, y: number, count?: number): void; // an item as a slot shows it clip(x: number, y: number, w: number, h: number, draw: () => void): void; // only draws inside the box diff --git a/docs/modding/inventories/menus.md b/docs/modding/inventories/menus.md index c723946..c470525 100644 --- a/docs/modding/inventories/menus.md +++ b/docs/modding/inventories/menus.md @@ -144,8 +144,8 @@ export function setup(ctx: ClientContext) { height: 166, on_render_background(g) { g.panel(0, 0, 176, 166); - const done = menu.data.progress / menu.data.progress_max || 0; - g.texture("bworld:arrow_full", 85, 34, 18 * done, 18, [0, 0, done, 1]); + const { progress, progress_max } = menu.data; + g.progress("bworld:arrow_empty", "bworld:arrow_full", 85, 34, 18, 18, progress / progress_max); }, on_render_labels(g) { g.text(menu.title, 8, 6); diff --git a/mods/bworld/scripts/client.ts b/mods/bworld/scripts/client.ts index ffae0e9..31aa94a 100644 --- a/mods/bworld/scripts/client.ts +++ b/mods/bworld/scripts/client.ts @@ -44,8 +44,9 @@ function chest_screen(menu: ClientMenu): MenuScreen { function furnace_screen(menu: ClientMenu): MenuScreen { return container_screen(menu, HEIGHT, (g) => { // the fuel left burns down, the progress fills to the right - bar(g, 55, 34, "up", menu.data.fuel, menu.data.fuel_max, "bworld:fire_empty", "bworld:fire_full"); - bar(g, 85, 34, "right", menu.data.progress, menu.data.progress_max, "bworld:arrow_empty", "bworld:arrow_full"); + const { fuel, fuel_max, progress, progress_max } = menu.data; + g.progress("bworld:fire_empty", "bworld:fire_full", 55, 34, 18, 18, fuel / fuel_max, "up"); + g.progress("bworld:arrow_empty", "bworld:arrow_full", 85, 34, 18, 18, progress / progress_max); }); } @@ -125,27 +126,6 @@ function stonecutter_screen(ctx: ClientContext, menu: ClientMenu): MenuScreen { }); } -// an 18 pixel square progress bar, value / max of full drawn over empty -function bar( - g: Graphics, - x: number, - y: number, - direction: "up" | "right", - value = 0, - max = 0, - empty: string, - full: string, -) { - const size = 18; - const done = max > 0 ? Math.max(0, Math.min(1, value / max)) : 0; - g.texture(empty, x, y, size, size); - if (direction === "right") { - g.texture(full, x, y, size * done, size, [0, 0, done, 1]); - } else { - g.texture(full, x, y + size * (1 - done), size, size * done, [0, 1 - done, 1, done]); - } -} - // a fishing minigame's screen, by the minigame's name, see minigames/mod.ts function fishing_minigame_screen(menu: ClientMenu): MenuScreen { const { minigame, fish } = menu.open_data as { minigame: string; fish: ItemStack }; diff --git a/mods/bworld/scripts/trees.ts b/mods/bworld/scripts/trees.ts index 37337fc..4d4d260 100644 --- a/mods/bworld/scripts/trees.ts +++ b/mods/bworld/scripts/trees.ts @@ -105,20 +105,10 @@ function grow_tree(kind: TreeKind, x: number, y: number, z: number, rng: Random, let top: number; switch (kind) { - case "oak": { - const height = random(4, 6); - top = y + height + 1; - if (top >= CHUNK_HEIGHT - 1) return false; - trunk(height); - layer(y + height - 2, 2, true); - layer(y + height - 1, 2, true); - layer(y + height, 1, true); - layer(y + height + 1, 1, false); - break; - } + case "oak": case "birch": { - // oak's canopy on a taller, straight trunk - const height = random(5, 7); + // birch is oak's canopy on a taller, straight trunk + const height = kind === "birch" ? random(5, 7) : random(4, 6); top = y + height + 1; if (top >= CHUNK_HEIGHT - 1) return false; trunk(height); diff --git a/mods/farmersdelight/scripts/client.ts b/mods/farmersdelight/scripts/client.ts index 29b284a..205d61f 100644 --- a/mods/farmersdelight/scripts/client.ts +++ b/mods/farmersdelight/scripts/client.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later // the cooking pot's screen, like the java mod's CookingPotScreen. its slots are in scripts/server.ts, in gui pixels -import type { ClientContext, Graphics } from "bworld/client"; +import type { ClientContext } from "bworld/client"; const WIDTH = 176; const HEIGHT = 166; @@ -14,17 +14,9 @@ export function setup(ctx: ClientContext) { on_render_background(g) { g.panel(0, 0, WIDTH, HEIGHT); // lit under the ingredients while something heats the pot, the arrow fills as the meal cooks - bar(g, 47, 53, "up", menu.data.heated, 1, "bworld:fire_empty", "bworld:fire_full"); - bar( - g, - 95, - 25, - "right", - menu.data.progress, - menu.data.progress_max, - "bworld:arrow_empty", - "bworld:arrow_full", - ); + g.progress("bworld:fire_empty", "bworld:fire_full", 47, 53, 18, 18, menu.data.heated, "up"); + const { progress, progress_max } = menu.data; + g.progress("bworld:arrow_empty", "bworld:arrow_full", 95, 25, 18, 18, progress / progress_max); }, on_render_labels(g) { g.text(menu.title, 8, 6); @@ -32,24 +24,3 @@ export function setup(ctx: ClientContext) { }, })); } - -// an 18 pixel square progress bar, value / max of full drawn over empty -function bar( - g: Graphics, - x: number, - y: number, - direction: "up" | "right", - value = 0, - max = 0, - empty: string, - full: string, -) { - const size = 18; - const done = max > 0 ? Math.max(0, Math.min(1, value / max)) : 0; - g.texture(empty, x, y, size, size); - if (direction === "right") { - g.texture(full, x, y, size * done, size, [0, 0, done, 1]); - } else { - g.texture(full, x, y + size * (1 - done), size, size * done, [0, 1 - done, 1, done]); - } -} diff --git a/server/game/entity/goals.ts b/server/game/entity/goals.ts index b437195..02b18a5 100644 --- a/server/game/entity/goals.ts +++ b/server/game/entity/goals.ts @@ -303,14 +303,28 @@ export class MeleeAttackGoal extends Goal { } } -// goes after the nearest player it can see within follow_range -export class NearestAttackablePlayerGoal extends Goal { +// picks the mob's target, and keeps it while it's alive and within follow_range +abstract class TargetGoal extends Goal { override flags: GoalFlag[] = ["target"]; constructor(readonly mob: Mob) { super(); } + override can_continue_to_use() { + const target = this.mob.target; + const mob = this.mob; + return target !== undefined && is_alive(target) && + Math.hypot(target.x - mob.x, target.y - mob.y, target.z - mob.z) <= mob.attribute(ATTRIBUTES.follow_range); + } + + override stop() { + this.mob.target = undefined; + } +} + +// goes after the nearest player it can see within follow_range +export class NearestAttackablePlayerGoal extends TargetGoal { #find() { const mob = this.mob; return mob.level.nearest_player(mob.x, mob.y, mob.z, mob.attribute(ATTRIBUTES.follow_range)); @@ -320,52 +334,25 @@ export class NearestAttackablePlayerGoal extends Goal { return this.mob.random() < 0.1 && this.#find() !== undefined; } - override can_continue_to_use() { - const target = this.mob.target; - const mob = this.mob; - return target !== undefined && is_alive(target) && - Math.hypot(target.x - mob.x, target.y - mob.y, target.z - mob.z) <= mob.attribute(ATTRIBUTES.follow_range); - } - override start() { this.mob.target = this.#find(); } - - override stop() { - this.mob.target = undefined; - } } // goes after whoever hurt it last, like minecraft's HurtByTargetGoal, for as long as they're within follow_range -export class HurtByTargetGoal extends Goal { - override flags: GoalFlag[] = ["target"]; +export class HurtByTargetGoal extends TargetGoal { // the Mob.times_hurt_by_attacker it last went after someone for, so each hit only starts it once #handled = 0; - constructor(readonly mob: Mob) { - super(); - } - can_use() { const attacker = this.mob.last_attacker; return this.mob.times_hurt_by_attacker !== this.#handled && attacker !== undefined && is_alive(attacker); } - override can_continue_to_use() { - const target = this.mob.target; - const mob = this.mob; - return target !== undefined && is_alive(target) && - Math.hypot(target.x - mob.x, target.y - mob.y, target.z - mob.z) <= mob.attribute(ATTRIBUTES.follow_range); - } - override start() { this.#handled = this.mob.times_hurt_by_attacker; this.mob.target = this.mob.last_attacker; } - - override stop() { - this.mob.target = undefined; - } } function is_alive(target: LivingEntity) { diff --git a/server/game/entity/mob.ts b/server/game/entity/mob.ts index 1e9bb38..7c45cb2 100644 --- a/server/game/entity/mob.ts +++ b/server/game/entity/mob.ts @@ -10,6 +10,7 @@ import { ItemEntity } from "./item_entity.ts"; import { EQUIPMENT_SLOTS, type EquipmentSlot, LivingEntity, type SavedLivingEntity } from "./living_entity.ts"; import type { EntityData } from "$/common/protocol.ts"; import type { ItemStack } from "$/common/inventory.ts"; +import { wrap_angle } from "$/common/utils.ts"; // minecraft's despawning distances: gone at once past the first, maybe after a while past the second const DESPAWN_DISTANCE = 128; @@ -401,14 +402,6 @@ export class JumpControl { } } -// -pi to pi -export function wrap_angle(angle: number) { - angle %= Math.PI * 2; - if (angle >= Math.PI) angle -= Math.PI * 2; - if (angle < -Math.PI) angle += Math.PI * 2; - return angle; -} - // from one angle towards another the short way round, at most max export function approach_angle(from: number, to: number, max: number) { const difference = Math.max(-max, Math.min(max, wrap_angle(to - from))); diff --git a/server/game/game_server.ts b/server/game/game_server.ts index 98225d4..df359dc 100644 --- a/server/game/game_server.ts +++ b/server/game/game_server.ts @@ -134,7 +134,7 @@ export interface SavedLevel { seed: string; // world time in ticks time: number; - tiles: SavedTile[]; + tiles: Tile[]; // every ctx.containers container, by id containers: Record; players: Record; @@ -144,19 +144,6 @@ export interface SavedLevel { mod_storage: Record>; } -interface SavedTile { - id: string; - x: number; - y: number; - z: number; - // what BlockRef.data holds - mod_data?: unknown; - // what it shows, see ServerWorld.set_block_item in the mod api - item?: ItemData; - // false when its components turned ticking off for it - ticking?: false; -} - // the loaded mods, see load_mods.ts export interface GameMods { listings: ModListing[]; @@ -270,17 +257,7 @@ export class GameServer { container.load(items); this.containers.set(id, container); } - for (const tile of saved?.tiles ?? []) { - this.world.add_tile({ - id: tile.id, - x: tile.x, - y: tile.y, - z: tile.z, - mod_data: tile.mod_data, - item: tile.item, - ticking: tile.ticking, - }); - } + for (const tile of saved?.tiles ?? []) this.world.add_tile({ ...tile }); this.entities.load(saved?.version === 4 ? upgrade_v4_entities(saved.entities) : saved?.entities ?? []); this.#saved_players = saved?.players ?? {}; // a new world is saved straight away @@ -430,15 +407,7 @@ export class GameServer { version: 5, seed: this.world.seed, time: this.world.time, - tiles: [...this.world.tiles.values()].map((tile) => ({ - id: tile.id, - x: tile.x, - y: tile.y, - z: tile.z, - mod_data: tile.mod_data, - item: tile.item, - ticking: tile.ticking, - })), + tiles: [...this.world.tiles.values()].map((tile) => ({ ...tile })), containers: Object.fromEntries( [...this.containers].map(([id, container]) => [id, container.to_data()]), ), @@ -1187,19 +1156,8 @@ export class GameServer { return; } - const place = { - player: player_api, - block: { id: held.block_id, x: tx, y: ty, z: tz }, - face, - hit: [hit[0], hit[1], hit[2]] as const, - item: player_api.held_item, - }; - const before_place = { ...place, cancel: false }; - this.mods.before.block_place.emit(before_place); - if (before_place.cancel) { - this.#correct(player, tx, ty, tz); - return; - } + const place = this.#place_event(player, { id: held.block_id, x: tx, y: ty, z: tz }, face, hit); + if (!place) return; this.set_block(tx, ty, tz, held.block_id, player, state); held_slot.amount = held_slot.amount! - 1; @@ -1210,20 +1168,13 @@ export class GameServer { // so a bucket empties like it does placing water anywhere else #waterlog(player: ServerPlayer, x: number, y: number, z: number, face: Faces, hit: number[]) { const held_slot = player.inventory.get_slot(player.selected_slot); - const player_api = this.mods.player(player); - const place = { - player: player_api, - block: { id: this.world.get_block_info(x, y, z)!.waterloggable!, x, y, z }, + const place = this.#place_event( + player, + { id: this.world.get_block_info(x, y, z)!.waterloggable!, x, y, z }, face, - hit: [hit[0], hit[1], hit[2]] as const, - item: player_api.held_item, - }; - const before_place = { ...place, cancel: false }; - this.mods.before.block_place.emit(before_place); - if (before_place.cancel) { - this.#correct(player, x, y, z); - return; - } + hit, + ); + if (!place) return; const info = this.world.get_block_info(x, y, z)!; this.set_block_state( x, @@ -1235,6 +1186,31 @@ export class GameServer { this.mods.after.block_place.emit(place); } + // the event for a player placing a block, after mods had the chance to cancel it. undefined when one did, and the + // player is told what's really there + #place_event( + player: ServerPlayer, + block: { id: string; x: number; y: number; z: number }, + face: Faces, + hit: number[], + ) { + const player_api = this.mods.player(player); + const place = { + player: player_api, + block, + face, + hit: [hit[0], hit[1], hit[2]] as const, + item: player_api.held_item, + }; + const before = { ...place, cancel: false }; + this.mods.before.block_place.emit(before); + if (before.cancel) { + this.#correct(player, block.x, block.y, block.z); + return undefined; + } + return place; + } + // whether a mob's or player's collision box overlaps a block with that shape at x, y, z #occupied(x: number, y: number, z: number, shape: Shape) { return this.players().some((player) => diff --git a/server/load_bmods.ts b/server/load_bmods.ts index 578ac8c..b6e422a 100644 --- a/server/load_bmods.ts +++ b/server/load_bmods.ts @@ -7,6 +7,7 @@ import { join } from "@std/path"; import { type Bmod, BMOD_EXTENSION, client_copy, read_bmod, write_bmod } from "$/common/bmod.ts"; import { check_references, load_order, type LoadedMod } from "$/common/mod_check.ts"; import type { ModListing } from "$/common/mod_loader.ts"; +import { sha256 } from "$/common/utils.ts"; export interface ServerMod { bmod: Bmod; @@ -74,7 +75,7 @@ export async function load_bmods(dir: string, engine_textures: Iterable) return await Promise.all(ordered.map(async (mod) => { const bmod = by_id.get(mod.id)!.bmod; const client_bytes = write_bmod(client_copy(bmod)); - const sha256 = await hex_sha256(client_bytes); + const hash = await sha256(client_bytes); return { bmod, client_bytes, @@ -82,8 +83,8 @@ export async function load_bmods(dir: string, engine_textures: Iterable) id: bmod.manifest.id, name: bmod.manifest.name, version: bmod.manifest.version, - sha256, - file: `mods/${sha256}${BMOD_EXTENSION}`, + sha256: hash, + file: `mods/${hash}${BMOD_EXTENSION}`, size: client_bytes.length, ...(bmod.manifest.engine_access ? { engine_access: true } : {}), }, @@ -121,8 +122,3 @@ function as_loaded_mod(file: string, bmod: Bmod): LoadedMod { texture_json: new Map(bmod.texture_json), }; } - -async function hex_sha256(bytes: Uint8Array) { - const digest = await crypto.subtle.digest("SHA-256", bytes); - return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join(""); -} diff --git a/tests/artifacts_test.ts b/tests/artifacts_test.ts index 85629a7..350f674 100644 --- a/tests/artifacts_test.ts +++ b/tests/artifacts_test.ts @@ -5,10 +5,7 @@ import { assertEquals } from "@std/assert"; import { ATTRIBUTES } from "$/server/game/entity/attributes.ts"; import { PLAYER_MENU_EXTRA } from "$/common/protocol.ts"; -import { test_game } from "./helpers.ts"; - -// deno-lint-ignore no-explicit-any -type Msg = any; +import { container_items, test_game } from "./helpers.ts"; async function setup() { const t = await test_game("mods"); @@ -39,7 +36,7 @@ Deno.test("the power glove and feral claws go in the hands slot, and only work w Deno.test("worn artifacts work again after rejoining, and say what they do", async () => { const t = await setup(); t.send(1, { type: "click", menu: 0, slot: 0, button: 0, shift: true }); - const worn = t.take(1).findLast((m: Msg) => m.type === "container" && m.container === "extra").items; + const worn = container_items(t.take(1), "extra"); assertEquals(worn[t.hands - PLAYER_MENU_EXTRA].lore, "When worn:\n+4 Attack Damage"); t.game.on_disconnect(1); diff --git a/tests/base_game_test.ts b/tests/base_game_test.ts index df6ad87..16564f3 100644 --- a/tests/base_game_test.ts +++ b/tests/base_game_test.ts @@ -6,22 +6,17 @@ import { assert, assertEquals } from "@std/assert"; import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts"; import { CYCLE_TICKS } from "$/common/time.ts"; import { display_name, get_state_value } from "$/common/utils.ts"; -import { menu_data, menu_items, opened_menu, test_game } from "./helpers.ts"; +import { container_items, menu_data, menu_items, opened_menu, stone_floor, test_game } from "./helpers.ts"; // deno-lint-ignore no-explicit-any type Msg = any; type Game = Awaited>; -const last_container = (messages: Msg[], container: string) => - messages.filter((m) => m.type === "container" && m.container === container).at(-1)?.items; - // a player standing on a stone floor at y 99, high above the terrain, with the items given in their inventory async function setup(items: [string, number][] = []) { const t = await test_game("mods"); t.join(1, "alice"); - for (let x = -3; x <= 3; x++) { - for (let z = -3; z <= 3; z++) t.game.set_block(x, 99, z, "bworld:stone"); - } + stone_floor(t.game); t.send(1, { type: "move", x: 0.5, y: 100, z: 0.5, yaw: 0, pitch: 0 }); for (const [id, count] of items) t.send(1, { type: "chat", text: `/give ${id} ${count}` }); return t; @@ -29,7 +24,7 @@ async function setup(items: [string, number][] = []) { // the inventory slot holding an item, from what the server sent last function slot_of(messages: Msg[], id: string) { - const slot = (last_container(messages, "inventory") ?? []).findIndex((i: Msg) => i?.id === id); + const slot = (container_items(messages, "inventory") ?? []).findIndex((i: Msg) => i?.id === id); assert(slot >= 0, `no ${id} in the inventory`); return slot; } @@ -109,7 +104,7 @@ Deno.test("a shipping bin sells what's in it every morning for as few coins as i assertEquals(EverythingRegistry.get("items", "bworld:oak_planks")?.base_sell_value, 2); t.game.set_block(1, 100, 0, "bworld:shipping_bin"); const messages = t.take(1); - const inventory = last_container(messages, "inventory"); + const inventory = container_items(messages, "inventory"); const planks = inventory.flatMap((item: Msg, slot: number) => item?.id === "bworld:oak_planks" ? [slot] : []); const copper = slot_of(messages, "bworld:copper_coin"); @@ -190,7 +185,7 @@ Deno.test("bone meal grows wheat until it's fully grown", async () => { assertEquals(age(), 1); for (let i = 0; i < 7; i++) t.send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" }); assertEquals(age(), 7); - assertEquals(last_container(t.take(1), "inventory")[slot]?.count, 1); + assertEquals(container_items(t.take(1), "inventory")[slot]?.count, 1); assertEquals(t.game.world.get_block_id(1, 101, 0), "bworld:air"); }); @@ -200,12 +195,12 @@ Deno.test("the last bone meal is used up", async () => { const slot = slot_of(t.take(1), "bworld:bone_meal"); t.send(1, { type: "select_slot", slot }); t.send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" }); - assertEquals(last_container(t.take(1), "inventory")[slot], null); + assertEquals(container_items(t.take(1), "inventory")[slot], null); }); Deno.test("a new watering can starts empty, and players are told so in its lore", async () => { const t = await setup([["bworld:copper_watering_can", 1]]); - const can = last_container(t.take(1), "inventory").find((i: Msg) => i?.id === "bworld:copper_watering_can"); + const can = container_items(t.take(1), "inventory").find((i: Msg) => i?.id === "bworld:copper_watering_can"); assertEquals(can.data, { water: 0, max_water: 32 }); assertEquals(can.lore, "Water: 0/32"); @@ -259,7 +254,7 @@ Deno.test("a smithing table upgrades a wooden pickaxe with 5 stone, using up exa // closing gives back the leftover stone, and the cursor's pickaxe goes into the inventory t.send(1, { type: "close_menu", menu: opened.id }); - const inventory = last_container(t.take(1), "inventory").filter((i: Msg) => i); + const inventory = container_items(t.take(1), "inventory").filter((i: Msg) => i); assertEquals( inventory.sort((a: Msg, b: Msg) => a.id.localeCompare(b.id)), [{ id: "bworld:stone", count: 2 }, { id: "bworld:stone_pickaxe", count: 1 }], @@ -339,7 +334,7 @@ Deno.test("a stonecutter cuts its input into the recipe picked with a button, on assertEquals(menu_data(latest).selected, -1); assertEquals(menu_items(latest)[1], null); t.send(1, { type: "close_menu", menu: opened.id }); - const inventory = last_container(t.take(1), "inventory").filter((i: Msg) => i); + const inventory = container_items(t.take(1), "inventory").filter((i: Msg) => i); assertEquals( inventory.map((i: Msg) => i.id).sort(), ["bworld:cobblestone", "bworld:dirt", result.id].sort(), diff --git a/tests/client_updates_test.ts b/tests/client_updates_test.ts index a3eb7af..c699ed5 100644 --- a/tests/client_updates_test.ts +++ b/tests/client_updates_test.ts @@ -3,7 +3,8 @@ import { assertEquals } from "@std/assert"; import { join } from "@std/path"; -import { CLIENT_MANIFEST, client_manifest, sha256, update_client } from "$/desktop/client_updates.ts"; +import { CLIENT_MANIFEST, client_manifest, update_client } from "$/desktop/client_updates.ts"; +import { sha256 } from "$/common/utils.ts"; const PROTOCOL = 7; diff --git a/tests/cooking_test.ts b/tests/cooking_test.ts index 6da6830..31f72e6 100644 --- a/tests/cooking_test.ts +++ b/tests/cooking_test.ts @@ -7,7 +7,7 @@ import { ItemStack } from "$/common/inventory.ts"; import { bake_model } from "$/common/block_models.ts"; import { validate_recipe } from "$/common/mod_data.ts"; import { get_state_value, set_state_value } from "$/common/utils.ts"; -import { test_game } from "./helpers.ts"; +import { stone_floor, test_game } from "./helpers.ts"; const POT = [0, 101, 0] as const; const FURNACE = [0, 100, 0] as const; @@ -15,9 +15,7 @@ const FURNACE = [0, 100, 0] as const; async function setup() { const t = await test_game("mods"); t.join(1, "alice"); - for (let x = -3; x <= 3; x++) { - for (let z = -3; z <= 3; z++) t.game.set_block(x, 99, z, "bworld:stone"); - } + stone_floor(t.game); t.send(1, { type: "move", x: 2.5, y: 100, z: 2.5, yaw: 0, pitch: 0 }); t.game.set_block(...FURNACE, "bworld:furnace"); t.game.set_block(...POT, "farmersdelight:cooking_pot"); diff --git a/tests/curios_test.ts b/tests/curios_test.ts index dd4463d..3322f93 100644 --- a/tests/curios_test.ts +++ b/tests/curios_test.ts @@ -5,16 +5,13 @@ // mods/bworld/scripts/curios.ts import { assert, assertEquals } from "@std/assert"; import { PLAYER_MENU_EXTRA, PROTOCOL_VERSION } from "$/common/protocol.ts"; -import { copy_dir, test_game } from "./helpers.ts"; +import { container_items, copy_dir, test_game } from "./helpers.ts"; import type { WorldSave } from "$/server/game/saves.ts"; // deno-lint-ignore no-explicit-any type Msg = any; type Game = Awaited>; -const last_container = (messages: Msg[], container: string) => - messages.filter((m) => m.type === "container" && m.container === container).at(-1)?.items; - // the base game, and a mod with a ring and an amulet that goes in any slot async function setup(save?: WorldSave) { const dir = Deno.makeTempDirSync({ prefix: "bworld_curios_" }); @@ -58,7 +55,7 @@ async function setup(save?: WorldSave) { } // what's in the curios slots, the ones the base game added to the player's own menu, as last synced -const curios_items = (messages: Msg[]) => last_container(messages, "extra"); +const curios_items = (messages: Msg[]) => container_items(messages, "extra"); // which of those is a slot type, found by its icon. which types there are depends on what items every mod has function curio_slot(t: Game, type: string) { @@ -86,8 +83,8 @@ Deno.test("items only go in the slots they fit, and fall out when the player die // #bworld:curios/curio items in any slot, the curio slot first for (const slot of [2, 0, 1]) t.send(1, { type: "click", menu: 0, slot, button: 0, shift: true }); const messages = t.take(1); - assertEquals(last_container(messages, "inventory").slice(0, 3), [null, null, null]); - assertEquals(last_container(messages, "inventory")[9], { id: "bworld:coal", count: 1 }); + assertEquals(container_items(messages, "inventory").slice(0, 3), [null, null, null]); + assertEquals(container_items(messages, "inventory")[9], { id: "bworld:coal", count: 1 }); const [curio, ring] = [curio_slot(t, "curio"), curio_slot(t, "ring")]; assertEquals(curios_items(messages)[curio], { id: "jewelry:amulet", count: 1 }); assertEquals(curios_items(messages)[ring], { id: "jewelry:ring", count: 1 }); @@ -125,7 +122,7 @@ Deno.test("curios worn when curios was a mod of its own are still worn", async ( Deno.test("the giant chestplate goes in the body slot and gives 20 more health while worn", async () => { const t = await setup(); t.send(1, { type: "chat", text: "/give bworld:giant_chestplate" }); - const slot = last_container(t.take(1), "inventory").findIndex((i: Msg) => i?.id === "bworld:giant_chestplate"); + const slot = container_items(t.take(1), "inventory").findIndex((i: Msg) => i?.id === "bworld:giant_chestplate"); const alice = t.game.players()[0]; t.send(1, { type: "click", menu: 0, slot, button: 0, shift: true }); // what curios give is worked out each tick, from what changed @@ -161,7 +158,7 @@ Deno.test("the giant chestplate goes in the body slot and gives 20 more health w Deno.test("the giant chestplate gives regeneration III after 10 seconds without being hurt", async () => { const t = await setup(); t.send(1, { type: "chat", text: "/give bworld:giant_chestplate" }); - const slot = last_container(t.take(1), "inventory").findIndex((i: Msg) => i?.id === "bworld:giant_chestplate"); + const slot = container_items(t.take(1), "inventory").findIndex((i: Msg) => i?.id === "bworld:giant_chestplate"); const alice = t.game.players()[0]; t.send(1, { type: "click", menu: 0, slot, button: 0, shift: true }); t.game.damage_player(alice, 2, "test"); diff --git a/tests/cutting_board_test.ts b/tests/cutting_board_test.ts index 06d73a1..b4346e9 100644 --- a/tests/cutting_board_test.ts +++ b/tests/cutting_board_test.ts @@ -4,16 +4,14 @@ // farmer's delight's cutting board: holds a stack of anything, shows it on top, and a knife cuts it one at a time import { assert, assertEquals } from "@std/assert"; import { get_state_value } from "$/common/utils.ts"; -import { test_game } from "./helpers.ts"; +import { stone_floor, test_game } from "./helpers.ts"; const BOARD = [0, 100, 0] as const; async function setup(yaw = 0) { const t = await test_game("mods"); t.join(1, "alice"); - for (let x = -3; x <= 3; x++) { - for (let z = -3; z <= 3; z++) t.game.set_block(x, 99, z, "bworld:stone"); - } + stone_floor(t.game); t.send(1, { type: "move", x: 2.5, y: 100, z: 2.5, yaw, pitch: 0 }); t.send(1, { type: "chat", text: "/give farmersdelight:cutting_board" }); t.send(1, { type: "select_slot", slot: 0 }); diff --git a/tests/farming_test.ts b/tests/farming_test.ts index a8bf83b..6bd38b5 100644 --- a/tests/farming_test.ts +++ b/tests/farming_test.ts @@ -7,7 +7,7 @@ import { assert, assertEquals } from "@std/assert"; import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts"; import { CYCLE_TICKS } from "$/common/time.ts"; import { get_state_value } from "$/common/utils.ts"; -import { test_game } from "./helpers.ts"; +import { container_items, stone_floor, test_game } from "./helpers.ts"; // deno-lint-ignore no-explicit-any type Msg = any; @@ -16,13 +16,10 @@ type Msg = any; async function setup(items: string[] = []) { const t = await test_game("mods"); t.join(1, "alice"); - for (let x = -3; x <= 3; x++) { - for (let z = -3; z <= 3; z++) t.game.set_block(x, 99, z, "bworld:stone"); - } + stone_floor(t.game); t.send(1, { type: "move", x: 0.5, y: 100, z: 0.5, yaw: 0, pitch: 0 }); for (const item of items) t.send(1, { type: "chat", text: `/give ${item}` }); - const inventory = () => - t.take(1).filter((m) => m.type === "container" && m.container === "inventory").at(-1)?.items ?? []; + const inventory = () => container_items(t.take(1), "inventory") ?? []; const hold = (id: string) => { const slot = inventory_now().findIndex((i: Msg) => i?.id === id); assert(slot >= 0 && slot < 9, `${id} isn't in the hotbar`); diff --git a/tests/fence_test.ts b/tests/fence_test.ts index f17e3be..0c4a779 100644 --- a/tests/fence_test.ts +++ b/tests/fence_test.ts @@ -10,7 +10,7 @@ import { collision_shape_at, covers_face, FULL_SHAPE, shape_at } from "$/common/ import { move_body } from "$/common/physics.ts"; import { get_state_value } from "$/common/utils.ts"; import { update_crafting_result } from "$/server/game/crafting.ts"; -import { test_game } from "./helpers.ts"; +import { stone_floor, test_game } from "./helpers.ts"; const Y = 100; @@ -108,9 +108,7 @@ Deno.test("six planks and two sticks make three fences of that wood", async () = Deno.test("clicking the ground beside a fence tells the client it's still joined, not a bare post", async () => { const t = await test_game("mods"); t.join(1, "alice"); - for (let x = -3; x <= 3; x++) { - for (let z = -3; z <= 3; z++) t.game.set_block(x, 99, z, "bworld:stone"); - } + stone_floor(t.game); t.send(1, { type: "move", x: 0.5, y: 100, z: 2.5, yaw: 0, pitch: 0 }); t.game.tick(); t.game.set_block(0, 100, 0, "bworld:oak_fence"); diff --git a/tests/golden.ts b/tests/golden.ts index f5904df..8075c99 100644 --- a/tests/golden.ts +++ b/tests/golden.ts @@ -6,6 +6,7 @@ import { AIR, ID_MASK } from "$/common/constants.ts"; import type { RawChunk } from "$/common/generation.ts"; import { AIR_ID } from "$/common/protocol.ts"; +import { sha256 } from "$/common/utils.ts"; export const FIXTURE = new URL("./fixtures/worldgen_golden.json", import.meta.url); export const SEEDS = ["golden-1", "golden-2", "golden-3"]; @@ -40,12 +41,12 @@ export function raw_hash(raw: RawChunk, name: (value: number) => string): Promis for (let i = 0; i < raw.spills.length; i += 4) { spills.push(raw.spills[i], raw.spills[i + 1], raw.spills[i + 2], name(raw.spills[i + 3])); } - return sha256(blocks_text(raw.blocks, name), JSON.stringify(spills), raw.biomes.join(",")); + return hash(blocks_text(raw.blocks, name), JSON.stringify(spills), raw.biomes.join(",")); } // what the fixture's "final" is: the chunk with its neighbors' spills export function final_hash(blocks: Uint32Array, name: (value: number) => string): Promise { - return sha256(blocks_text(blocks, name)); + return hash(blocks_text(blocks, name)); } // the blocks as a palette of names in the order they first appear, then each block's place in it @@ -63,7 +64,8 @@ function blocks_text(blocks: Uint32Array, name: (value: number) => string): (str return [JSON.stringify([...palette.keys()].map(name)), new Uint8Array(indices.buffer)]; } -async function sha256(...parts: (string | Uint8Array | (string | Uint8Array)[])[]) { +// the sha-256 of the parts one after another, strings each on their own line +function hash(...parts: (string | Uint8Array | (string | Uint8Array)[])[]) { const bytes = parts.flat().map((part) => typeof part === "string" ? new TextEncoder().encode(part + "\n") : part); const all = new Uint8Array(bytes.reduce((sum, part) => sum + part.length, 0)); let offset = 0; @@ -71,9 +73,5 @@ async function sha256(...parts: (string | Uint8Array | (string | Uint8Array)[])[ all.set(part, offset); offset += part.length; } - let hex = ""; - for (const byte of new Uint8Array(await crypto.subtle.digest("SHA-256", all))) { - hex += byte.toString(16).padStart(2, "0"); - } - return hex; + return sha256(all); } diff --git a/tests/helpers.ts b/tests/helpers.ts index d2ed77d..674c59f 100644 --- a/tests/helpers.ts +++ b/tests/helpers.ts @@ -4,6 +4,7 @@ import { resolve, toFileUrl } from "@std/path"; import { EverythingRegistry } from "$/common/everything_registry.ts"; import { load_and_check, load_order } from "$/tools/check_mods.ts"; +import { mod_data } from "$/common/mod_check.ts"; import type { ServerModSource } from "$/server/game/load_mods.ts"; import { GameServer } from "$/server/game/game_server.ts"; import { start_game } from "$/server/game/load_mods.ts"; @@ -41,25 +42,7 @@ function read_mod_sources(mods_dir: string): ServerModSource[] { size: 0, ...(mod.manifest?.engine_access === true ? { engine_access: true } : {}), }, - data: { - blocks: mod.blocks.map((b) => b.json), - models: mod.models.map((m) => m.json), - items: mod.items.map((i) => i.json), - recipes: mod.recipes.map((r) => r.json), - ores: mod.ores.map((o) => o.json), - spawns: mod.spawns.map((s) => s.json), - entities: mod.entities.map((e) => e.json), - entity_models: mod.entity_models.map((m) => m.json), - effects: mod.effects.map((e) => e.json), - tags: mod.tags.map((t) => t.json), - loot_tables: mod.loot_tables.map((t) => t.json), - biomes: mod.biomes.map((b) => b.json), - noises: mod.noises.map((n) => n.json), - density_functions: mod.density_functions.map((d) => d.json), - noise_settings: mod.noise_settings.map((n) => n.json), - biome_sources: mod.biome_sources.map((b) => b.json), - features: mod.features.map((f) => f.json), - }, + data: mod_data(mod), server_url: url(scripts.server), worldgen_url: url(scripts.worldgen), shared_url: url(scripts.shared), @@ -155,6 +138,13 @@ export function sent_block(messages: any[], join: { blocks: string[] }, x: numbe return [join.blocks[value & ID_MASK], value >>> 16]; } +// a stone floor at y 99 from -radius to radius on x and z, high above the terrain, for players to stand on at y 100 +export function stone_floor(game: GameServer, radius = 3) { + for (let x = -radius; x <= radius; x++) { + for (let z = -radius; z <= radius; z++) game.set_block(x, 99, z, "bworld:stone"); + } +} + export function copy_dir(from: string, to: string) { if (Deno.statSync(from).isDirectory) { Deno.mkdirSync(to, { recursive: true }); @@ -174,5 +164,9 @@ export const opened_menu = (messages: Msg[]) => messages.findLast((m) => m.type // what the open menu's slots last held among messages, by menu slot index export const menu_items = (messages: Msg[]) => messages.findLast((m) => m.type === "menu_content")?.items; +// what a container, like "inventory", last held among messages +export const container_items = (messages: Msg[], container: string) => + messages.findLast((m) => m.type === "container" && m.container === container)?.items; + // what the open menu's data last was among messages export const menu_data = (messages: Msg[]) => messages.findLast((m) => m.type === "menu_data")?.data; diff --git a/tests/item_entity_test.ts b/tests/item_entity_test.ts index 93c96ee..86a48cb 100644 --- a/tests/item_entity_test.ts +++ b/tests/item_entity_test.ts @@ -4,7 +4,7 @@ import { assert, assertEquals } from "@std/assert"; import { CRAFTING_RESULT_SLOT, PLAYER_MENU_CRAFTING } from "$/common/protocol.ts"; import { ItemStack } from "$/common/inventory.ts"; -import { test_game } from "./helpers.ts"; +import { container_items, test_game } from "./helpers.ts"; // a stone floor at y 99 so drops have something to land on, high above the generated terrain function build_floor(game: Awaited>["game"]) { @@ -15,11 +15,9 @@ function build_floor(game: Awaited>["game"]) { } } -const inventory_count = ( - messages: { type: string; container?: string; items?: ({ id: string; count: number } | null)[] }[], - id: string, -) => (messages.filter((m) => m.type === "container" && m.container === "inventory").at(-1)?.items ?? []) - .reduce((sum, item) => sum + (item?.id === id ? item.count : 0), 0); +const inventory_count = (messages: unknown[], id: string) => + ((container_items(messages, "inventory") ?? []) as ({ id: string; count: number } | null)[]) + .reduce((sum, item) => sum + (item?.id === id ? item.count : 0), 0); Deno.test("breaking a block drops its item, which lands and gets picked up by walking to it", async () => { const { game, take, send, join } = await test_game("mods"); diff --git a/tests/mod_entity_test.ts b/tests/mod_entity_test.ts index 0a88d11..58c7eae 100644 --- a/tests/mod_entity_test.ts +++ b/tests/mod_entity_test.ts @@ -6,7 +6,7 @@ import { assert, assertEquals, assertStringIncludes } from "@std/assert"; import { entity_model_from_geo, validate_entity } from "$/common/mod_data.ts"; import { Mob } from "$/server/game/entity/mob.ts"; import { create_entity } from "$/server/game/entity/entity_types.ts"; -import { test_game } from "./helpers.ts"; +import { container_items, test_game } from "./helpers.ts"; Deno.test("a bedrock geo.json becomes an entity model with only what the engine uses", () => { const geo = JSON.parse(Deno.readTextFileSync("mods/bworld/models/chicken.geo.json")); @@ -95,7 +95,7 @@ Deno.test("solid blocks can't be placed where a mob or player is", async () => { game.set_block(1, 100, 1, "bworld:stone"); send(1, { type: "move", x: 3.5, y: 101, z: 3.5, yaw: 0, pitch: 0 }); send(1, { type: "chat", text: "/give bworld:stone 2" }); - const inventory = take(1).filter((m) => m.type === "container" && m.container === "inventory").at(-1).items; + const inventory = container_items(take(1), "inventory"); send(1, { type: "select_slot", slot: inventory.findIndex((i: { id: string } | null) => i?.id === "bworld:stone") }); // the chicken's box pokes into the block above the stone, even from the one next to it diff --git a/tests/mod_loading_test.ts b/tests/mod_loading_test.ts index 88a61ea..708d873 100644 --- a/tests/mod_loading_test.ts +++ b/tests/mod_loading_test.ts @@ -10,7 +10,7 @@ import { block_variant } from "$/common/block_models.ts"; import { load_worldgen } from "$/common/worldgen_loader.ts"; import { create_mod } from "$/tools/new_mod.ts"; import { PLAYER_MENU_CRAFTING, PROTOCOL_VERSION } from "$/common/protocol.ts"; -import { copy_dir, test_game } from "./helpers.ts"; +import { container_items, copy_dir, test_game } from "./helpers.ts"; // mods/bworld plus a mod made from the template, in a temp folder function mods_with_template() { @@ -22,8 +22,7 @@ function mods_with_template() { // deno-lint-ignore no-explicit-any type Msg = any; -const inventory_of = (messages: Msg[]) => - messages.filter((m) => m.type === "container" && m.container === "inventory").at(-1)?.items ?? []; +const inventory_of = (messages: Msg[]) => container_items(messages, "inventory") ?? []; Deno.test("the base game loads from mods/bworld", async () => { const { game } = await test_game("mods"); diff --git a/tests/monster_test.ts b/tests/monster_test.ts index 2e57100..87a54d1 100644 --- a/tests/monster_test.ts +++ b/tests/monster_test.ts @@ -5,15 +5,13 @@ import { assert, assertEquals } from "@std/assert"; import { create_entity } from "$/server/game/entity/entity_types.ts"; import { Mob } from "$/server/game/entity/mob.ts"; -import { test_game } from "./helpers.ts"; +import { stone_floor, test_game } from "./helpers.ts"; // a stone floor with alice on it, and a rotwalker 3 blocks away async function setup() { const t = await test_game("mods"); t.join(1, "alice"); - for (let x = -8; x <= 8; x++) { - for (let z = -8; z <= 8; z++) t.game.set_block(x, 99, z, "bworld:stone"); - } + stone_floor(t.game, 8); t.send(1, { type: "move", x: 0.5, y: 100, z: 0.5, yaw: 0, pitch: 0 }); const rotwalker = create_entity(t.game.entities, "undergarden:rotwalker") as Mob; rotwalker.set_position(0.5, 100, 3.5); diff --git a/tests/shift_click_test.ts b/tests/shift_click_test.ts index 5d2e2fa..da00e76 100644 --- a/tests/shift_click_test.ts +++ b/tests/shift_click_test.ts @@ -4,21 +4,16 @@ // shift clicking a slot moves its stack to the other part of the screen, like minecraft's quick move import { assertEquals } from "@std/assert"; import { CRAFTING_RESULT_SLOT, PLAYER_MENU_CRAFTING } from "$/common/protocol.ts"; -import { menu_items, opened_menu, test_game } from "./helpers.ts"; +import { container_items, menu_items, opened_menu, stone_floor, test_game } from "./helpers.ts"; // deno-lint-ignore no-explicit-any type Msg = any; -const last_container = (messages: Msg[], container: string) => - messages.filter((m) => m.type === "container" && m.container === container).at(-1)?.items; - // a player standing on a stone floor, with the items given in their inventory from the first hotbar slot on async function setup(items: [string, number][] = []) { const t = await test_game("mods"); t.join(1, "alice"); - for (let x = -3; x <= 3; x++) { - for (let z = -3; z <= 3; z++) t.game.set_block(x, 99, z, "bworld:stone"); - } + stone_floor(t.game); t.send(1, { type: "move", x: 0.5, y: 100, z: 0.5, yaw: 0, pitch: 0 }); for (const [id, count] of items) t.send(1, { type: "chat", text: `/give ${id} ${count}` }); t.take(1); @@ -28,13 +23,13 @@ async function setup(items: [string, number][] = []) { Deno.test("without a container open, shift clicking moves between the hotbar and the rest of the inventory", async () => { const t = await setup([["bworld:coal", 10], ["bworld:stick", 5]]); t.send(1, { type: "click", menu: 0, slot: 0, button: 0, shift: true }); - let inventory = last_container(t.take(1), "inventory"); + let inventory = container_items(t.take(1), "inventory"); assertEquals(inventory[0], null); assertEquals(inventory[9], { id: "bworld:coal", count: 10 }); // back down it goes to the first free hotbar slot, the sticks are in the second t.send(1, { type: "click", menu: 0, slot: 9, button: 0, shift: true }); - inventory = last_container(t.take(1), "inventory"); + inventory = container_items(t.take(1), "inventory"); assertEquals(inventory[0], { id: "bworld:coal", count: 10 }); assertEquals(inventory[1], { id: "bworld:stick", count: 5 }); assertEquals(inventory[9], null); @@ -46,7 +41,7 @@ Deno.test("shift clicking tops up stacks of the same item before using empty slo t.send(1, { type: "click", menu: 0, slot: 0, button: 2 }); t.send(1, { type: "click", menu: 0, slot: 9, button: 0 }); t.send(1, { type: "click", menu: 0, slot: 0, button: 0, shift: true }); - const inventory = last_container(t.take(1), "inventory"); + const inventory = container_items(t.take(1), "inventory"); assertEquals(inventory[0], null); assertEquals(inventory[9], { id: "bworld:coal", count: 20 }); assertEquals(inventory[10], null); @@ -61,14 +56,14 @@ Deno.test("with a chest open, shift clicking moves between it and the inventory" // the chest's 27 slots, then the inventory's t.send(1, { type: "click", menu: id, slot: 27, button: 0, shift: true }); let messages = t.take(1); - assertEquals(last_container(messages, "inventory")[0], null); + assertEquals(container_items(messages, "inventory")[0], null); assertEquals(menu_items(messages)[0], { id: "bworld:coal", count: 10 }); // like minecraft, out of a container it fills the hotbar from the right t.send(1, { type: "click", menu: id, slot: 0, button: 0, shift: true }); messages = t.take(1); assertEquals(menu_items(messages)[0], null); - assertEquals(last_container(messages, "inventory")[8], { id: "bworld:coal", count: 10 }); + assertEquals(container_items(messages, "inventory")[8], { id: "bworld:coal", count: 10 }); }); Deno.test("shift clicking into a furnace goes by its slot filters, and takes the result out", async () => { @@ -86,13 +81,13 @@ Deno.test("shift clicking into a furnace goes by its slot filters, and takes the { id: "bworld:coal", count: 1 }, null, ]); - assertEquals(last_container(messages, "inventory")[2], { id: "bworld:stick", count: 1 }); + assertEquals(container_items(messages, "inventory")[2], { id: "bworld:stick", count: 1 }); for (let i = 0; i < 210; i++) t.game.tick(); t.send(1, { type: "click", menu: id, slot: 2, button: 0, shift: true }); messages = t.take(1); assertEquals(menu_items(messages)[2], null); - assertEquals(last_container(messages, "inventory")[8], { id: "bworld:iron_ingot", count: 1 }); + assertEquals(container_items(messages, "inventory")[8], { id: "bworld:iron_ingot", count: 1 }); }); Deno.test("shift clicking the crafting result crafts as many as fit", async () => { @@ -102,8 +97,8 @@ Deno.test("shift clicking the crafting result crafts as many as fit", async () = t.send(1, { type: "click", menu: 0, slot: PLAYER_MENU_CRAFTING, button: 0 }); t.send(1, { type: "click", menu: 0, slot: PLAYER_MENU_CRAFTING + CRAFTING_RESULT_SLOT, button: 0, shift: true }); const messages = t.take(1); - assertEquals(last_container(messages, "crafting").every((item: Msg) => item === null), true); - assertEquals(last_container(messages, "inventory")[8], { id: "bworld:oak_planks", count: 6 }); + assertEquals(container_items(messages, "crafting").every((item: Msg) => item === null), true); + assertEquals(container_items(messages, "inventory")[8], { id: "bworld:oak_planks", count: 6 }); }); Deno.test("shift clicking the crafting grid puts its items back in the inventory", async () => { @@ -112,6 +107,6 @@ Deno.test("shift clicking the crafting grid puts its items back in the inventory t.send(1, { type: "click", menu: 0, slot: PLAYER_MENU_CRAFTING + 4, button: 0 }); t.send(1, { type: "click", menu: 0, slot: PLAYER_MENU_CRAFTING + 4, button: 0, shift: true }); const messages = t.take(1); - assertEquals(last_container(messages, "crafting").every((item: Msg) => item === null), true); - assertEquals(last_container(messages, "inventory")[9], { id: "bworld:oak_log", count: 3 }); + assertEquals(container_items(messages, "crafting").every((item: Msg) => item === null), true); + assertEquals(container_items(messages, "inventory")[9], { id: "bworld:oak_log", count: 3 }); }); diff --git a/tools/check_mods.ts b/tools/check_mods.ts index 5c0bc76..7c26981 100644 --- a/tools/check_mods.ts +++ b/tools/check_mods.ts @@ -6,6 +6,7 @@ import { entity_model_from_geo, FORMAT_VERSION, + is_object, OreJson, type SpawnJson, type TagJson, @@ -288,8 +289,7 @@ async function typecheck_scripts(mod: LoadedMod) { .map((path) => `${mod.dir}/${path}`); if (scripts.length === 0) return; - // a mod with its own deno.json is its own deno project, see pack_mod.ts - const config = ["deno.json", "deno.jsonc"].map((name) => `${mod.dir}/${name}`).find(exists) ?? "deno.json"; + const config = mod_deno_config(mod.dir) ?? "deno.json"; const output = await new Deno.Command(Deno.execPath(), { args: ["check", "--config", config, ...scripts], stdout: "piped", @@ -341,6 +341,11 @@ function safe_read_dir(dir: string): Deno.DirEntry[] { } } +// a mod with its own deno.json is its own deno project, see pack_mod.ts +export function mod_deno_config(mod_dir: string): string | undefined { + return ["deno.json", "deno.jsonc"].map((name) => `${mod_dir}/${name}`).find(exists); +} + function exists(path: string) { try { Deno.statSync(path); @@ -350,10 +355,6 @@ function exists(path: string) { } } -function is_object(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value); -} - if (import.meta.main) { const reports = await check_mods(); let errors = 0; diff --git a/tools/pack_mod.ts b/tools/pack_mod.ts index 7b3ff4e..97dff23 100644 --- a/tools/pack_mod.ts +++ b/tools/pack_mod.ts @@ -7,7 +7,8 @@ import { basename, dirname, resolve } from "@std/path"; import { type Bmod, BMOD_EXTENSION, SCRIPT_SIDES, type ScriptSide, write_bmod } from "$/common/bmod.ts"; import type { ManifestJson } from "$/common/mod_data.ts"; -import { load_and_check, type LoadedMod } from "./check_mods.ts"; +import { load_and_check, type LoadedMod, mod_deno_config } from "./check_mods.ts"; +import { mod_data } from "$/common/mod_check.ts"; // what each script is bundled for: the server runs in deno, clients in browsers, worldgen and shared in both const PLATFORMS: Record = { @@ -34,25 +35,7 @@ export async function pack_mod(mod: LoadedMod): Promise> return write_bmod({ manifest, - data: { - blocks: mod.blocks.map((b) => b.json), - models: mod.models.map((m) => m.json), - items: mod.items.map((i) => i.json), - recipes: mod.recipes.map((r) => r.json), - ores: mod.ores.map((o) => o.json), - spawns: mod.spawns.map((s) => s.json), - entities: mod.entities.map((e) => e.json), - entity_models: mod.entity_models.map((m) => m.json), - effects: mod.effects.map((e) => e.json), - tags: mod.tags.map((t) => t.json), - loot_tables: mod.loot_tables.map((t) => t.json), - biomes: mod.biomes.map((b) => b.json), - noises: mod.noises.map((n) => n.json), - density_functions: mod.density_functions.map((d) => d.json), - noise_settings: mod.noise_settings.map((n) => n.json), - biome_sources: mod.biome_sources.map((b) => b.json), - features: mod.features.map((f) => f.json), - }, + data: mod_data(mod), scripts, textures, texture_json, @@ -63,7 +46,7 @@ export async function pack_mod(mod: LoadedMod): Promise> // a mod is a deno project: with its own deno.json its scripts are bundled with it (its imports, npm packages and // so on), otherwise with the deno.json of the folder the build runs in async function bundle_script(mod_dir: string, entry: string, platform: "deno" | "browser"): Promise { - const config = ["deno.json", "deno.jsonc"].map((name) => `${mod_dir}/${name}`).find(exists); + const config = mod_deno_config(mod_dir); if (!config) { const result = await Deno.bundle({ entrypoints: [entry], platform, write: false, minify: false }); if (!result.success || !result.outputFiles?.length) { @@ -89,15 +72,6 @@ async function bundle_script(mod_dir: string, entry: string, platform: "deno" | } } -function exists(path: string) { - try { - Deno.statSync(path); - return true; - } catch { - return false; - } -} - if (import.meta.main) { const [dir, out] = Deno.args; if (!dir) {