Curios and artifacts !

This commit is contained in:
2026-09-30 15:22:32 -03:00
parent 342b45d593
commit 3af5f6e54b
45 changed files with 729 additions and 43 deletions
+2 -3
View File
@@ -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.
+8 -1
View File
@@ -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,
),
);
}
}
+13 -2
View File
@@ -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<Texture>("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");
+32 -1
View File
@@ -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<string, { mod: string; handler: (data: unknown) => 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<string, string>();
@@ -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<ItemRegistry>("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;
+4
View File
@@ -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));
+20
View File
@@ -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<Id, unknown>;
}
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;
+9 -5
View File
@@ -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;
+26
View File
@@ -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
+2 -3
View File
@@ -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.
+1
View File
@@ -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.
+3
View File
@@ -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).
+9 -6
View File
@@ -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.
+5 -5
View File
@@ -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.
+28
View File
@@ -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.
```
+13
View File
@@ -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" }
]
}
}
}
+13
View File
@@ -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" }
]
}
}
}
+23
View File
@@ -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"
}
@@ -0,0 +1,6 @@
{
"format_version": 1,
"tag": {
"values": ["artifacts:power_glove", "artifacts:feral_claws"]
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 220 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

+21
View File
@@ -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 <https://www.gnu.org/licenses/>.
```
+45
View File
@@ -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.
+17
View File
@@ -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"
}
}
+21
View File
@@ -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", {});
}
},
});
}
+123
View File
@@ -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<WornModifier[]>("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<string, { attribute: string; id: string }[]>();
const stop_watching = new Map<string, () => 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<Record<string, string>>("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<Record<string, string>>("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}`;
}
+29
View File
@@ -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);
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 145 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 144 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 152 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 157 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 139 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 140 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 149 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 158 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 157 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 152 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 144 B

+4 -2
View File
@@ -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);
}
+16 -1
View File
@@ -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);
}
}
+73 -11
View File
@@ -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<ServerPlayer, Player>();
// mod channels, see ctx.net: who listens on each channel
#net_handlers = new Map<string, { mod: string; handler: (player: Player, data: unknown) => void }[]>();
// mod messages each player sent this second, to drop floods
#net_counts = new WeakMap<ServerPlayer, { second: number; count: number }>();
// 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<Player, ServerPlayer>();
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<ItemRegistry>("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<T>(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,
+10
View File
@@ -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);
}
+46
View File
@@ -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);
});
+74
View File
@@ -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);
});
+26 -2
View File
@@ -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);
+7 -1
View File
@@ -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");