From 3af5f6e54bbbc7ba2561b292c46482d9cf5c403c Mon Sep 17 00:00:00 2001 From: paulaboks Date: Wed, 30 Sep 2026 15:22:32 -0300 Subject: [PATCH] Curios and artifacts ! --- MODS.md | 5 +- client/gui/gui_container.ts | 9 +- client/gui/gui_screen.ts | 15 ++- client/mods.ts | 33 ++++- client/packet_listener.ts | 4 + common/mod_api/server.ts | 20 +++ common/protocol.ts | 14 ++- docs/modding/entities/players.md | 26 ++++ docs/modding/gui/index.md | 5 +- docs/modding/inventories/menus.md | 1 + docs/modding/items/index.md | 3 + docs/modding/networking/index.md | 15 ++- docs/modding_plan.md | 10 +- mods/artifacts/CREDITS.md | 28 +++++ mods/artifacts/items/feral_claws.json | 13 ++ mods/artifacts/items/power_glove.json | 13 ++ mods/artifacts/manifest.json | 23 ++++ mods/artifacts/tags/items/curios/hands.json | 6 + mods/artifacts/textures/feral_claws.png | Bin 0 -> 220 bytes mods/artifacts/textures/power_glove.png | Bin 0 -> 1529 bytes mods/curios/CREDITS.md | 21 ++++ mods/curios/README.md | 45 +++++++ mods/curios/manifest.json | 17 +++ mods/curios/scripts/client.ts | 21 ++++ mods/curios/scripts/server.ts | 123 +++++++++++++++++++ mods/curios/scripts/slots.ts | 29 +++++ mods/curios/textures/empty_back_slot.png | Bin 0 -> 145 bytes mods/curios/textures/empty_belt_slot.png | Bin 0 -> 144 bytes mods/curios/textures/empty_body_slot.png | Bin 0 -> 152 bytes mods/curios/textures/empty_bracelet_slot.png | Bin 0 -> 157 bytes mods/curios/textures/empty_charm_slot.png | Bin 0 -> 139 bytes mods/curios/textures/empty_curio_slot.png | Bin 0 -> 140 bytes mods/curios/textures/empty_feet_slot.png | Bin 0 -> 149 bytes mods/curios/textures/empty_hands_slot.png | Bin 0 -> 158 bytes mods/curios/textures/empty_head_slot.png | Bin 0 -> 157 bytes mods/curios/textures/empty_necklace_slot.png | Bin 0 -> 152 bytes mods/curios/textures/empty_ring_slot.png | Bin 0 -> 144 bytes server/game/entity/attributes.ts | 6 +- server/game/game_server.ts | 17 ++- server/game/mod_runtime.ts | 84 +++++++++++-- server/game/player.ts | 10 ++ tests/artifacts_test.ts | 46 +++++++ tests/curios_test.ts | 74 +++++++++++ tests/entity_test.ts | 28 ++++- tests/handshake_test.ts | 8 +- 45 files changed, 729 insertions(+), 43 deletions(-) create mode 100644 mods/artifacts/CREDITS.md create mode 100644 mods/artifacts/items/feral_claws.json create mode 100644 mods/artifacts/items/power_glove.json create mode 100644 mods/artifacts/manifest.json create mode 100644 mods/artifacts/tags/items/curios/hands.json create mode 100644 mods/artifacts/textures/feral_claws.png create mode 100644 mods/artifacts/textures/power_glove.png create mode 100644 mods/curios/CREDITS.md create mode 100644 mods/curios/README.md create mode 100644 mods/curios/manifest.json create mode 100644 mods/curios/scripts/client.ts create mode 100644 mods/curios/scripts/server.ts create mode 100644 mods/curios/scripts/slots.ts create mode 100644 mods/curios/textures/empty_back_slot.png create mode 100644 mods/curios/textures/empty_belt_slot.png create mode 100644 mods/curios/textures/empty_body_slot.png create mode 100644 mods/curios/textures/empty_bracelet_slot.png create mode 100644 mods/curios/textures/empty_charm_slot.png create mode 100644 mods/curios/textures/empty_curio_slot.png create mode 100644 mods/curios/textures/empty_feet_slot.png create mode 100644 mods/curios/textures/empty_hands_slot.png create mode 100644 mods/curios/textures/empty_head_slot.png create mode 100644 mods/curios/textures/empty_necklace_slot.png create mode 100644 mods/curios/textures/empty_ring_slot.png create mode 100644 tests/artifacts_test.ts create mode 100644 tests/curios_test.ts diff --git a/MODS.md b/MODS.md index 9c52ead..4132fbc 100644 --- a/MODS.md +++ b/MODS.md @@ -76,6 +76,5 @@ deno task build && deno task server # packs the mods and starts a se The API types are the reference for everything scripts can call. Scripts import them as `bworld/server`, `bworld/client` and `bworld/worldgen`, and they live in [`common/mod_api/`](common/mod_api/). -A few parts of those types aren't built yet and throw when used: forms, custom screens, HUD elements, keybinds and mod -channels. [`docs/modding_plan.md`](docs/modding_plan.md) covers those, what else is planned, and the design behind the -mod API. +A few parts of those types aren't built yet and throw when used: forms, custom screens, HUD elements and keybinds. +[`docs/modding_plan.md`](docs/modding_plan.md) covers those, what else is planned, and the design behind the mod API. diff --git a/client/gui/gui_container.ts b/client/gui/gui_container.ts index b53d2c8..8c1e7a6 100644 --- a/client/gui/gui_container.ts +++ b/client/gui/gui_container.ts @@ -36,7 +36,14 @@ export class GuiContainer extends GuiInventoryScreen { for (const slot of layout.slots) { this.slots.push( - new Slot("screen", slot.index, MARGIN + slot.x * SLOT_SIZE, AREA_Y + slot.y * SLOT_SIZE, slot.output), + new Slot( + "screen", + slot.index, + MARGIN + slot.x * SLOT_SIZE, + AREA_Y + slot.y * SLOT_SIZE, + slot.output, + slot.icon, + ), ); } } diff --git a/client/gui/gui_screen.ts b/client/gui/gui_screen.ts index ac8cfa0..6f7e26c 100644 --- a/client/gui/gui_screen.ts +++ b/client/gui/gui_screen.ts @@ -5,7 +5,9 @@ import { ClientMessage, ContainerKey, CRAFTING_RESULT_SLOT } from "$/common/prot import { point_inside_rec } from "../../common/utils.ts"; import { InputManager } from "../input_manager.ts"; import { ClientInventories } from "../inventory.ts"; -import { canvas } from "../renderer/mod.ts"; +import { canvas, draw_texture_region, Texture } from "../renderer/mod.ts"; +import { AssetManager } from "../assets.ts"; +import { get_sprite_region } from "../sprites.ts"; import { draw_item } from "../rendering/render_utils.ts"; import { draw_tooltip, item_tooltip } from "./tooltip.ts"; import { ModGraphics } from "./mod_graphics.ts"; @@ -22,13 +24,16 @@ export class Slot { y: number; // can only be taken from, like the crafting or furnace result output: boolean; + // a texture drawn while it's empty, like minecraft's armor slots + icon: string | undefined; - constructor(container: ContainerKey, index: number, x: number, y: number, output = false) { + constructor(container: ContainerKey, index: number, x: number, y: number, output = false, icon?: string) { this.container = container; this.index = index; this.x = x; this.y = y; this.output = output; + this.icon = icon; } } @@ -102,6 +107,12 @@ export class GuiInventoryScreen extends GuiScreen { const item = this.get_container(slot.container)?.get_item(slot.index); if (item) { draw_item(item, this.x + slot.x, this.y + slot.y); + } else if (slot.icon) { + // where an item's sprite would be + const icon = get_sprite_region(slot.icon); + const atlas = AssetManager.instance.get("bworld:textures"); + const [x, y, size] = [this.x + slot.x + 3, this.y + slot.y + 3, SLOT_SIZE - 6]; + draw_texture_region(atlas, icon.x, icon.y, icon.width, icon.height, x, y, size, size); } } highlight("slot_highlight_front"); diff --git a/client/mods.ts b/client/mods.ts index de118bc..20f31d9 100644 --- a/client/mods.ts +++ b/client/mods.ts @@ -20,6 +20,20 @@ let client: Client | undefined; // what mods draw on inventory screens, see GuiInventoryScreen export const inventory_overlays: { mod: string; overlay: InventoryOverlay }[] = []; +// mod channels, see ctx.net: who listens on each channel +const net_handlers = new Map void }[]>(); + +// the server sent a mod message +export function receive_mod_message(channel: string, data: unknown) { + for (const { mod, handler } of net_handlers.get(channel) ?? []) { + try { + handler(data); + } catch (e) { + console.error(`[${mod}] a ${channel} handler threw:`, e); + } + } +} + // the loaded mods' recipes, and their names by id let recipe_book = new RecipeBook(); const mod_names = new Map(); @@ -54,6 +68,7 @@ export async function load_client_mods(listings: ModListing[], bmods: Bmod[]) { const recipes = register_mod_data(bmods.map((bmod) => ({ id: bmod.manifest.id, data: bmod.data }))); recipe_book = recipes; inventory_overlays.length = 0; + net_handlers.clear(); mod_names.clear(); for (const listing of listings) mod_names.set(listing.id, listing.name); @@ -89,6 +104,11 @@ function client_context(listing: ModListing): ClientContext { const not_yet_fn = (name: string) => () => { throw new Error(`[${mod}] ctx.ui.${name} isn't implemented yet (custom screens, see docs/modding_plan.md)`); }; + const own = (channel: string) => { + if (!channel.startsWith(`${mod}:`)) { + throw new Error(`[${mod}] channel ${channel} must be in the namespace "${mod}"`); + } + }; const known_item = (id: string) => { const item = EverythingRegistry.get("items", id); if (!item) throw new Error(`[${mod}] unknown item ${id}`); @@ -106,7 +126,18 @@ function client_context(listing: ModListing): ClientContext { }, hud: not_yet("hud", "HUD elements") as ClientContext["hud"], input: not_yet("input", "keybinds") as ClientContext["input"], - net: not_yet("net", "mod channels") as ClientContext["net"], + net: { + on(channel, handler) { + own(channel); + const handlers = net_handlers.get(channel) ?? []; + handlers.push({ mod, handler: handler as (data: unknown) => void }); + net_handlers.set(channel, handlers); + }, + send(channel, data) { + own(channel); + need_client().connection.send({ type: "mod", channel, data }); + }, + }, player: { get name() { return need_client().connection.name; diff --git a/client/packet_listener.ts b/client/packet_listener.ts index 109b94c..ab9319d 100644 --- a/client/packet_listener.ts +++ b/client/packet_listener.ts @@ -7,6 +7,7 @@ import { RemotePlayer } from "./entity/remote_player.ts"; import { ItemEntity } from "./entity/item_entity.ts"; import { RemoteEntity } from "./entity/remote_entity.ts"; import { Player } from "./entity/player.ts"; +import { receive_mod_message } from "./mods.ts"; // minecraft's ChunkBatchSizeCalculator: how long loading a chunk takes here, so the server sends as many a tick as // fit in CHUNK_BUDGET_MS @@ -236,6 +237,9 @@ export class ClientPacketListener { } break; } + case "mod": + receive_mod_message(message.channel, message.data); + break; case "close_screen": // closed by the server (the block broke), it already put everything back client.screens = client.screens.filter((s) => !(s instanceof GuiContainer)); diff --git a/common/mod_api/server.ts b/common/mod_api/server.ts index 3170d3d..c750a8c 100644 --- a/common/mod_api/server.ts +++ b/common/mod_api/server.ts @@ -227,6 +227,21 @@ export interface Player { feed(nutrition: number, saturation_modifier: number): void; // tires them out: 4 costs a point of saturation, or of hunger once it's gone add_exhaustion(amount: number): void; + // their stats, like minecraft's attributes: "bworld:attack_damage", "bworld:attack_speed", "bworld:max_health"... + // see docs/modding/entities/players.md. modifiers aren't saved, they're gone when the player leaves + attribute(id: Id): number; + // replaces one with the same id on that attribute + add_modifier(attribute: Id, modifier: AttributeModifier): void; + // whether it had it + remove_modifier(attribute: Id, id: string): boolean; +} + +// like minecraft's: the base, plus every add_value, plus that times each add_multiplied_base, then times 1 + each +// add_multiplied_total +export interface AttributeModifier { + id: string; + amount: number; + operation: "add_value" | "add_multiplied_base" | "add_multiplied_total"; } export interface PlayerList { @@ -272,6 +287,9 @@ export interface ItemApi { max_stack(id: Id): number; // the tool type it is, like "pickaxe" or "shovel", from the item's "tool" tool(id: Id): string | undefined; + // the components its json lists and their params, a copy. a mod can read params of its components this way + // without a stack, like curios does for curios:attribute_modifiers + components(id: Id): Record; } export interface RecipeApi { @@ -328,6 +346,8 @@ export interface ContainerScreenOptions { output_only?: boolean; // runs when a player takes from an output_only slot, before they get it. false stops them taking it on_take?: (item: ItemStack) => boolean; + // a texture drawn in the slot while it's empty, like minecraft's armor slots + icon?: Id; }[]; // height of the screen's area in slots, fits the layout and bars when not set rows?: number; diff --git a/common/protocol.ts b/common/protocol.ts index 2de5f49..cf3bfb5 100644 --- a/common/protocol.ts +++ b/common/protocol.ts @@ -7,7 +7,7 @@ export const AIR_ID = "bworld:air"; // bump when a client and server of different versions can't play together. // the server rejects a different version before the client downloads anything -export const PROTOCOL_VERSION = 9; +export const PROTOCOL_VERSION = 10; export interface PlayerInfo { id: string; @@ -59,8 +59,8 @@ export interface ScreenLayout { // height of the screen's own area, in slots rows: number; // x and y in slots, can be fractional - // output slots can only be taken from, like the furnace result - slots: { index: number; x: number; y: number; output?: boolean }[]; + // output slots can only be taken from, like the furnace result. icon is a texture drawn in the slot while it's empty + slots: { index: number; x: number; y: number; output?: boolean; icon?: string }[]; // progress bars filled from properties[value] / properties[max] bars: { x: number; @@ -103,7 +103,9 @@ export type ClientMessage = | { type: "close_screen" } | { type: "chat"; text: string } // what could come next in a command being typed, answered with suggestions. id matches them up - | { type: "suggest"; id: number; text: string }; + | { type: "suggest"; id: number; text: string } + // a mod's client script talking to its server script, see ctx.net + | { type: "mod"; channel: string; data: unknown }; export type ServerMessage = // what to download before joining, see docs/modding/networking/index.md @@ -187,7 +189,9 @@ export type ServerMessage = // answers suggest: start is where in the text the suggestions replace from, up to the caret | { type: "suggestions"; id: number; start: number; suggestions: { text: string; tooltip?: string }[] } // the player's own health, hunger and saturation, when they change - | { type: "vitals"; health: number; food: number; saturation: number }; + | { type: "vitals"; health: number; food: number; saturation: number } + // a mod's server script talking to its client script, see ctx.net + | { type: "mod"; channel: string; data: unknown }; export const MAX_NAME_LENGTH = 16; export const MAX_CHAT_LENGTH = 256; diff --git a/docs/modding/entities/players.md b/docs/modding/entities/players.md index 777c749..81b66df 100644 --- a/docs/modding/entities/players.md +++ b/docs/modding/entities/players.md @@ -37,6 +37,10 @@ interface Player { heal(amount: number): void; feed(nutrition: number, saturation_modifier: number): void; add_exhaustion(amount: number): void; + + attribute(id: string): number; + add_modifier(attribute: string, modifier: AttributeModifier): void; + remove_modifier(attribute: string, id: string): boolean; } ``` @@ -64,6 +68,28 @@ even when their game isn't running, like in a background tab. `damage(amount, cause)` hurts them like anything else would. `cause` shows in the `player_damage` and `player_death` [events](../concepts/events.md) and in the death message. Before events can change the amount or cancel it. +## Attributes + +A player's stats are attributes, like Minecraft's: a base value that modifiers change without touching it. + +| Attribute | Base | Meaning | +| ---------------------- | ---- | -------------------------------------------------------------------------- | +| `bworld:attack_damage` | 1 | How much their hits do. | +| `bworld:attack_speed` | 4 | Full strength attacks a second. Hitting sooner than that does less damage. | + +```ts +player.add_modifier("bworld:attack_damage", { id: "my_mod:rage", amount: 2, operation: "add_value" }); +player.attribute("bworld:attack_damage"); // 3 +player.remove_modifier("bworld:attack_damage", "my_mod:rage"); +``` + +The value is the base, plus every `add_value`, plus that times the amount of each `add_multiplied_base`, then times 1 +plus the amount of each `add_multiplied_total`. A modifier with the same id replaces the old one. Modifiers aren't +saved: a mod that gives them should give them again when the player joins, the way Curios does for worn items. + +Like Minecraft, an attack right after the last one, or right after changing the held item, does only a fifth of the +damage, rising to full after `20 / attack_speed` ticks. + ## Death When a player dies, everything they carried falls out where they died, and their tools lose durability (see diff --git a/docs/modding/gui/index.md b/docs/modding/gui/index.md index 204025d..fbbe163 100644 --- a/docs/modding/gui/index.md +++ b/docs/modding/gui/index.md @@ -110,8 +110,7 @@ The client and server APIs have types for these, but calling them throws for now - **Custom screens** (`ctx.ui.register_screen` and `open` on the client, `open_screen` on the server): whole screens drawn with `Graphics`, opened by the server with some props. - **HUD elements** (`ctx.hud.register`): drawing over the world every frame. -- **Keybinds** (`ctx.input.bind`). -- **Mod channels** (`ctx.net`), for a mod's client and server scripts to talk. Without them, a client script can't send - anything to the server. +- **Keybinds** (`ctx.input.bind`). Until then, an inventory overlay can check `g.key_pressed` while an inventory is + open. See [the modding plan](../../modding_plan.md) for how they're meant to work. diff --git a/docs/modding/inventories/menus.md b/docs/modding/inventories/menus.md index b474390..38f240d 100644 --- a/docs/modding/inventories/menus.md +++ b/docs/modding/inventories/menus.md @@ -54,6 +54,7 @@ Give the block `"interactive": true` so clients don't guess that the click place | `filter` | What can be put in: `"smeltable"` (has a furnace recipe), `"fuel"`, or a function `(item) => boolean`. | | `output_only` | Can only be taken from, all at once, like the furnace result. | | `on_take` | For `output_only` slots: runs when a player takes from it, before they get the item. Return `false` to stop them. | +| `icon` | A texture drawn in the slot while it's empty, like Minecraft's armor slots. | `rows` sets the height of the screen's area in slots. By default it fits the slots and bars. diff --git a/docs/modding/items/index.md b/docs/modding/items/index.md index df91c32..eb449ae 100644 --- a/docs/modding/items/index.md +++ b/docs/modding/items/index.md @@ -96,6 +96,9 @@ and items list them with their parameters: At a block, the block's own [interaction](../blocks/components.md#interacting) comes first. An item with `on_use` is used instead of being placed. +`ctx.items.components(id)` gives the components an item's JSON lists and their parameters, so a mod can read its +components' parameters for an item without a stack, like Curios does for `curios:attribute_modifiers`. + `on_use` doesn't say which block was clicked. For that, pair it with a block component's `on_interact`, the way the watering can uses `bworld:water_source`, or subscribe to the `block_interact` [event](../concepts/events.md). diff --git a/docs/modding/networking/index.md b/docs/modding/networking/index.md index 805666c..b4308ed 100644 --- a/docs/modding/networking/index.md +++ b/docs/modding/networking/index.md @@ -59,10 +59,7 @@ server code are never sent at all. See [Sides](../concepts/sides.md#what-each-si ## Mod Channels -> [!NOTE] -> Not built yet. `ctx.net` exists on both sides but throws. - -Mod channels will let a mod's client and server scripts send each other JSON messages: +Mod channels let a mod's client and server scripts send each other JSON messages: ```ts // server.ts @@ -75,5 +72,11 @@ ctx.net.on("copper_tools:heat", (data) => {/* ... */}); ctx.net.send("copper_tools:reset_stats", {}); ``` -Until then, the server reaches the client through what's already synced: [container screens](../inventories/menus.md) -and their properties, item stack `data`, block states, and displayed items. +- Channel ids are in the mod's namespace, and a mod only listens and sends on its own. +- A message from a client is at most 16 KB of JSON, and each player can send at most 60 a second. The server drops + anything over that without telling anyone. +- Everything a client sends is untrusted: check it like a click or a chat message. +- A handler that throws is logged under its mod, and the other handlers still run. + +Curios (`mods/curios`) is a small example: its client script's button sends `curios:open`, and its server script opens +the curio slots for that player. diff --git a/docs/modding_plan.md b/docs/modding_plan.md index edf4854..2efc422 100644 --- a/docs/modding_plan.md +++ b/docs/modding_plan.md @@ -26,13 +26,13 @@ A mod is built from up to three layers. Most mods only need the first one or two server and worldgen scripts), delivery to clients (hashed downloads, the confirm screen for other sites, credits), the data layer (blocks, block models with variants, items, recipes including mods' own types, entities and entity models, ores), server scripts (components, events, commands, timers, storage, recipes, containers, container screens, displayed -items), client scripts (item and recipe lookups, inventory overlays with `Graphics`), worldgen features and ores, the -base game's block behavior as a mod, and world time. +items), client scripts (item and recipe lookups, inventory overlays with `Graphics`), mod channels, worldgen features +and ores, the base game's block behavior as a mod, and world time. The code is in `common/mod_loader.ts`, `common/mod_data.ts`, `common/mod_check.ts`, `common/bmod.ts`, `server/game/mod_runtime.ts`, `server/load_bmods.ts`, `client/mods.ts` and `common/worldgen_loader.ts`. -**In the API types but throwing:** forms, custom screens, HUD elements, keybinds, mod channels, `g.slider`, `g.slots`, +**In the API types but throwing:** forms, custom screens, HUD elements, keybinds, `g.slider`, `g.slots`, `register_terrain`. **Not built at all:** common scripts, the registry freeze and hash, overrides, engine access. @@ -315,8 +315,8 @@ manifest and its checks, and making the engine hookable where mods will want it. client and a worldgen method, hooks on one method run in priority order, and a throwing hook is logged without breaking the game. -**Phase 4: the rest of the Game API.** Mod channels, keybinds, forms, custom screens and HUD elements. More events: -items picked up and dropped, containers clicked, players moving between chunks, entities. +**Phase 4: the rest of the Game API.** Keybinds, forms, custom screens and HUD elements. More events: items picked up +and dropped, containers clicked, players moving between chunks, entities. **Phase 5: gameplay out of the engine.** Everything marked phase 5 in the table above moves into `mods/bworld`. Mining rules become something `mods/bworld` sets, with the engine asking it on both sides so clients still predict breaking. diff --git a/mods/artifacts/CREDITS.md b/mods/artifacts/CREDITS.md new file mode 100644 index 0000000..9cbc4c6 --- /dev/null +++ b/mods/artifacts/CREDITS.md @@ -0,0 +1,28 @@ +# Artifacts + +A bworld port of [Artifacts](https://github.com/ochotonida/artifacts) by ochotonida. Its textures and game design come +from the original, version 15.1.3 for NeoForge 26.1.2, under the MIT license: + +``` +MIT License + +Copyright (c) 2019 Wouter Pauwels + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` diff --git a/mods/artifacts/items/feral_claws.json b/mods/artifacts/items/feral_claws.json new file mode 100644 index 0000000..f467cce --- /dev/null +++ b/mods/artifacts/items/feral_claws.json @@ -0,0 +1,13 @@ +{ + "format_version": 1, + "item": { + "id": "artifacts:feral_claws", + "texture": "artifacts:feral_claws", + "max_stack": 1, + "components": { + "curios:attribute_modifiers": [ + { "attribute": "bworld:attack_speed", "amount": 0.3, "operation": "add_multiplied_base" } + ] + } + } +} diff --git a/mods/artifacts/items/power_glove.json b/mods/artifacts/items/power_glove.json new file mode 100644 index 0000000..30ed6b3 --- /dev/null +++ b/mods/artifacts/items/power_glove.json @@ -0,0 +1,13 @@ +{ + "format_version": 1, + "item": { + "id": "artifacts:power_glove", + "texture": "artifacts:power_glove", + "max_stack": 1, + "components": { + "curios:attribute_modifiers": [ + { "attribute": "bworld:attack_damage", "amount": 4, "operation": "add_value" } + ] + } + } +} diff --git a/mods/artifacts/manifest.json b/mods/artifacts/manifest.json new file mode 100644 index 0000000..f0d998e --- /dev/null +++ b/mods/artifacts/manifest.json @@ -0,0 +1,23 @@ +{ + "format_version": 1, + "id": "artifacts", + "name": "Artifacts", + "description": "A port of ochotonida's Artifacts: wearable items worn in Curios slots.", + "version": "0.1.0", + "authors": [ + "ochotonida (original)", + "paula (port)" + ], + "game_version": ">=0.1.0", + "dependencies": [ + { + "id": "bworld", + "version": "*" + }, + { + "id": "curios", + "version": "*" + } + ], + "credits": "CREDITS.md" +} diff --git a/mods/artifacts/tags/items/curios/hands.json b/mods/artifacts/tags/items/curios/hands.json new file mode 100644 index 0000000..12de837 --- /dev/null +++ b/mods/artifacts/tags/items/curios/hands.json @@ -0,0 +1,6 @@ +{ + "format_version": 1, + "tag": { + "values": ["artifacts:power_glove", "artifacts:feral_claws"] + } +} diff --git a/mods/artifacts/textures/feral_claws.png b/mods/artifacts/textures/feral_claws.png new file mode 100644 index 0000000000000000000000000000000000000000..e890ebbbd91af840976108bc3a173eb35ad6159e GIT binary patch literal 220 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!73?$#)eFPFv4DbnY1=7kwe2n(op?V6eQ34rG zrh;X{lHHJ`1Vqo=w#m7(@gT#JWqX_&Lm5tF6bFVUu)X?p zX4b`)CB7m{d_7loFlrn(YHf^cyehEbL}TMclK_UK)e9I7u`)!aidr1lYu5#|l)=;0 K&t;ucLK6Ubj!awt literal 0 HcmV?d00001 diff --git a/mods/artifacts/textures/power_glove.png b/mods/artifacts/textures/power_glove.png new file mode 100644 index 0000000000000000000000000000000000000000..7d901d4520370afb609741714a66052a21d2f1fa GIT binary patch literal 1529 zcmV zaB^>EX>4U6ba`-PAZ2)IW&i+q+Pzj=a_lG!{bv=k1SBC4%fURV?ha=8bFgXmBi%_S zxiuzfY>@RhN0M><-#^3sgNwa*7c^PSF?w7fhs*^x=C4;@^RY%g?7x?b)-SoI8;n^n z%dwck+Lg6_k&ovLMNc+JA6}5t4Br|~Wv#R4JC9=b$=_af{U4**82yN@ga{bo5!7MA zUDQBu14^>L7BLe3758Z$8N+<>m4a`+`VFH}CMNNN0yRg426bwfD^>UyxO2kHTv_%t zlf;>;cp(XM(BLFlnwYRu?jjPL@aYTfcJpqplEHE#h%!ML;gwH^`%2)QF-G;khzQZs z!U}#dPabH(DDxL$AcV%^O?QAVuBlhuIKd@!O$dQ@ZAs>?qLhs{*}|q<+|p)S-bzLK)KIm?nyS@YOXDUjG;Oh^ zW-YhUsUwwK4_$lgsawyz4CLC75r&R9(y)<7Iayn*ei+|ijTURXGd1PX$r@Hunu>N6 zH2aKB&cGN40^?~ifQ07BnKuf7Cv%fCpBYu53@3GR)5sS`5fp|_tbcf7w!d3t_A2+|9|3^hb>%8Hus~@or zmi1WbpsTd|JN|rB^kDy7PI@e7>j`bT?CTxbbq(#6uiu>ASCHJf(qlQE+QtrK?z5i44)m(~u^9wpb| z7Y-$KRQ@O+%-+1Tl(JM!HEXcp@ z_zd8z@_|iTQkJi6&Mk3Y1V@qeCKB?p`gWPPi^?LWFNH1!Z#=x()~80?T^s&|Pam8A zjc?y6e|Na@eN0|qj zkkPQYxsf#JqL^C1IJn{1gn@hxl_sUoI_Pb8_uk!mZ|>kftzA`R8fGu4u+cPujs&>6 zT`Iqx`t?$mhA!mW5V`i-RaI_dl-Ufp(=4Nb4S?rF{YKM_trcrf$gdbrR0{bO{h{FE z%%?vT04!!U?likwgLYMw!QKJ5Wd()TmXGJapr@vbxR}{^4&n6U^ZHN529~%}5y8il zHFO~h`4y$&5>1chT9%;e_(~#!uH!2PLY9hzLMB;eTX3E$qv^1JSPxl@Co1z?IbDO3 z(~7JaCYLt=pFkzd)eI9rKHT3aiI+HX9@pT|2k3P>e9YZs2Acr)`6*F@t@nMP9qoLg fckfmC(~tcIN9KC?dcX=700000NkvXXu0mjf3p?UE literal 0 HcmV?d00001 diff --git a/mods/curios/CREDITS.md b/mods/curios/CREDITS.md new file mode 100644 index 0000000..4eedecd --- /dev/null +++ b/mods/curios/CREDITS.md @@ -0,0 +1,21 @@ +# Curios + +A bworld port of [Curios](https://github.com/TheIllusiveC4/Curios) by C4. Its slot textures and game design come from +the original, version 17.0.0-beta.2 for NeoForge 26.3, under the GNU Lesser General Public License, version 3 or later: + +``` +Copyright (C) 2018-2024 C4 + +Curios is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published +by the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Curios is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with Curios. If not, see . +``` diff --git a/mods/curios/README.md b/mods/curios/README.md new file mode 100644 index 0000000..10e0623 --- /dev/null +++ b/mods/curios/README.md @@ -0,0 +1,45 @@ +# Curios + +A port of [Curios](https://github.com/TheIllusiveC4/Curios): accessory slots, like rings, necklaces and belts, for any +mod's items. Players open them with the Curios button next to their inventory, or G while an inventory is open. + +Like the original, Curios adds no items and no slots of its own. A slot type only shows up once some mod puts an item in +its tag. + +## Making an Item a Curio + +Add the item to the slot type's item tag. For a ring, `tags/items/curios/ring.json` in your mod: + +```json +{ "format_version": 1, "tag": { "values": ["jewelry:gold_ring"] } } +``` + +| Tag | Slot | +| ------------------ | ---------------------- | +| `#curios:curio` | Any slot, and its own. | +| `#curios:head` | Head | +| `#curios:necklace` | Necklace | +| `#curios:back` | Back | +| `#curios:body` | Body | +| `#curios:bracelet` | Bracelet | +| `#curios:hands` | Hands | +| `#curios:ring` | Ring | +| `#curios:belt` | Belt | +| `#curios:feet` | Feet | +| `#curios:charm` | Charm | + +Every player has one slot of each type. Curios drop when the player dies, like the rest of what they carry. + +## Attribute Modifiers + +An item with the `curios:attribute_modifiers` component changes the wearer's +[attributes](../../docs/modding/entities/players.md#attributes) while it's in a curio slot, and says so in its tooltip. +The Power Glove from Artifacts: + +```json +"components": { + "curios:attribute_modifiers": [{ "attribute": "bworld:attack_damage", "amount": 4, "operation": "add_value" }] +} +``` + +Depend on `curios` to use it. diff --git a/mods/curios/manifest.json b/mods/curios/manifest.json new file mode 100644 index 0000000..4a4c4c3 --- /dev/null +++ b/mods/curios/manifest.json @@ -0,0 +1,17 @@ +{ + "format_version": 1, + "id": "curios", + "name": "Curios", + "description": "A port of C4's Curios: accessory slots like rings, necklaces and belts, for any mod's items.", + "version": "0.1.0", + "authors": [ + "C4 (original)", + "paula (port)" + ], + "game_version": ">=0.1.0", + "credits": "CREDITS.md", + "scripts": { + "server": "scripts/server.ts", + "client": "scripts/client.ts" + } +} diff --git a/mods/curios/scripts/client.ts b/mods/curios/scripts/client.ts new file mode 100644 index 0000000..b70e64b --- /dev/null +++ b/mods/curios/scripts/client.ts @@ -0,0 +1,21 @@ +// the curios button next to every inventory screen, or G like curios' keybind, asks the server to show the slots +import type { ClientContext } from "bworld/client"; +import { active_slots } from "./slots.ts"; + +const GAP = 16; +const WIDTH = 120; +const HEIGHT = 32; + +export function setup(ctx: ClientContext) { + // no item goes in any slot, so there's nothing to show + if (active_slots(ctx.tags).length === 0) return; + + ctx.ui.add_inventory_overlay({ + on_render(g, screen) { + const clicked = g.button("Curios", screen.x - WIDTH - GAP, screen.y, WIDTH, HEIGHT); + if (clicked || g.key_pressed("KeyG")) { + ctx.net.send("curios:open", {}); + } + }, + }); +} diff --git a/mods/curios/scripts/server.ts b/mods/curios/scripts/server.ts new file mode 100644 index 0000000..c52e19e --- /dev/null +++ b/mods/curios/scripts/server.ts @@ -0,0 +1,123 @@ +// curios: accessory slots, shown with the player's inventory from the curios button. each player's curios are a +// container of their own, and fall out when they die like the rest of what they carry. items with the +// curios:attribute_modifiers component change the wearer's attributes, like curios' attribute modifiers +import type { AttributeModifier, Container, Player, ServerContext } from "bworld/server"; +import { active_slots, fits, SLOTS } from "./slots.ts"; + +// curios:attribute_modifiers' params, a list of these +interface WornModifier { + attribute: string; + amount: number; + operation: AttributeModifier["operation"]; +} + +export function setup(ctx: ServerContext) { + const active = active_slots(ctx.tags); + + ctx.components.register_item("curios:attribute_modifiers", { + get_lore: (_item, modifiers) => ["When worn:", ...modifiers.map(describe)].join("\n"), + }); + const modifiers_of = (id: string) => + (ctx.items.components(id)["curios:attribute_modifiers"] ?? []) as WornModifier[]; + + // the modifiers each online player's curios gave them, by player id, to take them off again + const applied = new Map(); + const stop_watching = new Map void>(); + + // by player name, like the players themselves are saved. undefined until they first open curios + function saved_curios(player: Player): Container | undefined { + const id = ctx.storage.get>("containers")?.[player.name]; + return id ? ctx.containers.get(id) : undefined; + } + + function curios_of(player: Player): Container { + const existing = saved_curios(player); + if (existing) return existing; + const container = ctx.containers.create(SLOTS.length); + const ids = ctx.storage.get>("containers") ?? {}; + ctx.storage.set("containers", { ...ids, [player.name]: container.id }); + watch(player, container); + return container; + } + + // keeps what their curios give them up to date + function watch(player: Player, curios: Container) { + stop_watching.get(player.id)?.(); + stop_watching.set(player.id, curios.on_change(() => update_modifiers(player, curios))); + update_modifiers(player, curios); + } + + function update_modifiers(player: Player, curios: Container) { + for (const { attribute, id } of applied.get(player.id) ?? []) player.remove_modifier(attribute, id); + const now: { attribute: string; id: string }[] = []; + for (const [index, slot] of SLOTS.entries()) { + const item = curios.get(index); + if (!item || !active.includes(slot)) continue; + for (const [i, { attribute, amount, operation }] of modifiers_of(item.id).entries()) { + const id = `curios:${slot}/${i}`; + player.add_modifier(attribute, { id, amount, operation }); + now.push({ attribute, id }); + } + } + applied.set(player.id, now); + } + + ctx.events.after.player_join.subscribe(({ player }) => { + const curios = saved_curios(player); + if (curios) watch(player, curios); + }); + ctx.events.after.player_leave.subscribe(({ player }) => { + stop_watching.get(player.id)?.(); + stop_watching.delete(player.id); + applied.delete(player.id); + }); + + ctx.net.on("curios:open", (player) => { + if (active.length === 0) return; + const curios = curios_of(player); + // what's in slot types no item goes in anymore, since the mod that added them was removed, goes back to them + for (const [index, slot] of SLOTS.entries()) { + const item = curios.get(index); + if (item && !active.includes(slot)) { + player.give_item(item.id, item.count, item.data); + curios.set(index, undefined); + } + } + // in rows of 9, each row centered + ctx.ui.open_container(player, { + container: curios, + layout: active.map((slot, i) => { + const row = Math.floor(i / 9); + const in_row = Math.min(9, active.length - row * 9); + return { + slot: SLOTS.indexOf(slot), + x: (9 - in_row) / 2 + (i % 9), + y: row, + filter: (item) => fits(ctx.tags, slot, item.id), + icon: `curios:empty_${slot}_slot`, + }; + }), + }); + }); + + ctx.events.after.player_death.subscribe(({ player }) => { + const curios = saved_curios(player); + if (!curios) return; + const { x, y, z } = player.position; + for (let i = 0; i < curios.size; i++) { + const item = curios.get(i); + if (!item) continue; + const { id, count, data } = item; + curios.set(i, undefined); + ctx.world.drop_item(Math.floor(x), Math.floor(Math.max(y, 0)), Math.floor(z), { id, count, data }); + } + }); +} + +// like minecraft's attribute tooltips: "+4 Attack Damage", "+30% Attack Speed" +function describe({ attribute, amount, operation }: WornModifier): string { + const name = attribute.split(":").at(-1)!.split("_").map((word) => word[0].toUpperCase() + word.slice(1)).join(" "); + const sign = amount < 0 ? "-" : "+"; + const value = operation === "add_value" ? `${Math.abs(amount)}` : `${Math.round(Math.abs(amount) * 100)}%`; + return `${sign}${value} ${name}`; +} diff --git a/mods/curios/scripts/slots.ts b/mods/curios/scripts/slots.ts new file mode 100644 index 0000000..b8aa0a9 --- /dev/null +++ b/mods/curios/scripts/slots.ts @@ -0,0 +1,29 @@ +// curios' slot types, both scripts share them +import type { TagApi } from "bworld/server"; + +// in curios' order. every player has one of each, at its index here in their curios container, so slots keep their +// items when mods come and go +export const SLOTS = [ + "curio", + "head", + "necklace", + "back", + "body", + "bracelet", + "hands", + "ring", + "belt", + "feet", + "charm", +]; + +// like curios, a slot type is only there once some item goes in it: something is in its item tag, #curios:ring for +// rings +export function active_slots(tags: TagApi): string[] { + return SLOTS.filter((slot) => tags.get("items", `curios:${slot}`).length > 0); +} + +// curios' tag validator: an item goes in the slot types whose tag it's in, and #curios:curio items go in any +export function fits(tags: TagApi, slot: string, id: string): boolean { + return tags.has("items", `curios:${slot}`, id) || tags.has("items", "curios:curio", id); +} diff --git a/mods/curios/textures/empty_back_slot.png b/mods/curios/textures/empty_back_slot.png new file mode 100644 index 0000000000000000000000000000000000000000..1ca9ed2e8466b8f53b4e6f022f7c29eca02baa51 GIT binary patch literal 145 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!63?wyl`GbKJV{wqX6T`Z5GB1G~&H$efS0F8^ zpcEP!dh3^vFp$Gs666=m@c+L{z%@l6SKZUaF+^f&a)JVvfuW*@0XL^3>x=^oiU(S} mj1^ulUCeMLmSg#2b_V?{hR_X{4&4K4VeoYIb6Mw<&;$U1q$H#O literal 0 HcmV?d00001 diff --git a/mods/curios/textures/empty_belt_slot.png b/mods/curios/textures/empty_belt_slot.png new file mode 100644 index 0000000000000000000000000000000000000000..2c0582317420637c7b4f89e117e404e87558bdd3 GIT binary patch literal 144 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!63?wyl`GbKJV{wqX6T`Z5GB1G~&H$efS0F8^ zpcEP!dh3^vFp$Gs666=m@c+L{z%@l6SIyJKF+^f&a>4?^geGPUc~34U1H~Uc0)Z`j kY9X=(wkv9UqBYnUG<6sP=kZ>P0_tG!boFyt=akR{05uOGb^rhX literal 0 HcmV?d00001 diff --git a/mods/curios/textures/empty_body_slot.png b/mods/curios/textures/empty_body_slot.png new file mode 100644 index 0000000000000000000000000000000000000000..10f4250719a5d73c8194e78fc2869dd907390048 GIT binary patch literal 152 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!63?wyl`GbKJV{wqX6T`Z5GB1G~wg8_HS0Ei4 z8Y+A@@*j}JR1)MD%gTe~DWM4fFO(v; literal 0 HcmV?d00001 diff --git a/mods/curios/textures/empty_bracelet_slot.png b/mods/curios/textures/empty_bracelet_slot.png new file mode 100644 index 0000000000000000000000000000000000000000..fe9cef189a0f259fffd2ae4d523bb35c37c03b92 GIT binary patch literal 157 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!63?wyl`GbKJV{wqX6T`Z5GB1G~wg8_HS0Ei4 z8Y+A@@*j}JR1)MD%bP0l+XkK&Kez>% literal 0 HcmV?d00001 diff --git a/mods/curios/textures/empty_feet_slot.png b/mods/curios/textures/empty_feet_slot.png new file mode 100644 index 0000000000000000000000000000000000000000..81f1d19cdda8339c32d2640c35c75f97f280f40f GIT binary patch literal 149 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!63?wyl`GbKJV{wqX6T`Z5GB1G~&H$efS0F8^ zpcEP!dh3^vFp$Gs666=m@c+L{z%@l6SKHIYF+^f&a>4<=83!0T`<(<;8BCcE3p`?d pFsm@aZHuQu@dKZZ*#R4;d2}#Mop8-8*+{F@GUM0E+HFPMl z1bj76+Bm^PLDMnZafaIt=9^1b*d-o#pv=f1F2JB6zEr~mXa<9)tDnm{r-UW|8@nmI literal 0 HcmV?d00001 diff --git a/mods/curios/textures/empty_head_slot.png b/mods/curios/textures/empty_head_slot.png new file mode 100644 index 0000000000000000000000000000000000000000..17161ad862cd70a32452f331f8bba3ecd90cfcd2 GIT binary patch literal 157 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!63?wyl`GbKJV{wqX6T`Z5GB1G~wg8_HS0Ei4 z8Y+A@@*j}JR1)MD%mdKI;Vst09qL%qyPW_ literal 0 HcmV?d00001 diff --git a/mods/curios/textures/empty_ring_slot.png b/mods/curios/textures/empty_ring_slot.png new file mode 100644 index 0000000000000000000000000000000000000000..75aa4186d9555c14f9eb0ef293e001d6c1f76b55 GIT binary patch literal 144 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!63?wyl`GbKJV{wqX6T`Z5GB1G~wg8_HS0Ei4 z8Y+A@@*j}JR1)MD%an`|*xjzopr09oWBfB*mh literal 0 HcmV?d00001 diff --git a/server/game/entity/attributes.ts b/server/game/entity/attributes.ts index 32c67df..4d7e5ed 100644 --- a/server/game/entity/attributes.ts +++ b/server/game/entity/attributes.ts @@ -2,7 +2,7 @@ // numbers are minecraft's, so movement_speed is its per tick value, see LivingEntity.travel export type ModifierOperation = "add_value" | "add_multiplied_base" | "add_multiplied_total"; -const OPERATIONS: ModifierOperation[] = ["add_value", "add_multiplied_base", "add_multiplied_total"]; +export const MODIFIER_OPERATIONS: ModifierOperation[] = ["add_value", "add_multiplied_base", "add_multiplied_total"]; export interface AttributeModifier { // unique on the attribute, so it can be replaced or taken off, like "bworld:effect.speed" @@ -31,6 +31,8 @@ export const ATTRIBUTES = { movement_speed: attribute("movement_speed", 0.7, 0, 1024), attack_damage: attribute("attack_damage", 2, 0, 2048), attack_knockback: attribute("attack_knockback", 0, 0, 5), + // full strength attacks a second, see ServerPlayer.attack_strength + attack_speed: attribute("attack_speed", 4, 0, 1024), // how far mobs notice players from, in blocks follow_range: attribute("follow_range", 32, 0, 2048), // how fast a jump starts, blocks per tick @@ -167,7 +169,7 @@ export class AttributeMap { for (const modifier of Array.isArray(entry.modifiers) ? entry.modifiers : []) { if ( typeof modifier?.id === "string" && typeof modifier.amount === "number" && - OPERATIONS.includes(modifier.operation) + MODIFIER_OPERATIONS.includes(modifier.operation) ) { attribute.add_modifier(modifier); } diff --git a/server/game/game_server.ts b/server/game/game_server.ts index 3cf378b..cd2ef69 100644 --- a/server/game/game_server.ts +++ b/server/game/game_server.ts @@ -463,6 +463,11 @@ export class GameServer { this.#send(player, { type: "chat", text }); } + // a mod's server script to its client script, see ctx.net + send_mod_message(player: ServerPlayer, channel: string, data: unknown) { + this.#send(player, { type: "mod", channel, data }); + } + teleport(player: ServerPlayer, x: number, y: number, z: number) { Object.assign(player, { x, y, z }); player.fall_distance = 0; @@ -765,6 +770,7 @@ export class GameServer { break; case "select_slot": if (is_int(message.slot) && message.slot >= 0 && message.slot < 9) { + if (message.slot !== player.selected_slot) player.attack_strength_ticker = 0; player.selected_slot = message.slot; } break; @@ -783,6 +789,11 @@ export class GameServer { case "suggest": this.#suggest(player, message.id, message.text); break; + case "mod": + if (typeof message.channel === "string") { + this.mods.receive(player, message.channel, message.data); + } + break; } } @@ -838,7 +849,11 @@ export class GameServer { return; } const source = { type: "physical", cause: "player_attack", attacker: player, by_player: true } as const; - if (entity.hurt(player.attribute(ATTRIBUTES.attack_damage), source)) { + // like minecraft, attacking again before the attack speed allows hits weaker + const strength = player.attack_strength(); + player.attack_strength_ticker = 0; + const damage = player.attribute(ATTRIBUTES.attack_damage) * (0.2 + strength * strength * 0.8); + if (entity.hurt(damage, source)) { player.vitals.add_exhaustion(EXHAUSTION.attack); } } diff --git a/server/game/mod_runtime.ts b/server/game/mod_runtime.ts index be4885e..09a39dc 100644 --- a/server/game/mod_runtime.ts +++ b/server/game/mod_runtime.ts @@ -44,6 +44,7 @@ import type { OpenScreen, ServerPlayer } from "./player.ts"; import { MAX_HEALTH } from "./vitals.ts"; import type { Entity } from "./entity/entity.ts"; import { create_entity } from "./entity/entity_types.ts"; +import { attribute_type, type AttributeType, MODIFIER_OPERATIONS } from "./entity/attributes.ts"; import type { ScreenLayout } from "$/common/protocol.ts"; // a list of handlers that can't break each other: one throwing is logged under its mod and the rest still run @@ -138,6 +139,25 @@ export class ModRuntime { #next_timer = 1; #setting_up = true; #players = new WeakMap(); + // mod channels, see ctx.net: who listens on each channel + #net_handlers = new Map void }[]>(); + // mod messages each player sent this second, to drop floods + #net_counts = new WeakMap(); + + // a player's client sent a mod message. clients are untrusted: too big or too many are dropped + receive(player: ServerPlayer, channel: string, data: unknown) { + const second = Math.floor(Date.now() / 1000); + let counts = this.#net_counts.get(player); + if (!counts || counts.second !== second) { + counts = { second, count: 0 }; + this.#net_counts.set(player, counts); + } + if (++counts.count > MAX_MOD_MESSAGES_PER_SECOND) return; + if ((JSON.stringify(data) ?? "").length > MAX_MOD_MESSAGE_LENGTH) return; + for (const { mod, handler } of this.#net_handlers.get(channel) ?? []) { + run_guarded(mod, `a ${channel} handler`, () => handler(this.player(player), data)); + } + } // the other way, for apis that take a player #server_players = new WeakMap(); game!: GameServer; @@ -498,6 +518,11 @@ export class ModRuntime { if (!item) throw new Error(`unknown item ${id}`); return item.tool?.type; }, + components: (id) => { + const item = EverythingRegistry.get("items", id); + if (!item) throw new Error(`unknown item ${id}`); + return structuredClone(item.components ?? {}); + }, }, recipes: { furnace_result: (input) => { @@ -537,7 +562,26 @@ export class ModRuntime { modal_form: not_yet(mod, "ui.modal_form", "see docs/modding_plan.md"), open_screen: not_yet(mod, "ui.open_screen", "see docs/modding_plan.md"), }, - net: not_yet_object(mod, "net", "see docs/modding_plan.md"), + net: { + on: (channel, handler) => { + own(channel, "channel"); + const handlers = this.#net_handlers.get(channel) ?? []; + handlers.push({ mod, handler: handler as (player: Player, data: unknown) => void }); + this.#net_handlers.set(channel, handlers); + }, + send: (player, channel, data) => { + own(channel, "channel"); + const server_player = this.#server_players.get(player); + if (!server_player || !game().players().includes(server_player)) { + throw new Error(`${player.name} isn't online`); + } + game().send_mod_message(server_player, channel, data); + }, + broadcast: (channel, data) => { + own(channel, "channel"); + for (const player of game().players()) game().send_mod_message(player, channel, data); + }, + }, storage: { get: (key) => structuredClone(this.storage[mod]?.[key]) as never, set: (key, value) => { @@ -587,9 +631,13 @@ export class ModRuntime { const bottom = Math.max(0, ...options.layout.map((s) => s.y + 1), ...bars.map((b) => b.y + 1)); const layout: ScreenLayout = { rows: options.rows ?? Math.ceil(bottom), - slots: options.layout.map(({ slot, x, y, output_only }) => - output_only ? { index: slot, x, y, output: true } : { index: slot, x, y } - ), + slots: options.layout.map(({ slot, x, y, output_only, icon }) => ({ + index: slot, + x, + y, + ...(output_only ? { output: true } : {}), + ...(icon ? { icon } : {}), + })), bars: bars.map(({ x, y, value, max, direction, empty_texture, full_texture }) => ({ x, y, @@ -673,14 +721,10 @@ function not_yet(mod: string, name: string, why: string) { }; } -// every method on it throws, saying what isn't built yet -function not_yet_object(mod: string, name: string, where: string): T { - return new Proxy({}, { - get: (_, prop) => not_yet(mod, `${name}.${String(prop)}`, where), - }) as T; -} - const MAX_CONTAINER_SIZE = 256; +// what a client may send on mod channels, see docs/modding/networking/index.md +const MAX_MOD_MESSAGE_LENGTH = 16 * 1024; +const MAX_MOD_MESSAGES_PER_SECOND = 60; // who ran a command, as the engine sees it: what mods see plus the engine's player export interface ServerCommandSource extends CommandSource { @@ -813,9 +857,27 @@ function player_api(game: GameServer, player: ServerPlayer): Player { } player.vitals.add_exhaustion(amount); }, + attribute: (id) => player.attribute(known_attribute(id)), + add_modifier(attribute, modifier) { + const type = known_attribute(attribute); + const { id, amount, operation } = modifier; + if (typeof id !== "string" || typeof amount !== "number" || !Number.isFinite(amount)) { + throw new Error("a modifier needs a string id and a number amount"); + } + if (!MODIFIER_OPERATIONS.includes(operation)) throw new Error(`unknown modifier operation ${operation}`); + player.attributes.get(type)?.add_modifier({ id, amount, operation }); + }, + remove_modifier: (attribute, id) => + player.attributes.get(known_attribute(attribute))?.remove_modifier(id) ?? false, }; } +function known_attribute(id: string): AttributeType { + const type = attribute_type(id); + if (!type) throw new Error(`unknown attribute ${id}`); + return type; +} + function entity_ref(entity: Entity): EntityRef { return { id: entity.id, diff --git a/server/game/player.ts b/server/game/player.ts index bf76b09..3eeff29 100644 --- a/server/game/player.ts +++ b/server/game/player.ts @@ -66,6 +66,8 @@ export class ServerPlayer extends LivingEntity { knockback_ticks: number | undefined; // when the last move came, to tell walking from sprinting last_move_tick = 0; + // ticks since they last attacked or changed their held item, like minecraft's attackStrengthTicker + attack_strength_ticker = 0; crafting = new Container(CRAFTING_SIZE); cursor: Cursor = { item: undefined }; selected_slot = 0; @@ -94,6 +96,7 @@ export class ServerPlayer extends LivingEntity { ...super.default_attributes(), // a fist does half a heart, like minecraft [ATTRIBUTES.attack_damage, 1], + [ATTRIBUTES.attack_speed], [ATTRIBUTES.physical_shielding], [ATTRIBUTES.arcane_shielding], ]; @@ -113,6 +116,7 @@ export class ServerPlayer extends LivingEntity { // knocked back it moves them like a mob that isn't walking anywhere, landing hands them back to their client override tick() { this.base_tick(); + this.attack_strength_ticker += 1; if (!this.dead) { this.tick_effects(); } @@ -155,6 +159,12 @@ export class ServerPlayer extends LivingEntity { this.level.on_death(this, source); } + // like minecraft's getAttackStrengthScale: 0 right after attacking, filling up to 1 over 20 / attack_speed ticks + attack_strength(): number { + const delay = 20 / this.attribute(ATTRIBUTES.attack_speed); + return Math.min(1, Math.max(0, (this.attack_strength_ticker + 0.5) / delay)); + } + get held_item(): ItemStack | undefined { return this.inventory.get_item(this.selected_slot); } diff --git a/tests/artifacts_test.ts b/tests/artifacts_test.ts new file mode 100644 index 0000000..f1a34b5 --- /dev/null +++ b/tests/artifacts_test.ts @@ -0,0 +1,46 @@ +// artifacts: items worn in curios slots that change the wearer's attributes, see mods/artifacts +import { assertEquals } from "@std/assert"; +import { ATTRIBUTES } from "$/server/game/entity/attributes.ts"; +import { test_game } from "./helpers.ts"; + +// deno-lint-ignore no-explicit-any +type Msg = any; + +async function setup() { + const t = await test_game("mods"); + t.join(1, "alice"); + t.send(1, { type: "chat", text: "/give artifacts:power_glove" }); + t.send(1, { type: "chat", text: "/give artifacts:feral_claws" }); + t.take(1); + return { ...t, alice: t.game.players()[0] }; +} + +Deno.test("the power glove and feral claws go in the hands slot, and only work while worn", async () => { + const t = await setup(); + t.send(1, { type: "mod", channel: "curios:open", data: {} }); + const screen = t.take(1).find((m: Msg) => m.type === "open_screen"); + assertEquals(screen.layout.slots.map((s: Msg) => s.icon), ["curios:empty_hands_slot"]); + + t.send(1, { type: "click", container: "inventory", index: 0, button: 0, shift: true }); + t.game.tick(); + assertEquals(t.alice.attribute(ATTRIBUTES.attack_damage), 1 + 4); + + // swapped for the claws by hand: the glove's damage goes, the claws' speed comes + t.send(1, { type: "click", container: "inventory", index: 1, button: 0 }); + t.send(1, { type: "click", container: "screen", index: 6, button: 0 }); + t.game.tick(); + assertEquals(t.alice.attribute(ATTRIBUTES.attack_damage), 1); + assertEquals(t.alice.attribute(ATTRIBUTES.attack_speed), 4 * 1.3); +}); + +Deno.test("worn artifacts work again after rejoining, and say what they do", async () => { + const t = await setup(); + t.send(1, { type: "mod", channel: "curios:open", data: {} }); + t.send(1, { type: "click", container: "inventory", index: 0, button: 0, shift: true }); + const curios = t.take(1).filter((m: Msg) => m.type === "container" && m.container === "screen").at(-1).items; + assertEquals(curios[6].lore, "When worn:\n+4 Attack Damage"); + + t.game.on_disconnect(1); + t.join(1, "alice"); + assertEquals(t.game.players()[0].attribute(ATTRIBUTES.attack_damage), 1 + 4); +}); diff --git a/tests/curios_test.ts b/tests/curios_test.ts new file mode 100644 index 0000000..f33b844 --- /dev/null +++ b/tests/curios_test.ts @@ -0,0 +1,74 @@ +// curios: accessory slots for items in the curios tags, opened over mod channels, see mods/curios +import { assert, assertEquals } from "@std/assert"; +import { copy_dir, 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; + +// the base game, curios, and a mod with a ring and an amulet that goes in any slot +async function setup() { + const dir = Deno.makeTempDirSync({ prefix: "bworld_curios_" }); + copy_dir("mods/bworld", `${dir}/bworld`); + copy_dir("mods/curios", `${dir}/curios`); + const write = (path: string, json: unknown) => { + Deno.mkdirSync(`${dir}/jewelry/${path}`.replace(/\/[^/]+$/, ""), { recursive: true }); + Deno.writeTextFileSync(`${dir}/jewelry/${path}`, JSON.stringify(json)); + }; + write("manifest.json", { format_version: 1, id: "jewelry", name: "Jewelry", version: "1.0.0" }); + write("items/ring.json", { format_version: 1, item: { id: "jewelry:ring", texture: "bworld:coal" } }); + write("items/amulet.json", { format_version: 1, item: { id: "jewelry:amulet", texture: "bworld:coal" } }); + write("tags/items/curios/ring.json", { format_version: 1, tag: { values: ["jewelry:ring"] } }); + write("tags/items/curios/curio.json", { format_version: 1, tag: { values: ["jewelry:amulet"] } }); + + const t = await test_game(dir); + t.join(1, "alice"); + for (const id of ["jewelry:ring", "jewelry:amulet", "bworld:coal"]) { + t.send(1, { type: "chat", text: `/give ${id}` }); + } + t.take(1); + return t; +} + +Deno.test("the curios screen shows the slot types some item goes in, with their icons", async () => { + const t = await setup(); + t.send(1, { type: "mod", channel: "curios:open", data: {} }); + const screen = t.take(1).find((m) => m.type === "open_screen"); + assertEquals(screen.layout.slots, [ + { index: 0, x: 3.5, y: 0, icon: "curios:empty_curio_slot" }, + { index: 7, x: 4.5, y: 0, icon: "curios:empty_ring_slot" }, + ]); +}); + +Deno.test("items only go in the slots they fit, and fall out when the player dies", async () => { + const t = await setup(); + t.send(1, { type: "mod", channel: "curios:open", data: {} }); + t.take(1); + + // coal fits nowhere, the ring only in the ring slot, and #curios:curio items in any slot, the curio slot first + t.send(1, { type: "click", container: "inventory", index: 2, button: 0, shift: true }); + t.send(1, { type: "click", container: "inventory", index: 0, button: 0, shift: true }); + t.send(1, { type: "click", container: "inventory", index: 1, button: 0, shift: true }); + const messages = t.take(1); + assertEquals(last_container(messages, "inventory").slice(0, 3), [null, null, { id: "bworld:coal", count: 1 }]); + const curios = last_container(messages, "screen"); + assertEquals(curios[0], { id: "jewelry:amulet", count: 1 }); + assertEquals(curios[7], { id: "jewelry:ring", count: 1 }); + + const player = t.game.players()[0]; + t.game.damage_player(player, 100, "fall"); + const dropped = t.game.item_entities().map((e) => e.item.type_id).sort(); + assertEquals(dropped, ["bworld:coal", "jewelry:amulet", "jewelry:ring"]); + t.send(1, { type: "mod", channel: "curios:open", data: {} }); + assertEquals(last_container(t.take(1), "screen").filter(Boolean), []); +}); + +Deno.test("mod messages that are too big or too many are dropped", async () => { + const t = await setup(); + t.send(1, { type: "mod", channel: "curios:open", data: "x".repeat(20_000) }); + assertEquals(t.take(1).filter((m) => m.type === "open_screen"), []); + for (let i = 0; i < 100; i++) t.send(1, { type: "mod", channel: "curios:open", data: {} }); + assert(t.take(1).filter((m) => m.type === "open_screen").length < 100); +}); diff --git a/tests/entity_test.ts b/tests/entity_test.ts index 197e17a..ef613bf 100644 --- a/tests/entity_test.ts +++ b/tests/entity_test.ts @@ -149,7 +149,8 @@ Deno.test("players hit entities they can reach, pushing them away", async () => const mob = spawn(0.5, 100, 2.5); const far = spawn(0.5, 100, 20.5); far.tags.add("stays"); - ticks(2); + // long enough for a full strength attack + ticks(5); send(1, { type: "attack_entity", id: mob.id }); assertEquals(mob.health, 9); @@ -161,12 +162,35 @@ Deno.test("players hit entities they can reach, pushing them away", async () => send(1, { type: "attack_entity", id: "nothing" }); }); +Deno.test("attacking again before the attack speed allows hits weaker, like minecraft", async () => { + const { game, spawn, ticks, send } = await floor_game(); + const [alice] = game.players(); + alice.attributes.get(ATTRIBUTES.attack_damage)!.base = 5; + const mob = spawn(0.5, 100, 2.5); + ticks(5); + send(1, { type: "attack_entity", id: mob.id }); + assertEquals(mob.health, 5, "4 attacks a second, so 5 ticks is full strength"); + + // right away is a fifth, a tick later a bit more. past the hurt cooldown, so it isn't just the difference + ticks(20); + alice.attack_strength_ticker = 0; + send(1, { type: "attack_entity", id: mob.id }); + assertEquals(mob.health, 5 - 5 * (0.2 + 0.1 * 0.1 * 0.8)); + + // faster attack speed fills up sooner + ticks(10); + alice.attributes.get(ATTRIBUTES.attack_speed)!.base = 20; + alice.attack_strength_ticker = 1; + assertEquals(alice.attack_strength(), 1); +}); + Deno.test("players hit each other, knocking them back and flashing red for everyone else", async () => { const { game, ticks, send, join, take } = await floor_game(); join(2, "bob"); send(2, { type: "move", x: 0.5, y: 100, z: 2.5, yaw: 0, pitch: 0 }); const [alice, bob] = game.players(); - ticks(1); + // long enough for a full strength attack + ticks(5); take(1); take(2); diff --git a/tests/handshake_test.ts b/tests/handshake_test.ts index b28c483..5d8f763 100644 --- a/tests/handshake_test.ts +++ b/tests/handshake_test.ts @@ -29,7 +29,13 @@ Deno.test("welcome lists what to download, and nothing happens until ready", asy send(2, { type: "hello", name: "bob", protocol: PROTOCOL_VERSION }); const [welcome] = take(2); assertEquals(welcome.type, "welcome"); - assertEquals(welcome.mods.map((m: { id: string }) => m.id), ["bworld", "farmersdelight", "recipe_viewer"]); + assertEquals(welcome.mods.map((m: { id: string }) => m.id), [ + "bworld", + "curios", + "artifacts", + "farmersdelight", + "recipe_viewer", + ]); assert(welcome.mods.every((m: { sha256: string; file: string }) => m.sha256 && m.file)); assert(!("players" in welcome) && !("changes" in welcome), "welcome shouldn't have world state");